package opencode import ( "context" "encoding/json" "errors" "maps" "slices" "strconv" "sync" "time" "amadan.net/oficina/equipo/internal/runner/provider" ) // Launcher runs `opencode acp` in a namespace the ProcessHost owns // (provider.Launcher). One process is one session; a run is one prompt // and its updates to the prompt's answer. Ending a run is the // namespace's work, never OpenCode's (rev 3 §5): Interrupt asks it to // cancel, and the caller kills the namespace and waits for its proof. type Launcher struct { host provider.ProcessHost // CostBase is the reported cost of the session a launch resumes, as // recorded when it was kept (RestoreSession); 0 for a new one. CostBase float64 mu sync.Mutex sessions map[string]*session } var _ provider.Launcher = (*Launcher)(nil) type session struct { launch provider.Launch process provider.Process client *Client events chan provider.Event id string mu sync.Mutex decoder *Decoder turn string next int pending map[string]chan Message asks map[string]permission // done ends the reader when the session closes, however full its // events are (security round finding 7). done chan struct{} once sync.Once } // maxPendingAsks bounds the permission requests waiting on Equipo; one // over it is answered cancelled at once and never recorded. const maxPendingAsks = 64 // permission is a pending session/request_permission: its raw id (sent // back as given) and the options OpenCode offered. type permission struct { id json.RawMessage allow, block string } // 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 an OpenCode 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.IsOpenCode() || p.KeyEnv() == "" || !b.Token { return provider.Identity{}, provider.ErrPolicy } return provider.Identity{AccountID: b.ID, ProviderVersion: Version}, nil } // openTimeout bounds OpenCode's start: initialize and the session. const openTimeout = 90 * time.Second // Open starts OpenCode, initializes ACP, and opens the session: a new // one, or the launch's kept one loaded. OpenCode must be the pinned // version and run the launch's model. 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 (security round finding 6): lifetime owns the namespace (its // end kills it), startup bounds the wait for initialize and the session, // so a step's cancellation or deadline gives up a start that never // answers without ending the attempt's own kill and proof. func (l *Launcher) OpenWithin(lifetime, startup context.Context, launch provider.Launch) (provider.Session, error) { ctx := lifetime argv := launch.Policy.OpenCodeArgv() model, resume, ok := launch.Policy.OpenCodeSelection() if argv == nil || !ok || model != launch.Selection.Model || resume != launch.ResumeSessionID { return provider.Session{}, provider.ErrPolicy } 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()), events: make(chan provider.Event, 64), decoder: &Decoder{Model: model, CostBase: l.CostBase}, pending: map[string]chan Message{}, asks: map[string]permission{}, done: make(chan struct{})} go s.read() sctx, cancel := context.WithTimeout(startup, openTimeout) defer cancel() id, err := s.open(sctx, model, resume) if err != nil { s.shutdown() proc.Stdin().Close() return provider.Session{}, err } sess := provider.Session{ID: id, AttemptKey: launch.AttemptKey, Provider: launch.Selection.Provider, AccountID: launch.Selection.AccountID, Model: launch.Selection.Model, Family: launch.Selection.Family} l.mu.Lock() l.sessions[sess.ID] = s l.mu.Unlock() return sess, nil } func (s *session) open(ctx context.Context, model, resume string) (string, error) { var init struct { ProtocolVersion int `json:"protocolVersion"` AgentInfo struct { Name, Version string } `json:"agentInfo"` } if err := s.call(ctx, "initialize", map[string]any{"protocolVersion": 1, "clientCapabilities": map[string]any{"fs": map[string]bool{"readTextFile": false, "writeTextFile": false}, "terminal": false}}, &init); err != nil { return "", err } if init.ProtocolVersion != 1 || init.AgentInfo.Version != Version { return "", provider.ErrIdentity } var opened struct { SessionID string `json:"sessionId"` ConfigOptions []struct { ID string `json:"id"` CurrentValue string `json:"currentValue"` } `json:"configOptions"` } id := resume if resume == "" { if err := s.call(ctx, "session/new", map[string]any{"cwd": "/workspace", "mcpServers": []any{}}, &opened); err != nil { return "", err } id = opened.SessionID } else if err := s.call(ctx, "session/load", map[string]any{"sessionId": resume, "cwd": "/workspace", "mcpServers": []any{}}, &opened); err != nil { return "", err } if !provider.OpenCodeSessionID(id) || resume != "" && opened.SessionID != "" && opened.SessionID != resume { return "", provider.ErrIdentity } current := "" for _, o := range opened.ConfigOptions { if o.ID == "model" { current = o.CurrentValue } } if current != provider.OpenCodeModel(model) { return "", provider.ErrIdentity } s.mu.Lock() s.id, s.decoder.Session = id, id s.mu.Unlock() return id, nil } // errRefused: OpenCode answered a request with an error. var errRefused = errors.New("opencode: a request was refused") // call sends a request and waits for its answer. func (s *session) call(ctx context.Context, method string, params any, out any) error { s.mu.Lock() s.next++ id := "equipo-" + strconv.Itoa(s.next) ch := make(chan Message, 1) s.pending[id] = ch s.mu.Unlock() forget := func() { s.mu.Lock() delete(s.pending, id) s.mu.Unlock() } if err := s.client.Send(ctx, map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}); err != nil { forget() return err } select { case <-ctx.Done(): forget() return ctx.Err() case m, ok := <-ch: if !ok { return ErrClosed } if m.Error != nil { return errRefused } if out != nil && json.Unmarshal(m.Result, out) != nil { return provider.ErrIdentity } return nil } } // read routes OpenCode's messages until its stdout ends: answers to the // runner's requests to their caller, a permission request recorded and // decoded as an ask, any other request refused, everything else decoded // into the session's events. func (s *session) read() { defer func() { s.mu.Lock() for id, ch := range s.pending { close(ch) delete(s.pending, id) } s.mu.Unlock() close(s.events) }() for line := range s.client.Messages { var m Message err := json.Unmarshal(line, &m) s.client.Release(len(line)) if err != nil { s.mu.Lock() s.decoder.unknown("not json-rpc") s.mu.Unlock() continue } s.mu.Lock() if m.Response() { if ch := s.pending[rawID(m.ID)]; ch != nil { delete(s.pending, rawID(m.ID)) s.mu.Unlock() ch <- m continue } } if m.Request() && m.Method == methodPermission && len(s.asks) >= maxPendingAsks { // Over the bound: answered at once, never recorded or decoded. s.decoder.unknown("permission requests over the bound") s.mu.Unlock() s.client.TrySend(map[string]any{"jsonrpc": "2.0", "id": m.ID, "result": map[string]any{"outcome": map[string]any{"outcome": "cancelled"}}}) continue } if m.Request() && m.Method == methodPermission { if len(m.ID) > maxToolID { s.decoder.unknown("permission id too long") s.mu.Unlock() continue } s.asks[rawID(m.ID)] = permissionOf(m) } else if m.Request() { // The client offers OpenCode no file system and no terminal: // refused through the bounded writer, or not at all when it is // full (security round finding 5). s.decoder.unknown(m.Method) s.mu.Unlock() if len(m.ID) <= maxToolID && !s.client.TrySend(map[string]any{"jsonrpc": "2.0", "id": m.ID, "error": map[string]any{"code": -32601, "message": "not offered"}}) { s.mu.Lock() s.decoder.unknown("refusals dropped") s.mu.Unlock() } continue } evs := s.decoder.Decode(m) turn := s.turn s.mu.Unlock() for _, e := range evs { e.SessionID, e.TurnID = s.id, turn select { case s.events <- e: case <-s.done: return } } } } func permissionOf(m Message) permission { var p struct { Options []struct { OptionID string `json:"optionId"` Kind string `json:"kind"` } `json:"options"` } _ = json.Unmarshal(m.Params, &p) out := permission{id: m.ID} for _, o := range p.Options { switch o.Kind { case "allow_once": out.allow = o.OptionID case "reject_once": out.block = o.OptionID } } return out } 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 OpenCode'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; its answer, read later, ends the turn. 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() if s.decoder.Active() { s.mu.Unlock() return errors.New("opencode: a turn is running") } if s.decoder.ModelChanged() { // The model is fixed for the session (§16.5): no prompt goes to // one whose model OpenCode says changed. s.mu.Unlock() return provider.ErrIdentity } s.next++ id := "equipo-" + strconv.Itoa(s.next) s.turn = t.ID s.decoder.Start(id) s.mu.Unlock() return s.client.Send(ctx, map[string]any{"jsonrpc": "2.0", "id": id, "method": "session/prompt", "params": map[string]any{"sessionId": s.id, "prompt": []map[string]string{{"type": "text", "text": t.Prompt}}}}) } // Respond answers a permission request: Behavior "allow" lets the call // run; anything else rejects it (which ends OpenCode's turn). 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() p, pending := s.asks[a.RequestID] delete(s.asks, a.RequestID) s.mu.Unlock() if !pending { return provider.ErrIdentity } option := p.block if a.Behavior == "allow" { option = p.allow } outcome := map[string]any{"outcome": "selected", "optionId": option} if option == "" { outcome = map[string]any{"outcome": "cancelled"} } return s.client.Send(ctx, map[string]any{"jsonrpc": "2.0", "id": p.id, "result": map[string]any{"outcome": outcome}}) } // Interrupt answers every pending permission request as cancelled, then // asks OpenCode to cancel the turn. It gives up when ctx ends: the run's // end is the namespace's kill, never OpenCode'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 := slices.Sorted(maps.Keys(s.asks)) asks := s.asks s.asks = map[string]permission{} s.mu.Unlock() for _, id := range ids { if err := s.client.Send(ctx, map[string]any{"jsonrpc": "2.0", "id": asks[id].id, "result": map[string]any{"outcome": map[string]any{"outcome": "cancelled"}}}); err != nil { return err } } return s.client.Send(ctx, map[string]any{"jsonrpc": "2.0", "method": "session/cancel", "params": map[string]any{"sessionId": s.id}}) } // Close closes OpenCode'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() s.shutdown() return s.process.Stdin().Close() } // shutdown ends both reading layers and the writer: the session's reader // stops however full its events are, and the client's however full its // queue is. func (s *session) shutdown() { s.once.Do(func() { close(s.done) s.client.Shutdown() }) } // 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 } // SessionCost is the session's reported cost so far, to record when the // session is kept. func (l *Launcher) SessionCost(sess provider.Session) float64 { s, err := l.state(sess) if err != nil { return 0 } s.mu.Lock() defer s.mu.Unlock() return s.decoder.SessionCost() } // Unknown is how many messages of each unknown kind 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) }