| 1 | package claude |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/rand" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "path/filepath" |
| 11 | "reflect" |
| 12 | "slices" |
| 13 | "sort" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 19 | ) |
| 20 | |
| 21 | const Version = provider.ClaudeVersion |
| 22 | const ExecutableSHA256 = "4f4178ce41d83e23341ebfbaecdbcf8ea6bf7baea0690025abe49eeec3a5d01d" |
| 23 | const errNotReady provider.Error = "claude_not_ready" |
| 24 | const errUncertain provider.Error = "claude_turn_uncertain" |
| 25 | const errFailed provider.Error = "claude_process_failed" |
| 26 | const helper = "/opt/equipo-tool-proxy" |
| 27 | |
| 28 | var _ provider.Launcher = (*Launcher)(nil) |
| 29 | |
| 30 | type Launcher struct { |
| 31 | host provider.ProcessHost |
| 32 | captures provider.CaptureFactory |
| 33 | digest string |
| 34 | mu sync.Mutex |
| 35 | sessions map[string]*sessionState |
| 36 | } |
| 37 | type sessionState struct { |
| 38 | permissions map[string]*pendingPermission |
| 39 | session provider.Session |
| 40 | launch provider.Launch |
| 41 | base provider.Policy |
| 42 | lease *provider.AccountLease |
| 43 | process provider.Process |
| 44 | capture *provider.Capture |
| 45 | ctx context.Context |
| 46 | cancel context.CancelFunc |
| 47 | events chan provider.Event |
| 48 | done chan struct{} |
| 49 | attached, active, finished, closed, clean bool |
| 50 | turn provider.Turn |
| 51 | used map[string]bool |
| 52 | err error |
| 53 | } |
| 54 | |
| 55 | type manifest struct { |
| 56 | Action string |
| 57 | AuthHost string |
| 58 | CredentialHome string |
| 59 | Argv []string |
| 60 | Files []struct { |
| 61 | Mount provider.Mount |
| 62 | SHA256 string |
| 63 | } |
| 64 | Instructions []struct { |
| 65 | Mount provider.Mount |
| 66 | SHA256 string |
| 67 | } |
| 68 | DeniedPaths, EgressHosts, Tools []string |
| 69 | ProviderVersion, LauncherVersion, BwrapVersion, Workspace, Scratch string |
| 70 | Settings, MCP, ThreadPolicy, TurnPolicy json.RawMessage |
| 71 | Env map[string]string |
| 72 | // A Mac launch's roots (native.go); a Linux manifest has none. |
| 73 | NativeRoots |
| 74 | } |
| 75 | type threadPolicy struct { |
| 76 | Specialist string `json:"specialist"` |
| 77 | Model string `json:"model"` |
| 78 | Start string `json:"start"` |
| 79 | Resume string `json:"resume"` |
| 80 | } |
| 81 | |
| 82 | func New(host provider.ProcessHost, captures provider.CaptureFactory) (*Launcher, error) { |
| 83 | if missing(host) || missing(captures) { |
| 84 | return nil, errNotReady |
| 85 | } |
| 86 | return &Launcher{host: host, captures: captures, digest: ExecutableSHA256, sessions: map[string]*sessionState{}}, nil |
| 87 | } |
| 88 | func missing(v any) bool { |
| 89 | if v == nil { |
| 90 | return true |
| 91 | } |
| 92 | r := reflect.ValueOf(v) |
| 93 | switch r.Kind() { |
| 94 | case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: |
| 95 | return r.IsNil() |
| 96 | } |
| 97 | return false |
| 98 | } |
| 99 | |
| 100 | // AuthStatusArgs returns a fresh copy of the exact document-framed auth command. |
| 101 | func AuthStatusArgs() []string { |
| 102 | return []string{"/opt/claude", "--setting-sources", "", "--settings", provider.SettingsPath, "--strict-mcp-config", "--mcp-config", provider.MCPPath, "--disable-slash-commands", "auth", "status", "--json"} |
| 103 | } |
| 104 | |
| 105 | // AssistEffort is the Assistant's effort level (the pinned CLI's |
| 106 | // --effort: low, medium, high, xhigh). |
| 107 | const AssistEffort = "low" |
| 108 | |
| 109 | // GlanceModel is the small model a glance runs (provider.LaunchModel). |
| 110 | const GlanceModel = provider.ClaudeGlanceModel |
| 111 | |
| 112 | func baseArgs(model, tools string) []string { |
| 113 | return []string{"/opt/claude", "-p", "--verbose", "--include-hook-events", "--input-format", "stream-json", "--output-format", "stream-json", "--model", model, "--setting-sources", "", "--disable-slash-commands", "--strict-mcp-config", "--mcp-config", provider.MCPPath, "--settings", provider.SettingsPath, "--permission-mode", "manual", "--permission-prompt-tool", "mcp__equipo__permission", "--tools", tools} |
| 114 | } |
| 115 | func nativeTools(role string) ([]string, error) { |
| 116 | switch role { |
| 117 | case "Engineering", "Copy", "Design": |
| 118 | return []string{"Bash", "Read", "Write", "Edit", "Glob", "Grep"}, nil |
| 119 | case "Coordinator", provider.ResearchSpecialist, provider.GlanceSpecialist: |
| 120 | // The Research step and a glance read only their prompt: --tools "". |
| 121 | return []string{}, nil |
| 122 | case "Review", "Product", "Scope", "Research": |
| 123 | return []string{"Read", "Glob", "Grep", "Bash"}, nil |
| 124 | case "Reviewer", "Answerer": |
| 125 | return []string{"Read", "Glob", "Grep"}, nil |
| 126 | } |
| 127 | return nil, provider.ErrPolicy |
| 128 | } |
| 129 | |
| 130 | // PolicyInputs renders the provider policy before the runner calls BuildPolicy. |
| 131 | // Tools may contain additional explicitly registered Equipo MCP tool names. |
| 132 | // assistMCP is the Assistant's tool set (provider.AssistTools) as MCP |
| 133 | // names, so a tool added there needs no second list here. |
| 134 | var assistMCP = func() []string { |
| 135 | out := []string{} |
| 136 | for _, t := range provider.AssistTools() { |
| 137 | out = append(out, "mcp__equipo__"+t) |
| 138 | } |
| 139 | return out |
| 140 | }() |
| 141 | |
| 142 | func PolicyInputs(b provider.Binding, in provider.PolicyInputs, specialist, model string) (provider.PolicyInputs, error) { |
| 143 | if in.Action != "" { |
| 144 | profile, err := provider.Profile(in.Action) |
| 145 | if err != nil || !profile.AcceptsTools(in.Tools) || (specialist != profile.Specialist && !(in.Action == "reproduce" && specialist == "Product")) { |
| 146 | return in, provider.ErrPolicy |
| 147 | } |
| 148 | } |
| 149 | native, e := nativeTools(specialist) |
| 150 | if e != nil || model == "" || strings.HasPrefix(model, "-") { |
| 151 | return in, provider.ErrPolicy |
| 152 | } |
| 153 | tools := append(append([]string{}, native...), "mcp__equipo__permission") |
| 154 | for _, tool := range in.Tools { |
| 155 | converse := in.Action == "converse" && slices.Contains([]string{"mcp__equipo__request_access", "mcp__equipo__status", "mcp__equipo__find", "mcp__equipo__search_code", "mcp__equipo__read_file", "mcp__equipo__add_project", "mcp__equipo__create_project", "mcp__equipo__set_project_home", "mcp__equipo__star_project", "mcp__equipo__write_note", "mcp__equipo__read_notes", "mcp__equipo__record_task", "mcp__equipo__add_finding", "mcp__equipo__start_task", "mcp__equipo__read_task", "mcp__equipo__cancel_task", "mcp__equipo__add_report", "mcp__equipo__hold_merge", "mcp__equipo__set_merge_policy", "mcp__equipo__propose_specialist", "mcp__equipo__research", "mcp__equipo__offer_retry", "mcp__equipo__retry_step", "mcp__equipo__places", "mcp__equipo__propose_place", "mcp__equipo__publish_site", "mcp__equipo__site_status"}, tool) |
| 156 | assist := in.Action == "assist" && slices.Contains(assistMCP, tool) |
| 157 | answer := in.Action == "answer" && slices.Contains([]string{"mcp__equipo__git_log", "mcp__equipo__git_diff", "mcp__equipo__git_show"}, tool) |
| 158 | research := provider.ResearchAction(in.Action) && slices.Contains([]string{"mcp__equipo__submit_findings", "mcp__equipo__keep_image"}, tool) |
| 159 | // render_page only for the Design step (profile.AcceptsTools has |
| 160 | // already held it to exactly design-v1's three tools). |
| 161 | design := provider.DesignAction(in.Action) && slices.Contains(provider.DesignMCPTools(), tool) |
| 162 | if in.Action != "coordinate" && !converse && !assist && !answer && !research && !design && !slices.Contains([]string{"mcp__equipo__ask_person", "mcp__equipo__submit_candidate", "mcp__equipo__submit_review", "mcp__equipo__submit_reproduction", "mcp__equipo__submit_acceptance", "mcp__equipo__submit_answer", "mcp__equipo__submit_render"}, tool) { |
| 163 | return in, provider.ErrPolicy |
| 164 | } |
| 165 | tools = append(tools, tool) |
| 166 | } |
| 167 | denied := append([]string{}, in.DeniedPaths...) |
| 168 | denied = append(denied, b.CredentialHome, b.Home, b.RuntimeRoot, "/home/runner", "/egress", "/tool", "/tool/equipo.sock", "/config", "/proc", "/dev/fd") |
| 169 | sort.Strings(denied) |
| 170 | denied = compact(denied) |
| 171 | // Host-home aliases are absent from /workspace and cannot be approved. |
| 172 | settingsDenied := compact(append(append([]string{}, denied...), "/home")) |
| 173 | nativeDenies, e := NativeDenyRules(settingsDenied) |
| 174 | if e != nil { |
| 175 | return in, e |
| 176 | } |
| 177 | // The Design step reads its captures at /render and writes nothing |
| 178 | // there: Write and Edit are denied it, as is every write in the |
| 179 | // sandbox (containment binds it read-only too). Reads are its |
| 180 | // callback's (DesignPermission). |
| 181 | var readOnly []string |
| 182 | if provider.DesignAction(in.Action) { |
| 183 | readOnly = provider.DesignReadOnly() |
| 184 | } |
| 185 | for _, path := range readOnly { |
| 186 | if !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "*?[]()\n\r") { |
| 187 | return in, provider.ErrPolicy |
| 188 | } |
| 189 | for _, tool := range []string{"Write", "Edit"} { |
| 190 | nativeDenies = append(nativeDenies, tool+"(/"+path+")", tool+"(/"+path+"/**)") |
| 191 | } |
| 192 | } |
| 193 | allow := append([]string{}, in.Tools...) |
| 194 | // No shell command is reserved: ordinary sandboxed Bash commands run |
| 195 | // without a prompt, and no command's text is evidence of anything. |
| 196 | // (Two printf "control" commands once were; the live-gate harness |
| 197 | // that read them left with the certification evidence, bbf490ed.) |
| 198 | ask := []string{} |
| 199 | for _, tool := range native { |
| 200 | if slices.Contains([]string{"Write", "Edit", "Read", "Glob", "Grep"}, tool) { |
| 201 | ask = append(ask, tool+"(//workspace/**)") |
| 202 | } |
| 203 | } |
| 204 | // Every Bash command runs in the CLI's sandbox: in the pinned CLI a |
| 205 | // new user and PID namespace with a fresh /proc, so it cannot name the |
| 206 | // CLI or read its environment, where a token connection's token is. |
| 207 | // The CLI binds the inherited /proc only when |
| 208 | // sandbox.enableWeakerNestedSandbox is true; it is left at its false |
| 209 | // default (adding the key would change the certified policy hashes), |
| 210 | // and validatePolicy refuses settings that differ from these. |
| 211 | settings := map[string]any{ |
| 212 | "env": map[string]string{"MCP_TOOL_TIMEOUT": "600000"}, |
| 213 | "disableAllHooks": true, "enabledPlugins": map[string]any{"agents-md@builtin": false, "plugin-authoring@builtin": false}, "autoMemoryEnabled": false, "autoDreamEnabled": false, |
| 214 | "sandbox": map[string]any{"enabled": true, "failIfUnavailable": true, "allowUnsandboxedCommands": false, "autoAllowBashIfSandboxed": true, "excludedCommands": []string{}, "filesystem": map[string]any{"denyRead": settingsDenied, "denyWrite": append(slices.Clone(settingsDenied), readOnly...)}, "network": map[string]any{"allowUnixSockets": []string{}}}, |
| 215 | "permissions": map[string]any{"deny": nativeDenies, "allow": allow, "ask": ask}, |
| 216 | } |
| 217 | if in.Action != "" { |
| 218 | p, _ := provider.Profile(in.Action) |
| 219 | if p.ReadOnly { |
| 220 | settings["sandbox"].(map[string]any)["filesystem"].(map[string]any)["denyWrite"] = append(append([]string{}, settingsDenied...), "/workspace") |
| 221 | } |
| 222 | } |
| 223 | if provider.CoordinatorAction(in.Action) { |
| 224 | settings["permissions"].(map[string]any)["allow"] = []string{} |
| 225 | } |
| 226 | if in.Action == "converse" || in.Action == "assist" { |
| 227 | // Exactly the conversation's Equipo tools run without a prompt; |
| 228 | // the instance authorises each call. Nothing else is allowed. |
| 229 | settings["permissions"].(map[string]any)["allow"] = append([]string{}, in.Tools...) |
| 230 | } |
| 231 | in.Settings, _ = json.Marshal(settings) |
| 232 | in.MCP = json.RawMessage(`{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}`) |
| 233 | in.ThreadPolicy, _ = json.Marshal(threadPolicy{specialist, model, "session-id", "resume"}) |
| 234 | in.TurnPolicy = json.RawMessage(`{}`) |
| 235 | in.Tools = tools |
| 236 | in.DeniedPaths = denied |
| 237 | in.ProviderVersion = Version |
| 238 | // The thread policy keeps the bound model (the session's identity); |
| 239 | // only a glance launches another, its provider's small model. |
| 240 | in.Argv = baseArgs(provider.LaunchModel(in.Action, "claude", model), strings.Join(native, ",")) |
| 241 | // The coordinator and an answering session stream their text. |
| 242 | if provider.CoordinatorAction(in.Action) || specialist == "Coordinator" || in.Action == "answer" { |
| 243 | in.Argv = append(in.Argv, "--include-partial-messages") |
| 244 | } |
| 245 | // The Assistant answers a person who is waiting: the lowest effort |
| 246 | // on the connection's own model. Its model is the person's choice and |
| 247 | // stays as bound; the team's launches keep the CLI's default effort. |
| 248 | if in.Action == "assist" { |
| 249 | in.Argv = append(in.Argv, "--effort", AssistEffort) |
| 250 | } |
| 251 | return in, nil |
| 252 | } |
| 253 | func compact(v []string) []string { |
| 254 | out := []string{} |
| 255 | for _, s := range v { |
| 256 | if s != "" && (len(out) == 0 || out[len(out)-1] != s) { |
| 257 | out = append(out, s) |
| 258 | } |
| 259 | } |
| 260 | return out |
| 261 | } |
| 262 | func policyInputs(p provider.Policy) (provider.PolicyInputs, manifest, error) { |
| 263 | var m manifest |
| 264 | if !uniqueJSON(p.Manifest) || json.Unmarshal(p.Manifest, &m) != nil { |
| 265 | return provider.PolicyInputs{}, m, provider.ErrPolicy |
| 266 | } |
| 267 | in := provider.PolicyInputs{Action: m.Action, AuthHost: m.AuthHost, Argv: append([]string{}, m.Argv...), DeniedPaths: m.DeniedPaths, EgressHosts: m.EgressHosts, ProviderVersion: m.ProviderVersion, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, Workspace: m.Workspace, Scratch: m.Scratch, Settings: m.Settings, MCP: m.MCP, ThreadPolicy: m.ThreadPolicy, TurnPolicy: m.TurnPolicy, Tools: m.Tools, Env: map[string]string{}} |
| 268 | for _, automatic := range []string{m.CredentialHome, "/home/runner"} { |
| 269 | for i, path := range in.DeniedPaths { |
| 270 | if path == automatic { |
| 271 | in.DeniedPaths = append(append([]string{}, in.DeniedPaths[:i]...), in.DeniedPaths[i+1:]...) |
| 272 | break |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | for _, f := range m.Files { |
| 277 | in.RuntimeFiles = append(in.RuntimeFiles, f.Mount) |
| 278 | } |
| 279 | for _, f := range m.Instructions { |
| 280 | in.InstructionFiles = append(in.InstructionFiles, f.Mount) |
| 281 | } |
| 282 | for _, key := range []string{"LANG", "LC_ALL", "TERM"} { |
| 283 | if v, ok := m.Env[key]; ok { |
| 284 | in.Env[key] = v |
| 285 | } |
| 286 | } |
| 287 | return in, m, nil |
| 288 | } |
| 289 | func (l *Launcher) validatePolicy(b provider.Binding, p provider.Policy) (provider.PolicyInputs, error) { |
| 290 | in, m, e := policyInputs(p) |
| 291 | if e != nil { |
| 292 | return in, e |
| 293 | } |
| 294 | if b.Provider != "claude" || b.Expected.ProviderVersion != Version || in.ProviderVersion != Version { |
| 295 | return in, provider.ErrVersion |
| 296 | } |
| 297 | if e = p.ValidateSources(b); e != nil { |
| 298 | return in, e |
| 299 | } |
| 300 | var tp threadPolicy |
| 301 | if json.Unmarshal(in.ThreadPolicy, &tp) != nil { |
| 302 | return in, provider.ErrPolicy |
| 303 | } |
| 304 | native, e := nativeTools(tp.Specialist) |
| 305 | if e != nil { |
| 306 | return in, e |
| 307 | } |
| 308 | if len(in.Tools) < len(native)+1 || !reflect.DeepEqual(in.Tools[:len(native)], native) || in.Tools[len(native)] != "mcp__equipo__permission" { |
| 309 | return in, provider.ErrPolicy |
| 310 | } |
| 311 | expectedIn := in |
| 312 | expectedIn.Tools = append([]string{}, in.Tools[len(native)+1:]...) |
| 313 | expected, e := PolicyInputs(b, expectedIn, tp.Specialist, tp.Model) |
| 314 | if e != nil { |
| 315 | return in, e |
| 316 | } |
| 317 | for _, pair := range [][2]json.RawMessage{{in.Settings, expected.Settings}, {in.MCP, expected.MCP}, {in.ThreadPolicy, expected.ThreadPolicy}, {in.TurnPolicy, expected.TurnPolicy}} { |
| 318 | if !sameJSON(pair[0], pair[1]) { |
| 319 | return in, provider.ErrPolicy |
| 320 | } |
| 321 | } |
| 322 | if !reflect.DeepEqual(in.Argv, expected.Argv) || !reflect.DeepEqual(in.Tools, expected.Tools) { |
| 323 | return in, provider.ErrPolicy |
| 324 | } |
| 325 | for _, file := range in.InstructionFiles { |
| 326 | if strings.HasPrefix(file.Target, "/etc/") && file.Target != "/etc/claude-code/CLAUDE.md" { |
| 327 | return in, provider.ErrPolicy |
| 328 | } |
| 329 | } |
| 330 | found := false |
| 331 | helperFound := false |
| 332 | for _, f := range m.Files { |
| 333 | if strings.HasPrefix(f.Mount.Target, "/etc/") { |
| 334 | return in, provider.ErrPolicy |
| 335 | } |
| 336 | if f.Mount.Target == helper { |
| 337 | helperFound = true |
| 338 | } |
| 339 | if f.Mount.Target == "/opt/claude" { |
| 340 | found = f.SHA256 == l.digest |
| 341 | } |
| 342 | } |
| 343 | if !helperFound { |
| 344 | return in, provider.ErrPolicy |
| 345 | } |
| 346 | if !found { |
| 347 | return in, provider.ErrVersion |
| 348 | } |
| 349 | for k, v := range map[string]string{"CLAUDE_CONFIG_DIR": "/home/runner", "CLAUDE_SECURESTORAGE_CONFIG_DIR": "/home/runner", "CLAUDE_TMPDIR": "/tmp", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "DISABLE_AUTOUPDATER": "1"} { |
| 350 | if p.Env[k] != v { |
| 351 | return in, provider.ErrPolicy |
| 352 | } |
| 353 | } |
| 354 | // Rebuilding validates every manifest input and the lease's generated files. |
| 355 | rebuilt, e := provider.BuildPolicy(b, in) |
| 356 | if e != nil || rebuilt.Hash != p.Hash || rebuilt.ManifestHash != p.ManifestHash { |
| 357 | return in, provider.ErrPolicy |
| 358 | } |
| 359 | return in, nil |
| 360 | } |
| 361 | func sameJSON(a, b []byte) bool { |
| 362 | var x, y any |
| 363 | return json.Unmarshal(a, &x) == nil && json.Unmarshal(b, &y) == nil && reflect.DeepEqual(x, y) |
| 364 | } |
| 365 | func uuid() string { |
| 366 | var b [16]byte |
| 367 | if _, e := rand.Read(b[:]); e != nil { |
| 368 | panic(e) |
| 369 | } |
| 370 | b[6] = (b[6] & 15) | 64 |
| 371 | b[8] = (b[8] & 63) | 128 |
| 372 | return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) |
| 373 | } |
| 374 | |
| 375 | func (l *Launcher) Preflight(ctx context.Context, b provider.Binding, p provider.Policy) (provider.Identity, error) { |
| 376 | lease, e := b.AccountLease() |
| 377 | if e != nil { |
| 378 | return provider.Identity{}, e |
| 379 | } |
| 380 | in, e := l.validatePolicy(b, p) |
| 381 | if e != nil { |
| 382 | return provider.Identity{}, e |
| 383 | } |
| 384 | return l.preflight(ctx, b, lease, in) |
| 385 | } |
| 386 | func (l *Launcher) preflight(ctx context.Context, b provider.Binding, lease *provider.AccountLease, in provider.PolicyInputs) (provider.Identity, error) { |
| 387 | var e error |
| 388 | var observed provider.Identity |
| 389 | probe := func(ctx context.Context, b provider.Binding) (provider.Identity, error) { |
| 390 | var e error |
| 391 | observed, e = l.probeIdentity(ctx, b, in) |
| 392 | return observed, e |
| 393 | } |
| 394 | if e = lease.Validate(ctx); errors.Is(e, provider.ErrRefreshPending) { |
| 395 | return observed, provider.ErrAccountMaintenance |
| 396 | } |
| 397 | if e = lease.Preflight(ctx, probe); e != nil { |
| 398 | return observed, e |
| 399 | } |
| 400 | // Closing stdin proves dependency availability without supplying a user turn. |
| 401 | args := append(append([]string{}, in.Argv...), "--session-id", uuid()) |
| 402 | if _, e = l.probe(ctx, b, in, args); e != nil { |
| 403 | return observed, e |
| 404 | } |
| 405 | _, e = provider.BuildPolicy(b, in) |
| 406 | return observed, e |
| 407 | } |
| 408 | func (l *Launcher) probeIdentity(ctx context.Context, b provider.Binding, in provider.PolicyInputs) (provider.Identity, error) { |
| 409 | frames, e := l.probe(ctx, b, in, AuthStatusArgs()) |
| 410 | if e != nil { |
| 411 | return provider.Identity{}, e |
| 412 | } |
| 413 | if len(frames) != 1 { |
| 414 | return provider.Identity{}, provider.ErrIdentity |
| 415 | } |
| 416 | return provider.ClaudeLoginIdentity(frames[0]) |
| 417 | } |
| 418 | func (l *Launcher) probe(ctx context.Context, b provider.Binding, in provider.PolicyInputs, args []string) ([][]byte, error) { |
| 419 | ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 420 | defer cancel() |
| 421 | in.Argv = args |
| 422 | p, e := provider.BuildPolicy(b, in) |
| 423 | if e != nil { |
| 424 | return nil, e |
| 425 | } |
| 426 | launch := provider.Launch{AttemptKey: "claude-preflight-" + uuid(), Workspace: in.Workspace, Binding: b, Policy: p, Selection: provider.Selection{Provider: "claude", AccountID: b.AccountID}} |
| 427 | proc, e := l.host.Start(ctx, launch, args) |
| 428 | if e != nil { |
| 429 | return nil, e |
| 430 | } |
| 431 | defer func() { |
| 432 | cancel() |
| 433 | waitCtx, stop := context.WithTimeout(context.Background(), 5*time.Second) |
| 434 | defer stop() |
| 435 | proc.Wait(waitCtx) |
| 436 | }() |
| 437 | cap, e := l.captures.Open(ctx, proc, launch) |
| 438 | if e != nil { |
| 439 | cancel() |
| 440 | proc.Wait(context.Background()) |
| 441 | return nil, e |
| 442 | } |
| 443 | if cap == nil || cap.Input == nil || cap.Frames == nil || cap.Done == nil { |
| 444 | cancel() |
| 445 | proc.Wait(context.Background()) |
| 446 | return nil, errNotReady |
| 447 | } |
| 448 | if e = cap.Input.Close(); e != nil { |
| 449 | return nil, e |
| 450 | } |
| 451 | var frames [][]byte |
| 452 | total := 0 |
| 453 | for { |
| 454 | select { |
| 455 | case <-ctx.Done(): |
| 456 | return nil, ctx.Err() |
| 457 | case f, ok := <-cap.Frames: |
| 458 | if !ok { |
| 459 | goto drained |
| 460 | } |
| 461 | total += len(f.Bytes) |
| 462 | if total > MaxFrameBytes || !uniqueJSON(f.Bytes) { |
| 463 | return nil, errProtocol |
| 464 | } |
| 465 | frames = append(frames, bytes.Clone(f.Bytes)) |
| 466 | } |
| 467 | } |
| 468 | drained: |
| 469 | select { |
| 470 | case e = <-cap.Done: |
| 471 | if e != nil { |
| 472 | exit, _ := proc.Wait(ctx) |
| 473 | return nil, probeDiagnostic(exit, cap, e) |
| 474 | } |
| 475 | case <-ctx.Done(): |
| 476 | return nil, ctx.Err() |
| 477 | } |
| 478 | exit, e := proc.Wait(ctx) |
| 479 | if e != nil || exit.Code != 0 || exit.Signal != 0 { |
| 480 | return nil, probeDiagnostic(exit, cap, e) |
| 481 | } |
| 482 | for _, raw := range frames { |
| 483 | var v struct { |
| 484 | Type string `json:"type"` |
| 485 | Error bool `json:"is_error"` |
| 486 | } |
| 487 | json.Unmarshal(raw, &v) |
| 488 | if v.Type == "result" || v.Error { |
| 489 | return nil, probeDiagnostic(exit, cap, errFailed) |
| 490 | } |
| 491 | } |
| 492 | return frames, nil |
| 493 | } |
| 494 | |
| 495 | func (l *Launcher) Open(ctx context.Context, launch provider.Launch) (provider.Session, error) { |
| 496 | l.mu.Lock() |
| 497 | defer l.mu.Unlock() |
| 498 | if launch.AttemptKey == "" || l.sessions[launch.AttemptKey] != nil { |
| 499 | return provider.Session{}, errNotReady |
| 500 | } |
| 501 | for _, prior := range l.sessions { |
| 502 | if prior.launch.Binding == launch.Binding && !prior.closed { |
| 503 | return provider.Session{}, provider.ErrAccountBusy |
| 504 | } |
| 505 | } |
| 506 | in, e := l.validatePolicy(launch.Binding, launch.Policy) |
| 507 | if e != nil { |
| 508 | return provider.Session{}, e |
| 509 | } |
| 510 | var tp threadPolicy |
| 511 | json.Unmarshal(in.ThreadPolicy, &tp) |
| 512 | if launch.Selection.Model != tp.Model { |
| 513 | return provider.Session{}, provider.ErrIdentity |
| 514 | } |
| 515 | lease, e := launch.Binding.AccountLease() |
| 516 | if e != nil { |
| 517 | return provider.Session{}, e |
| 518 | } |
| 519 | id := uuid() |
| 520 | var previous *sessionState |
| 521 | if launch.ResumeSessionID != "" { |
| 522 | prior := (*sessionState)(nil) |
| 523 | for _, s := range l.sessions { |
| 524 | if s.session.ID == launch.ResumeSessionID && s.closed && s.clean && s.finished && s.err == nil { |
| 525 | prior = s |
| 526 | } |
| 527 | } |
| 528 | if prior == nil || prior.base.Hash != launch.Policy.Hash || prior.launch.Binding != launch.Binding || prior.launch.Selection != launch.Selection { |
| 529 | return provider.Session{}, errUncertain |
| 530 | } |
| 531 | id = launch.ResumeSessionID |
| 532 | previous = prior |
| 533 | } |
| 534 | session := provider.Session{ID: id, AttemptKey: launch.AttemptKey, Provider: launch.Selection.Provider, AccountID: launch.Selection.AccountID, Model: launch.Selection.Model, Family: launch.Selection.Family} |
| 535 | if e = session.Validate(launch); e != nil { |
| 536 | return provider.Session{}, e |
| 537 | } |
| 538 | if _, e = l.preflight(ctx, launch.Binding, lease, in); e != nil { |
| 539 | return provider.Session{}, e |
| 540 | } |
| 541 | if e = lease.ValidatePolicy(ctx); e != nil { |
| 542 | return provider.Session{}, e |
| 543 | } |
| 544 | base := launch.Policy |
| 545 | flag := "--session-id" |
| 546 | if launch.ResumeSessionID != "" { |
| 547 | flag = "--resume" |
| 548 | } |
| 549 | args := append(append([]string{}, in.Argv...), flag, id) |
| 550 | in.Argv = args |
| 551 | launch.Policy, e = provider.BuildPolicy(launch.Binding, in) |
| 552 | if e != nil { |
| 553 | return provider.Session{}, e |
| 554 | } |
| 555 | attempt, cancel := context.WithCancel(ctx) |
| 556 | process, e := l.host.Start(attempt, launch, args) |
| 557 | if e != nil { |
| 558 | cancel() |
| 559 | return provider.Session{}, e |
| 560 | } |
| 561 | capture, e := l.captures.Open(attempt, process, launch) |
| 562 | if e != nil { |
| 563 | cancel() |
| 564 | process.Wait(context.Background()) |
| 565 | return provider.Session{}, e |
| 566 | } |
| 567 | if capture == nil || capture.Input == nil || capture.Frames == nil || capture.Done == nil { |
| 568 | cancel() |
| 569 | process.Wait(context.Background()) |
| 570 | return provider.Session{}, errNotReady |
| 571 | } |
| 572 | if binding, ok := capture.Input.(provider.SessionBinding); ok { |
| 573 | if e = binding.BindSession(ctx, session); e != nil { |
| 574 | cancel() |
| 575 | process.Wait(context.Background()) |
| 576 | return provider.Session{}, e |
| 577 | } |
| 578 | } |
| 579 | s := &sessionState{session: session, launch: launch, base: base, lease: lease, process: process, capture: capture, ctx: attempt, cancel: cancel, events: make(chan provider.Event, 64), done: make(chan struct{}), used: map[string]bool{}} |
| 580 | if previous != nil { |
| 581 | previous.clean = false |
| 582 | for key, value := range previous.used { |
| 583 | s.used[key] = value |
| 584 | } |
| 585 | } |
| 586 | l.sessions[session.AttemptKey] = s |
| 587 | go l.read(s) |
| 588 | return session, nil |
| 589 | } |
| 590 | func (l *Launcher) state(s provider.Session) (*sessionState, error) { |
| 591 | v := l.sessions[s.AttemptKey] |
| 592 | if v == nil || v.session != s { |
| 593 | return nil, provider.ErrIdentity |
| 594 | } |
| 595 | return v, nil |
| 596 | } |
| 597 | func (l *Launcher) Events(ctx context.Context, s provider.Session) (<-chan provider.Event, error) { |
| 598 | l.mu.Lock() |
| 599 | defer l.mu.Unlock() |
| 600 | v, e := l.state(s) |
| 601 | if e != nil { |
| 602 | return nil, e |
| 603 | } |
| 604 | if e = ctx.Err(); e != nil { |
| 605 | return nil, e |
| 606 | } |
| 607 | if v.attached { |
| 608 | return nil, errNotReady |
| 609 | } |
| 610 | v.attached = true |
| 611 | return v.events, nil |
| 612 | } |
| 613 | func (l *Launcher) StartTurn(ctx context.Context, s provider.Session, t provider.Turn) error { |
| 614 | l.mu.Lock() |
| 615 | defer l.mu.Unlock() |
| 616 | v, e := l.state(s) |
| 617 | if e != nil { |
| 618 | return e |
| 619 | } |
| 620 | if v.closed || v.err != nil || v.active || !v.attached || t.ID == "" || t.AdmissionID == "" || v.used[t.ID] || v.used[t.AdmissionID] { |
| 621 | return errNotReady |
| 622 | } |
| 623 | if e = ctx.Err(); e != nil { |
| 624 | return e |
| 625 | } |
| 626 | if e = v.ctx.Err(); e != nil { |
| 627 | return e |
| 628 | } |
| 629 | fail := func(e error) error { v.err = e; v.cancel(); return e } |
| 630 | if e = v.lease.ValidatePolicy(ctx); errors.Is(e, provider.ErrRefreshPending) || errors.Is(e, provider.ErrPreflightRequired) { |
| 631 | // Rebuild the base policy only after checking the currently mounted sources. |
| 632 | if sourceErr := v.launch.Policy.ValidateSources(v.launch.Binding); sourceErr != nil { |
| 633 | return fail(sourceErr) |
| 634 | } |
| 635 | in, _, inputErr := policyInputs(v.base) |
| 636 | if inputErr != nil { |
| 637 | return fail(inputErr) |
| 638 | } |
| 639 | base, buildErr := provider.BuildPolicy(v.launch.Binding, in) |
| 640 | if buildErr != nil { |
| 641 | return fail(buildErr) |
| 642 | } |
| 643 | if _, e = l.Preflight(ctx, v.launch.Binding, base); e == nil { |
| 644 | actual, _, inputErr := policyInputs(v.launch.Policy) |
| 645 | if inputErr != nil { |
| 646 | return fail(inputErr) |
| 647 | } |
| 648 | _, e = provider.BuildPolicy(v.launch.Binding, actual) |
| 649 | } |
| 650 | } |
| 651 | if e != nil { |
| 652 | return fail(e) |
| 653 | } |
| 654 | if _, e = provider.AttestLaunch(v.launch, argv(v.launch.Policy)); e != nil { |
| 655 | return fail(e) |
| 656 | } |
| 657 | raw, e := userEnvelope(s.ID, t.Prompt) |
| 658 | if e != nil { |
| 659 | return e |
| 660 | } |
| 661 | if e = v.lease.BeginTurn(ctx); e != nil { |
| 662 | return fail(e) |
| 663 | } |
| 664 | v.active = true |
| 665 | v.finished = false |
| 666 | v.turn = t |
| 667 | v.used[t.ID] = true |
| 668 | v.used[t.AdmissionID] = true |
| 669 | if barrier, ok := v.capture.Input.(provider.TurnBarrier); ok { |
| 670 | if e = barrier.BeginTurn(ctx, s, t); e != nil { |
| 671 | return fail(e) |
| 672 | } |
| 673 | } |
| 674 | l.mu.Unlock() |
| 675 | stopWrite := context.AfterFunc(ctx, func() { v.cancel(); v.capture.Input.Close() }) |
| 676 | n, e := v.capture.Input.Write(raw) |
| 677 | stopWrite() |
| 678 | l.mu.Lock() |
| 679 | if e != nil || n != len(raw) || ctx.Err() != nil || v.ctx.Err() != nil { |
| 680 | v.err = errUncertain |
| 681 | v.cancel() |
| 682 | return errUncertain |
| 683 | } |
| 684 | return nil |
| 685 | } |
| 686 | func argv(p provider.Policy) []string { var m manifest; json.Unmarshal(p.Manifest, &m); return m.Argv } |
| 687 | func (l *Launcher) Respond(ctx context.Context, s provider.Session, a provider.Answer) error { |
| 688 | return l.respond(ctx, s, a) |
| 689 | } |
| 690 | func (l *Launcher) Interrupt(ctx context.Context, s provider.Session) error { |
| 691 | l.mu.Lock() |
| 692 | defer l.mu.Unlock() |
| 693 | v, e := l.state(s) |
| 694 | if e != nil { |
| 695 | return e |
| 696 | } |
| 697 | v.err = errUncertain |
| 698 | v.cancel() |
| 699 | return nil |
| 700 | } |
| 701 | func (l *Launcher) Close(ctx context.Context, s provider.Session) error { |
| 702 | ctx, stop := context.WithTimeout(ctx, 5*time.Second) |
| 703 | defer stop() |
| 704 | l.mu.Lock() |
| 705 | v, e := l.state(s) |
| 706 | if e != nil { |
| 707 | l.mu.Unlock() |
| 708 | return e |
| 709 | } |
| 710 | if !v.closed { |
| 711 | v.closed = true |
| 712 | if v.active { |
| 713 | v.err = errUncertain |
| 714 | v.cancel() |
| 715 | } |
| 716 | v.capture.Input.Close() |
| 717 | } |
| 718 | l.mu.Unlock() |
| 719 | select { |
| 720 | case <-ctx.Done(): |
| 721 | v.cancel() |
| 722 | return ctx.Err() |
| 723 | case <-v.done: |
| 724 | } |
| 725 | v.cancel() |
| 726 | l.mu.Lock() |
| 727 | defer l.mu.Unlock() |
| 728 | return v.err |
| 729 | } |
| 730 | func (l *Launcher) read(s *sessionState) { |
| 731 | defer close(s.done) |
| 732 | defer close(s.events) |
| 733 | var sequence int64 |
| 734 | lastFrame := "none" |
| 735 | for { |
| 736 | select { |
| 737 | case <-s.ctx.Done(): |
| 738 | goto finished |
| 739 | case frame, ok := <-s.capture.Frames: |
| 740 | if !ok { |
| 741 | goto finished |
| 742 | } |
| 743 | lastFrame = frameCategory(frame.Bytes) |
| 744 | l.mu.Lock() |
| 745 | var events []provider.Event |
| 746 | var e error |
| 747 | if frame.Sequence <= sequence { |
| 748 | e = errProtocol |
| 749 | } else { |
| 750 | events, e = Decode(frame.Bytes) |
| 751 | } |
| 752 | sequence = frame.Sequence |
| 753 | if e == nil { |
| 754 | for i := range events { |
| 755 | ev := &events[i] |
| 756 | ev.Sequence = frame.Sequence |
| 757 | if ev.SessionID != s.session.ID { |
| 758 | e = provider.ErrIdentity |
| 759 | break |
| 760 | } |
| 761 | if !s.active && ev.Kind != "session.init" { |
| 762 | e = errProtocol |
| 763 | break |
| 764 | } |
| 765 | ev.TurnID = s.turn.ID |
| 766 | if ev.Kind == "session.init" { |
| 767 | e = l.validateInit(s, ev.Payload) |
| 768 | if e != nil { |
| 769 | break |
| 770 | } |
| 771 | } |
| 772 | if ev.Kind == "turn.completed" || ev.Kind == "turn.failed" { |
| 773 | endErr := s.lease.EndTurn(context.Background()) |
| 774 | s.active = false |
| 775 | if endErr != nil && !errors.Is(endErr, provider.ErrRefreshPending) { |
| 776 | e = endErr |
| 777 | break |
| 778 | } |
| 779 | s.finished = ev.Kind == "turn.completed" |
| 780 | if !s.finished { |
| 781 | e = errFailed |
| 782 | } |
| 783 | } |
| 784 | } |
| 785 | } |
| 786 | if e != nil { |
| 787 | s.err = e |
| 788 | s.cancel() |
| 789 | } |
| 790 | l.mu.Unlock() |
| 791 | if e != nil { |
| 792 | goto finished |
| 793 | } |
| 794 | for _, ev := range events { |
| 795 | select { |
| 796 | case s.events <- ev: |
| 797 | case <-s.ctx.Done(): |
| 798 | goto finished |
| 799 | } |
| 800 | } |
| 801 | } |
| 802 | } |
| 803 | finished: |
| 804 | waitCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 805 | defer cancel() |
| 806 | var captureErr error |
| 807 | select { |
| 808 | case captureErr = <-s.capture.Done: |
| 809 | case <-waitCtx.Done(): |
| 810 | captureErr = waitCtx.Err() |
| 811 | } |
| 812 | exit, waitErr := s.process.Wait(waitCtx) |
| 813 | l.mu.Lock() |
| 814 | if s.active { |
| 815 | s.lease.EndTurn(context.Background()) |
| 816 | s.active = false |
| 817 | if s.err == nil { |
| 818 | s.err = errUncertain |
| 819 | } |
| 820 | } |
| 821 | if captureErr != nil || waitErr != nil || exit.Code != 0 || exit.Signal != 0 { |
| 822 | if s.err == nil { |
| 823 | s.err = errFailed |
| 824 | } |
| 825 | } |
| 826 | s.clean = s.closed && s.err == nil && s.finished |
| 827 | failed := s.err != nil |
| 828 | payload := failurePayload(s, lastFrame, exit, waitErr) |
| 829 | l.mu.Unlock() |
| 830 | if failed { |
| 831 | select { |
| 832 | case s.events <- provider.Event{SessionID: s.session.ID, TurnID: s.turn.ID, Kind: "turn.failed", Payload: payload}: |
| 833 | default: |
| 834 | } |
| 835 | } |
| 836 | s.cancel() |
| 837 | } |
| 838 | func (l *Launcher) validateInit(s *sessionState, raw []byte) error { |
| 839 | return ValidateInit(s.launch.Policy, s.session.Model, raw) |
| 840 | } |
| 841 | |
| 842 | // ValidateInit checks a system/init frame against the launch policy: the |
| 843 | // pinned version, model, permission mode, no skills, only the bundled |
| 844 | // plugins, exactly the policy's tools and only the Equipo MCP server. |
| 845 | func ValidateInit(p provider.Policy, model string, raw []byte) error { |
| 846 | var v struct { |
| 847 | Version string `json:"claude_code_version"` |
| 848 | Model string `json:"model"` |
| 849 | Permission string `json:"permissionMode"` |
| 850 | Tools []string `json:"tools"` |
| 851 | Skills []string `json:"skills"` |
| 852 | Plugins []struct{ Name, Path, Source string } `json:"plugins"` |
| 853 | Servers []struct{ Name, Status string } `json:"mcp_servers"` |
| 854 | } |
| 855 | var m manifest |
| 856 | if json.Unmarshal(p.Manifest, &m) != nil { |
| 857 | return provider.ErrPolicy |
| 858 | } |
| 859 | if json.Unmarshal(raw, &v) != nil || v.Version != Version || v.Model != provider.LaunchModel(m.Action, "claude", model) || v.Permission != "default" || len(v.Skills) != 0 { |
| 860 | return provider.ErrPolicy |
| 861 | } |
| 862 | // These two plugins are bundled into the pinned executable, not loaded homes. |
| 863 | for _, p := range v.Plugins { |
| 864 | if p.Path != "builtin" || (p.Name != "cc-plugin-agents-md" && p.Name != "cc-plugin-plugin-authoring") || p.Source != p.Name+"@builtin" { |
| 865 | return provider.ErrPolicy |
| 866 | } |
| 867 | } |
| 868 | // The pinned CLI hides the permission callback from model-visible tools. |
| 869 | want := slices.DeleteFunc(slices.Clone(m.Tools), func(tool string) bool { return tool == "mcp__equipo__permission" }) |
| 870 | sort.Strings(want) |
| 871 | sort.Strings(v.Tools) |
| 872 | if !reflect.DeepEqual(want, v.Tools) || len(v.Servers) != 1 || v.Servers[0].Name != "equipo" || v.Servers[0].Status != "connected" { |
| 873 | return provider.ErrPolicy |
| 874 | } |
| 875 | // A Research step reports exactly its two Equipo tools and no native |
| 876 | // tool, whatever the manifest it was handed lists. |
| 877 | if provider.ResearchAction(m.Action) { |
| 878 | research := []string{} |
| 879 | for _, tool := range provider.ResearchTools() { |
| 880 | research = append(research, "mcp__equipo__"+tool) |
| 881 | } |
| 882 | sort.Strings(research) |
| 883 | if !reflect.DeepEqual(research, v.Tools) { |
| 884 | return provider.ErrPolicy |
| 885 | } |
| 886 | } |
| 887 | return nil |
| 888 | } |
| 889 | |
| 890 | func probeDiagnostic(exit provider.Exit, cap *provider.Capture, cause error) error { |
| 891 | line := "" |
| 892 | if cap.Diagnostics != nil { |
| 893 | line = strings.SplitN(cap.Diagnostics(), "\n", 2)[0] |
| 894 | } |
| 895 | return fmt.Errorf("%w: exit=%d signal=%d stderr=%s: %v", errFailed, exit.Code, exit.Signal, line, cause) |
| 896 | } |
| 897 | |
| 898 | // ExecutableDigest is the pinned file digest of /opt/claude in a policy. |
| 899 | func ExecutableDigest(p provider.Policy) string { |
| 900 | var m manifest |
| 901 | if json.Unmarshal(p.Manifest, &m) != nil { |
| 902 | return "" |
| 903 | } |
| 904 | for _, f := range m.Files { |
| 905 | if f.Mount.Target == "/opt/claude" { |
| 906 | return f.SHA256 |
| 907 | } |
| 908 | } |
| 909 | return "" |
| 910 | } |
| 911 | |