| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "io" |
| 10 | "os" |
| 11 | "sync/atomic" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 15 | "amadan.net/oficina/equipo/internal/runner/mac" |
| 16 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 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 | ) |
| 21 | |
| 22 | // macStopMargin is what a stopped Mac launch may take beyond its |
| 23 | // executor's own budgets (Executor.StopBudget: the 30 s termination |
| 24 | // proof, then the user-temp cleanup's CleanLimit) before it counts as |
| 25 | // unproven. Either way the launch waits for the executor's Wait to |
| 26 | // return before it gives the turn back. |
| 27 | var macStopMargin = 30 * time.Second |
| 28 | |
| 29 | // macStopGrace is how long a launch that ended its turn is given to |
| 30 | // exit by itself before it is stopped. |
| 31 | var macStopGrace = 10 * time.Second |
| 32 | |
| 33 | // launch is Engineer.run on a Mac worker: the pinned CLI through the |
| 34 | // darwin launch (mac.Starter), its implement policy (or, for a question, |
| 35 | // the read-only answer policy) for the worktree at its real path, the connection's runtime copy as its config dir and the |
| 36 | // token by descriptor, watched for a Keychain item as a sign-in is. ctx |
| 37 | // holds the Mac's turn. A start whose record was lost (ErrRecord) or |
| 38 | // whose stop was not proven (ErrUnproven) ends unproven: not terminated, |
| 39 | // no Retry until a restart proves it. |
| 40 | func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun, marker string, forms [][]byte) stepResult { |
| 41 | e, m := w.Engine, w.Eng.Creds |
| 42 | o := e.O |
| 43 | b := spec.binding |
| 44 | done := func(reason string) stepResult { return stepResult{reason: reason, terminated: true} } |
| 45 | if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken { |
| 46 | // A Mac keeps only Claude token connections (§8.5). |
| 47 | return done("account_unavailable") |
| 48 | } |
| 49 | if err := m.Gate(); err != nil { |
| 50 | e.log("worker guard", err) |
| 51 | return done(wire.ReasonEngineeringUnavailable) |
| 52 | } |
| 53 | // Readiness and the Xcode proof may have changed while the attempt |
| 54 | // waited for the turn (a probe run holds it): asked again in it. |
| 55 | if reason := w.readyNow(ctx, r); reason != "" && !spec.probe { |
| 56 | return done(reason) |
| 57 | } |
| 58 | direct, err := o.Runner.DirectBinding(b) |
| 59 | if err != nil { |
| 60 | return done("account_unavailable") |
| 61 | } |
| 62 | refresh := m.authStatus |
| 63 | if w.Eng.refresh != nil { |
| 64 | refresh = w.Eng.refresh |
| 65 | } |
| 66 | lease, err := provider.OpenRuntimeCopy(ctx, direct, refresh, o.LockWait) |
| 67 | if err != nil { |
| 68 | e.log("worker account", err) |
| 69 | switch { |
| 70 | case errors.Is(err, mac.ErrUnproven), errors.Is(err, mac.ErrRecord): |
| 71 | // The auth status read's end is not proven: neither is the |
| 72 | // attempt's. |
| 73 | return stepResult{reason: wire.ReasonEngineeringUnavailable} |
| 74 | case errors.Is(err, provider.ErrLoginRequired): |
| 75 | // Sign in again: the step fails over as on a refused run. |
| 76 | return stepResult{reason: "sign_in_again", auth: true, terminated: true} |
| 77 | } |
| 78 | return done(reasonFor(err)) |
| 79 | } |
| 80 | defer lease.Close() |
| 81 | binding := lease.Binding() |
| 82 | scratch := spec.scratch |
| 83 | if scratch == "" { |
| 84 | if scratch, err = os.MkdirTemp(o.Runner.ScratchRoot, "policy-"); err != nil { |
| 85 | return done("provider_failed") |
| 86 | } |
| 87 | defer os.RemoveAll(scratch) |
| 88 | } |
| 89 | var policy provider.Policy |
| 90 | var refused atomic.Int64 |
| 91 | permission := countRefusals(spec.permission, &refused) |
| 92 | set := toolSet{list: spec.tools, names: spec.names, permission: func(raw json.RawMessage) string { return string(permission(raw, policy)) }} |
| 93 | // Under toolRoot (<scratch root>/t on a Mac): the socket path must fit |
| 94 | // sun_path. |
| 95 | root, err := toolRoot(o.Runner) |
| 96 | if err != nil { |
| 97 | return done("provider_failed") |
| 98 | } |
| 99 | tool, err := openToolSet(context.Background(), root, set, spec.call) |
| 100 | if err != nil { |
| 101 | return done("provider_failed") |
| 102 | } |
| 103 | defer tool.Close() |
| 104 | session, resume := uuid(), false |
| 105 | if spec.resume != "" { |
| 106 | // The kept transcript goes into the fresh runtime copy first. |
| 107 | if err := placeTranscript(firstNonEmpty(spec.from, spec.keep), binding.Home, tree.Dir, spec.resume); err != nil { |
| 108 | return done("session_gone") |
| 109 | } |
| 110 | session, resume = spec.resume, true |
| 111 | } |
| 112 | model := firstNonEmpty(b.Model, firstNonEmpty(o.Runner.ClaudeModel, DefaultModels[wire.ProviderClaude])) |
| 113 | action, xcode := claude.DarwinImplement, r.XcodeAccess |
| 114 | if spec.action == "answer" { |
| 115 | // A question: Read, Glob and Grep, the worktree read-only, never |
| 116 | // with Xcode. |
| 117 | action, xcode = claude.DarwinAnswer, "" |
| 118 | } |
| 119 | in := mac.EngineeringInput{Paths: m.paths, Action: action, Model: model, Worktree: tree.Dir, Scratch: scratch, Runner: m.runner, ToolRoot: root, Socket: tool.Path, |
| 120 | ConfigDir: binding.Home, CredentialHome: b.ProviderHome, RuntimeRoot: direct.RuntimeRoot, XcodeAccess: xcode, DeveloperDir: w.Eng.DeveloperDir, Attempt: marker, SessionID: session, Resume: resume} |
| 121 | exec := m.exec |
| 122 | if xcode != "" { |
| 123 | in.Mach = mac.CheckMachServices |
| 124 | if w.Eng.XcodeExec != nil { |
| 125 | exec = w.Eng.XcodeExec |
| 126 | } |
| 127 | } |
| 128 | if policy, err = mac.EngineeringPolicy(m.cli, in); err != nil { |
| 129 | e.log("worker policy", err) |
| 130 | return done(wire.ReasonEngineeringUnavailable) |
| 131 | } |
| 132 | if err = lease.CheckCopy(ctx); err != nil { |
| 133 | return done(reasonFor(err)) |
| 134 | } |
| 135 | if spec.copied != nil && spec.copied(binding.Home) != nil { |
| 136 | return done(wire.ReasonEngineeringUnavailable) |
| 137 | } |
| 138 | limit := e.maxStep() |
| 139 | if spec.limit > 0 { |
| 140 | limit = spec.limit |
| 141 | } |
| 142 | limit = min(limit, time.Until(lease.FreshUntil())-o.Margin) |
| 143 | if limit < minTurn { |
| 144 | return done("account_unavailable") |
| 145 | } |
| 146 | sel := provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID} |
| 147 | launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "step/" + stepKey(r) + "/" + uuid(), Workspace: tree.Dir, Selection: sel, Binding: binding, Policy: policy} |
| 148 | env, err := provider.LaunchSecretEnv(launch) |
| 149 | if err != nil { |
| 150 | return done("account_unavailable") |
| 151 | } |
| 152 | token := []byte(env[provider.OAuthTokenEnv]) |
| 153 | defer clear(token) |
| 154 | if reason := w.readyNow(ctx, r); reason != "" && !spec.probe { |
| 155 | return done(reason) |
| 156 | } |
| 157 | // Watched as a sign-in is: the Keychain listed before the CLI starts, |
| 158 | // looked at again once its end is proven. |
| 159 | if err = m.keychain.Before(ctx, marker, in.ConfigDir); err != nil { |
| 160 | e.log("worker keychain", err) |
| 161 | return done(wire.ReasonEngineeringUnavailable) |
| 162 | } |
| 163 | pctx, kill := context.WithCancel(context.WithoutCancel(ctx)) |
| 164 | defer kill() |
| 165 | s := &mac.Starter{Exec: exec, CLI: m.cli, Input: in, Token: bytes.Clone(token)} |
| 166 | proc, err := s.StartRecorded(pctx, launch, claude.DarwinArgv(policy), func(rctx context.Context, rec containment.Record) error { |
| 167 | if err := m.keychain.Ran(marker, rec.ID); err != nil { |
| 168 | return err |
| 169 | } |
| 170 | if spec.record != nil { |
| 171 | // A question's attempt keeps its own record. |
| 172 | return spec.record(context.WithoutCancel(rctx), rec.ID) |
| 173 | } |
| 174 | return w.State.setStepNamespace(context.WithoutCancel(rctx), r, rec.ID) |
| 175 | }) |
| 176 | if err != nil { |
| 177 | e.log("worker start", err) |
| 178 | if errors.Is(err, mac.ErrUnproven) || errors.Is(err, mac.ErrRecord) { |
| 179 | m.keychain.Abandon(marker) |
| 180 | return stepResult{reason: wire.ReasonEngineeringUnavailable} |
| 181 | } |
| 182 | e.log("worker keychain", m.after(marker)) |
| 183 | return done(wire.ReasonEngineeringUnavailable) |
| 184 | } |
| 185 | exited, waited := make(chan error, 1), make(chan struct{}) |
| 186 | go func() { |
| 187 | _, err := proc.Wait(context.Background()) |
| 188 | exited <- err |
| 189 | close(waited) |
| 190 | }() |
| 191 | go func() { _, _ = io.Copy(io.Discard, io.LimitReader(proc.Stderr(), 1<<20)) }() |
| 192 | frames := make(chan []byte, 64) |
| 193 | go func() { |
| 194 | defer close(frames) |
| 195 | scan := bufio.NewScanner(proc.Stdout()) |
| 196 | scan.Buffer(make([]byte, 0, 64<<10), stepFrameLimit) |
| 197 | for scan.Scan() { |
| 198 | if line := scan.Bytes(); len(line) > 0 { |
| 199 | if spec.tap != nil { |
| 200 | spec.tap(line) |
| 201 | } |
| 202 | // Every known secret goes from the whole frame before any of |
| 203 | // it is parsed, clipped or kept (whole-branch fix 3, #4). |
| 204 | frames <- redactForms(line, forms) |
| 205 | } |
| 206 | } |
| 207 | }() |
| 208 | // The step log keeps only redacted frames; a question keeps none. |
| 209 | var logFile io.Writer = io.Discard |
| 210 | if !spec.noLog { |
| 211 | raw := e.openLog(r) |
| 212 | defer raw.Close() |
| 213 | logFile = redactingWriter{w: raw, forms: forms} |
| 214 | } |
| 215 | var shell shellUse |
| 216 | res := e.converse(ctx, proc, session, policy, model, frames, logFile, limit, spec.prompt, nil, spec.stream, spec.activity, &shell) |
| 217 | res.session, res.refused, res.noShell = session, refused.Load(), shell.none() |
| 218 | res.terminated = stopStep(func() { proc.Stdin().Close() }, exited, kill, ctx.Err() == nil && res.reason == "", macStopGrace, exec.StopBudget()+macStopMargin) |
| 219 | // Past that wait too, the turn and the evidence stay until the stop, |
| 220 | // its proof and the cleanup have returned (they are bounded there). |
| 221 | <-waited |
| 222 | if !res.terminated { |
| 223 | // The record and the Keychain watch stay: a restart settles them. |
| 224 | m.keychain.Abandon(marker) |
| 225 | e.log("worker stop", errors.New("end not proven")) |
| 226 | return res |
| 227 | } |
| 228 | if err := m.after(marker); err != nil { |
| 229 | // The launch left a Keychain item (or the Keychain could not be |
| 230 | // listed): the Mac holds a credential, and the attempt stops. |
| 231 | return stepResult{reason: wire.ReasonEngineeringUnavailable, terminated: true, tokens: res.tokens} |
| 232 | } |
| 233 | if spec.keep != "" { |
| 234 | n, err := keepTranscript(binding.Home, tree.Dir, session, spec.keep) |
| 235 | e.log("kept sessions", err) |
| 236 | res.kept = n |
| 237 | } |
| 238 | return res |
| 239 | } |
| 240 | |
| 241 | // readyNow is why the Mac cannot launch the attempt now ("" when it |
| 242 | // can): its Engineering status is not ready, or sandboxed Xcode access |
| 243 | // that its trusted report no longer allows. |
| 244 | func (w *Worker) readyNow(ctx context.Context, r stepRow) string { |
| 245 | if s := w.Eng.Status(ctx); s == nil || s.State != wire.EngineeringReady { |
| 246 | return wire.ReasonEngineeringUnavailable |
| 247 | } |
| 248 | if r.XcodeAccess != "" && (w.Eng.Xcode == nil || !w.Eng.Xcode()) { |
| 249 | return wire.ReasonEngineeringUnavailable |
| 250 | } |
| 251 | return "" |
| 252 | } |
| 253 | |
| 254 | // redactForms is a copy of b with every known secret form replaced by |
| 255 | // *** (only the forms: a frame stays valid JSON). |
| 256 | func redactForms(b []byte, forms [][]byte) []byte { |
| 257 | out := append([]byte(nil), b...) |
| 258 | for _, f := range forms { |
| 259 | out = bytes.ReplaceAll(out, f, []byte("***")) |
| 260 | } |
| 261 | return out |
| 262 | } |
| 263 | |
| 264 | // redactingWriter writes each frame with every known secret redacted. |
| 265 | type redactingWriter struct { |
| 266 | w io.Writer |
| 267 | forms [][]byte |
| 268 | } |
| 269 | |
| 270 | func (r redactingWriter) Write(p []byte) (int, error) { |
| 271 | if _, err := io.WriteString(r.w, redactText(string(p), r.forms)); err != nil { |
| 272 | return 0, err |
| 273 | } |
| 274 | return len(p), nil |
| 275 | } |
| 276 | |