package thin import ( "amadan.net/oficina/equipo/internal/wire/forgekey" "context" "database/sql" "encoding/json" "errors" "io" "os" "slices" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/egress" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/runner/provider/pi" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire" ) // PiOptions is where this runner's Pi is (EQUIPO_PI_ROOT, laid out as // pi.Paths says) and the pins a launch requires: this platform's // committed ones in production, a test's fake's in tests. type PiOptions struct { Install pi.Install } // piTextLimit bounds the reply text a Pi run keeps: a step's summary // and a question's answer are far shorter. A run that goes past it is // ended, failed, with its usage incomplete. var piTextLimit = 1 << 20 // reasonHeld is a step's run held by the metered guard: the slot is // taken, the budget reached or the spend unknown (connectors spec §2.3). // The step waits, deferred, and is looked at again when the // connection's standing changes. const reasonHeld = "metered_held" // meteredRole is the guard's role for a step's action. func meteredRole(action string) string { switch action { case "implement": return metered.RoleEngineering case "answer": return metered.RoleAsk } return metered.RoleReview } // runPi runs a step's specialist on a metered connection through Pi // (connectors spec §4.1, slice S2), through the metered guard: admitted // with the slot claimed, the attempt's usage priced and charged once, // the slot released only after the namespace's exit is proven. func (e *Engineer) runPi(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun) stepResult { b := spec.binding if e.Conns == nil || e.Conns.Meter == nil || !e.meteredInstalled(b) { // No guard, or no harness here for this connection: nothing is // admitted, so no slot is claimed and nothing is charged. return stepResult{reason: "account_unavailable", terminated: true} } // The attempt runs on the model the choice bound (§16.5): the guard // admits it only while that model is allowed and proven healthy. h := metered.Holder{Turn: spec.meterTurn, Step: r.StepID, Attempt: r.Attempt, Role: meteredRole(spec.action), Model: b.Model} var res stepResult var priced []wire.Usage var admit func(*sql.Tx) error if spec.admit != nil { // The scheduler's admission commits with the slot's claim. admit = func(t *sql.Tx) error { return spec.admit(ctx, t) } } if e.beforeAdmit != nil { e.beforeAdmit(b.LocalID) } adm, _, err := e.Conns.Meter.RunAdmitted(ctx, b.LocalID, h, admit, func(ctx context.Context, l metered.Launch) metered.Result { var ending metered.Ending res, ending = e.piAttempt(ctx, r, tree, spec, l) return metered.Result{Usage: usageRows(res.tokens, b, r.Attempt, outcomeOf(res, ctx)), Ending: ending} }, func(_ *sql.Tx, rows []wire.Usage) error { priced = rows return nil }) if errors.Is(err, errFactsMoved) { // The facts moved before the admission committed: looked at again // at once. wake := time.Now().Add(heldRetry) return stepResult{reason: reasonHeld, terminated: true, hold: &wire.StepHold{Reason: wire.HoldBusy, Connection: b.ID, Provider: b.Provider, WakeAt: &wake}} } if err != nil { e.log("step metered", err) if !adm.Admitted { return stepResult{reason: "account_unavailable", terminated: true} } } if !adm.Admitted && adm.Hold == metered.HoldModel { // Its model left the set or stopped answering between the choice // and the guard: decided again at once. wake := time.Now().Add(heldRetry) return stepResult{reason: reasonHeld, terminated: true, hold: &wire.StepHold{Reason: wire.HoldBusy, Connection: b.ID, Provider: b.Provider, WakeAt: &wake}} } if !adm.Admitted { // The guard held it (its slot, budget or spend): held there, until // the next budget period or a change of its standing. h := &wire.StepHold{Reason: adm.Hold, Connection: b.ID, Provider: b.Provider} if !adm.WakeAt.IsZero() { at := adm.WakeAt h.WakeAt = &at } return stepResult{reason: reasonHeld, terminated: true, hold: h} } if priced != nil { res.tokens = priced } if res.auth { e.Conns.KeyRefused(context.WithoutCancel(ctx), b.LocalID) } if res.modelGone { // The provider does not have the model now (§16.4): unhealthy, so // the next choice runs without it. e.Conns.ModelGone(context.WithoutCancel(ctx), b.LocalID, b.Model) } return res } // ModelGone records that a step found its model gone at the provider: // the model becomes unhealthy (not_found) until Check again or a probe // a day later says otherwise. func (c *Conns) ModelGone(ctx context.Context, local, model string) { if c.Meter == nil || model == "" { return } err := c.State.tx(ctx, func(t *sql.Tx) error { return metered.MarkModel(ctx, t, local, model, wire.ModelUnhealthy, wire.ModelNotFound, time.Now()) }) if err != nil { c.warn("metered model", err) } c.changed() } // outcomeOf is a run's usage outcome. func outcomeOf(res stepResult, ctx context.Context) string { switch { case res.reason == "": return wire.OutcomeReplied case res.reason == "cancelled" || ctx.Err() != nil: return wire.OutcomeCancelled } return wire.OutcomeFailed } // piHost starts a Pi launch through the containment, recording its // namespace for the step (or question) and in the metered slot before // it starts, and keeps the process so its exit can be proven. type piHost struct { m *containment.Manager record func(context.Context, string) error mu sync.Mutex proc provider.Process } func (h *piHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { p, err := recordedStart(ctx, h.m, l, argv, h.record) if err == nil { h.mu.Lock() h.proc = p h.mu.Unlock() } return p, err } func (h *piHost) started() provider.Process { h.mu.Lock() defer h.mu.Unlock() return h.proc } // piAttempt is one admitted Pi run: Pi prepared and certified, started // in the action's containment, one prompt read to its end, the // namespace stopped and its exit proven. func (e *Engineer) piAttempt(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun, l metered.Launch) (stepResult, metered.Ending) { o, b := e.O, spec.binding notStarted := metered.Ending{Proven: true, NotStarted: true} scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-") if err != nil { return stepResult{reason: "provider_failed", terminated: true}, notStarted } defer os.RemoveAll(scratch) // A step can read the key (spec §2.1) and so echo it: everything the // harness says is redacted of it before it is logged, reported or // handed to Equipo's tools. key, err := provider.ReadToken(b.CredentialHome) if err != nil { return stepResult{reason: "account_unavailable", terminated: true}, notStarted } red := pi.NewRedactor(string(key)) clear(key) call := spec.call if call != nil { call = func(ctx context.Context, name, id string, args json.RawMessage) (string, bool) { return spec.call(ctx, name, id, red.RedactJSON(args)) } } tool, err := openToolSet(context.Background(), o.Runner.StateDir, toolSet{list: spec.tools, names: spec.names}, call) if err != nil { return stepResult{reason: "provider_failed", terminated: true}, notStarted } defer tool.Close() network, err := egress.ProviderPolicy(provider.NetworkContract{Provider: b.Provider, Harness: harnessOf(b)}, false) if err != nil { return stepResult{reason: "policy_rejected", terminated: true}, notStarted } prep, reason := e.prepareMetered(tree, spec, scratch, network.Hosts) if reason != "" { return stepResult{reason: reason, terminated: true}, notStarted } defer prep.cleanup() policy := prep.policy limit := e.MaxStep if spec.limit > 0 { limit = spec.limit } record := spec.record if record == nil { record = func(ctx context.Context, id string) error { return e.O.State.setStepNamespace(ctx, r, id) } } host := &piHost{m: o.Manager, record: func(ctx context.Context, id string) error { if err := record(ctx, id); err != nil { return err } return l.Namespace(id) }} launcher := prep.launcher(host) 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} // pctx is the attempt's lifetime: cancelling it kills the namespace. pctx, kill := context.WithCancel(context.Background()) defer kill() // The step's cancellation and its deadline reach the harness's start // too (security round finding 6); the run gets what is left of it. deadline := time.Now().Add(limit) sctx, stopStart := context.WithDeadline(ctx, deadline) sess, err := launcher.OpenWithin(pctx, sctx, launch) startExpired := sctx.Err() != nil stopStart() proc := host.started() if proc == nil { e.log("step start", err) return stepResult{reason: "policy_rejected", terminated: true}, notStarted } exited := make(chan error, 1) go func() { _, err := proc.Wait(context.Background()) exited <- err }() go func() { _, _ = io.Copy(io.Discard, io.LimitReader(proc.Stderr(), 1<<20)) }() var res stepResult session := prep.session cost := 0.0 if err != nil { e.log("step "+prep.harness, err) res = stepResult{reason: "policy_rejected"} switch { case ctx.Err() != nil || startExpired: // Given up while starting: cancelled, or out of time. res = piCancelled(ctx) case errors.Is(err, provider.ErrIdentity): res.reason = "provider_failed" } } else { if session == "" { // OpenCode names its own sessions: the one it opened. session = sess.ID } var logFile io.WriteCloser = nopWriteCloser{} if !spec.noLog { logFile = e.openLog(r) } res = e.piRun(ctx, launcher, sess, max(time.Until(deadline), time.Second), spec, logFile, red, prep.family) logFile.Close() if c, ok := launcher.(interface { SessionCost(provider.Session) float64 }); ok { // Read before Close forgets the session: the baseline the kept // session's next launch starts from. cost = c.SessionCost(sess) } // Events Equipo does not know were dropped: their type names and // how many, nothing else of them. if unknown := launcher.Unknown(sess); len(unknown) > 0 && e.O.Logger != nil { named := map[string]int{} for name, n := range unknown { named[red.Redact(name)] += n } e.O.Logger.Info(prep.harness+" unknown events", "types", named) } } res.session = session res.terminated = stopStep(func() { if err == nil { launcher.Close(context.Background(), sess) } else { proc.Stdin().Close() } }, exited, kill, ctx.Err() == nil && res.reason == "", 10*time.Second, 30*time.Second) if !res.terminated { // The namespace record stays: a restarted runner verifies it, and // the metered slot stays held until it is proven (Recover). e.log("step stop", errors.New("exit not verified")) return res, metered.Ending{} } e.forget(proc.ID()) if spec.keep != "" && err == nil { n, err := prep.keep(prep.home, session, spec.keep, cost) e.log("kept sessions", err) res.kept = n } return res, metered.Ending{Proven: true} } // piRun sends the prompt and reads Pi's events to the run's end. Every // question Equipo's extension asks is refused: in a step nobody can // answer, and the namespace is the containment (connectors spec §3). 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 { tail := &stepTail{} tally := &pi.Tally{} tctx, cancel := context.WithTimeout(ctx, limit) defer cancel() refused := int64(0) finish := func(res stepResult) stepResult { res.tail, res.refused = tail.String(), refused // One row per model the provider reported (§16.5): a later // request on another model is its own row, mismatch and price. res.tokens = tally.Rows() res.family = family(tally.Model()) return res } events, err := l.Events(tctx, sess) if err == nil { err = l.StartTurn(tctx, sess, provider.Turn{ID: uuid(), Prompt: spec.prompt}) } if spec.stream != nil { spec.stream.stdin = time.Now() } if err != nil { if tctx.Err() != nil { return finish(piCancelled(ctx)) } return finish(stepResult{reason: "provider_failed"}) } written := 0 text := &strings.Builder{} lastActivity := "" for { select { case <-tctx.Done(): // Ask Pi to stop, aside: the namespace is killed next // (stopStep) whether or not Pi ever reads the request. go func() { ictx, stop := context.WithTimeout(context.Background(), 2*time.Second) defer stop() _ = l.Interrupt(ictx, sess) }() return finish(piCancelled(ctx)) case ev, ok := <-events: if !ok { return finish(stepResult{reason: "provider_failed", summary: text.String()}) } payload := ev.Payload var d pi.Delta if ev.Kind == pi.KindDelta { // A key can fall across deltas: the stream holds back an // end that could still become it. _ = json.Unmarshal(ev.Payload, &d) d.Text = red.Stream(d.Text) payload, _ = json.Marshal(d) } if line, err := json.Marshal(map[string]any{"kind": ev.Kind, "payload": payload}); err == nil && written+len(line) < stepLogLimit { n, _ := logFile.Write(append([]byte(red.Redact(string(line))), '\n')) written += n } tally.Add(ev) if ev.Kind == pi.KindDone { d.Text = red.Flush() } if d.Text != "" && text.Len() <= piTextLimit { text.WriteString(d.Text) if s := spec.stream; s != nil && s.delta != nil { s.delta(s.offset, d.Text) s.offset += int64(len(d.Text)) } } switch ev.Kind { case pi.KindDelta: if text.Len() > piTextLimit { tail.add("The reply was too long") go func() { ictx, stop := context.WithTimeout(context.Background(), 2*time.Second) defer stop() _ = l.Interrupt(ictx, sess) }() return finish(stepResult{reason: "provider_failed"}) } if s := spec.stream; s != nil { s.mark(&s.timing.FirstEventMs) s.mark(&s.timing.FirstTextMs) s.timing.LastTextMs = max(time.Since(s.stdin).Milliseconds(), 1) } case pi.KindToolCall: // The final answer is what follows the last tool. text.Reset() var c pi.ToolCall _ = json.Unmarshal(ev.Payload, &c) c.Args = red.RedactJSON(c.Args) kind, subject, line := piActivity(c) if line != "" { tail.add(line) } if kind != "" && spec.activity != nil && kind+"\x00"+subject != lastActivity { lastActivity = kind + "\x00" + subject spec.activity(kind, subject) } if s := spec.stream; s != nil && s.activity != nil { s.mark(&s.timing.FirstToolMs) s.activity(wire.ActivityTool, piAnswerTool(c.Tool)) } case pi.KindAsk: tail.add("Refused a call Equipo does not allow") refused++ _ = l.Respond(tctx, sess, provider.Answer{RequestID: ev.RequestID, Behavior: "deny"}) case pi.KindDone: var d pi.Done _ = json.Unmarshal(ev.Payload, &d) final := strings.TrimSpace(text.String()) if final != "" { tail.add(final) } switch d.Status { case pi.StatusCompleted: return finish(stepResult{summary: final}) case pi.StatusInterrupted: return finish(piCancelled(ctx)) } if d.Error != "" { tail.add(red.Redact(d.Error)) } switch d.Failure { case pi.FailAuth: return finish(stepResult{reason: "sign_in_again", auth: true}) case pi.FailModel: return finish(stepResult{reason: "provider_failed", summary: final, modelGone: true}) case pi.FailQuota: return finish(stepResult{reason: "limited", limit: &connect.Limit{Limited: true}}) } return finish(stepResult{reason: "provider_failed", summary: final}) } } } } func piCancelled(ctx context.Context) stepResult { if ctx.Err() != nil { return stepResult{reason: "cancelled"} } return stepResult{reason: "step_timeout"} } // piActivity is what a Pi tool call shows: the activity kind and its // subject (clipped), and the line it adds to the step's tail. func piActivity(c pi.ToolCall) (kind, subject, line string) { var args struct{ Command, Path string } _ = json.Unmarshal(c.Args, &args) switch c.Tool { case "bash", "shell": kind, subject = wire.ActivityRun, args.Command case "edit", "write": kind, subject = wire.ActivityEdit, args.Path default: if t := equipoTool(c.Tool); t != "" { return wire.ActivityOther, "", t } return "", "", "" } subject = strings.TrimPrefix(strings.TrimSpace(strings.SplitN(strings.TrimSpace(subject), "\n", 2)[0]), "/workspace/") line = map[string]string{wire.ActivityRun: "Bash ", wire.ActivityEdit: "Edit "}[kind] + subject return kind, clip(subject, wire.MaxActivitySubject), line } // piAnswerTool is what an answering session shows for a tool. func piAnswerTool(tool string) string { switch tool { case "read": return wire.ToolReadFile case "grep", "find", "ls", "glob": return wire.ToolSearchCode } switch equipoTool(tool) { case "git_log", "git_diff", "git_show": return "read_change" } return "other" } // KeyRefused records that the provider refused a metered connection's // key in a run: the connection is refused (hello says sign in again) // until a Check again proves the key. func (c *Conns) KeyRefused(ctx context.Context, local string) { if c.Meter == nil { return } tx, err := c.State.db.BeginTx(ctx, nil) if err == nil { err = metered.Checked(ctx, tx, local, false) if err == nil { err = tx.Commit() } else { tx.Rollback() } } if err != nil { c.warn("metered key refused", err) } c.SignInAgain(local) c.changed() } // askBinding is the metered binding a kept session ran on. func (e *Engineer) askBinding(ctx context.Context, person, account string) (runner.AccountBinding, bool) { if e.Conns == nil { return runner.AccountBinding{}, false } for _, b := range e.Conns.MeteredMine(ctx, person) { if b.LocalID == account { return b, true } } return runner.AccountBinding{}, false } // askPi answers a question from a step's kept Pi session, on the // session's own metered connection, after the guard admitted it // (askMetered, connectors spec §7): the exact commit read-only, the // session resumed, the answer's usage charged. func (e *Engineer) askPi(ctx context.Context, a askRow, l metered.Launch, progress func(wire.AnswerReport)) (wire.AnswerReport, metered.Ending) { notStarted := metered.Ending{Proven: true, NotStarted: true} rep := wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt} fail := func(reason string) (wire.AnswerReport, metered.Ending) { rep.State, rep.Reason = wire.QuestionFailed, reason if ctx.Err() != nil { rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" } return rep, notStarted } 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) { return fail("policy_rejected") } kept, found, mismatch, err := e.O.State.keptForAsk(ctx, a.AskCommand) if err != nil { return fail("provider_failed") } if !found || kept.TaskID != a.TaskID || kept.Person != a.Person || kept.Specialist != a.Specialist || !hasKeptSession(kept.Dir, kept.SessionID) { return fail("session_gone") } if mismatch || kept.Candidate != a.CandidateSHA { return fail("policy_rejected") } b, ok := e.askBinding(ctx, a.Person, kept.Account) if !ok || b.LocalID != l.Conn.LocalID { return fail("account_unavailable") } // The session's own model, the one the guard admitted (§16.3). if kept.Model == "" || l.Holder.Model != kept.Model { return fail(wire.ReasonModelUnavailable) } b = withModel(b, kept.Model, kept.Family) 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} tree, reason, err := e.judgeTree(ctx, r) if err != nil { return fail(reason) } defer os.RemoveAll(tree.GitDir) defer os.RemoveAll(tree.Dir) rep.State = wire.QuestionRunning progress(rep) stream := &answerStream{} if e.Delta != nil { stream.delta = func(offset int64, text string) { e.Delta(wire.DeltaReport{TurnID: a.QuestionID, Attempt: a.Attempt, Offset: offset, Text: text}) } } if e.Activity != nil { stream.activity = func(kind, tool string) { e.Activity(wire.ActivityReport{TurnID: a.QuestionID, Attempt: a.Attempt, Kind: kind, Tool: tool}) } } var mu sync.Mutex call := func(cctx context.Context, name, _ string, args json.RawMessage) (string, bool) { mu.Lock() defer mu.Unlock() return answerGit(cctx, tree.Git, tree.GitDir, a.BaseSHA, a.CandidateSHA, name, args) } limit := e.MaxAnswer if limit <= 0 { limit = maxAnswer } 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, record: func(ctx context.Context, id string) error { return e.O.State.setAskNamespace(ctx, a, id) }}, l) if res.kept > 0 { e.log("kept sessions", e.O.State.touchKept(context.WithoutCancel(ctx), kept, res.kept)) } switch { case ctx.Err() != nil: rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" case res.reason == "step_timeout": rep.State, rep.Reason = wire.QuestionFailed, "turn_timeout" case res.reason != "": if !wire.AnswerReasons[res.reason] { res.reason = "provider_failed" } rep.State, rep.Reason = wire.QuestionFailed, res.reason case strings.TrimSpace(res.summary) == "": rep.State, rep.Reason = wire.QuestionFailed, "provider_failed" default: rep.State, rep.Text = wire.QuestionAnswered, clip(strings.TrimSpace(res.summary), wire.MaxAnswerText) t := stream.timing t.Cold = true rep.Timing = &t } outcome := wire.OutcomeFailed switch rep.State { case wire.QuestionAnswered: outcome = wire.OutcomeReplied case wire.QuestionCancelled: outcome = wire.OutcomeCancelled } rep.Usage = usageRows(res.tokens, b, a.Attempt, outcome) if res.auth { e.Conns.KeyRefused(context.WithoutCancel(ctx), b.LocalID) } return rep, ending }