| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/wire/forgekey" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "io" |
| 10 | "os" |
| 11 | "slices" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/runner" |
| 17 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 18 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 19 | "amadan.net/oficina/equipo/internal/runner/egress" |
| 20 | "amadan.net/oficina/equipo/internal/runner/metered" |
| 21 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 22 | "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| 23 | "amadan.net/oficina/equipo/internal/runner/provider/pi" |
| 24 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 25 | "amadan.net/oficina/equipo/internal/wire" |
| 26 | ) |
| 27 | |
| 28 | // PiOptions is where this runner's Pi is (EQUIPO_PI_ROOT, laid out as |
| 29 | // pi.Paths says) and the pins a launch requires: this platform's |
| 30 | // committed ones in production, a test's fake's in tests. |
| 31 | type PiOptions struct { |
| 32 | Install pi.Install |
| 33 | } |
| 34 | |
| 35 | // piTextLimit bounds the reply text a Pi run keeps: a step's summary |
| 36 | // and a question's answer are far shorter. A run that goes past it is |
| 37 | // ended, failed, with its usage incomplete. |
| 38 | var piTextLimit = 1 << 20 |
| 39 | |
| 40 | // reasonHeld is a step's run held by the metered guard: the slot is |
| 41 | // taken, the budget reached or the spend unknown (connectors spec §2.3). |
| 42 | // The step waits, deferred, and is looked at again when the |
| 43 | // connection's standing changes. |
| 44 | const reasonHeld = "metered_held" |
| 45 | |
| 46 | // meteredRole is the guard's role for a step's action. |
| 47 | func meteredRole(action string) string { |
| 48 | switch action { |
| 49 | case "implement": |
| 50 | return metered.RoleEngineering |
| 51 | case "answer": |
| 52 | return metered.RoleAsk |
| 53 | } |
| 54 | return metered.RoleReview |
| 55 | } |
| 56 | |
| 57 | // runPi runs a step's specialist on a metered connection through Pi |
| 58 | // (connectors spec §4.1, slice S2), through the metered guard: admitted |
| 59 | // with the slot claimed, the attempt's usage priced and charged once, |
| 60 | // the slot released only after the namespace's exit is proven. |
| 61 | func (e *Engineer) runPi(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun) stepResult { |
| 62 | b := spec.binding |
| 63 | if e.Conns == nil || e.Conns.Meter == nil || !e.meteredInstalled(b) { |
| 64 | // No guard, or no harness here for this connection: nothing is |
| 65 | // admitted, so no slot is claimed and nothing is charged. |
| 66 | return stepResult{reason: "account_unavailable", terminated: true} |
| 67 | } |
| 68 | // The attempt runs on the model the choice bound (§16.5): the guard |
| 69 | // admits it only while that model is allowed and proven healthy. |
| 70 | h := metered.Holder{Turn: spec.meterTurn, Step: r.StepID, Attempt: r.Attempt, Role: meteredRole(spec.action), Model: b.Model} |
| 71 | var res stepResult |
| 72 | var priced []wire.Usage |
| 73 | var admit func(*sql.Tx) error |
| 74 | if spec.admit != nil { |
| 75 | // The scheduler's admission commits with the slot's claim. |
| 76 | admit = func(t *sql.Tx) error { return spec.admit(ctx, t) } |
| 77 | } |
| 78 | if e.beforeAdmit != nil { |
| 79 | e.beforeAdmit(b.LocalID) |
| 80 | } |
| 81 | adm, _, err := e.Conns.Meter.RunAdmitted(ctx, b.LocalID, h, admit, func(ctx context.Context, l metered.Launch) metered.Result { |
| 82 | var ending metered.Ending |
| 83 | res, ending = e.piAttempt(ctx, r, tree, spec, l) |
| 84 | return metered.Result{Usage: usageRows(res.tokens, b, r.Attempt, outcomeOf(res, ctx)), Ending: ending} |
| 85 | }, func(_ *sql.Tx, rows []wire.Usage) error { |
| 86 | priced = rows |
| 87 | return nil |
| 88 | }) |
| 89 | if errors.Is(err, errFactsMoved) { |
| 90 | // The facts moved before the admission committed: looked at again |
| 91 | // at once. |
| 92 | wake := time.Now().Add(heldRetry) |
| 93 | return stepResult{reason: reasonHeld, terminated: true, hold: &wire.StepHold{Reason: wire.HoldBusy, Connection: b.ID, Provider: b.Provider, WakeAt: &wake}} |
| 94 | } |
| 95 | if err != nil { |
| 96 | e.log("step metered", err) |
| 97 | if !adm.Admitted { |
| 98 | return stepResult{reason: "account_unavailable", terminated: true} |
| 99 | } |
| 100 | } |
| 101 | if !adm.Admitted && adm.Hold == metered.HoldModel { |
| 102 | // Its model left the set or stopped answering between the choice |
| 103 | // and the guard: decided again at once. |
| 104 | wake := time.Now().Add(heldRetry) |
| 105 | return stepResult{reason: reasonHeld, terminated: true, hold: &wire.StepHold{Reason: wire.HoldBusy, Connection: b.ID, Provider: b.Provider, WakeAt: &wake}} |
| 106 | } |
| 107 | if !adm.Admitted { |
| 108 | // The guard held it (its slot, budget or spend): held there, until |
| 109 | // the next budget period or a change of its standing. |
| 110 | h := &wire.StepHold{Reason: adm.Hold, Connection: b.ID, Provider: b.Provider} |
| 111 | if !adm.WakeAt.IsZero() { |
| 112 | at := adm.WakeAt |
| 113 | h.WakeAt = &at |
| 114 | } |
| 115 | return stepResult{reason: reasonHeld, terminated: true, hold: h} |
| 116 | } |
| 117 | if priced != nil { |
| 118 | res.tokens = priced |
| 119 | } |
| 120 | if res.auth { |
| 121 | e.Conns.KeyRefused(context.WithoutCancel(ctx), b.LocalID) |
| 122 | } |
| 123 | if res.modelGone { |
| 124 | // The provider does not have the model now (§16.4): unhealthy, so |
| 125 | // the next choice runs without it. |
| 126 | e.Conns.ModelGone(context.WithoutCancel(ctx), b.LocalID, b.Model) |
| 127 | } |
| 128 | return res |
| 129 | } |
| 130 | |
| 131 | // ModelGone records that a step found its model gone at the provider: |
| 132 | // the model becomes unhealthy (not_found) until Check again or a probe |
| 133 | // a day later says otherwise. |
| 134 | func (c *Conns) ModelGone(ctx context.Context, local, model string) { |
| 135 | if c.Meter == nil || model == "" { |
| 136 | return |
| 137 | } |
| 138 | err := c.State.tx(ctx, func(t *sql.Tx) error { |
| 139 | return metered.MarkModel(ctx, t, local, model, wire.ModelUnhealthy, wire.ModelNotFound, time.Now()) |
| 140 | }) |
| 141 | if err != nil { |
| 142 | c.warn("metered model", err) |
| 143 | } |
| 144 | c.changed() |
| 145 | } |
| 146 | |
| 147 | // outcomeOf is a run's usage outcome. |
| 148 | func outcomeOf(res stepResult, ctx context.Context) string { |
| 149 | switch { |
| 150 | case res.reason == "": |
| 151 | return wire.OutcomeReplied |
| 152 | case res.reason == "cancelled" || ctx.Err() != nil: |
| 153 | return wire.OutcomeCancelled |
| 154 | } |
| 155 | return wire.OutcomeFailed |
| 156 | } |
| 157 | |
| 158 | // piHost starts a Pi launch through the containment, recording its |
| 159 | // namespace for the step (or question) and in the metered slot before |
| 160 | // it starts, and keeps the process so its exit can be proven. |
| 161 | type piHost struct { |
| 162 | m *containment.Manager |
| 163 | record func(context.Context, string) error |
| 164 | mu sync.Mutex |
| 165 | proc provider.Process |
| 166 | } |
| 167 | |
| 168 | func (h *piHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { |
| 169 | p, err := recordedStart(ctx, h.m, l, argv, h.record) |
| 170 | if err == nil { |
| 171 | h.mu.Lock() |
| 172 | h.proc = p |
| 173 | h.mu.Unlock() |
| 174 | } |
| 175 | return p, err |
| 176 | } |
| 177 | |
| 178 | func (h *piHost) started() provider.Process { |
| 179 | h.mu.Lock() |
| 180 | defer h.mu.Unlock() |
| 181 | return h.proc |
| 182 | } |
| 183 | |
| 184 | // piAttempt is one admitted Pi run: Pi prepared and certified, started |
| 185 | // in the action's containment, one prompt read to its end, the |
| 186 | // namespace stopped and its exit proven. |
| 187 | func (e *Engineer) piAttempt(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun, l metered.Launch) (stepResult, metered.Ending) { |
| 188 | o, b := e.O, spec.binding |
| 189 | notStarted := metered.Ending{Proven: true, NotStarted: true} |
| 190 | scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-") |
| 191 | if err != nil { |
| 192 | return stepResult{reason: "provider_failed", terminated: true}, notStarted |
| 193 | } |
| 194 | defer os.RemoveAll(scratch) |
| 195 | // A step can read the key (spec §2.1) and so echo it: everything the |
| 196 | // harness says is redacted of it before it is logged, reported or |
| 197 | // handed to Equipo's tools. |
| 198 | key, err := provider.ReadToken(b.CredentialHome) |
| 199 | if err != nil { |
| 200 | return stepResult{reason: "account_unavailable", terminated: true}, notStarted |
| 201 | } |
| 202 | red := pi.NewRedactor(string(key)) |
| 203 | clear(key) |
| 204 | call := spec.call |
| 205 | if call != nil { |
| 206 | call = func(ctx context.Context, name, id string, args json.RawMessage) (string, bool) { |
| 207 | return spec.call(ctx, name, id, red.RedactJSON(args)) |
| 208 | } |
| 209 | } |
| 210 | tool, err := openToolSet(context.Background(), o.Runner.StateDir, toolSet{list: spec.tools, names: spec.names}, call) |
| 211 | if err != nil { |
| 212 | return stepResult{reason: "provider_failed", terminated: true}, notStarted |
| 213 | } |
| 214 | defer tool.Close() |
| 215 | network, err := egress.ProviderPolicy(provider.NetworkContract{Provider: b.Provider, Harness: harnessOf(b)}, false) |
| 216 | if err != nil { |
| 217 | return stepResult{reason: "policy_rejected", terminated: true}, notStarted |
| 218 | } |
| 219 | prep, reason := e.prepareMetered(tree, spec, scratch, network.Hosts) |
| 220 | if reason != "" { |
| 221 | return stepResult{reason: reason, terminated: true}, notStarted |
| 222 | } |
| 223 | defer prep.cleanup() |
| 224 | policy := prep.policy |
| 225 | limit := e.MaxStep |
| 226 | if spec.limit > 0 { |
| 227 | limit = spec.limit |
| 228 | } |
| 229 | record := spec.record |
| 230 | if record == nil { |
| 231 | record = func(ctx context.Context, id string) error { return e.O.State.setStepNamespace(ctx, r, id) } |
| 232 | } |
| 233 | host := &piHost{m: o.Manager, record: func(ctx context.Context, id string) error { |
| 234 | if err := record(ctx, id); err != nil { |
| 235 | return err |
| 236 | } |
| 237 | return l.Namespace(id) |
| 238 | }} |
| 239 | launcher := prep.launcher(host) |
| 240 | launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "step/" + stepKey(r) + "/" + uuid(), Workspace: tree.Dir, ResumeSessionID: prep.resume, Selection: provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID}, Binding: prep.binding, Policy: policy} |
| 241 | // pctx is the attempt's lifetime: cancelling it kills the namespace. |
| 242 | pctx, kill := context.WithCancel(context.Background()) |
| 243 | defer kill() |
| 244 | // The step's cancellation and its deadline reach the harness's start |
| 245 | // too (security round finding 6); the run gets what is left of it. |
| 246 | deadline := time.Now().Add(limit) |
| 247 | sctx, stopStart := context.WithDeadline(ctx, deadline) |
| 248 | sess, err := launcher.OpenWithin(pctx, sctx, launch) |
| 249 | startExpired := sctx.Err() != nil |
| 250 | stopStart() |
| 251 | proc := host.started() |
| 252 | if proc == nil { |
| 253 | e.log("step start", err) |
| 254 | return stepResult{reason: "policy_rejected", terminated: true}, notStarted |
| 255 | } |
| 256 | exited := make(chan error, 1) |
| 257 | go func() { |
| 258 | _, err := proc.Wait(context.Background()) |
| 259 | exited <- err |
| 260 | }() |
| 261 | go func() { _, _ = io.Copy(io.Discard, io.LimitReader(proc.Stderr(), 1<<20)) }() |
| 262 | var res stepResult |
| 263 | session := prep.session |
| 264 | cost := 0.0 |
| 265 | if err != nil { |
| 266 | e.log("step "+prep.harness, err) |
| 267 | res = stepResult{reason: "policy_rejected"} |
| 268 | switch { |
| 269 | case ctx.Err() != nil || startExpired: |
| 270 | // Given up while starting: cancelled, or out of time. |
| 271 | res = piCancelled(ctx) |
| 272 | case errors.Is(err, provider.ErrIdentity): |
| 273 | res.reason = "provider_failed" |
| 274 | } |
| 275 | } else { |
| 276 | if session == "" { |
| 277 | // OpenCode names its own sessions: the one it opened. |
| 278 | session = sess.ID |
| 279 | } |
| 280 | var logFile io.WriteCloser = nopWriteCloser{} |
| 281 | if !spec.noLog { |
| 282 | logFile = e.openLog(r) |
| 283 | } |
| 284 | res = e.piRun(ctx, launcher, sess, max(time.Until(deadline), time.Second), spec, logFile, red, prep.family) |
| 285 | logFile.Close() |
| 286 | if c, ok := launcher.(interface { |
| 287 | SessionCost(provider.Session) float64 |
| 288 | }); ok { |
| 289 | // Read before Close forgets the session: the baseline the kept |
| 290 | // session's next launch starts from. |
| 291 | cost = c.SessionCost(sess) |
| 292 | } |
| 293 | // Events Equipo does not know were dropped: their type names and |
| 294 | // how many, nothing else of them. |
| 295 | if unknown := launcher.Unknown(sess); len(unknown) > 0 && e.O.Logger != nil { |
| 296 | named := map[string]int{} |
| 297 | for name, n := range unknown { |
| 298 | named[red.Redact(name)] += n |
| 299 | } |
| 300 | e.O.Logger.Info(prep.harness+" unknown events", "types", named) |
| 301 | } |
| 302 | } |
| 303 | res.session = session |
| 304 | res.terminated = stopStep(func() { |
| 305 | if err == nil { |
| 306 | launcher.Close(context.Background(), sess) |
| 307 | } else { |
| 308 | proc.Stdin().Close() |
| 309 | } |
| 310 | }, exited, kill, ctx.Err() == nil && res.reason == "", 10*time.Second, 30*time.Second) |
| 311 | if !res.terminated { |
| 312 | // The namespace record stays: a restarted runner verifies it, and |
| 313 | // the metered slot stays held until it is proven (Recover). |
| 314 | e.log("step stop", errors.New("exit not verified")) |
| 315 | return res, metered.Ending{} |
| 316 | } |
| 317 | e.forget(proc.ID()) |
| 318 | if spec.keep != "" && err == nil { |
| 319 | n, err := prep.keep(prep.home, session, spec.keep, cost) |
| 320 | e.log("kept sessions", err) |
| 321 | res.kept = n |
| 322 | } |
| 323 | return res, metered.Ending{Proven: true} |
| 324 | } |
| 325 | |
| 326 | // piRun sends the prompt and reads Pi's events to the run's end. Every |
| 327 | // question Equipo's extension asks is refused: in a step nobody can |
| 328 | // answer, and the namespace is the containment (connectors spec §3). |
| 329 | func (e *Engineer) piRun(ctx context.Context, l meteredLauncher, sess provider.Session, limit time.Duration, spec specialistRun, logFile io.Writer, red *pi.Redactor, family func(string) string) stepResult { |
| 330 | tail := &stepTail{} |
| 331 | tally := &pi.Tally{} |
| 332 | tctx, cancel := context.WithTimeout(ctx, limit) |
| 333 | defer cancel() |
| 334 | refused := int64(0) |
| 335 | finish := func(res stepResult) stepResult { |
| 336 | res.tail, res.refused = tail.String(), refused |
| 337 | // One row per model the provider reported (§16.5): a later |
| 338 | // request on another model is its own row, mismatch and price. |
| 339 | res.tokens = tally.Rows() |
| 340 | res.family = family(tally.Model()) |
| 341 | return res |
| 342 | } |
| 343 | events, err := l.Events(tctx, sess) |
| 344 | if err == nil { |
| 345 | err = l.StartTurn(tctx, sess, provider.Turn{ID: uuid(), Prompt: spec.prompt}) |
| 346 | } |
| 347 | if spec.stream != nil { |
| 348 | spec.stream.stdin = time.Now() |
| 349 | } |
| 350 | if err != nil { |
| 351 | if tctx.Err() != nil { |
| 352 | return finish(piCancelled(ctx)) |
| 353 | } |
| 354 | return finish(stepResult{reason: "provider_failed"}) |
| 355 | } |
| 356 | written := 0 |
| 357 | text := &strings.Builder{} |
| 358 | lastActivity := "" |
| 359 | for { |
| 360 | select { |
| 361 | case <-tctx.Done(): |
| 362 | // Ask Pi to stop, aside: the namespace is killed next |
| 363 | // (stopStep) whether or not Pi ever reads the request. |
| 364 | go func() { |
| 365 | ictx, stop := context.WithTimeout(context.Background(), 2*time.Second) |
| 366 | defer stop() |
| 367 | _ = l.Interrupt(ictx, sess) |
| 368 | }() |
| 369 | return finish(piCancelled(ctx)) |
| 370 | case ev, ok := <-events: |
| 371 | if !ok { |
| 372 | return finish(stepResult{reason: "provider_failed", summary: text.String()}) |
| 373 | } |
| 374 | payload := ev.Payload |
| 375 | var d pi.Delta |
| 376 | if ev.Kind == pi.KindDelta { |
| 377 | // A key can fall across deltas: the stream holds back an |
| 378 | // end that could still become it. |
| 379 | _ = json.Unmarshal(ev.Payload, &d) |
| 380 | d.Text = red.Stream(d.Text) |
| 381 | payload, _ = json.Marshal(d) |
| 382 | } |
| 383 | if line, err := json.Marshal(map[string]any{"kind": ev.Kind, "payload": payload}); err == nil && written+len(line) < stepLogLimit { |
| 384 | n, _ := logFile.Write(append([]byte(red.Redact(string(line))), '\n')) |
| 385 | written += n |
| 386 | } |
| 387 | tally.Add(ev) |
| 388 | if ev.Kind == pi.KindDone { |
| 389 | d.Text = red.Flush() |
| 390 | } |
| 391 | if d.Text != "" && text.Len() <= piTextLimit { |
| 392 | text.WriteString(d.Text) |
| 393 | if s := spec.stream; s != nil && s.delta != nil { |
| 394 | s.delta(s.offset, d.Text) |
| 395 | s.offset += int64(len(d.Text)) |
| 396 | } |
| 397 | } |
| 398 | switch ev.Kind { |
| 399 | case pi.KindDelta: |
| 400 | if text.Len() > piTextLimit { |
| 401 | tail.add("The reply was too long") |
| 402 | go func() { |
| 403 | ictx, stop := context.WithTimeout(context.Background(), 2*time.Second) |
| 404 | defer stop() |
| 405 | _ = l.Interrupt(ictx, sess) |
| 406 | }() |
| 407 | return finish(stepResult{reason: "provider_failed"}) |
| 408 | } |
| 409 | if s := spec.stream; s != nil { |
| 410 | s.mark(&s.timing.FirstEventMs) |
| 411 | s.mark(&s.timing.FirstTextMs) |
| 412 | s.timing.LastTextMs = max(time.Since(s.stdin).Milliseconds(), 1) |
| 413 | } |
| 414 | case pi.KindToolCall: |
| 415 | // The final answer is what follows the last tool. |
| 416 | text.Reset() |
| 417 | var c pi.ToolCall |
| 418 | _ = json.Unmarshal(ev.Payload, &c) |
| 419 | c.Args = red.RedactJSON(c.Args) |
| 420 | kind, subject, line := piActivity(c) |
| 421 | if line != "" { |
| 422 | tail.add(line) |
| 423 | } |
| 424 | if kind != "" && spec.activity != nil && kind+"\x00"+subject != lastActivity { |
| 425 | lastActivity = kind + "\x00" + subject |
| 426 | spec.activity(kind, subject) |
| 427 | } |
| 428 | if s := spec.stream; s != nil && s.activity != nil { |
| 429 | s.mark(&s.timing.FirstToolMs) |
| 430 | s.activity(wire.ActivityTool, piAnswerTool(c.Tool)) |
| 431 | } |
| 432 | case pi.KindAsk: |
| 433 | tail.add("Refused a call Equipo does not allow") |
| 434 | refused++ |
| 435 | _ = l.Respond(tctx, sess, provider.Answer{RequestID: ev.RequestID, Behavior: "deny"}) |
| 436 | case pi.KindDone: |
| 437 | var d pi.Done |
| 438 | _ = json.Unmarshal(ev.Payload, &d) |
| 439 | final := strings.TrimSpace(text.String()) |
| 440 | if final != "" { |
| 441 | tail.add(final) |
| 442 | } |
| 443 | switch d.Status { |
| 444 | case pi.StatusCompleted: |
| 445 | return finish(stepResult{summary: final}) |
| 446 | case pi.StatusInterrupted: |
| 447 | return finish(piCancelled(ctx)) |
| 448 | } |
| 449 | if d.Error != "" { |
| 450 | tail.add(red.Redact(d.Error)) |
| 451 | } |
| 452 | switch d.Failure { |
| 453 | case pi.FailAuth: |
| 454 | return finish(stepResult{reason: "sign_in_again", auth: true}) |
| 455 | case pi.FailModel: |
| 456 | return finish(stepResult{reason: "provider_failed", summary: final, modelGone: true}) |
| 457 | case pi.FailQuota: |
| 458 | return finish(stepResult{reason: "limited", limit: &connect.Limit{Limited: true}}) |
| 459 | } |
| 460 | return finish(stepResult{reason: "provider_failed", summary: final}) |
| 461 | } |
| 462 | } |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | func piCancelled(ctx context.Context) stepResult { |
| 467 | if ctx.Err() != nil { |
| 468 | return stepResult{reason: "cancelled"} |
| 469 | } |
| 470 | return stepResult{reason: "step_timeout"} |
| 471 | } |
| 472 | |
| 473 | // piActivity is what a Pi tool call shows: the activity kind and its |
| 474 | // subject (clipped), and the line it adds to the step's tail. |
| 475 | func piActivity(c pi.ToolCall) (kind, subject, line string) { |
| 476 | var args struct{ Command, Path string } |
| 477 | _ = json.Unmarshal(c.Args, &args) |
| 478 | switch c.Tool { |
| 479 | case "bash", "shell": |
| 480 | kind, subject = wire.ActivityRun, args.Command |
| 481 | case "edit", "write": |
| 482 | kind, subject = wire.ActivityEdit, args.Path |
| 483 | default: |
| 484 | if t := equipoTool(c.Tool); t != "" { |
| 485 | return wire.ActivityOther, "", t |
| 486 | } |
| 487 | return "", "", "" |
| 488 | } |
| 489 | subject = strings.TrimPrefix(strings.TrimSpace(strings.SplitN(strings.TrimSpace(subject), "\n", 2)[0]), "/workspace/") |
| 490 | line = map[string]string{wire.ActivityRun: "Bash ", wire.ActivityEdit: "Edit "}[kind] + subject |
| 491 | return kind, clip(subject, wire.MaxActivitySubject), line |
| 492 | } |
| 493 | |
| 494 | // piAnswerTool is what an answering session shows for a tool. |
| 495 | func piAnswerTool(tool string) string { |
| 496 | switch tool { |
| 497 | case "read": |
| 498 | return wire.ToolReadFile |
| 499 | case "grep", "find", "ls", "glob": |
| 500 | return wire.ToolSearchCode |
| 501 | } |
| 502 | switch equipoTool(tool) { |
| 503 | case "git_log", "git_diff", "git_show": |
| 504 | return "read_change" |
| 505 | } |
| 506 | return "other" |
| 507 | } |
| 508 | |
| 509 | // KeyRefused records that the provider refused a metered connection's |
| 510 | // key in a run: the connection is refused (hello says sign in again) |
| 511 | // until a Check again proves the key. |
| 512 | func (c *Conns) KeyRefused(ctx context.Context, local string) { |
| 513 | if c.Meter == nil { |
| 514 | return |
| 515 | } |
| 516 | tx, err := c.State.db.BeginTx(ctx, nil) |
| 517 | if err == nil { |
| 518 | err = metered.Checked(ctx, tx, local, false) |
| 519 | if err == nil { |
| 520 | err = tx.Commit() |
| 521 | } else { |
| 522 | tx.Rollback() |
| 523 | } |
| 524 | } |
| 525 | if err != nil { |
| 526 | c.warn("metered key refused", err) |
| 527 | } |
| 528 | c.SignInAgain(local) |
| 529 | c.changed() |
| 530 | } |
| 531 | |
| 532 | // askBinding is the metered binding a kept session ran on. |
| 533 | func (e *Engineer) askBinding(ctx context.Context, person, account string) (runner.AccountBinding, bool) { |
| 534 | if e.Conns == nil { |
| 535 | return runner.AccountBinding{}, false |
| 536 | } |
| 537 | for _, b := range e.Conns.MeteredMine(ctx, person) { |
| 538 | if b.LocalID == account { |
| 539 | return b, true |
| 540 | } |
| 541 | } |
| 542 | return runner.AccountBinding{}, false |
| 543 | } |
| 544 | |
| 545 | // askPi answers a question from a step's kept Pi session, on the |
| 546 | // session's own metered connection, after the guard admitted it |
| 547 | // (askMetered, connectors spec §7): the exact commit read-only, the |
| 548 | // session resumed, the answer's usage charged. |
| 549 | func (e *Engineer) askPi(ctx context.Context, a askRow, l metered.Launch, progress func(wire.AnswerReport)) (wire.AnswerReport, metered.Ending) { |
| 550 | notStarted := metered.Ending{Proven: true, NotStarted: true} |
| 551 | rep := wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt} |
| 552 | fail := func(reason string) (wire.AnswerReport, metered.Ending) { |
| 553 | rep.State, rep.Reason = wire.QuestionFailed, reason |
| 554 | if ctx.Err() != nil { |
| 555 | rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" |
| 556 | } |
| 557 | return rep, notStarted |
| 558 | } |
| 559 | if !slices.Contains(e.Owners, a.Person) || !forgekey.ValidHub(a.Repo) || !wire.ValidTaskBranch(a.Branch) || !shaPattern.MatchString(a.CandidateSHA) || a.BaseSHA != "" && !shaPattern.MatchString(a.BaseSHA) { |
| 560 | return fail("policy_rejected") |
| 561 | } |
| 562 | kept, found, mismatch, err := e.O.State.keptForAsk(ctx, a.AskCommand) |
| 563 | if err != nil { |
| 564 | return fail("provider_failed") |
| 565 | } |
| 566 | if !found || kept.TaskID != a.TaskID || kept.Person != a.Person || kept.Specialist != a.Specialist || !hasKeptSession(kept.Dir, kept.SessionID) { |
| 567 | return fail("session_gone") |
| 568 | } |
| 569 | if mismatch || kept.Candidate != a.CandidateSHA { |
| 570 | return fail("policy_rejected") |
| 571 | } |
| 572 | b, ok := e.askBinding(ctx, a.Person, kept.Account) |
| 573 | if !ok || b.LocalID != l.Conn.LocalID { |
| 574 | return fail("account_unavailable") |
| 575 | } |
| 576 | // The session's own model, the one the guard admitted (§16.3). |
| 577 | if kept.Model == "" || l.Holder.Model != kept.Model { |
| 578 | return fail(wire.ReasonModelUnavailable) |
| 579 | } |
| 580 | b = withModel(b, kept.Model, kept.Family) |
| 581 | r := stepRow{DispatchCommand: wire.DispatchCommand{Person: a.Person, TaskID: a.TaskID, StepID: a.QuestionID, Attempt: a.Attempt, Repo: a.Repo, Branch: a.Branch, BaseSHA: a.BaseSHA, CandidateSHA: a.CandidateSHA}, Question: true} |
| 582 | tree, reason, err := e.judgeTree(ctx, r) |
| 583 | if err != nil { |
| 584 | return fail(reason) |
| 585 | } |
| 586 | defer os.RemoveAll(tree.GitDir) |
| 587 | defer os.RemoveAll(tree.Dir) |
| 588 | rep.State = wire.QuestionRunning |
| 589 | progress(rep) |
| 590 | stream := &answerStream{} |
| 591 | if e.Delta != nil { |
| 592 | stream.delta = func(offset int64, text string) { |
| 593 | e.Delta(wire.DeltaReport{TurnID: a.QuestionID, Attempt: a.Attempt, Offset: offset, Text: text}) |
| 594 | } |
| 595 | } |
| 596 | if e.Activity != nil { |
| 597 | stream.activity = func(kind, tool string) { |
| 598 | e.Activity(wire.ActivityReport{TurnID: a.QuestionID, Attempt: a.Attempt, Kind: kind, Tool: tool}) |
| 599 | } |
| 600 | } |
| 601 | var mu sync.Mutex |
| 602 | call := func(cctx context.Context, name, _ string, args json.RawMessage) (string, bool) { |
| 603 | mu.Lock() |
| 604 | defer mu.Unlock() |
| 605 | return answerGit(cctx, tree.Git, tree.GitDir, a.BaseSHA, a.CandidateSHA, name, args) |
| 606 | } |
| 607 | limit := e.MaxAnswer |
| 608 | if limit <= 0 { |
| 609 | limit = maxAnswer |
| 610 | } |
| 611 | res, ending := e.piAttempt(ctx, r, tree, specialistRun{action: "answer", binding: b, tools: answerTools, names: []string{"git_log", "git_diff", "git_show"}, call: call, prompt: e.askPrompt(a, claude.LinuxWorkspaceRoot), resume: kept.SessionID, keep: kept.Dir, stream: stream, limit: limit, noLog: true, |
| 612 | record: func(ctx context.Context, id string) error { return e.O.State.setAskNamespace(ctx, a, id) }}, l) |
| 613 | if res.kept > 0 { |
| 614 | e.log("kept sessions", e.O.State.touchKept(context.WithoutCancel(ctx), kept, res.kept)) |
| 615 | } |
| 616 | switch { |
| 617 | case ctx.Err() != nil: |
| 618 | rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" |
| 619 | case res.reason == "step_timeout": |
| 620 | rep.State, rep.Reason = wire.QuestionFailed, "turn_timeout" |
| 621 | case res.reason != "": |
| 622 | if !wire.AnswerReasons[res.reason] { |
| 623 | res.reason = "provider_failed" |
| 624 | } |
| 625 | rep.State, rep.Reason = wire.QuestionFailed, res.reason |
| 626 | case strings.TrimSpace(res.summary) == "": |
| 627 | rep.State, rep.Reason = wire.QuestionFailed, "provider_failed" |
| 628 | default: |
| 629 | rep.State, rep.Text = wire.QuestionAnswered, clip(strings.TrimSpace(res.summary), wire.MaxAnswerText) |
| 630 | t := stream.timing |
| 631 | t.Cold = true |
| 632 | rep.Timing = &t |
| 633 | } |
| 634 | outcome := wire.OutcomeFailed |
| 635 | switch rep.State { |
| 636 | case wire.QuestionAnswered: |
| 637 | outcome = wire.OutcomeReplied |
| 638 | case wire.QuestionCancelled: |
| 639 | outcome = wire.OutcomeCancelled |
| 640 | } |
| 641 | rep.Usage = usageRows(res.tokens, b, a.Attempt, outcome) |
| 642 | if res.auth { |
| 643 | e.Conns.KeyRefused(context.WithoutCancel(ctx), b.LocalID) |
| 644 | } |
| 645 | return rep, ending |
| 646 | } |
| 647 | |