package pi import ( "context" "encoding/json" "errors" "maps" "slices" "sync" "time" "amadan.net/oficina/equipo/internal/runner/provider" ) // Launcher runs Pi in RPC mode in a namespace the ProcessHost owns // (provider.Launcher). One process is one session; a run is one prompt // and its events to the end. Ending a run is the namespace's work, never // Pi's (rev 3 ยง5): Interrupt asks Pi to abort, and the caller kills the // namespace and waits for its proof. type Launcher struct { host provider.ProcessHost mu sync.Mutex sessions map[string]*session } var _ provider.Launcher = (*Launcher)(nil) type session struct { launch provider.Launch process provider.Process client *Client decoder *Decoder events chan provider.Event turn string mu sync.Mutex asks map[string]bool } // New is a launcher on host. func New(host provider.ProcessHost) (*Launcher, error) { if host == nil { return nil, provider.ErrPolicy } return &Launcher{host: host, sessions: map[string]*session{}}, nil } // Preflight checks the policy is a Pi one for this binding; the key and // the pins are checked again at the launch's attestation. func (l *Launcher) Preflight(_ context.Context, b provider.Binding, p provider.Policy) (provider.Identity, error) { if !p.IsPi() || p.KeyEnv() == "" || !b.Token { return provider.Identity{}, provider.ErrPolicy } return provider.Identity{AccountID: b.ID, ProviderVersion: Version}, nil } // Open starts Pi and reads its state: the provider, model and session // it runs must be the launch's. ctx is the attempt's lifetime: the // ProcessHost kills the namespace when it is cancelled. func (l *Launcher) Open(ctx context.Context, launch provider.Launch) (provider.Session, error) { return l.OpenWithin(ctx, ctx, launch) } // OpenWithin is Open with the start bounded apart from the attempt's // lifetime: lifetime owns the namespace, startup bounds the wait for // Pi's state (a step's cancellation and deadline reach it). func (l *Launcher) OpenWithin(lifetime, startup context.Context, launch provider.Launch) (provider.Session, error) { argv := launch.Policy.PiArgv() if argv == nil { return provider.Session{}, provider.ErrPolicy } return l.openWith(lifetime, startup, launch, argv) } func (l *Launcher) openWith(ctx, startup context.Context, launch provider.Launch, argv []string) (provider.Session, error) { proc, err := l.host.Start(ctx, launch, argv) if err != nil { return provider.Session{}, err } s := &session{launch: launch, process: proc, client: NewClient(proc.Stdout(), proc.Stdin()), decoder: &Decoder{}, events: make(chan provider.Event, 64), asks: map[string]bool{}} sctx, cancel := context.WithTimeout(startup, 60*time.Second) defer cancel() r, err := s.client.Call(sctx, map[string]any{"type": "get_state"}) var state struct { SessionID string `json:"sessionId"` Model struct { ID, Provider string } `json:"model"` } if err == nil && json.Unmarshal(r.Data, &state) != nil { err = provider.ErrPolicy } if err == nil && (state.Model.ID != launch.Selection.Model || state.Model.Provider != launch.Selection.Provider || state.SessionID == "" || launch.ResumeSessionID != "" && state.SessionID != launch.ResumeSessionID) { err = provider.ErrIdentity } if err != nil { proc.Stdin().Close() return provider.Session{}, err } sess := provider.Session{ID: state.SessionID, AttemptKey: launch.AttemptKey, Provider: launch.Selection.Provider, AccountID: launch.Selection.AccountID, Model: launch.Selection.Model, Family: launch.Selection.Family} go s.read(sess.ID) l.mu.Lock() l.sessions[sess.ID] = s l.mu.Unlock() return sess, nil } // read decodes Pi's records into the session's events until stdout ends. func (s *session) read(id string) { defer close(s.events) for line := range s.client.Records { s.mu.Lock() evs, err := s.decoder.Decode(line) s.mu.Unlock() s.client.Release(len(line)) if err != nil { continue } for _, e := range evs { e.SessionID = id s.mu.Lock() e.TurnID = s.turn if e.Kind == KindAsk { var a Ask _ = json.Unmarshal(e.Payload, &a) s.asks[a.ID] = true e.RequestID = a.ID } s.mu.Unlock() s.events <- e } } } func (l *Launcher) state(sess provider.Session) (*session, error) { l.mu.Lock() defer l.mu.Unlock() s := l.sessions[sess.ID] if s == nil { return nil, provider.ErrIdentity } return s, nil } // Events are the session's decoded events, closed when Pi's stdout ends. func (l *Launcher) Events(_ context.Context, sess provider.Session) (<-chan provider.Event, error) { s, err := l.state(sess) if err != nil { return nil, err } return s.events, nil } // StartTurn sends the prompt; Pi must start a run for it. func (l *Launcher) StartTurn(ctx context.Context, sess provider.Session, t provider.Turn) error { s, err := l.state(sess) if err != nil { return err } s.mu.Lock() s.turn = t.ID s.mu.Unlock() r, err := s.client.Call(ctx, map[string]any{"type": "prompt", "message": t.Prompt}) if err != nil { return err } var d struct{ Disposition string } if json.Unmarshal(r.Data, &d) != nil || d.Disposition != "started" { return errors.New("pi: the prompt started no run") } return nil } // Respond answers the extension's question: Behavior "allow" lets the // call run; anything else blocks it. func (l *Launcher) Respond(ctx context.Context, sess provider.Session, a provider.Answer) error { s, err := l.state(sess) if err != nil { return err } s.mu.Lock() pending := s.asks[a.RequestID] delete(s.asks, a.RequestID) s.mu.Unlock() if !pending { return provider.ErrIdentity } return s.client.Send(ctx, map[string]any{"type": "extension_ui_response", "id": a.RequestID, "confirmed": a.Behavior == "allow"}) } // Interrupt cancels any question Pi waits on (an abort does not end a // pending dialog), then aborts the run. It gives up when ctx ends: the // run's end is the namespace's kill, never Pi's answer. func (l *Launcher) Interrupt(ctx context.Context, sess provider.Session) error { s, err := l.state(sess) if err != nil { return err } s.mu.Lock() ids := make([]string, 0, len(s.asks)) for id := range s.asks { ids = append(ids, id) } s.asks = map[string]bool{} s.mu.Unlock() slices.Sort(ids) for _, id := range ids { if err := s.client.Send(ctx, map[string]any{"type": "extension_ui_response", "id": id, "cancelled": true}); err != nil { return err } } _, err = s.client.Call(ctx, map[string]any{"type": "abort"}) return err } // Close closes Pi's stdin, its request for an orderly shutdown. The // namespace's end is the ProcessHost's. func (l *Launcher) Close(_ context.Context, sess provider.Session) error { s, err := l.state(sess) if err != nil { return err } l.mu.Lock() delete(l.sessions, sess.ID) l.mu.Unlock() return s.process.Stdin().Close() } // Process is the session's process (its namespace record and Wait). func (l *Launcher) Process(sess provider.Session) (provider.Process, error) { s, err := l.state(sess) if err != nil { return nil, err } return s.process, nil } // Unknown is how many records of each unknown type the session dropped. func (l *Launcher) Unknown(sess provider.Session) map[string]int { s, err := l.state(sess) if err != nil { return nil } s.mu.Lock() defer s.mu.Unlock() return maps.Clone(s.decoder.Unknown) }