| 1 | package opencode |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "maps" |
| 8 | "slices" |
| 9 | "strconv" |
| 10 | "sync" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 14 | ) |
| 15 | |
| 16 | // Launcher runs `opencode acp` in a namespace the ProcessHost owns |
| 17 | // (provider.Launcher). One process is one session; a run is one prompt |
| 18 | // and its updates to the prompt's answer. Ending a run is the |
| 19 | // namespace's work, never OpenCode's (rev 3 §5): Interrupt asks it to |
| 20 | // cancel, and the caller kills the namespace and waits for its proof. |
| 21 | type Launcher struct { |
| 22 | host provider.ProcessHost |
| 23 | // CostBase is the reported cost of the session a launch resumes, as |
| 24 | // recorded when it was kept (RestoreSession); 0 for a new one. |
| 25 | CostBase float64 |
| 26 | |
| 27 | mu sync.Mutex |
| 28 | sessions map[string]*session |
| 29 | } |
| 30 | |
| 31 | var _ provider.Launcher = (*Launcher)(nil) |
| 32 | |
| 33 | type session struct { |
| 34 | launch provider.Launch |
| 35 | process provider.Process |
| 36 | client *Client |
| 37 | events chan provider.Event |
| 38 | id string |
| 39 | |
| 40 | mu sync.Mutex |
| 41 | decoder *Decoder |
| 42 | turn string |
| 43 | next int |
| 44 | pending map[string]chan Message |
| 45 | asks map[string]permission |
| 46 | |
| 47 | // done ends the reader when the session closes, however full its |
| 48 | // events are (security round finding 7). |
| 49 | done chan struct{} |
| 50 | once sync.Once |
| 51 | } |
| 52 | |
| 53 | // maxPendingAsks bounds the permission requests waiting on Equipo; one |
| 54 | // over it is answered cancelled at once and never recorded. |
| 55 | const maxPendingAsks = 64 |
| 56 | |
| 57 | // permission is a pending session/request_permission: its raw id (sent |
| 58 | // back as given) and the options OpenCode offered. |
| 59 | type permission struct { |
| 60 | id json.RawMessage |
| 61 | allow, block string |
| 62 | } |
| 63 | |
| 64 | // New is a launcher on host. |
| 65 | func New(host provider.ProcessHost) (*Launcher, error) { |
| 66 | if host == nil { |
| 67 | return nil, provider.ErrPolicy |
| 68 | } |
| 69 | return &Launcher{host: host, sessions: map[string]*session{}}, nil |
| 70 | } |
| 71 | |
| 72 | // Preflight checks the policy is an OpenCode one for this binding; the |
| 73 | // key and the pins are checked again at the launch's attestation. |
| 74 | func (l *Launcher) Preflight(_ context.Context, b provider.Binding, p provider.Policy) (provider.Identity, error) { |
| 75 | if !p.IsOpenCode() || p.KeyEnv() == "" || !b.Token { |
| 76 | return provider.Identity{}, provider.ErrPolicy |
| 77 | } |
| 78 | return provider.Identity{AccountID: b.ID, ProviderVersion: Version}, nil |
| 79 | } |
| 80 | |
| 81 | // openTimeout bounds OpenCode's start: initialize and the session. |
| 82 | const openTimeout = 90 * time.Second |
| 83 | |
| 84 | // Open starts OpenCode, initializes ACP, and opens the session: a new |
| 85 | // one, or the launch's kept one loaded. OpenCode must be the pinned |
| 86 | // version and run the launch's model. ctx is the attempt's lifetime: the |
| 87 | // ProcessHost kills the namespace when it is cancelled. |
| 88 | func (l *Launcher) Open(ctx context.Context, launch provider.Launch) (provider.Session, error) { |
| 89 | return l.OpenWithin(ctx, ctx, launch) |
| 90 | } |
| 91 | |
| 92 | // OpenWithin is Open with the start bounded apart from the attempt's |
| 93 | // lifetime (security round finding 6): lifetime owns the namespace (its |
| 94 | // end kills it), startup bounds the wait for initialize and the session, |
| 95 | // so a step's cancellation or deadline gives up a start that never |
| 96 | // answers without ending the attempt's own kill and proof. |
| 97 | func (l *Launcher) OpenWithin(lifetime, startup context.Context, launch provider.Launch) (provider.Session, error) { |
| 98 | ctx := lifetime |
| 99 | argv := launch.Policy.OpenCodeArgv() |
| 100 | model, resume, ok := launch.Policy.OpenCodeSelection() |
| 101 | if argv == nil || !ok || model != launch.Selection.Model || resume != launch.ResumeSessionID { |
| 102 | return provider.Session{}, provider.ErrPolicy |
| 103 | } |
| 104 | proc, err := l.host.Start(ctx, launch, argv) |
| 105 | if err != nil { |
| 106 | return provider.Session{}, err |
| 107 | } |
| 108 | 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{})} |
| 109 | go s.read() |
| 110 | sctx, cancel := context.WithTimeout(startup, openTimeout) |
| 111 | defer cancel() |
| 112 | id, err := s.open(sctx, model, resume) |
| 113 | if err != nil { |
| 114 | s.shutdown() |
| 115 | proc.Stdin().Close() |
| 116 | return provider.Session{}, err |
| 117 | } |
| 118 | sess := provider.Session{ID: id, AttemptKey: launch.AttemptKey, Provider: launch.Selection.Provider, AccountID: launch.Selection.AccountID, Model: launch.Selection.Model, Family: launch.Selection.Family} |
| 119 | l.mu.Lock() |
| 120 | l.sessions[sess.ID] = s |
| 121 | l.mu.Unlock() |
| 122 | return sess, nil |
| 123 | } |
| 124 | |
| 125 | func (s *session) open(ctx context.Context, model, resume string) (string, error) { |
| 126 | var init struct { |
| 127 | ProtocolVersion int `json:"protocolVersion"` |
| 128 | AgentInfo struct { |
| 129 | Name, Version string |
| 130 | } `json:"agentInfo"` |
| 131 | } |
| 132 | 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 { |
| 133 | return "", err |
| 134 | } |
| 135 | if init.ProtocolVersion != 1 || init.AgentInfo.Version != Version { |
| 136 | return "", provider.ErrIdentity |
| 137 | } |
| 138 | var opened struct { |
| 139 | SessionID string `json:"sessionId"` |
| 140 | ConfigOptions []struct { |
| 141 | ID string `json:"id"` |
| 142 | CurrentValue string `json:"currentValue"` |
| 143 | } `json:"configOptions"` |
| 144 | } |
| 145 | id := resume |
| 146 | if resume == "" { |
| 147 | if err := s.call(ctx, "session/new", map[string]any{"cwd": "/workspace", "mcpServers": []any{}}, &opened); err != nil { |
| 148 | return "", err |
| 149 | } |
| 150 | id = opened.SessionID |
| 151 | } else if err := s.call(ctx, "session/load", map[string]any{"sessionId": resume, "cwd": "/workspace", "mcpServers": []any{}}, &opened); err != nil { |
| 152 | return "", err |
| 153 | } |
| 154 | if !provider.OpenCodeSessionID(id) || resume != "" && opened.SessionID != "" && opened.SessionID != resume { |
| 155 | return "", provider.ErrIdentity |
| 156 | } |
| 157 | current := "" |
| 158 | for _, o := range opened.ConfigOptions { |
| 159 | if o.ID == "model" { |
| 160 | current = o.CurrentValue |
| 161 | } |
| 162 | } |
| 163 | if current != provider.OpenCodeModel(model) { |
| 164 | return "", provider.ErrIdentity |
| 165 | } |
| 166 | s.mu.Lock() |
| 167 | s.id, s.decoder.Session = id, id |
| 168 | s.mu.Unlock() |
| 169 | return id, nil |
| 170 | } |
| 171 | |
| 172 | // errRefused: OpenCode answered a request with an error. |
| 173 | var errRefused = errors.New("opencode: a request was refused") |
| 174 | |
| 175 | // call sends a request and waits for its answer. |
| 176 | func (s *session) call(ctx context.Context, method string, params any, out any) error { |
| 177 | s.mu.Lock() |
| 178 | s.next++ |
| 179 | id := "equipo-" + strconv.Itoa(s.next) |
| 180 | ch := make(chan Message, 1) |
| 181 | s.pending[id] = ch |
| 182 | s.mu.Unlock() |
| 183 | forget := func() { |
| 184 | s.mu.Lock() |
| 185 | delete(s.pending, id) |
| 186 | s.mu.Unlock() |
| 187 | } |
| 188 | if err := s.client.Send(ctx, map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}); err != nil { |
| 189 | forget() |
| 190 | return err |
| 191 | } |
| 192 | select { |
| 193 | case <-ctx.Done(): |
| 194 | forget() |
| 195 | return ctx.Err() |
| 196 | case m, ok := <-ch: |
| 197 | if !ok { |
| 198 | return ErrClosed |
| 199 | } |
| 200 | if m.Error != nil { |
| 201 | return errRefused |
| 202 | } |
| 203 | if out != nil && json.Unmarshal(m.Result, out) != nil { |
| 204 | return provider.ErrIdentity |
| 205 | } |
| 206 | return nil |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | // read routes OpenCode's messages until its stdout ends: answers to the |
| 211 | // runner's requests to their caller, a permission request recorded and |
| 212 | // decoded as an ask, any other request refused, everything else decoded |
| 213 | // into the session's events. |
| 214 | func (s *session) read() { |
| 215 | defer func() { |
| 216 | s.mu.Lock() |
| 217 | for id, ch := range s.pending { |
| 218 | close(ch) |
| 219 | delete(s.pending, id) |
| 220 | } |
| 221 | s.mu.Unlock() |
| 222 | close(s.events) |
| 223 | }() |
| 224 | for line := range s.client.Messages { |
| 225 | var m Message |
| 226 | err := json.Unmarshal(line, &m) |
| 227 | s.client.Release(len(line)) |
| 228 | if err != nil { |
| 229 | s.mu.Lock() |
| 230 | s.decoder.unknown("not json-rpc") |
| 231 | s.mu.Unlock() |
| 232 | continue |
| 233 | } |
| 234 | s.mu.Lock() |
| 235 | if m.Response() { |
| 236 | if ch := s.pending[rawID(m.ID)]; ch != nil { |
| 237 | delete(s.pending, rawID(m.ID)) |
| 238 | s.mu.Unlock() |
| 239 | ch <- m |
| 240 | continue |
| 241 | } |
| 242 | } |
| 243 | if m.Request() && m.Method == methodPermission && len(s.asks) >= maxPendingAsks { |
| 244 | // Over the bound: answered at once, never recorded or decoded. |
| 245 | s.decoder.unknown("permission requests over the bound") |
| 246 | s.mu.Unlock() |
| 247 | s.client.TrySend(map[string]any{"jsonrpc": "2.0", "id": m.ID, "result": map[string]any{"outcome": map[string]any{"outcome": "cancelled"}}}) |
| 248 | continue |
| 249 | } |
| 250 | if m.Request() && m.Method == methodPermission { |
| 251 | if len(m.ID) > maxToolID { |
| 252 | s.decoder.unknown("permission id too long") |
| 253 | s.mu.Unlock() |
| 254 | continue |
| 255 | } |
| 256 | s.asks[rawID(m.ID)] = permissionOf(m) |
| 257 | } else if m.Request() { |
| 258 | // The client offers OpenCode no file system and no terminal: |
| 259 | // refused through the bounded writer, or not at all when it is |
| 260 | // full (security round finding 5). |
| 261 | s.decoder.unknown(m.Method) |
| 262 | s.mu.Unlock() |
| 263 | 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"}}) { |
| 264 | s.mu.Lock() |
| 265 | s.decoder.unknown("refusals dropped") |
| 266 | s.mu.Unlock() |
| 267 | } |
| 268 | continue |
| 269 | } |
| 270 | evs := s.decoder.Decode(m) |
| 271 | turn := s.turn |
| 272 | s.mu.Unlock() |
| 273 | for _, e := range evs { |
| 274 | e.SessionID, e.TurnID = s.id, turn |
| 275 | select { |
| 276 | case s.events <- e: |
| 277 | case <-s.done: |
| 278 | return |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | func permissionOf(m Message) permission { |
| 285 | var p struct { |
| 286 | Options []struct { |
| 287 | OptionID string `json:"optionId"` |
| 288 | Kind string `json:"kind"` |
| 289 | } `json:"options"` |
| 290 | } |
| 291 | _ = json.Unmarshal(m.Params, &p) |
| 292 | out := permission{id: m.ID} |
| 293 | for _, o := range p.Options { |
| 294 | switch o.Kind { |
| 295 | case "allow_once": |
| 296 | out.allow = o.OptionID |
| 297 | case "reject_once": |
| 298 | out.block = o.OptionID |
| 299 | } |
| 300 | } |
| 301 | return out |
| 302 | } |
| 303 | |
| 304 | func (l *Launcher) state(sess provider.Session) (*session, error) { |
| 305 | l.mu.Lock() |
| 306 | defer l.mu.Unlock() |
| 307 | s := l.sessions[sess.ID] |
| 308 | if s == nil { |
| 309 | return nil, provider.ErrIdentity |
| 310 | } |
| 311 | return s, nil |
| 312 | } |
| 313 | |
| 314 | // Events are the session's decoded events, closed when OpenCode's stdout |
| 315 | // ends. |
| 316 | func (l *Launcher) Events(_ context.Context, sess provider.Session) (<-chan provider.Event, error) { |
| 317 | s, err := l.state(sess) |
| 318 | if err != nil { |
| 319 | return nil, err |
| 320 | } |
| 321 | return s.events, nil |
| 322 | } |
| 323 | |
| 324 | // StartTurn sends the prompt; its answer, read later, ends the turn. |
| 325 | func (l *Launcher) StartTurn(ctx context.Context, sess provider.Session, t provider.Turn) error { |
| 326 | s, err := l.state(sess) |
| 327 | if err != nil { |
| 328 | return err |
| 329 | } |
| 330 | s.mu.Lock() |
| 331 | if s.decoder.Active() { |
| 332 | s.mu.Unlock() |
| 333 | return errors.New("opencode: a turn is running") |
| 334 | } |
| 335 | if s.decoder.ModelChanged() { |
| 336 | // The model is fixed for the session (§16.5): no prompt goes to |
| 337 | // one whose model OpenCode says changed. |
| 338 | s.mu.Unlock() |
| 339 | return provider.ErrIdentity |
| 340 | } |
| 341 | s.next++ |
| 342 | id := "equipo-" + strconv.Itoa(s.next) |
| 343 | s.turn = t.ID |
| 344 | s.decoder.Start(id) |
| 345 | s.mu.Unlock() |
| 346 | 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}}}}) |
| 347 | } |
| 348 | |
| 349 | // Respond answers a permission request: Behavior "allow" lets the call |
| 350 | // run; anything else rejects it (which ends OpenCode's turn). |
| 351 | func (l *Launcher) Respond(ctx context.Context, sess provider.Session, a provider.Answer) error { |
| 352 | s, err := l.state(sess) |
| 353 | if err != nil { |
| 354 | return err |
| 355 | } |
| 356 | s.mu.Lock() |
| 357 | p, pending := s.asks[a.RequestID] |
| 358 | delete(s.asks, a.RequestID) |
| 359 | s.mu.Unlock() |
| 360 | if !pending { |
| 361 | return provider.ErrIdentity |
| 362 | } |
| 363 | option := p.block |
| 364 | if a.Behavior == "allow" { |
| 365 | option = p.allow |
| 366 | } |
| 367 | outcome := map[string]any{"outcome": "selected", "optionId": option} |
| 368 | if option == "" { |
| 369 | outcome = map[string]any{"outcome": "cancelled"} |
| 370 | } |
| 371 | return s.client.Send(ctx, map[string]any{"jsonrpc": "2.0", "id": p.id, "result": map[string]any{"outcome": outcome}}) |
| 372 | } |
| 373 | |
| 374 | // Interrupt answers every pending permission request as cancelled, then |
| 375 | // asks OpenCode to cancel the turn. It gives up when ctx ends: the run's |
| 376 | // end is the namespace's kill, never OpenCode's answer. |
| 377 | func (l *Launcher) Interrupt(ctx context.Context, sess provider.Session) error { |
| 378 | s, err := l.state(sess) |
| 379 | if err != nil { |
| 380 | return err |
| 381 | } |
| 382 | s.mu.Lock() |
| 383 | ids := slices.Sorted(maps.Keys(s.asks)) |
| 384 | asks := s.asks |
| 385 | s.asks = map[string]permission{} |
| 386 | s.mu.Unlock() |
| 387 | for _, id := range ids { |
| 388 | 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 { |
| 389 | return err |
| 390 | } |
| 391 | } |
| 392 | return s.client.Send(ctx, map[string]any{"jsonrpc": "2.0", "method": "session/cancel", "params": map[string]any{"sessionId": s.id}}) |
| 393 | } |
| 394 | |
| 395 | // Close closes OpenCode's stdin, its request for an orderly shutdown. |
| 396 | // The namespace's end is the ProcessHost's. |
| 397 | func (l *Launcher) Close(_ context.Context, sess provider.Session) error { |
| 398 | s, err := l.state(sess) |
| 399 | if err != nil { |
| 400 | return err |
| 401 | } |
| 402 | l.mu.Lock() |
| 403 | delete(l.sessions, sess.ID) |
| 404 | l.mu.Unlock() |
| 405 | s.shutdown() |
| 406 | return s.process.Stdin().Close() |
| 407 | } |
| 408 | |
| 409 | // shutdown ends both reading layers and the writer: the session's reader |
| 410 | // stops however full its events are, and the client's however full its |
| 411 | // queue is. |
| 412 | func (s *session) shutdown() { |
| 413 | s.once.Do(func() { |
| 414 | close(s.done) |
| 415 | s.client.Shutdown() |
| 416 | }) |
| 417 | } |
| 418 | |
| 419 | // Process is the session's process (its namespace record and Wait). |
| 420 | func (l *Launcher) Process(sess provider.Session) (provider.Process, error) { |
| 421 | s, err := l.state(sess) |
| 422 | if err != nil { |
| 423 | return nil, err |
| 424 | } |
| 425 | return s.process, nil |
| 426 | } |
| 427 | |
| 428 | // SessionCost is the session's reported cost so far, to record when the |
| 429 | // session is kept. |
| 430 | func (l *Launcher) SessionCost(sess provider.Session) float64 { |
| 431 | s, err := l.state(sess) |
| 432 | if err != nil { |
| 433 | return 0 |
| 434 | } |
| 435 | s.mu.Lock() |
| 436 | defer s.mu.Unlock() |
| 437 | return s.decoder.SessionCost() |
| 438 | } |
| 439 | |
| 440 | // Unknown is how many messages of each unknown kind the session dropped. |
| 441 | func (l *Launcher) Unknown(sess provider.Session) map[string]int { |
| 442 | s, err := l.state(sess) |
| 443 | if err != nil { |
| 444 | return nil |
| 445 | } |
| 446 | s.mu.Lock() |
| 447 | defer s.mu.Unlock() |
| 448 | return maps.Clone(s.decoder.Unknown) |
| 449 | } |
| 450 | |