package claude import ( "bytes" "context" "crypto/rand" "encoding/json" "errors" "fmt" "path/filepath" "reflect" "slices" "sort" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/runner/provider" ) const Version = provider.ClaudeVersion const ExecutableSHA256 = "4f4178ce41d83e23341ebfbaecdbcf8ea6bf7baea0690025abe49eeec3a5d01d" const errNotReady provider.Error = "claude_not_ready" const errUncertain provider.Error = "claude_turn_uncertain" const errFailed provider.Error = "claude_process_failed" const helper = "/opt/equipo-tool-proxy" var _ provider.Launcher = (*Launcher)(nil) type Launcher struct { host provider.ProcessHost captures provider.CaptureFactory digest string mu sync.Mutex sessions map[string]*sessionState } type sessionState struct { permissions map[string]*pendingPermission session provider.Session launch provider.Launch base provider.Policy lease *provider.AccountLease process provider.Process capture *provider.Capture ctx context.Context cancel context.CancelFunc events chan provider.Event done chan struct{} attached, active, finished, closed, clean bool turn provider.Turn used map[string]bool err error } type manifest struct { Action string AuthHost string CredentialHome string Argv []string Files []struct { Mount provider.Mount SHA256 string } Instructions []struct { Mount provider.Mount SHA256 string } DeniedPaths, EgressHosts, Tools []string ProviderVersion, LauncherVersion, BwrapVersion, Workspace, Scratch string Settings, MCP, ThreadPolicy, TurnPolicy json.RawMessage Env map[string]string // A Mac launch's roots (native.go); a Linux manifest has none. NativeRoots } type threadPolicy struct { Specialist string `json:"specialist"` Model string `json:"model"` Start string `json:"start"` Resume string `json:"resume"` } func New(host provider.ProcessHost, captures provider.CaptureFactory) (*Launcher, error) { if missing(host) || missing(captures) { return nil, errNotReady } return &Launcher{host: host, captures: captures, digest: ExecutableSHA256, sessions: map[string]*sessionState{}}, nil } func missing(v any) bool { if v == nil { return true } r := reflect.ValueOf(v) switch r.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: return r.IsNil() } return false } // AuthStatusArgs returns a fresh copy of the exact document-framed auth command. func AuthStatusArgs() []string { return []string{"/opt/claude", "--setting-sources", "", "--settings", provider.SettingsPath, "--strict-mcp-config", "--mcp-config", provider.MCPPath, "--disable-slash-commands", "auth", "status", "--json"} } // AssistEffort is the Assistant's effort level (the pinned CLI's // --effort: low, medium, high, xhigh). const AssistEffort = "low" // GlanceModel is the small model a glance runs (provider.LaunchModel). const GlanceModel = provider.ClaudeGlanceModel func baseArgs(model, tools string) []string { 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} } func nativeTools(role string) ([]string, error) { switch role { case "Engineering", "Copy", "Design": return []string{"Bash", "Read", "Write", "Edit", "Glob", "Grep"}, nil case "Coordinator", provider.ResearchSpecialist, provider.GlanceSpecialist: // The Research step and a glance read only their prompt: --tools "". return []string{}, nil case "Review", "Product", "Scope", "Research": return []string{"Read", "Glob", "Grep", "Bash"}, nil case "Reviewer", "Answerer": return []string{"Read", "Glob", "Grep"}, nil } return nil, provider.ErrPolicy } // PolicyInputs renders the provider policy before the runner calls BuildPolicy. // Tools may contain additional explicitly registered Equipo MCP tool names. // assistMCP is the Assistant's tool set (provider.AssistTools) as MCP // names, so a tool added there needs no second list here. var assistMCP = func() []string { out := []string{} for _, t := range provider.AssistTools() { out = append(out, "mcp__equipo__"+t) } return out }() func PolicyInputs(b provider.Binding, in provider.PolicyInputs, specialist, model string) (provider.PolicyInputs, error) { if in.Action != "" { profile, err := provider.Profile(in.Action) if err != nil || !profile.AcceptsTools(in.Tools) || (specialist != profile.Specialist && !(in.Action == "reproduce" && specialist == "Product")) { return in, provider.ErrPolicy } } native, e := nativeTools(specialist) if e != nil || model == "" || strings.HasPrefix(model, "-") { return in, provider.ErrPolicy } tools := append(append([]string{}, native...), "mcp__equipo__permission") for _, tool := range in.Tools { 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) assist := in.Action == "assist" && slices.Contains(assistMCP, tool) answer := in.Action == "answer" && slices.Contains([]string{"mcp__equipo__git_log", "mcp__equipo__git_diff", "mcp__equipo__git_show"}, tool) research := provider.ResearchAction(in.Action) && slices.Contains([]string{"mcp__equipo__submit_findings", "mcp__equipo__keep_image"}, tool) // render_page only for the Design step (profile.AcceptsTools has // already held it to exactly design-v1's three tools). design := provider.DesignAction(in.Action) && slices.Contains(provider.DesignMCPTools(), tool) 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) { return in, provider.ErrPolicy } tools = append(tools, tool) } denied := append([]string{}, in.DeniedPaths...) denied = append(denied, b.CredentialHome, b.Home, b.RuntimeRoot, "/home/runner", "/egress", "/tool", "/tool/equipo.sock", "/config", "/proc", "/dev/fd") sort.Strings(denied) denied = compact(denied) // Host-home aliases are absent from /workspace and cannot be approved. settingsDenied := compact(append(append([]string{}, denied...), "/home")) nativeDenies, e := NativeDenyRules(settingsDenied) if e != nil { return in, e } // The Design step reads its captures at /render and writes nothing // there: Write and Edit are denied it, as is every write in the // sandbox (containment binds it read-only too). Reads are its // callback's (DesignPermission). var readOnly []string if provider.DesignAction(in.Action) { readOnly = provider.DesignReadOnly() } for _, path := range readOnly { if !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "*?[]()\n\r") { return in, provider.ErrPolicy } for _, tool := range []string{"Write", "Edit"} { nativeDenies = append(nativeDenies, tool+"(/"+path+")", tool+"(/"+path+"/**)") } } allow := append([]string{}, in.Tools...) // No shell command is reserved: ordinary sandboxed Bash commands run // without a prompt, and no command's text is evidence of anything. // (Two printf "control" commands once were; the live-gate harness // that read them left with the certification evidence, bbf490ed.) ask := []string{} for _, tool := range native { if slices.Contains([]string{"Write", "Edit", "Read", "Glob", "Grep"}, tool) { ask = append(ask, tool+"(//workspace/**)") } } // Every Bash command runs in the CLI's sandbox: in the pinned CLI a // new user and PID namespace with a fresh /proc, so it cannot name the // CLI or read its environment, where a token connection's token is. // The CLI binds the inherited /proc only when // sandbox.enableWeakerNestedSandbox is true; it is left at its false // default (adding the key would change the certified policy hashes), // and validatePolicy refuses settings that differ from these. settings := map[string]any{ "env": map[string]string{"MCP_TOOL_TIMEOUT": "600000"}, "disableAllHooks": true, "enabledPlugins": map[string]any{"agents-md@builtin": false, "plugin-authoring@builtin": false}, "autoMemoryEnabled": false, "autoDreamEnabled": false, "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{}}}, "permissions": map[string]any{"deny": nativeDenies, "allow": allow, "ask": ask}, } if in.Action != "" { p, _ := provider.Profile(in.Action) if p.ReadOnly { settings["sandbox"].(map[string]any)["filesystem"].(map[string]any)["denyWrite"] = append(append([]string{}, settingsDenied...), "/workspace") } } if provider.CoordinatorAction(in.Action) { settings["permissions"].(map[string]any)["allow"] = []string{} } if in.Action == "converse" || in.Action == "assist" { // Exactly the conversation's Equipo tools run without a prompt; // the instance authorises each call. Nothing else is allowed. settings["permissions"].(map[string]any)["allow"] = append([]string{}, in.Tools...) } in.Settings, _ = json.Marshal(settings) in.MCP = json.RawMessage(`{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}`) in.ThreadPolicy, _ = json.Marshal(threadPolicy{specialist, model, "session-id", "resume"}) in.TurnPolicy = json.RawMessage(`{}`) in.Tools = tools in.DeniedPaths = denied in.ProviderVersion = Version // The thread policy keeps the bound model (the session's identity); // only a glance launches another, its provider's small model. in.Argv = baseArgs(provider.LaunchModel(in.Action, "claude", model), strings.Join(native, ",")) // The coordinator and an answering session stream their text. if provider.CoordinatorAction(in.Action) || specialist == "Coordinator" || in.Action == "answer" { in.Argv = append(in.Argv, "--include-partial-messages") } // The Assistant answers a person who is waiting: the lowest effort // on the connection's own model. Its model is the person's choice and // stays as bound; the team's launches keep the CLI's default effort. if in.Action == "assist" { in.Argv = append(in.Argv, "--effort", AssistEffort) } return in, nil } func compact(v []string) []string { out := []string{} for _, s := range v { if s != "" && (len(out) == 0 || out[len(out)-1] != s) { out = append(out, s) } } return out } func policyInputs(p provider.Policy) (provider.PolicyInputs, manifest, error) { var m manifest if !uniqueJSON(p.Manifest) || json.Unmarshal(p.Manifest, &m) != nil { return provider.PolicyInputs{}, m, provider.ErrPolicy } 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{}} for _, automatic := range []string{m.CredentialHome, "/home/runner"} { for i, path := range in.DeniedPaths { if path == automatic { in.DeniedPaths = append(append([]string{}, in.DeniedPaths[:i]...), in.DeniedPaths[i+1:]...) break } } } for _, f := range m.Files { in.RuntimeFiles = append(in.RuntimeFiles, f.Mount) } for _, f := range m.Instructions { in.InstructionFiles = append(in.InstructionFiles, f.Mount) } for _, key := range []string{"LANG", "LC_ALL", "TERM"} { if v, ok := m.Env[key]; ok { in.Env[key] = v } } return in, m, nil } func (l *Launcher) validatePolicy(b provider.Binding, p provider.Policy) (provider.PolicyInputs, error) { in, m, e := policyInputs(p) if e != nil { return in, e } if b.Provider != "claude" || b.Expected.ProviderVersion != Version || in.ProviderVersion != Version { return in, provider.ErrVersion } if e = p.ValidateSources(b); e != nil { return in, e } var tp threadPolicy if json.Unmarshal(in.ThreadPolicy, &tp) != nil { return in, provider.ErrPolicy } native, e := nativeTools(tp.Specialist) if e != nil { return in, e } if len(in.Tools) < len(native)+1 || !reflect.DeepEqual(in.Tools[:len(native)], native) || in.Tools[len(native)] != "mcp__equipo__permission" { return in, provider.ErrPolicy } expectedIn := in expectedIn.Tools = append([]string{}, in.Tools[len(native)+1:]...) expected, e := PolicyInputs(b, expectedIn, tp.Specialist, tp.Model) if e != nil { return in, e } for _, pair := range [][2]json.RawMessage{{in.Settings, expected.Settings}, {in.MCP, expected.MCP}, {in.ThreadPolicy, expected.ThreadPolicy}, {in.TurnPolicy, expected.TurnPolicy}} { if !sameJSON(pair[0], pair[1]) { return in, provider.ErrPolicy } } if !reflect.DeepEqual(in.Argv, expected.Argv) || !reflect.DeepEqual(in.Tools, expected.Tools) { return in, provider.ErrPolicy } for _, file := range in.InstructionFiles { if strings.HasPrefix(file.Target, "/etc/") && file.Target != "/etc/claude-code/CLAUDE.md" { return in, provider.ErrPolicy } } found := false helperFound := false for _, f := range m.Files { if strings.HasPrefix(f.Mount.Target, "/etc/") { return in, provider.ErrPolicy } if f.Mount.Target == helper { helperFound = true } if f.Mount.Target == "/opt/claude" { found = f.SHA256 == l.digest } } if !helperFound { return in, provider.ErrPolicy } if !found { return in, provider.ErrVersion } 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"} { if p.Env[k] != v { return in, provider.ErrPolicy } } // Rebuilding validates every manifest input and the lease's generated files. rebuilt, e := provider.BuildPolicy(b, in) if e != nil || rebuilt.Hash != p.Hash || rebuilt.ManifestHash != p.ManifestHash { return in, provider.ErrPolicy } return in, nil } func sameJSON(a, b []byte) bool { var x, y any return json.Unmarshal(a, &x) == nil && json.Unmarshal(b, &y) == nil && reflect.DeepEqual(x, y) } func uuid() string { var b [16]byte if _, e := rand.Read(b[:]); e != nil { panic(e) } b[6] = (b[6] & 15) | 64 b[8] = (b[8] & 63) | 128 return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) } func (l *Launcher) Preflight(ctx context.Context, b provider.Binding, p provider.Policy) (provider.Identity, error) { lease, e := b.AccountLease() if e != nil { return provider.Identity{}, e } in, e := l.validatePolicy(b, p) if e != nil { return provider.Identity{}, e } return l.preflight(ctx, b, lease, in) } func (l *Launcher) preflight(ctx context.Context, b provider.Binding, lease *provider.AccountLease, in provider.PolicyInputs) (provider.Identity, error) { var e error var observed provider.Identity probe := func(ctx context.Context, b provider.Binding) (provider.Identity, error) { var e error observed, e = l.probeIdentity(ctx, b, in) return observed, e } if e = lease.Validate(ctx); errors.Is(e, provider.ErrRefreshPending) { return observed, provider.ErrAccountMaintenance } if e = lease.Preflight(ctx, probe); e != nil { return observed, e } // Closing stdin proves dependency availability without supplying a user turn. args := append(append([]string{}, in.Argv...), "--session-id", uuid()) if _, e = l.probe(ctx, b, in, args); e != nil { return observed, e } _, e = provider.BuildPolicy(b, in) return observed, e } func (l *Launcher) probeIdentity(ctx context.Context, b provider.Binding, in provider.PolicyInputs) (provider.Identity, error) { frames, e := l.probe(ctx, b, in, AuthStatusArgs()) if e != nil { return provider.Identity{}, e } if len(frames) != 1 { return provider.Identity{}, provider.ErrIdentity } return provider.ClaudeLoginIdentity(frames[0]) } func (l *Launcher) probe(ctx context.Context, b provider.Binding, in provider.PolicyInputs, args []string) ([][]byte, error) { ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() in.Argv = args p, e := provider.BuildPolicy(b, in) if e != nil { return nil, e } launch := provider.Launch{AttemptKey: "claude-preflight-" + uuid(), Workspace: in.Workspace, Binding: b, Policy: p, Selection: provider.Selection{Provider: "claude", AccountID: b.AccountID}} proc, e := l.host.Start(ctx, launch, args) if e != nil { return nil, e } defer func() { cancel() waitCtx, stop := context.WithTimeout(context.Background(), 5*time.Second) defer stop() proc.Wait(waitCtx) }() cap, e := l.captures.Open(ctx, proc, launch) if e != nil { cancel() proc.Wait(context.Background()) return nil, e } if cap == nil || cap.Input == nil || cap.Frames == nil || cap.Done == nil { cancel() proc.Wait(context.Background()) return nil, errNotReady } if e = cap.Input.Close(); e != nil { return nil, e } var frames [][]byte total := 0 for { select { case <-ctx.Done(): return nil, ctx.Err() case f, ok := <-cap.Frames: if !ok { goto drained } total += len(f.Bytes) if total > MaxFrameBytes || !uniqueJSON(f.Bytes) { return nil, errProtocol } frames = append(frames, bytes.Clone(f.Bytes)) } } drained: select { case e = <-cap.Done: if e != nil { exit, _ := proc.Wait(ctx) return nil, probeDiagnostic(exit, cap, e) } case <-ctx.Done(): return nil, ctx.Err() } exit, e := proc.Wait(ctx) if e != nil || exit.Code != 0 || exit.Signal != 0 { return nil, probeDiagnostic(exit, cap, e) } for _, raw := range frames { var v struct { Type string `json:"type"` Error bool `json:"is_error"` } json.Unmarshal(raw, &v) if v.Type == "result" || v.Error { return nil, probeDiagnostic(exit, cap, errFailed) } } return frames, nil } func (l *Launcher) Open(ctx context.Context, launch provider.Launch) (provider.Session, error) { l.mu.Lock() defer l.mu.Unlock() if launch.AttemptKey == "" || l.sessions[launch.AttemptKey] != nil { return provider.Session{}, errNotReady } for _, prior := range l.sessions { if prior.launch.Binding == launch.Binding && !prior.closed { return provider.Session{}, provider.ErrAccountBusy } } in, e := l.validatePolicy(launch.Binding, launch.Policy) if e != nil { return provider.Session{}, e } var tp threadPolicy json.Unmarshal(in.ThreadPolicy, &tp) if launch.Selection.Model != tp.Model { return provider.Session{}, provider.ErrIdentity } lease, e := launch.Binding.AccountLease() if e != nil { return provider.Session{}, e } id := uuid() var previous *sessionState if launch.ResumeSessionID != "" { prior := (*sessionState)(nil) for _, s := range l.sessions { if s.session.ID == launch.ResumeSessionID && s.closed && s.clean && s.finished && s.err == nil { prior = s } } if prior == nil || prior.base.Hash != launch.Policy.Hash || prior.launch.Binding != launch.Binding || prior.launch.Selection != launch.Selection { return provider.Session{}, errUncertain } id = launch.ResumeSessionID previous = prior } session := provider.Session{ID: id, AttemptKey: launch.AttemptKey, Provider: launch.Selection.Provider, AccountID: launch.Selection.AccountID, Model: launch.Selection.Model, Family: launch.Selection.Family} if e = session.Validate(launch); e != nil { return provider.Session{}, e } if _, e = l.preflight(ctx, launch.Binding, lease, in); e != nil { return provider.Session{}, e } if e = lease.ValidatePolicy(ctx); e != nil { return provider.Session{}, e } base := launch.Policy flag := "--session-id" if launch.ResumeSessionID != "" { flag = "--resume" } args := append(append([]string{}, in.Argv...), flag, id) in.Argv = args launch.Policy, e = provider.BuildPolicy(launch.Binding, in) if e != nil { return provider.Session{}, e } attempt, cancel := context.WithCancel(ctx) process, e := l.host.Start(attempt, launch, args) if e != nil { cancel() return provider.Session{}, e } capture, e := l.captures.Open(attempt, process, launch) if e != nil { cancel() process.Wait(context.Background()) return provider.Session{}, e } if capture == nil || capture.Input == nil || capture.Frames == nil || capture.Done == nil { cancel() process.Wait(context.Background()) return provider.Session{}, errNotReady } if binding, ok := capture.Input.(provider.SessionBinding); ok { if e = binding.BindSession(ctx, session); e != nil { cancel() process.Wait(context.Background()) return provider.Session{}, e } } 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{}} if previous != nil { previous.clean = false for key, value := range previous.used { s.used[key] = value } } l.sessions[session.AttemptKey] = s go l.read(s) return session, nil } func (l *Launcher) state(s provider.Session) (*sessionState, error) { v := l.sessions[s.AttemptKey] if v == nil || v.session != s { return nil, provider.ErrIdentity } return v, nil } func (l *Launcher) Events(ctx context.Context, s provider.Session) (<-chan provider.Event, error) { l.mu.Lock() defer l.mu.Unlock() v, e := l.state(s) if e != nil { return nil, e } if e = ctx.Err(); e != nil { return nil, e } if v.attached { return nil, errNotReady } v.attached = true return v.events, nil } func (l *Launcher) StartTurn(ctx context.Context, s provider.Session, t provider.Turn) error { l.mu.Lock() defer l.mu.Unlock() v, e := l.state(s) if e != nil { return e } if v.closed || v.err != nil || v.active || !v.attached || t.ID == "" || t.AdmissionID == "" || v.used[t.ID] || v.used[t.AdmissionID] { return errNotReady } if e = ctx.Err(); e != nil { return e } if e = v.ctx.Err(); e != nil { return e } fail := func(e error) error { v.err = e; v.cancel(); return e } if e = v.lease.ValidatePolicy(ctx); errors.Is(e, provider.ErrRefreshPending) || errors.Is(e, provider.ErrPreflightRequired) { // Rebuild the base policy only after checking the currently mounted sources. if sourceErr := v.launch.Policy.ValidateSources(v.launch.Binding); sourceErr != nil { return fail(sourceErr) } in, _, inputErr := policyInputs(v.base) if inputErr != nil { return fail(inputErr) } base, buildErr := provider.BuildPolicy(v.launch.Binding, in) if buildErr != nil { return fail(buildErr) } if _, e = l.Preflight(ctx, v.launch.Binding, base); e == nil { actual, _, inputErr := policyInputs(v.launch.Policy) if inputErr != nil { return fail(inputErr) } _, e = provider.BuildPolicy(v.launch.Binding, actual) } } if e != nil { return fail(e) } if _, e = provider.AttestLaunch(v.launch, argv(v.launch.Policy)); e != nil { return fail(e) } raw, e := userEnvelope(s.ID, t.Prompt) if e != nil { return e } if e = v.lease.BeginTurn(ctx); e != nil { return fail(e) } v.active = true v.finished = false v.turn = t v.used[t.ID] = true v.used[t.AdmissionID] = true if barrier, ok := v.capture.Input.(provider.TurnBarrier); ok { if e = barrier.BeginTurn(ctx, s, t); e != nil { return fail(e) } } l.mu.Unlock() stopWrite := context.AfterFunc(ctx, func() { v.cancel(); v.capture.Input.Close() }) n, e := v.capture.Input.Write(raw) stopWrite() l.mu.Lock() if e != nil || n != len(raw) || ctx.Err() != nil || v.ctx.Err() != nil { v.err = errUncertain v.cancel() return errUncertain } return nil } func argv(p provider.Policy) []string { var m manifest; json.Unmarshal(p.Manifest, &m); return m.Argv } func (l *Launcher) Respond(ctx context.Context, s provider.Session, a provider.Answer) error { return l.respond(ctx, s, a) } func (l *Launcher) Interrupt(ctx context.Context, s provider.Session) error { l.mu.Lock() defer l.mu.Unlock() v, e := l.state(s) if e != nil { return e } v.err = errUncertain v.cancel() return nil } func (l *Launcher) Close(ctx context.Context, s provider.Session) error { ctx, stop := context.WithTimeout(ctx, 5*time.Second) defer stop() l.mu.Lock() v, e := l.state(s) if e != nil { l.mu.Unlock() return e } if !v.closed { v.closed = true if v.active { v.err = errUncertain v.cancel() } v.capture.Input.Close() } l.mu.Unlock() select { case <-ctx.Done(): v.cancel() return ctx.Err() case <-v.done: } v.cancel() l.mu.Lock() defer l.mu.Unlock() return v.err } func (l *Launcher) read(s *sessionState) { defer close(s.done) defer close(s.events) var sequence int64 lastFrame := "none" for { select { case <-s.ctx.Done(): goto finished case frame, ok := <-s.capture.Frames: if !ok { goto finished } lastFrame = frameCategory(frame.Bytes) l.mu.Lock() var events []provider.Event var e error if frame.Sequence <= sequence { e = errProtocol } else { events, e = Decode(frame.Bytes) } sequence = frame.Sequence if e == nil { for i := range events { ev := &events[i] ev.Sequence = frame.Sequence if ev.SessionID != s.session.ID { e = provider.ErrIdentity break } if !s.active && ev.Kind != "session.init" { e = errProtocol break } ev.TurnID = s.turn.ID if ev.Kind == "session.init" { e = l.validateInit(s, ev.Payload) if e != nil { break } } if ev.Kind == "turn.completed" || ev.Kind == "turn.failed" { endErr := s.lease.EndTurn(context.Background()) s.active = false if endErr != nil && !errors.Is(endErr, provider.ErrRefreshPending) { e = endErr break } s.finished = ev.Kind == "turn.completed" if !s.finished { e = errFailed } } } } if e != nil { s.err = e s.cancel() } l.mu.Unlock() if e != nil { goto finished } for _, ev := range events { select { case s.events <- ev: case <-s.ctx.Done(): goto finished } } } } finished: waitCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() var captureErr error select { case captureErr = <-s.capture.Done: case <-waitCtx.Done(): captureErr = waitCtx.Err() } exit, waitErr := s.process.Wait(waitCtx) l.mu.Lock() if s.active { s.lease.EndTurn(context.Background()) s.active = false if s.err == nil { s.err = errUncertain } } if captureErr != nil || waitErr != nil || exit.Code != 0 || exit.Signal != 0 { if s.err == nil { s.err = errFailed } } s.clean = s.closed && s.err == nil && s.finished failed := s.err != nil payload := failurePayload(s, lastFrame, exit, waitErr) l.mu.Unlock() if failed { select { case s.events <- provider.Event{SessionID: s.session.ID, TurnID: s.turn.ID, Kind: "turn.failed", Payload: payload}: default: } } s.cancel() } func (l *Launcher) validateInit(s *sessionState, raw []byte) error { return ValidateInit(s.launch.Policy, s.session.Model, raw) } // ValidateInit checks a system/init frame against the launch policy: the // pinned version, model, permission mode, no skills, only the bundled // plugins, exactly the policy's tools and only the Equipo MCP server. func ValidateInit(p provider.Policy, model string, raw []byte) error { var v struct { Version string `json:"claude_code_version"` Model string `json:"model"` Permission string `json:"permissionMode"` Tools []string `json:"tools"` Skills []string `json:"skills"` Plugins []struct{ Name, Path, Source string } `json:"plugins"` Servers []struct{ Name, Status string } `json:"mcp_servers"` } var m manifest if json.Unmarshal(p.Manifest, &m) != nil { return provider.ErrPolicy } if json.Unmarshal(raw, &v) != nil || v.Version != Version || v.Model != provider.LaunchModel(m.Action, "claude", model) || v.Permission != "default" || len(v.Skills) != 0 { return provider.ErrPolicy } // These two plugins are bundled into the pinned executable, not loaded homes. for _, p := range v.Plugins { if p.Path != "builtin" || (p.Name != "cc-plugin-agents-md" && p.Name != "cc-plugin-plugin-authoring") || p.Source != p.Name+"@builtin" { return provider.ErrPolicy } } // The pinned CLI hides the permission callback from model-visible tools. want := slices.DeleteFunc(slices.Clone(m.Tools), func(tool string) bool { return tool == "mcp__equipo__permission" }) sort.Strings(want) sort.Strings(v.Tools) if !reflect.DeepEqual(want, v.Tools) || len(v.Servers) != 1 || v.Servers[0].Name != "equipo" || v.Servers[0].Status != "connected" { return provider.ErrPolicy } // A Research step reports exactly its two Equipo tools and no native // tool, whatever the manifest it was handed lists. if provider.ResearchAction(m.Action) { research := []string{} for _, tool := range provider.ResearchTools() { research = append(research, "mcp__equipo__"+tool) } sort.Strings(research) if !reflect.DeepEqual(research, v.Tools) { return provider.ErrPolicy } } return nil } func probeDiagnostic(exit provider.Exit, cap *provider.Capture, cause error) error { line := "" if cap.Diagnostics != nil { line = strings.SplitN(cap.Diagnostics(), "\n", 2)[0] } return fmt.Errorf("%w: exit=%d signal=%d stderr=%s: %v", errFailed, exit.Code, exit.Signal, line, cause) } // ExecutableDigest is the pinned file digest of /opt/claude in a policy. func ExecutableDigest(p provider.Policy) string { var m manifest if json.Unmarshal(p.Manifest, &m) != nil { return "" } for _, f := range m.Files { if f.Mount.Target == "/opt/claude" { return f.SHA256 } } return "" }