| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "time" |
| 13 | "unicode/utf8" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/runner" |
| 16 | "amadan.net/oficina/equipo/internal/runner/mac" |
| 17 | "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| 18 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 19 | "amadan.net/oficina/equipo/internal/wire" |
| 20 | "amadan.net/oficina/equipo/internal/wire/forgekey" |
| 21 | ) |
| 22 | |
| 23 | // Ask the implementer on a Mac worker (Mac runners slice F, task 13). |
| 24 | // The worker kept each Engineering attempt's session (kept_sessions, one |
| 25 | // per step and attempt, with its account and session id) and pinned its |
| 26 | // candidate in its store (candidateRef). A question resumes exactly the |
| 27 | // session the instance froze on it: that step, attempt, account and |
| 28 | // session id, on the commit it made; anything else is refused before |
| 29 | // anything runs. It runs in the Mac's turn (OpAsk), through the darwin |
| 30 | // launch with the read-only answer settings (task 8), in a fresh tree of |
| 31 | // the candidate under the scratch root, and git_log, git_diff and |
| 32 | // git_show read the change from the store (its shallow boundaries end |
| 33 | // the history at the base). The answer passes the known-secret redaction |
| 34 | // before it leaves. |
| 35 | |
| 36 | // ask answers one question attempt about an Engineering step this worker |
| 37 | // ran; terminated is false only when its launch started and its end was |
| 38 | // not proven. |
| 39 | func (w *Worker) ask(ctx context.Context, a askRow, progress func(wire.AnswerReport)) askResult { |
| 40 | terminated := true |
| 41 | rep := w.answer(ctx, a, progress, &terminated) |
| 42 | return askResult{Report: rep, Terminated: terminated} |
| 43 | } |
| 44 | |
| 45 | func (w *Worker) answer(ctx context.Context, a askRow, progress func(wire.AnswerReport), terminated *bool) (rep wire.AnswerReport) { |
| 46 | e := w.Engine |
| 47 | received := time.Now() |
| 48 | rep = wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt} |
| 49 | fail := func(reason string) wire.AnswerReport { |
| 50 | rep.State, rep.Reason = wire.QuestionFailed, reason |
| 51 | if ctx.Err() != nil { |
| 52 | rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" |
| 53 | } |
| 54 | return rep |
| 55 | } |
| 56 | // The instance's pinning, whole: a worker answers only about the |
| 57 | // Engineering it ran, and only for the attempt, account and session |
| 58 | // frozen on the question. |
| 59 | if !slices.Contains(e.Owners, a.Person) || !forgekey.ValidHub(a.Repo) || !wire.ValidTaskBranch(a.Branch) || !refName.MatchString(a.TaskID) || !refName.MatchString(a.StepID) || |
| 60 | !wire.ValidCommitSHA(a.CandidateSHA) || !wire.ValidCommitSHA(a.BaseSHA) || a.Specialist != wire.SpecialistEngineering || a.EngAttempt < 1 || a.EngAccount == "" || a.EngSession == "" { |
| 61 | return fail("policy_rejected") |
| 62 | } |
| 63 | kept, found, err := w.State.keptAttempt(ctx, a.StepID, a.EngAttempt) |
| 64 | if err != nil { |
| 65 | e.log("ask session", err) |
| 66 | return fail("provider_failed") |
| 67 | } |
| 68 | if !found || kept.TaskID != a.TaskID || kept.Person != a.Person || kept.Specialist != wire.SpecialistEngineering { |
| 69 | return fail("session_gone") |
| 70 | } |
| 71 | if kept.Account != a.EngAccount || kept.SessionID != a.EngSession || kept.Candidate != a.CandidateSHA { |
| 72 | return fail("policy_rejected") |
| 73 | } |
| 74 | if _, err := os.Stat(keptTranscript(kept.Dir, kept.SessionID)); err != nil { |
| 75 | return fail("session_gone") |
| 76 | } |
| 77 | if w.Eng == nil || w.Eng.Creds == nil || w.Eng.Status == nil || w.Eng.Secrets == nil || e.Conns == nil { |
| 78 | return fail("account_unavailable") |
| 79 | } |
| 80 | // The session's own connection, while it can run; never another. One |
| 81 | // reading of the bindings: a sign-out meanwhile cannot shift another |
| 82 | // connection into its place. |
| 83 | mine := e.Conns.Mine |
| 84 | if w.mine != nil { |
| 85 | mine = w.mine |
| 86 | } |
| 87 | var b runner.AccountBinding |
| 88 | bs := mine(a.Person) |
| 89 | if i := slices.IndexFunc(bs, func(c runner.AccountBinding) bool { |
| 90 | return c.Provider == wire.ProviderClaude && c.LocalID == kept.Account |
| 91 | }); i >= 0 { |
| 92 | b = bs[i] |
| 93 | } |
| 94 | if b.ID == "" || e.Healthy != nil && !e.Healthy(b.ID) { |
| 95 | return fail("account_unavailable") |
| 96 | } |
| 97 | // Only an instance that pins questions (protocol 37), and only under |
| 98 | // its lease. |
| 99 | if e.Spoken == nil || e.Spoken() < wire.ProtocolMacEngineering || e.Authorize == nil { |
| 100 | return fail("policy_rejected") |
| 101 | } |
| 102 | r := stepRow{DispatchCommand: wire.DispatchCommand{Person: a.Person, TaskID: a.TaskID, StepID: a.QuestionID, Attempt: a.Attempt, Specialist: wire.SpecialistEngineering, Repo: a.Repo, Branch: a.Branch, BaseSHA: a.BaseSHA, CandidateSHA: a.CandidateSHA}, Question: true} |
| 103 | w.mu.Lock() |
| 104 | defer w.mu.Unlock() |
| 105 | if ctx.Err() != nil { |
| 106 | return fail("cancelled") |
| 107 | } |
| 108 | m := w.Eng.Creds |
| 109 | if m.turns != nil { |
| 110 | u, err := m.turns.Take(ctx, mac.OpAsk) |
| 111 | if err != nil { |
| 112 | e.log("worker ask turn", err) |
| 113 | return fail("account_unavailable") |
| 114 | } |
| 115 | defer u.Give() |
| 116 | ctx = u.Context(ctx) |
| 117 | } |
| 118 | // The runner's current lease, confirmed as a question's, in the turn |
| 119 | // and before anything is prepared: a runner (or person) that lost its |
| 120 | // authority while the question waited runs nothing. |
| 121 | if err := e.lease(ctx, r); err != nil { |
| 122 | if errors.Is(err, ErrWithdrawn) { |
| 123 | return fail("superseded") |
| 124 | } |
| 125 | return fail("cancelled") |
| 126 | } |
| 127 | secrets, err := w.Eng.Secrets(ctx) |
| 128 | if err != nil { |
| 129 | // What it cannot name it cannot keep from leaving: nothing runs. |
| 130 | e.log("worker secrets", err) |
| 131 | return fail("account_unavailable") |
| 132 | } |
| 133 | known := secretForms(secrets) |
| 134 | defer func() { rep.Text = redactText(rep.Text, known) }() |
| 135 | marker := engineeringMarker("ask/" + a.QuestionID + "/" + itoa(a.Attempt)) |
| 136 | w.marker = marker |
| 137 | defer func() { w.marker = "" }() |
| 138 | if err := w.State.setAskNamespace(ctx, a, mac.RecordID(0, marker)); err != nil { |
| 139 | e.log("worker record", err) |
| 140 | return fail("provider_failed") |
| 141 | } |
| 142 | // The candidate as the store pins it for that attempt. |
| 143 | store := w.objects(a.Repo) |
| 144 | ref := candidateRef(stepRow{DispatchCommand: wire.DispatchCommand{TaskID: a.TaskID, StepID: a.StepID, Attempt: a.EngAttempt}}) |
| 145 | if tip, err := w.git(ctx, nil, "--git-dir="+store, "rev-parse", "--verify", "--end-of-options", ref+"^{commit}"); err != nil || tip != a.CandidateSHA { |
| 146 | return fail("candidate_unavailable") |
| 147 | } |
| 148 | dir := filepath.Join(w.stepsDir(), "ask-"+stepKey(r)) |
| 149 | defer os.RemoveAll(dir) |
| 150 | tree, err := workspace.PrepareTaskTree(ctx, e.O.Runner.GitPath, store, a.CandidateSHA, a.Branch, filepath.Join(dir, "tree"), filepath.Join(dir, "git")) |
| 151 | if err != nil { |
| 152 | e.log("worker ask tree", err) |
| 153 | return fail("candidate_unavailable") |
| 154 | } |
| 155 | rep.State = wire.QuestionRunning |
| 156 | progress(rep) |
| 157 | stream := &answerStream{} |
| 158 | if e.Delta != nil { |
| 159 | // A secret can arrive split across chunks: the text is redacted |
| 160 | // whole as it grows (redactedStream). |
| 161 | held := newRedactedStream(known, func(offset int64, text string) { |
| 162 | e.Delta(wire.DeltaReport{TurnID: a.QuestionID, Attempt: a.Attempt, Offset: offset, Text: text}) |
| 163 | }) |
| 164 | stream.delta = func(_ int64, text string) { held.add(text) } |
| 165 | defer held.flush() |
| 166 | } |
| 167 | if e.Activity != nil { |
| 168 | stream.activity = func(kind, tool string) { |
| 169 | e.Activity(wire.ActivityReport{TurnID: a.QuestionID, Attempt: a.Attempt, Kind: kind, Tool: tool}) |
| 170 | } |
| 171 | } |
| 172 | var mu sync.Mutex |
| 173 | call := func(cctx context.Context, name, _ string, args json.RawMessage) (string, bool) { |
| 174 | mu.Lock() |
| 175 | defer mu.Unlock() |
| 176 | return answerGit(cctx, tree.Git, tree.GitDir, a.BaseSHA, a.CandidateSHA, name, args) |
| 177 | } |
| 178 | limit := e.MaxAnswer |
| 179 | if limit <= 0 { |
| 180 | limit = maxAnswer |
| 181 | } |
| 182 | res := w.launch(ctx, r, tree, specialistRun{action: "answer", binding: b, tools: answerTools, names: []string{"git_log", "git_diff", "git_show"}, permission: claude.ReadPermission, call: call, prompt: e.askPrompt(a, tree.Dir), resume: kept.SessionID, keep: kept.Dir, stream: stream, limit: limit, noLog: true, |
| 183 | record: func(ctx context.Context, id string) error { return w.State.setAskNamespace(ctx, a, id) }}, marker, known) |
| 184 | *terminated = res.terminated |
| 185 | if res.kept > 0 { |
| 186 | e.log("kept sessions", w.State.touchKept(context.WithoutCancel(ctx), kept, res.kept)) |
| 187 | } |
| 188 | switch { |
| 189 | case ctx.Err() != nil: |
| 190 | rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" |
| 191 | case res.reason == "step_timeout": |
| 192 | rep.State, rep.Reason = wire.QuestionFailed, "turn_timeout" |
| 193 | case res.reason != "": |
| 194 | if !wire.AnswerReasons[res.reason] { |
| 195 | res.reason = "provider_failed" |
| 196 | } |
| 197 | rep.State, rep.Reason = wire.QuestionFailed, res.reason |
| 198 | case strings.TrimSpace(res.summary) == "": |
| 199 | rep.State, rep.Reason = wire.QuestionFailed, "provider_failed" |
| 200 | default: |
| 201 | // Redacted whole, then cut: a secret crossing the bound is still |
| 202 | // whole when the redaction looks for it. |
| 203 | rep.State, rep.Text = wire.QuestionAnswered, clip(strings.TrimSpace(redactText(res.summary, known)), wire.MaxAnswerText) |
| 204 | t := stream.timing |
| 205 | t.Cold = true |
| 206 | if !stream.stdin.IsZero() { |
| 207 | t.StartMs = stream.stdin.Sub(received).Milliseconds() |
| 208 | } |
| 209 | rep.Timing = &t |
| 210 | } |
| 211 | outcome := wire.OutcomeFailed |
| 212 | switch rep.State { |
| 213 | case wire.QuestionAnswered: |
| 214 | outcome = wire.OutcomeReplied |
| 215 | case wire.QuestionCancelled: |
| 216 | outcome = wire.OutcomeCancelled |
| 217 | } |
| 218 | rep.Usage = usageRows(res.tokens, b, a.Attempt, outcome) |
| 219 | return rep |
| 220 | } |
| 221 | |
| 222 | // redactedStream sends a session's streamed text with every known secret |
| 223 | // redacted, whichever chunks it arrives in: the text so far is redacted |
| 224 | // whole, and its last hold bytes (room for the longest form of a secret |
| 225 | // to complete) wait for the next chunk or the flush. A form can only |
| 226 | // match where new text ends it, so what was sent stays a prefix of what |
| 227 | // the whole text redacts to. Offsets are the redacted text's. |
| 228 | type redactedStream struct { |
| 229 | forms [][]byte |
| 230 | hold int |
| 231 | raw strings.Builder |
| 232 | sent int |
| 233 | send func(offset int64, text string) |
| 234 | } |
| 235 | |
| 236 | func newRedactedStream(forms [][]byte, send func(offset int64, text string)) *redactedStream { |
| 237 | hold := 64 |
| 238 | for _, f := range forms { |
| 239 | hold = max(hold, len(f)) |
| 240 | } |
| 241 | return &redactedStream{forms: forms, hold: hold, send: send} |
| 242 | } |
| 243 | |
| 244 | func (r *redactedStream) add(text string) { |
| 245 | r.raw.WriteString(text) |
| 246 | r.emit(false) |
| 247 | } |
| 248 | |
| 249 | // flush sends what is held, once the session has said everything. |
| 250 | func (r *redactedStream) flush() { r.emit(true) } |
| 251 | |
| 252 | func (r *redactedStream) emit(all bool) { |
| 253 | out := redactText(r.raw.String(), r.forms) |
| 254 | end := len(out) |
| 255 | if !all { |
| 256 | end -= r.hold |
| 257 | } |
| 258 | for end > r.sent && end < len(out) && !utf8.RuneStart(out[end]) { |
| 259 | end-- |
| 260 | } |
| 261 | if end <= r.sent { |
| 262 | return |
| 263 | } |
| 264 | r.send(int64(r.sent), out[r.sent:end]) |
| 265 | r.sent = end |
| 266 | } |
| 267 | |