oficina / equipo Public

feat: relay direct provider tools and fenced answers

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 64da7c8b90dcf3134dc1afa08b169560c880d038 parent 8c9ecac
39 files changed, +4,853 −38
  • cmd/equipo-runner/main.go +7 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md +1,449 −0
  • internal/equipo/copy.go +2 −0
  • internal/equipo/question_handlers.go +8 −4
  • internal/equipo/task_views.go +7 −1
  • internal/equipo/templates/question.html +1 −1
  • internal/equipotest/questions_test.go +78 −0
  • internal/runner/containment/mounts.go +5 −0
  • internal/runner/containment/tool.go +37 −0
  • internal/runner/containment/tool_test.go +63 −0
  • internal/runner/direct_answer_capture.go +112 −0
  • internal/runner/direct_questions.go +212 −0
  • internal/runner/direct_recovery.go +1 −1
  • internal/runner/direct_recovery_test.go +1 −1
  • internal/runner/direct_tools_test.go +533 −0
  • internal/runner/journal.go +6 −1
  • internal/runner/journal_test.go +1 −1
  • internal/runner/provider/answers.go +29 −0
  • internal/runner/provider/claude/answers.go +183 −0
  • internal/runner/provider/claude/answers_test.go +112 −0
  • internal/runner/provider/claude/launcher.go +6 −4
  • internal/runner/provider/codex/answers.go +223 −0
  • internal/runner/provider/codex/answers_test.go +252 −0
  • internal/runner/provider/codex/events.go +11 −1
  • internal/runner/provider/codex/launcher.go +61 −7
  • internal/runner/provider/codex/launcher_test.go +2 −2
  • internal/runner/provider/codex/rpc.go +73 −0
  • internal/runner/provider/codex/testdata/answers-provenance.json +22 −0
  • internal/runner/provider/codex/testdata/schema-McpServerElicitationRequestParams.json +651 −0
  • internal/runner/provider/codex/testdata/schema-McpServerElicitationRequestResponse.json +29 −0
  • internal/runner/provider/codex/testdata/schema-ToolRequestUserInputParams.json +98 −0
  • internal/runner/provider/codex/testdata/schema-ToolRequestUserInputResponse.json +34 −0
  • internal/runner/provider/types.go +15 −1
  • internal/runner/questions.go +35 −4
  • internal/runner/tool_journal.go +19 −0
  • internal/runner/tool_proxy.go +395 −0
  • internal/runner/tool_socket.go +20 −3
  • internal/runner/tools.go +29 −5
  • internal/runnerproto/questions.go +31 −1

CI failed — run details

diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go
index ebe329eb..a3b8b346 100644
--- a/cmd/equipo-runner/main.go
+++ b/cmd/equipo-runner/main.go
@@ -22,6 +22,13 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu
_, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, code, variable)
return 1
}
+ if len(args) == 2 && args[0] == "--socket" {
+ if runner.ServeToolProxy(ctx, input, output, args[1]) != nil {
+ _, _ = io.WriteString(errorOutput, equipo.CopyToolRejected+"\n")
+ return 1
+ }
+ return 0
+ }
if len(args) != 1 {
return fail(nil)
}
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
index d35bf47c..ce1043a4 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
@@ -14874,3 +14874,1452 @@ No new user-facing strings, error codes or copy.go entries. No pending copy entr
No unresolved findings from this round. The original Task 7 runtime-composition and live-certification boundaries still apply; this fix does not cut over runtime composition or prompt a provider. Full CI and live gates were not run, as instructed. The targeted covering command and the single race command passed, and all 28 mutations compiled and failed as expected. Formatting and git diff --check passed.
Work stayed on plan-2b in the authorized checkout. No agents, provider sessions, credentials, sign-ins, enrolments, model prompts, servers, deployments, pushes, merges, sudo commands or .claude/HANDOFF.md were created. Default Go caches were retained. All test invocations were awaited. Session-owned evidence scratch is removed after the report and commit are saved; no session-started process needs to remain running.
+
+## Task 8: Direct provider tools, permissions and questions
+
+Status: DONE_WITH_CONCERNS.
+Commit subject: `feat: relay direct provider tools and fenced answers`.
+Branch: `plan-2b`. Work stayed in `/home/paulca/amadan.net/oficina/equipo-plan-2b`.
+
+### What was built
+
+`OpenToolProxy(context.Context, ToolBinding)` returns a per-attempt MCP endpoint, the fixed `MCP()` configuration and idempotent `Close()`. The runner keeps the authenticating broker and its random capability in memory outside the namespace. Neither credential files nor a runner bearer are given to the helper. The runner binary supports the fixed helper invocation `/opt/equipo-tool-proxy --socket /tool/equipo.sock`.
+
+The endpoint treats every frame as hostile. It exposes only bound typed reproduce, candidate, review and ask verbs, plus Claude's permission callback when configured. Scope and provider session come from the endpoint binding. Calls repeat current authority, lease, full session identity, durable active-turn, fence, argument and journal admission checks. Approval checks also use the existing submission idempotency key; executing an approved tool repeats the broker checks. Host reads, publishing, check attestations and submitted scope fields have no endpoint operation. Existing legacy ServeTools and broker behavior remain covered by regression tests.
+
+The socket is created through a verified private directory fd, including when the host path exceeds the Unix address limit. Containment imports only the socket inode at `/tool/equipo.sock` through a read-only fd mount. It checks owner, private modes and socket type and refuses symlinks and regular files. The parent directory and capability remain absent from the namespace. Both adapters retain `/tool/equipo.sock`, `/tool` and `/egress` in their inner deny lists. The helper binary must be a hashed read-only runtime mount.
+
+Proxy cancellation, expired or lost leases and direct restart recovery close connections, invalidate the broker and remove the endpoint. Trusted renewal extends the live lease but cannot revive a closed proxy. A pending proxy can be created before provider Open. BindTurn selects the observed session and intended local turn before StartTurn; tool execution remains blocked until durable dispatch. Rebinding cannot replace an active turn.
+
+Claude Permission publishes the original hook request and waits for Launcher.Respond to resolve that same MCP call. It never sends an ordinary prompt. Question answers must cover exactly the original question keys; they are merged into the original input without replacing its questions or options. Native approvals retain the original action and reject unsupported input fields, protected paths and submitted replacements. The specialist native tool lists still exclude AskUserQuestion. Only the four known, explicitly registered Equipo verbs get generated MCP allow rules; their actual calls still pass through the broker.
+
+Codex records server requests separately from client calls, preserving numeric versus string IDs. It answers asynchronous agentMessage.questions with turn/steer and the exact provider expectedTurnId. Schema item/tool/requestUserInput gets the structured answers response. Responses cannot start a new turn. Resolved requests, completed turns, completed MCP items, ambiguous MCP calls and changed requests cannot be answered. The legacy MCP-approval question prefix is refused so a question answer cannot carry a permanent grant.
+
+The actual pinned Codex MCP approval is mcpServer/elicitation/request. The adapter requires form mode, the privileged mcp_tool_call discriminator, an empty approval schema and metadata arguments matching a unique active item/started MCP call. The server and tool name come from that captured item. Only Equipo calls can reach the runner's automatic response, and only after broker validation. Accept replies contain an empty content object and null metadata; advertised persistent options are never returned. Other approvals go through the durable person-question path. Command/file approvals remain deny-only under the conservative policy interpretation below. No automatic reviewer is configured or launched.
+
+DirectQuestionRelay joins provider events and scoped ask calls to the existing instance question and answer contracts. Its Current callback must revalidate the instance question revision, answerer, lease and fence. QuestionRelay journals the answer intent before delivery and now associates it with the direct attempt and turn. Replays with changed content or a different turn fail. The instance still derives actors from verified sessions and rechecks the roster in the write transaction and answer poll.
+
+Capture has a separate AnswerWriter path for correlated replies and steering. It validates the envelope, records intent before stdin, checks the active durable turn and refuses replay, policy amendments and hidden turn/start calls. The additive local journal migration is version 4, with a direct_answer_scopes table; existing receipts and legacy outboxes are retained. interruptDirect invalidates only pending answers associated with the cancelled attempt. The regression test creates active attempts A and B, leaves both answers pending, cancels A and verifies that B remains dispatched and its answer remains pending. Restart recovery still invalidates every pending answer, as required.
+
+The browser now offers Allow once for a current native Claude request that Question.ValidateAnswer permits. It accepts an approval without inventing answer fields, rejects unsupported grants and retains the session-derived actor and transactional authority checks. This uses one new pending copy entry.
+
+### Interpretations and integration contract
+
+1. Codex's brief names the approval behavior, not an MCP RPC spelling. The pinned public source and schema use mcpServer/elicitation/request, not item/mcpToolCall/requestApproval. An early synthetic test used the latter; it was replaced after checking the pinned source. The final implementation has no invented MCP approval method. Four pinned schema fixtures and their source hashes are committed. Since approval metadata does not reliably supply a tool name, the adapter correlates it with a captured live MCP item. Missing, changed or ambiguous evidence refuses automatic approval.
+2. Native Codex command/file approval can grant execution outside the inner sandbox or a wider file root. No certified safe subset is established in this task's pinned evidence. Such requests are shown to a person but cannot receive accept, even from an allow answer. Deny is supported. This serves the brief's requirement that a person cannot broaden the certified outer/inner policy. Additional native approval forms require explicit certification and tests.
+3. Runtime composition remains Task 9. The caller opens the proxy with the attempt authority, supplies Launch.ToolSocket, mounts the runner binary at the fixed helper path and uses the returned MCP shape when building policy. After Open establishes identity, it calls BindTurn before StartTurn, attaches the event consumer, routes requests through DirectQuestionRelay and wires the authenticated instance question callback and Current revalidation. It renews the proxy with the lease and closes it with the attempt. Permission is bound to claude.Launcher.Permission; an Ask callback can return the scoped person's answer through that MCP call. Existing ToolSubmissions/AckTool processing remains the durable delivery path; wiring must not independently ask the same question a second time.
+4. The small containment extension and AnswerWriter contract are necessary to make the relay usable with the existing namespace and capture implementations. The original containment mount allowlist rejected sockets, and ordinary capture stdin intentionally rejects answer frames. These are separate narrow paths, not general mount or RPC escape hatches. The browser extension is also necessary: the prior form rejected every allow answer without text fields.
+5. Pending capabilities can be bound before prompt dispatch, but no operation can run until the captured admission is dispatched. This avoids a race where a provider makes its first tool call before StartTurn returns.
+6. The dispatch rules override generic delegation, copy-review and handoff workflows. No agents or model-based writing tools were used, no review server was started and no .claude/HANDOFF.md was created.
+
+Pinned primary sources used to settle wire details:
+
+- [https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts](https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts)
+- [https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/core/src/mcp_tool_call.rs](https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/core/src/mcp_tool_call.rs)
+- [https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/protocol/src/mcp_approval_meta.rs](https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/protocol/src/mcp_approval_meta.rs)
+- [https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/features/src/lib.rs](https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/features/src/lib.rs)
+
+### Files
+
+- `cmd/equipo-runner/main.go`
+- `internal/equipo/copy.go`
+- `internal/equipo/question_handlers.go`
+- `internal/equipo/task_views.go`
+- `internal/equipo/templates/question.html`
+- `internal/equipotest/questions_test.go`
+- `internal/runner/containment/mounts.go`
+- `internal/runner/direct_recovery.go`
+- `internal/runner/direct_recovery_test.go`
+- `internal/runner/journal.go`
+- `internal/runner/journal_test.go`
+- `internal/runner/provider/claude/launcher.go`
+- `internal/runner/provider/codex/events.go`
+- `internal/runner/provider/codex/launcher.go`
+- `internal/runner/provider/codex/launcher_test.go`
+- `internal/runner/provider/codex/rpc.go`
+- `internal/runner/provider/types.go`
+- `internal/runner/questions.go`
+- `internal/runner/tool_journal.go`
+- `internal/runner/tool_socket.go`
+- `internal/runner/tools.go`
+- `internal/runnerproto/questions.go`
+- `internal/runner/containment/tool.go`
+- `internal/runner/containment/tool_test.go`
+- `internal/runner/direct_answer_capture.go`
+- `internal/runner/direct_questions.go`
+- `internal/runner/direct_tools_test.go`
+- `internal/runner/provider/answers.go`
+- `internal/runner/provider/claude/answers.go`
+- `internal/runner/provider/claude/answers_test.go`
+- `internal/runner/provider/codex/answers.go`
+- `internal/runner/provider/codex/answers_test.go`
+- `internal/runner/provider/codex/testdata/answers-provenance.json`
+- `internal/runner/provider/codex/testdata/schema-McpServerElicitationRequestParams.json`
+- `internal/runner/provider/codex/testdata/schema-McpServerElicitationRequestResponse.json`
+- `internal/runner/provider/codex/testdata/schema-ToolRequestUserInputParams.json`
+- `internal/runner/provider/codex/testdata/schema-ToolRequestUserInputResponse.json`
+- `internal/runner/tool_proxy.go`
+
+The controller section and this ignored task report contain the evidence. No README, application database migration or vendored asset changed.
+
+### RED evidence
+
+Commands ran from the authorized checkout with the supplied on-disk TMPDIR, CGO_ENABLED=0 and default Go caches. Exit status was 1 for these red commands. Initial API reds are recorded separately from behavioral guard evidence. The first combined run exposed missing APIs; its unbounded synthetic Codex waiter was terminated, then corrected to use a bounded wait. The following isolated Codex red compiled and failed because Respond returned codex_not_ready. No terminated or noncompiling run is counted as mutation proof.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/equipotest ./internal/runner/provider/... -run 'TestDirectTool|TestClaudePermission|TestCodexApproval|TestCodexAsyncQuestion|TestDirectStaleAnswer|TestToolProxy' -count=1
+```
+
+```text
+# amadan.net/oficina/equipo/internal/runner/provider/claude [amadan.net/oficina/equipo/internal/runner/provider/claude.test]
+internal/runner/provider/claude/answers_test.go:17:21: f.l.Permission undefined (type *Launcher has no field or method Permission)
+# amadan.net/oficina/equipo/internal/runner [amadan.net/oficina/equipo/internal/runner.test]
+internal/runner/direct_tools_test.go:26:32: unknown field Session in struct literal of type ToolBinding
+internal/runner/direct_tools_test.go:26:43: unknown field TurnID in struct literal of type ToolBinding
+internal/runner/direct_tools_test.go:30:7: undefined: OpenToolProxy
+internal/runner/direct_tools_test.go:43: b.Session undefined (type ToolBinding has no field or method Session)
+internal/runner/direct_tools_test.go:48:31: undefined: OpenToolProxy
+internal/runner/direct_tools_test.go:60:7: undefined: openToolProxy
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run 'TestCodexApproval|TestCodexAsyncQuestion' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponse (0.42s)
+ --- FAIL: TestCodexApprovalResponse/item/commandExecution/requestApproval (0.14s)
+ answers_test.go:29: codex_not_ready
+ --- FAIL: TestCodexApprovalResponse/item/fileChange/requestApproval (0.14s)
+ answers_test.go:29: codex_not_ready
+ --- FAIL: TestCodexApprovalResponse/item/mcpToolCall/requestApproval (0.13s)
+ answers_test.go:29: codex_not_ready
+--- FAIL: TestCodexAsyncQuestionAnswer (0.26s)
+ --- FAIL: TestCodexAsyncQuestionAnswer/async (0.13s)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/runner/provider/codex ./internal/runner/containment -run 'TestDirectToolAnswerCapture|TestCodexApprovalResponseRouting|TestCodexApprovalResponseFixedMCPPolicy|TestDirectToolMount' -count=1
+```
+
+```text
+# amadan.net/oficina/equipo/internal/runner/containment [amadan.net/oficina/equipo/internal/runner/containment.test]
+internal/runner/containment/tool_test.go:6:38: p.bindTool undefined (type *mounts has no field or method bindTool)
+internal/runner/containment/tool_test.go:8: q.bindTool undefined (type *mounts has no field or method bindTool)
+# amadan.net/oficina/equipo/internal/runner [amadan.net/oficina/equipo/internal/runner.test]
+internal/runner/direct_tools_test.go:238:16: input.WriteAnswer undefined (type *captureInput has no field or method WriteAnswer)
+internal/runner/direct_tools_test.go:239:38: input.WriteAnswer undefined (type *captureInput has no field or method WriteAnswer)
+internal/runner/direct_tools_test.go:240:178: input.WriteAnswer undefined (type *captureInput has no field or method WriteAnswer)
+internal/runner/direct_tools_test.go:241:73: input.WriteAnswer undefined (type *captureInput has no field or method WriteAnswer)
+internal/runner/direct_tools_test.go:249:9: undefined: DirectQuestionRelay
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestToolProxyLifecycle|TestCodexApprovalResponseChangedOriginal' -count=1
+```
+
+```text
+# amadan.net/oficina/equipo/internal/runner [amadan.net/oficina/equipo/internal/runner.test]
+internal/runner/direct_tools_test.go:265:152: p.BindTurn undefined (type *ToolProxy has no field or method BindTurn)
+FAIL amadan.net/oficina/equipo/internal/runner [build failed]
+FAIL
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/runner/provider/claude -run 'TestClaudePermissionResponseNativePolicy|TestDirectStaleAnswerTurnAssociation' -count=1
+```
+
+```text
+--- FAIL: TestDirectStaleAnswerTurnAssociation (0.32s)
+ direct_tools_test.go:298: previous turn answer reused in replacement turn
+FAIL
+rastrillo-budget/v1 ran 322ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.325s
+--- FAIL: TestClaudePermissionResponseNativePolicy (0.10s)
+ answers_test.go:77: native policy widened {"file_path":"/workspace/a","content":"hi","policyAmendment":true}
+FAIL
+rastrillo-budget/v1 ran 102ms
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/runner/provider/codex -run 'TestCodexApprovalResponse' -count=1
+```
+
+```text
+# amadan.net/oficina/equipo/internal/runner [amadan.net/oficina/equipo/internal/runner.test]
+internal/runner/direct_tools_test.go:305:5: ev.ToolCall undefined (type provider.Event has no field or method ToolCall)
+FAIL amadan.net/oficina/equipo/internal/runner [build failed]
+--- FAIL: TestCodexApprovalResponse (0.42s)
+ --- FAIL: TestCodexApprovalResponse/mcpServer/elicitation/request (0.14s)
+ answers_test.go:58: provider_policy_rejected
+--- FAIL: TestCodexApprovalResponseValidatedMCP (0.14s)
+ answers_test.go:141: provider_policy_rejected
+FAIL
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectToolScopedAskAnswer -count=1
+```
+
+```text
+# amadan.net/oficina/equipo/internal/runner [amadan.net/oficina/equipo/internal/runner.test]
+internal/runner/direct_tools_test.go:312:4: b.Ask undefined (type ToolBinding has no field or method Ask)
+internal/runner/direct_tools_test.go:314:15: relay.Ask undefined (type DirectQuestionRelay has no field or method Ask)
+FAIL amadan.net/oficina/equipo/internal/runner [build failed]
+FAIL
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestToolProxyBindBeforeDispatch -count=1
+```
+
+```text
+--- FAIL: TestToolProxyBindBeforeDispatch (0.09s)
+ direct_tools_test.go:439: runner.invalid
+FAIL
+rastrillo-budget/v1 ran 86ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.088s
+FAIL
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestCodexApprovalResponseIdempotency|TestToolProxyBindingIdentity' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseIdempotency (0.09s)
+ direct_tools_test.go:456: changed replay arguments approved
+--- FAIL: TestToolProxyBindingIdentity (0.34s)
+ --- FAIL: TestToolProxyBindingIdentity/account (0.09s)
+ direct_tools_test.go:462: mismatched bound identity account
+ --- FAIL: TestToolProxyBindingIdentity/model (0.09s)
+ direct_tools_test.go:462: mismatched bound identity model
+ --- FAIL: TestToolProxyBindingIdentity/provider (0.09s)
+ direct_tools_test.go:462: mismatched bound identity provider
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run TestCodexApprovalResponseNoQuestionFallback -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseNoQuestionFallback (0.24s)
+ answers_test.go:247: permission amendment through question fallback
+FAIL
+rastrillo-budget/v1 ran 240ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.242s
+FAIL
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestToolProxyRenewedLease -count=1
+```
+
+```text
+# amadan.net/oficina/equipo/internal/runner [amadan.net/oficina/equipo/internal/runner.test]
+internal/runner/direct_tools_test.go:501:18: p.RenewLease undefined (type *ToolProxy has no field or method RenewLease)
+internal/runner/direct_tools_test.go:504:32: p.RenewLease undefined (type *ToolProxy has no field or method RenewLease)
+FAIL amadan.net/oficina/equipo/internal/runner [build failed]
+FAIL
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run TestClaudePermissionResponseScopedMCPPolicy -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponseScopedMCPPolicy (0.17s)
+ answers_test.go:99: scoped MCP would fall through native permission hook {"disableAllHooks":true,"enabledPlugins":{},"permissions":{"deny":["Read(//alias/login)","Read(//alias/login/**)","Write(//alias/login)","Write(//alias/login/**)","Edit(//alias/login)","Edit(//alias/login/**)","Glob(//alias/login)","Glob(//alias/login/**)","Grep(//alias/lo ... [line shortened]
+FAIL
+rastrillo-budget/v1 ran 166ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 0.168s
+FAIL
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestClaudePermissionResponseBrowser -count=1
+```
+
+```text
+2026/11/03 16:23:00 INFO Apply migrations. applied=[] skipped=22 adopted=false
+--- FAIL: TestClaudePermissionResponseBrowser (4.10s)
+ questions_test.go:280: native permission has no approval control 200
+FAIL
+rastrillo-budget/v1 ran 4.103s
+FAIL amadan.net/oficina/equipo/internal/equipotest 4.223s
+FAIL
+```
+
+### GREEN and verification
+
+All commands below exited 0. The final required command includes the proxy, both answer protocols, browser approval and stale-answer tests. Focused follow-ups cover the legacy broker, policy rendering, journal upgrade and socket mount. No whole-suite test or make ci was run.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/equipotest ./internal/runner/provider/... -run 'TestDirectTool|TestClaudePermission|TestCodexApproval|TestCodexAsyncQuestion|TestDirectStaleAnswer|TestToolProxy' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 8.912s
+ok amadan.net/oficina/equipo/internal/equipotest 6.168s
+ok amadan.net/oficina/equipo/internal/runner/provider 0.002s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 0.898s
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 5.201s
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/equipotest ./internal/runner/provider/claude ./internal/runner/provider/codex ./internal/runner/containment ./cmd/equipo-runner -run 'TestQuestion|TestToolVerb|TestAgentToolScope|TestToolSocket|TestDirectToolMount|TestDirectJournalUpgrade|TestRunnerJournalDurabilityConfiguration|TestCodexAppServerPolicy|TestCodexNoLegacyPolicyOverride|TestCodexUnexpectedPolicyChange|TestCodexThreadConfigPinned|TestCodexPolicyShape|TestClaudeLaunchPolicy|TestClaudeInitPolicy|TestCodexRPCInterleaving' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 4.956s
+ok amadan.net/oficina/equipo/internal/equipotest 21.322s
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 3.999s
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 1.704s
+ok amadan.net/oficina/equipo/internal/runner/containment 0.006s
+ok amadan.net/oficina/equipo/cmd/equipo-runner 0.050s
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run 'TestClaudePermission|TestClaudeLaunchPolicy|TestClaudeInitPolicy|TestClaudeToolHash|TestClaudePolicyRefusals' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 9.409s
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run 'TestClaudePermissionResponseBrowser|TestQuestionBrowserAuthority|TestQuestionStaleAnswer|TestDirectStaleAnswer' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/equipotest 13.357s
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run 'TestClaudePermissionResponse' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/equipotest 5.823s
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectStaleAnswerCancelIsAttemptScoped -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.385s
+```
+
+```sh
+CGO_ENABLED=0 go vet ./internal/equipo ./internal/runner ./internal/runner/provider/... ./internal/runner/containment ./internal/runnerproto ./cmd/equipo-runner
+```
+
+```text
+PASS (no diagnostic output)
+```
+
+Formatting and `git diff --check` passed. The real helper binary is built with CGO_ENABLED=0 inside TestDirectToolScope and driven by a fake provider. No live provider was invoked.
+
+### Compiling guard mutations
+
+46 mutations compiled and caused the named test to fail. Each mutation was applied alone and restored in a finally block before the next test. The final green and vet commands ran after restoration. The changes below are the exact source substitutions; multi-substitution entries remove one logical guard enforced at more than one storage step.
+
+#### 1. claude-ordinary-prompt
+
+File: `internal/runner/provider/claude/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: p.reply <- result
+AFTER: raw,_:=userEnvelope(session.ID,"permission");_,_=s.capture.Input.Write(raw)
+ p.reply <- result
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run '^TestClaudePermissionResponse$' -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponse (0.22s)
+ answers_test.go:61: permission reply sent an ordinary prompt
+FAIL
+rastrillo-budget/v1 ran 221ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 0.223s
+FAIL
+```
+
+#### 2. claude-original-input
+
+File: `internal/runner/provider/claude/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: return json.Marshal(map[string]any{"behavior": "allow", "updatedInput": input})
+AFTER: delete(input,"questions");return json.Marshal(map[string]any{"behavior": "allow", "updatedInput": input})
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run '^TestClaudePermissionResponse$' -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponse (0.22s)
+ answers_test.go:55: {"behavior":"allow","updatedInput":{"answers":{"Which?":"blue"}}}
+FAIL
+rastrillo-budget/v1 ran 222ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 0.224s
+FAIL
+```
+
+#### 3. question-answer-allowlist
+
+File: `internal/runner/provider/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: d.DisallowUnknownFields()
+AFTER: // mutation: allow unknown answer fields
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run '^TestClaudePermissionResponse$' -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponse (0.23s)
+ answers_test.go:37: widened answer accepted {"answers":{"Which?":"blue"},"command":"evil"}
+FAIL
+rastrillo-budget/v1 ran 233ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 0.235s
+FAIL
+```
+
+#### 4. claude-native-fields
+
+File: `internal/runner/provider/claude/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if !slices.Contains(fields[q.Tool], key) {
+AFTER: if false && !slices.Contains(fields[q.Tool], key) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run '^TestClaudePermissionResponseNativePolicy$' -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponseNativePolicy (0.05s)
+ answers_test.go:84: native policy widened {"file_path":"/workspace/a","content":"hi","policyAmendment":true}
+FAIL
+rastrillo-budget/v1 ran 54ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 0.055s
+FAIL
+```
+
+#### 5. claude-protected-path
+
+File: `internal/runner/provider/claude/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if path == deny || strings.HasPrefix(path, deny+"/") {
+AFTER: if false && (path == deny || strings.HasPrefix(path, deny+"/")) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run '^TestClaudePermissionResponseNativePolicy$' -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponseNativePolicy (0.06s)
+ answers_test.go:84: native policy widened {"file_path":"/tool/equipo.sock","content":"hi"}
+FAIL
+rastrillo-budget/v1 ran 57ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 0.059s
+FAIL
+```
+
+#### 6. claude-input-replacement
+
+File: `internal/runner/provider/claude/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if len(a.Input) != 0 || !slices.Contains
+AFTER: if !slices.Contains
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run '^TestClaudePermissionResponseNativePolicy$' -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponseNativePolicy (0.05s)
+ answers_test.go:88: native tool input replaced
+FAIL
+rastrillo-budget/v1 ran 54ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 0.056s
+FAIL
+```
+
+#### 7. codex-expected-turn
+
+File: `internal/runner/provider/codex/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: "expectedTurnId": providerTurn
+AFTER: "expectedTurnId": a.TurnID
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run '^TestCodexAsyncQuestionAnswer/async$' -count=1
+```
+
+```text
+--- FAIL: TestCodexAsyncQuestionAnswer (0.14s)
+ --- FAIL: TestCodexAsyncQuestionAnswer/async (0.14s)
+ answers_test.go:115: wrong steer: {ID:[34 101 113 117 105 112 111 58 49 34] Method:turn/steer Params:{ThreadID:thread-1 ExpectedTurnID:local-turn} Result:{Answers:map[]}}
+FAIL
+rastrillo-budget/v1 ran 136ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.138s
+FAIL
+```
+
+#### 8. codex-policy-amendment
+
+File: `internal/runner/provider/codex/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if len(a.Input) != 0 {
+AFTER: if len(a.Input)>0{return s.rpc.answer(ctx,session,a.TurnID,map[string]any{"id":json.RawMessage(a.RequestID),"result":a.Input})}
+ if len(a.Input) != 0 {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run '^TestCodexApprovalResponse$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponse (0.44s)
+ --- FAIL: TestCodexApprovalResponse/item/commandExecution/requestApproval (0.14s)
+ answers_test.go:52: policy amendment accepted {"decision":"acceptForSession"}
+ --- FAIL: TestCodexApprovalResponse/item/fileChange/requestApproval (0.15s)
+ answers_test.go:52: policy amendment accepted {"decision":"acceptForSession"}
+ --- FAIL: TestCodexApprovalResponse/mcpServer/elicitation/request (0.15s)
+ answers_test.go:52: policy amendment accepted {"decision":"acceptForSession"}
+```
+
+#### 9. broker-fence
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: || q.Fence != b.Fence
+AFTER:
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCodexApprovalResponseBroker/fence$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseBroker (0.09s)
+ --- FAIL: TestCodexApprovalResponseBroker/fence (0.09s)
+ direct_tools_test.go:164: invalid approval fence
+FAIL
+rastrillo-budget/v1 ran 92ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.097s
+FAIL
+```
+
+#### 10. broker-attempt
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: || q.Attempt != b.Attempt
+AFTER:
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCodexApprovalResponseBroker/attempt$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseBroker (0.07s)
+ --- FAIL: TestCodexApprovalResponseBroker/attempt (0.07s)
+ direct_tools_test.go:164: invalid approval attempt
+FAIL
+rastrillo-budget/v1 ran 73ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.076s
+FAIL
+```
+
+#### 11. broker-arguments
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if err := validateToolArguments(q.Name, q.Arguments); err != nil {
+AFTER: if err := validateToolArguments(q.Name, q.Arguments); false && err != nil {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCodexApprovalResponseBroker/arguments$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseBroker (0.08s)
+ --- FAIL: TestCodexApprovalResponseBroker/arguments (0.08s)
+ direct_tools_test.go:164: invalid approval arguments
+FAIL
+rastrillo-budget/v1 ran 76ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.078s
+FAIL
+```
+
+#### 12. broker-execution-revalidation
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if err := b.Current(ctx); err != nil {
+ return err
+AFTER: if err := b.Current(ctx); false && err != nil {
+ return err
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCodexApprovalResponseBroker/execute-revalidate$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseBroker (0.09s)
+ --- FAIL: TestCodexApprovalResponseBroker/execute-revalidate (0.09s)
+ direct_tools_test.go:169: execution did not revalidate
+FAIL
+rastrillo-budget/v1 ran 92ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.095s
+FAIL
+```
+
+#### 13. codex-correlated-arguments
+
+File: `internal/runner/provider/codex/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: || !sameJSON(c.Item.Arguments, p.Meta.Arguments)
+AFTER:
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run '^TestCodexApprovalResponseMCPCorrelation/arguments$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseMCPCorrelation (0.14s)
+ --- FAIL: TestCodexApprovalResponseMCPCorrelation/arguments (0.14s)
+ answers_test.go:237: uncorrelated MCP approved arguments
+FAIL
+rastrillo-budget/v1 ran 144ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.146s
+FAIL
+```
+
+#### 14. codex-elicitation-schema
+
+File: `internal/runner/provider/codex/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: || !sameJSON(p.RequestedSchema, []byte(`{"type":"object","properties":{}}`))
+AFTER:
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run '^TestCodexApprovalResponseMCPCorrelation/schema$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseMCPCorrelation (0.15s)
+ --- FAIL: TestCodexApprovalResponseMCPCorrelation/schema (0.15s)
+ answers_test.go:237: uncorrelated MCP approved schema
+FAIL
+rastrillo-budget/v1 ran 152ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.154s
+FAIL
+```
+
+#### 15. codex-ambiguous-call
+
+File: `internal/runner/provider/codex/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if len(ev.ToolCall) > 0 {
+AFTER: if false && len(ev.ToolCall) > 0 {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run '^TestCodexApprovalResponseMCPCorrelation/ambiguous$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseMCPCorrelation (0.14s)
+ --- FAIL: TestCodexApprovalResponseMCPCorrelation/ambiguous (0.14s)
+ answers_test.go:237: uncorrelated MCP approved ambiguous
+FAIL
+rastrillo-budget/v1 ran 144ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.146s
+FAIL
+```
+
+#### 16. codex-completed-call
+
+File: `internal/runner/provider/codex/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if len(current.ToolCall) == 0 || !bytes.Equal(current.ToolCall, ev.ToolCall) {
+AFTER: if false && (len(current.ToolCall) == 0 || !bytes.Equal(current.ToolCall, ev.ToolCall)) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run '^TestCodexApprovalResponseMCPCorrelation/completed-item$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseMCPCorrelation (0.16s)
+ --- FAIL: TestCodexApprovalResponseMCPCorrelation/completed-item (0.16s)
+ answers_test.go:237: uncorrelated MCP approved completed-item
+FAIL
+rastrillo-budget/v1 ran 164ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.168s
+FAIL
+```
+
+#### 17. codex-resolved-request
+
+File: `internal/runner/provider/codex/launcher.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: delete(s.requests, string(envelope.Params.RequestID))
+AFTER: // mutation: keep resolved requests
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run '^TestCodexApprovalResponseResolvedRequest$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseResolvedRequest (0.15s)
+ answers_test.go:207: resolved request answered
+FAIL
+rastrillo-budget/v1 ran 147ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.150s
+FAIL
+```
+
+#### 18. codex-exact-id
+
+File: `internal/runner/provider/codex/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: ev, ok := s.requests[a.RequestID]
+AFTER: ev, ok := s.requests[strings.Trim(a.RequestID, "\"")]
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run '^TestCodexApprovalResponse$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponse (0.48s)
+ --- FAIL: TestCodexApprovalResponse/item/commandExecution/requestApproval (0.16s)
+ answers_test.go:48: string ID answered numeric request
+ --- FAIL: TestCodexApprovalResponse/item/fileChange/requestApproval (0.16s)
+ answers_test.go:48: string ID answered numeric request
+ --- FAIL: TestCodexApprovalResponse/mcpServer/elicitation/request (0.16s)
+ answers_test.go:48: string ID answered numeric request
+```
+
+#### 19. durable-active-turn
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: func (j *Journal) currentDirectTurn(ctx context.Context, s provider.Session, turn string) error {
+AFTER: func (j *Journal) currentDirectTurn(ctx context.Context, s provider.Session, turn string) error {
+ return nil
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectStaleAnswer/(cancel|restart|replaced-turn)$' -count=1
+```
+
+```text
+--- FAIL: TestDirectStaleAnswer (0.31s)
+ --- FAIL: TestDirectStaleAnswer/replaced-turn (0.12s)
+ direct_tools_test.go:205: stale answer delivered replaced-turn
+FAIL
+rastrillo-budget/v1 ran 625ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.628s
+FAIL
+```
+
+#### 20. cancel-is-attempt-scoped
+
+File: `internal/runner/direct_recovery.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: UPDATE journal_answers SET state='invalid' WHERE state='pending' AND answer_key IN (SELECT answer_key FROM direct_answer_scopes WHERE attempt=?)", attempt
+AFTER: UPDATE journal_answers SET state='invalid' WHERE state='pending'"
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectStaleAnswerCancelIsAttemptScoped$' -count=1
+```
+
+```text
+--- FAIL: TestDirectStaleAnswerCancelIsAttemptScoped (0.15s)
+ direct_tools_test.go:223: attempt B answer invalidated by A invalid
+FAIL
+rastrillo-budget/v1 ran 148ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.151s
+FAIL
+```
+
+#### 21. stored-answer-turn
+
+File: `internal/runner/questions.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: || turn != r.TurnID
+AFTER:
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectStaleAnswerTurnAssociation$' -count=1
+```
+
+```text
+--- FAIL: TestDirectStaleAnswerTurnAssociation (0.15s)
+ direct_tools_test.go:393: previous turn answer reused in replacement turn
+FAIL
+rastrillo-budget/v1 ran 149ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.151s
+FAIL
+```
+
+#### 22. changed-answer-replay
+
+File: `internal/runner/questions.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if old != hash {
+AFTER: if false && old != hash {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectStaleAnswer/replayed-changed-payload$' -count=1
+```
+
+```text
+--- FAIL: TestDirectStaleAnswer (0.11s)
+ --- FAIL: TestDirectStaleAnswer/replayed-changed-payload (0.11s)
+ direct_tools_test.go:205: stale answer delivered replayed-changed-payload
+FAIL
+rastrillo-budget/v1 ran 443ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.449s
+FAIL
+```
+
+#### 23. capture-no-hidden-turn
+
+File: `internal/runner/direct_answer_capture.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if v.Method == "turn/steer" {
+AFTER: if v.Method=="turn/start"{return c.input.Write(raw)}
+ if v.Method == "turn/steer" {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectToolAnswerCapture$' -count=1
+```
+
+```text
+--- FAIL: TestDirectToolAnswerCapture (0.12s)
+ direct_tools_test.go:252: hidden turn or policy amendment {"id":8,"method":"turn/start","params":{}}
+
+FAIL
+rastrillo-budget/v1 ran 118ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.121s
+FAIL
+```
+
+#### 24. capture-no-policy-amendment
+
+File: `internal/runner/direct_answer_capture.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if runnerproto.DecodeLimit(bytes.NewReader(v.Result), &r, MaxFrameBytes) != nil {
+ return 0, runnerproto.ErrInvalid
+AFTER: if runnerproto.DecodeLimit(bytes.NewReader(v.Result), &r, MaxFrameBytes) != nil {
+ return c.input.Write(raw)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectToolAnswerCapture$' -count=1
+```
+
+```text
+--- FAIL: TestDirectToolAnswerCapture (0.10s)
+ direct_tools_test.go:252: hidden turn or policy amendment {"id":8,"result":{"decision":{"acceptWithExecpolicyAmendment":{}}}}
+
+FAIL
+rastrillo-budget/v1 ran 104ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.107s
+FAIL
+```
+
+#### 25. capture-no-replay
+
+File: `internal/runner/direct_answer_capture.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: INSERT INTO journal_answers VALUES(?,?,'pending')
+AFTER: INSERT OR IGNORE INTO journal_answers VALUES(?,?,'pending')
+```
+
+```text
+BEFORE: INSERT INTO direct_answer_scopes VALUES(?,?,?)
+AFTER: INSERT OR IGNORE INTO direct_answer_scopes VALUES(?,?,?)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectToolAnswerCapture$' -count=1
+```
+
+```text
+--- FAIL: TestDirectToolAnswerCapture (0.11s)
+ direct_tools_test.go:248: answer replay transmitted
+FAIL
+rastrillo-budget/v1 ran 108ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.110s
+FAIL
+```
+
+#### 26. proxy-unbound-endpoint
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: pending: b.Session.AttemptKey == ""
+AFTER: pending: false
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestToolProxyLifecycle/pending$' -count=1
+```
+
+```text
+--- FAIL: TestToolProxyLifecycle (0.09s)
+ --- FAIL: TestToolProxyLifecycle/pending (0.09s)
+ direct_tools_test.go:322: unbound attempt accepted
+FAIL
+rastrillo-budget/v1 ran 89ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.092s
+FAIL
+```
+
+#### 27. proxy-restart
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if recovered != 0 {
+AFTER: if false && recovered != 0 {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestToolProxyLifecycle/restart$' -count=1
+```
+
+```text
+--- FAIL: TestToolProxyLifecycle (2.09s)
+ --- FAIL: TestToolProxyLifecycle/restart (2.09s)
+ direct_tools_test.go:344: invalid endpoint remained live restart
+FAIL
+rastrillo-budget/v1 ran 2.092s
+FAIL amadan.net/oficina/equipo/internal/runner 2.097s
+FAIL
+```
+
+#### 28. proxy-secret-config
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: return json.RawMessage(directMCP)
+AFTER: raw,_:=json.Marshal(p.broker.capability);return raw
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestToolProxyCannotExposeSecrets$' -count=1
+```
+
+```text
+--- FAIL: TestToolProxyCannotExposeSecrets (0.08s)
+ direct_tools_test.go:101: {"copy":{"accepted":"accepted","rejected":"rejected","ask":"","candidate":"","review":"","reproduction":""},"secret":"NBO2RNULWLXWKOWLPXAZK4AC54LQCT2SP5AIVGNGYBODXODZCLDX","instance_id":"instance","task_id":"task","attempt":1,"fence":7,"tools":["ask_person","submit_candidate","submit_review","submit_reproduction"],"exp ... [line shortened]
+FAIL
+rastrillo-budget/v1 ran 81ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.087s
+FAIL
+```
+
+#### 29. proxy-long-socket
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: Name: fmt.Sprintf("/proc/self/fd/%d/equipo.sock", fd.Fd())
+AFTER: Name: path
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestToolProxyLongPath$' -count=1
+```
+
+```text
+--- FAIL: TestToolProxyLongPath (0.09s)
+ direct_tools_test.go:124: listen unix /home/paulca/t/e2b/TestToolProxyLongPath2611924194/002/longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong/tool-1654921756/equipo.sock: bind: invalid argument
+FAIL
+rastrillo-budget/v1 ran 95ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.097s
+FAIL
+```
+
+#### 30. mount-private-mode
+
+File: `internal/runner/containment/tool.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: || stat.Mode&0777 != 0600
+AFTER:
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestDirectToolMount/public$' -count=1
+```
+
+```text
+--- FAIL: TestDirectToolMount (0.00s)
+ --- FAIL: TestDirectToolMount/public (0.00s)
+ tool_test.go:56: unsafe socket mount public
+FAIL
+rastrillo-budget/v1 ran 1ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.004s
+FAIL
+```
+
+#### 31. mount-socket-type
+
+File: `internal/runner/containment/tool.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: || stat.Mode&unix.S_IFMT != unix.S_IFSOCK
+AFTER:
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestDirectToolMount/regular$' -count=1
+```
+
+```text
+--- FAIL: TestDirectToolMount (0.00s)
+ --- FAIL: TestDirectToolMount/regular (0.00s)
+ tool_test.go:59: unsafe socket mount regular
+FAIL
+rastrillo-budget/v1 ran 1ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.016s
+FAIL
+```
+
+#### 32. mount-symlink
+
+File: `internal/runner/containment/tool.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC
+AFTER: unix.O_PATH|unix.O_CLOEXEC
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestDirectToolMount/symlink$' -count=1
+```
+
+```text
+--- FAIL: TestDirectToolMount (0.00s)
+ --- FAIL: TestDirectToolMount/symlink (0.00s)
+ tool_test.go:59: unsafe socket mount symlink
+FAIL
+rastrillo-budget/v1 ran 1ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.009s
+FAIL
+```
+
+#### 33. proxy-lease-loss-fixed
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE:
+ err := b.Current(ctx)
+AFTER:
+ var err error
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestToolProxyLifecycle/lease$' -count=1
+```
+
+```text
+--- FAIL: TestToolProxyLifecycle (2.12s)
+ --- FAIL: TestToolProxyLifecycle/lease (2.12s)
+ direct_tools_test.go:344: invalid endpoint remained live lease
+FAIL
+rastrillo-budget/v1 ran 2.119s
+FAIL amadan.net/oficina/equipo/internal/runner 2.128s
+FAIL
+```
+
+#### 34. broker-replayed-arguments
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if err := b.Journal.validateToolReplay(ctx, q); err != nil {
+AFTER: if err := b.Journal.validateToolReplay(ctx, q); false && err != nil {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCodexApprovalResponseIdempotency$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseIdempotency (0.13s)
+ direct_tools_test.go:464: changed replay arguments approved
+FAIL
+rastrillo-budget/v1 ran 129ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.134s
+FAIL
+```
+
+#### 35. bound-launch-identity
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: || s.Validate(launch) != nil
+AFTER:
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestToolProxyBindingIdentity/(account|model|provider)$' -count=1
+```
+
+```text
+--- FAIL: TestToolProxyBindingIdentity (0.31s)
+ --- FAIL: TestToolProxyBindingIdentity/account (0.10s)
+ direct_tools_test.go:486: mismatched bound identity account
+ --- FAIL: TestToolProxyBindingIdentity/model (0.09s)
+ direct_tools_test.go:486: mismatched bound identity model
+ --- FAIL: TestToolProxyBindingIdentity/provider (0.11s)
+ direct_tools_test.go:486: mismatched bound identity provider
+```
+
+#### 36. bound-agent-session
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if b.Agent.AgentID != b.Session.AttemptKey || b.Agent.ProviderSessionID != b.Session.ID || b.Agent.Provider != b.Session.Provider {
+AFTER: if false && (b.Agent.AgentID != b.Session.AttemptKey || b.Agent.ProviderSessionID != b.Session.ID || b.Agent.Provider != b.Session.Provider) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestToolProxyBindingIdentity/session$' -count=1
+```
+
+```text
+--- FAIL: TestToolProxyBindingIdentity (0.11s)
+ --- FAIL: TestToolProxyBindingIdentity/session (0.11s)
+ direct_tools_test.go:486: mismatched bound identity session
+FAIL
+rastrillo-budget/v1 ran 106ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.114s
+FAIL
+```
+
+#### 37. question-permission-fallback
+
+File: `internal/runner/provider/codex/answers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: || strings.HasPrefix(k, "mcp_tool_call_approval_")
+AFTER:
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run '^TestCodexApprovalResponseNoQuestionFallback$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseNoQuestionFallback (0.16s)
+ answers_test.go:250: permission amendment through question fallback
+FAIL
+rastrillo-budget/v1 ran 158ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.168s
+FAIL
+```
+
+#### 38. broker-tool-allowlist
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: || !slices.Contains(b.Tools, q.Name)
+AFTER:
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCodexApprovalResponseToolAllowlist$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseToolAllowlist (0.16s)
+ direct_tools_test.go:495: valid but unscoped tool approved
+FAIL
+rastrillo-budget/v1 ran 157ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.165s
+FAIL
+```
+
+#### 39. original-approval-event
+
+File: `internal/runner/direct_questions.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if original.SessionID != ev.SessionID || original.TurnID != ev.TurnID || original.RequestID != ev.RequestID || (!bytes.Equal(original.Payload, ev.Payload) || !bytes.Equal(original.ToolCall, ev.ToolCall)) {
+AFTER: if false && (original.SessionID != ev.SessionID || original.TurnID != ev.TurnID || original.RequestID != ev.RequestID || (!bytes.Equal(original.Payload, ev.Payload) || !bytes.Equal(original.ToolCall, ev.ToolCall))) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCodexApprovalResponseChangedOriginal$' -count=1
+```
+
+```text
+--- FAIL: TestCodexApprovalResponseChangedOriginal (0.11s)
+ direct_tools_test.go:362: changed arguments approved
+FAIL
+rastrillo-budget/v1 ran 112ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.120s
+FAIL
+```
+
+#### 40. renewed-proxy-lifetime
+
+File: `internal/runner/tool_proxy.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: ctx, cancel := context.WithCancel(ctx)
+AFTER: ctx, cancel := context.WithDeadline(ctx, b.LeaseDeadline)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestToolProxyRenewedLease$' -count=1
+```
+
+```text
+--- FAIL: TestToolProxyRenewedLease (0.29s)
+ direct_tools_test.go:512: runner.invalid
+FAIL
+rastrillo-budget/v1 ran 286ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.299s
+FAIL
+```
+
+#### 41. claude-scoped-mcp-allow
+
+File: `internal/runner/provider/claude/launcher.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: "allow": append([]string{}, in.Tools...)
+AFTER: "allow": []string{}
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run '^TestClaudePermissionResponseScopedMCPPolicy$' -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponseScopedMCPPolicy (0.12s)
+ answers_test.go:106: scoped MCP would fall through native permission hook {"disableAllHooks":true,"enabledPlugins":{},"permissions":{"allow":[],"deny":["Read(//alias/login)","Read(//alias/login/**)","Write(//alias/login)","Write(//alias/login/**)","Edit(//alias/login)","Edit(//alias/login/**)","Glob(//alias/login)","Glob(//alias/login/**)","Gre ... [line shortened]
+FAIL
+rastrillo-budget/v1 ran 116ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 0.118s
+FAIL
+```
+
+#### 42. claude-fixed-mcp-verbs
+
+File: `internal/runner/provider/claude/launcher.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if !slices.Contains([]string{"mcp__equipo__ask_person", "mcp__equipo__submit_candidate", "mcp__equipo__submit_review", "mcp__equipo__submit_reproduction"}, tool) {
+AFTER: if false && !slices.Contains([]string{"mcp__equipo__ask_person", "mcp__equipo__submit_candidate", "mcp__equipo__submit_review", "mcp__equipo__submit_reproduction"}, tool) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run '^TestClaudePermissionResponseScopedMCPPolicy$' -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponseScopedMCPPolicy (0.16s)
+ answers_test.go:110: unscoped MCP permission
+FAIL
+rastrillo-budget/v1 ran 164ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 0.166s
+FAIL
+```
+
+#### 43. browser-native-no-input
+
+File: `internal/equipo/question_handlers.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if len(fields) == 0 && !canAllow {
+AFTER: _ = canAllow; if len(fields) == 0 {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestClaudePermissionResponseBrowser$' -count=1
+```
+
+```text
+2026/11/03 16:24:24 INFO Apply migrations. applied=[] skipped=22 adopted=false
+--- FAIL: TestClaudePermissionResponseBrowser (4.19s)
+ questions_test.go:302: unchanged native permission not accepted 422
+FAIL
+rastrillo-budget/v1 ran 4.189s
+FAIL amadan.net/oficina/equipo/internal/equipotest 4.238s
+FAIL
+```
+
+#### 44. native-direct-shape
+
+File: `internal/runnerproto/questions.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if raw.Direct && raw.Provider == "claude" && slices.Contains
+AFTER: if raw.Provider == "claude" && slices.Contains
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestClaudePermissionResponseNoEscalation$' -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponseNoEscalation (1.87s)
+ questions_test.go:327: unsafe permission control {"id":"native","kind":"tool","direct":false,"provider":"claude","name":"Write","input":{}}
+FAIL
+rastrillo-budget/v1 ran 1.872s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.925s
+FAIL
+```
+
+#### 45. native-fixed-verbs
+
+File: `internal/runnerproto/questions.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: if raw.Direct && raw.Provider == "claude" && slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep", "Bash"}, raw.Name) {
+AFTER: if raw.Direct && raw.Provider == "claude" {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestClaudePermissionResponseNoEscalation$' -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponseNoEscalation (0.93s)
+ questions_test.go:327: unsafe permission control {"id":"native","kind":"tool","direct":true,"provider":"claude","name":"publish","input":{}}
+FAIL
+rastrillo-budget/v1 ran 929ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.977s
+FAIL
+```
+
+#### 46. browser-only-valid-native-fixed
+
+File: `internal/equipo/task_views.go`. Exit 1; compiled; named test failed.
+
+```text
+BEFORE: canAllow = can && value.ValidateAnswer(runnerproto.QuestionAnswer{Behavior: "allow"}) == nil
+AFTER: _ = value;_ = runnerproto.QuestionAnswer{};canAllow = can
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestClaudePermissionResponseNoEscalation$' -count=1
+```
+
+```text
+--- FAIL: TestClaudePermissionResponseNoEscalation (0.59s)
+ questions_test.go:327: unsafe permission control {"id":"native","kind":"tool","direct":true,"provider":"claude","name":"publish","input":{}}
+FAIL
+rastrillo-budget/v1 ran 594ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.641s
+FAIL
+```
+
+### Discarded mutation attempts
+
+These four attempts are not counted as proof. The two mount tests originally used nonprivate parent directories, so the unchanged parent guard masked the socket-type and symlink mutations. The fixtures were corrected to reach those guards, and the compiling mutations then failed. The two compile errors were corrected while keeping the relevant imports or declarations used, and rerun successfully.
+
+- `proxy-lease-loss`: compile/setup failure. Command: `CGO_ENABLED=0 go test ./internal/runner -run ^TestToolProxyLifecycle/lease$ -count=1`.
+
+```text
+FAIL amadan.net/oficina/equipo/internal/runner [build failed]
+FAIL
+# amadan.net/oficina/equipo/internal/runner [amadan.net/oficina/equipo/internal/runner.test]
+internal/runner/tool_proxy.go:52:9: syntax error: var declaration not allowed in if initializer
+```
+
+- `mount-socket-type`: test unexpectedly passed. Command: `CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestDirectToolMount/regular$ -count=1`.
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/containment 0.002s
+```
+
+- `mount-symlink`: test unexpectedly passed. Command: `CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestDirectToolMount/symlink$ -count=1`.
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/containment 0.002s
+```
+
+- `browser-only-valid-native`: compile/setup failure. Command: `CGO_ENABLED=0 go test ./internal/equipotest -run ^TestClaudePermissionResponseNoEscalation$ -count=1`.
+
+```text
+FAIL amadan.net/oficina/equipo/internal/equipotest [build failed]
+FAIL
+# amadan.net/oficina/equipo/internal/equipo
+internal/equipo/task_views.go:13:2: "amadan.net/oficina/equipo/internal/runnerproto" imported and not used
+```
+
+### User-facing strings
+
+One new app-owned string: `question.allow_once` = `Allow once`, in `internal/equipo/copy.go`, marked individually `COPY REVIEW REQUIRED: question.allow_once`. It has not had a copy pass and needs review before release. No copy-review skill or server was invoked, as instructed. Existing accepted/rejected tool text is reused. Protocol method names, schemas, test fixtures and error sentinels are technical data, not new product prose.
+
+### Concerns and handback
+
+- Native Codex command/file approvals are deliberately deny-only until a certified non-escalating action shape exists. Unsupported or uncorrelated shapes never approve.
+- The new Allow once label is pending copy review before release.
+- Task 9 still owns runtime composition; Task 11b owns live provider and deployed-policy certification. This task ran only fake providers. Full CI, live gates, sign-in, enrolment and real credential-home creation were not performed. Synthetic test homes contain fixture values only.
+- All requested targeted checks pass. No unresolved test failure remains. The four discarded mutation attempts are documented above and replaced by valid compiling evidence.
+
+No push, merge, deployment, sudo, provider prompt, helper agent or .claude/HANDOFF.md. All session-started tests and processes are awaited. Scratch evidence is removed after these reports and the task commit are saved. No session-started server is intended to remain running.
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 73360e69..d322da95 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -409,6 +409,8 @@ var runnerDraftCopy = map[string]string{
"question.behavior": "Decision",
// COPY REVIEW REQUIRED: question.allow
"question.allow": "Allow within the current policy",
+ // COPY REVIEW REQUIRED: question.allow_once
+ "question.allow_once": "Allow once",
// COPY REVIEW REQUIRED: question.deny
"question.deny": "Deny",
// COPY REVIEW REQUIRED: question.input
diff --git a/internal/equipo/question_handlers.go b/internal/equipo/question_handlers.go
index ccc34cb7..13b80905 100644
--- a/internal/equipo/question_handlers.go
+++ b/internal/equipo/question_handlers.go
@@ -52,12 +52,14 @@ func (a *application) answerQuestion(w http.ResponseWriter, r *http.Request) {
return
}
var fields []QuestionField
+ canAllow := false
for _, q := range view.Questions {
if q.ID == chi.URLParam(r, "question") {
fields = q.Fields
+ canAllow = q.CanAllow
}
}
- if len(fields) == 0 {
+ if len(fields) == 0 && !canAllow {
a.failure(w, r, ErrInvalid)
return
}
@@ -74,9 +76,11 @@ func (a *application) answerQuestion(w http.ResponseWriter, r *http.Request) {
return
}
}
- answer.UpdatedInput, _ = json.Marshal(struct {
- Answers map[string]string `json:"answers"`
- }{answers})
+ if len(fields) > 0 {
+ answer.UpdatedInput, _ = json.Marshal(struct {
+ Answers map[string]string `json:"answers"`
+ }{answers})
+ }
}
if err := a.store.answerQuestion(r.Context(), Actor{Address: actor.Address}, chi.URLParam(r, "id"), chi.URLParam(r, "question"), rev, answer); err != nil {
a.failure(w, r, err)
diff --git a/internal/equipo/task_views.go b/internal/equipo/task_views.go
index df932baf..92adcd83 100644
--- a/internal/equipo/task_views.go
+++ b/internal/equipo/task_views.go
@@ -10,6 +10,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
"gorm.io/gorm"
"gorm.io/plugin/dbresolver"
)
@@ -31,6 +32,7 @@ type TaskQuestion struct {
ID, Text, State string
Revision int64
CanAnswer bool
+ CanAllow bool
}
type TaskEvidence struct {
Actual string
@@ -375,6 +377,10 @@ func (s *Store) taskViewAt(tx *gorm.DB, actor Actor, task Task) (TaskViewData, e
if state == "pending" && !q.ExpiresAt.After(s.runnerClock.Now()) {
state = "expired"
}
+ canAllow := false
+ if value, err := q.value(); err == nil {
+ canAllow = can && value.ValidateAnswer(runnerproto.QuestionAnswer{Behavior: "allow"}) == nil
+ }
fields := questionFields(q.Kind, q.RawRequest)
text := displayJSON(q.RawRequest)
if len(fields) > 0 {
@@ -384,7 +390,7 @@ func (s *Store) taskViewAt(tx *gorm.DB, actor Actor, task Task) (TaskViewData, e
}
text = strings.Join(prompts, "\n\n")
}
- v.Questions = append(v.Questions, TaskQuestion{ID: q.ID, Text: text, State: state, Revision: q.Revision, CanAnswer: can, Fields: fields})
+ v.Questions = append(v.Questions, TaskQuestion{ID: q.ID, Text: text, State: state, Revision: q.Revision, CanAnswer: can, CanAllow: canAllow, Fields: fields})
if current && state == "pending" {
v.Group = "needs-person"
if member.Address == task.Requester {
diff --git a/internal/equipo/templates/question.html b/internal/equipo/templates/question.html
index 6c11e17d..0999a07c 100644
--- a/internal/equipo/templates/question.html
+++ b/internal/equipo/templates/question.html
@@ -1,4 +1,4 @@
{{define "content"}}<h1>{{copy "task.answer"}}</h1>{{if not .Question.Fields}}<pre>{{.Question.Text}}</pre>{{end}}<form equipo-form method="post" action="/tasks/{{.TaskView.Task.ID}}/questions/{{.Question.ID}}/answer">
<input type="hidden" name="revision" value="{{.Question.Revision}}">
{{range $i,$field:=.Question.Fields}}<label>{{$field.Prompt}}<textarea rst-input name="answer_{{$i}}" rows="4" maxlength="8192"></textarea></label>{{end}}
-{{if .Question.Fields}}<button rst-btn="primary" type="submit" name="behavior" value="allow">{{copy "question.send_answer"}}</button>{{end}}<button rst-btn type="submit" name="behavior" value="deny">{{copy "question.deny"}}</button></form>{{end}}
+{{if .Question.Fields}}<button rst-btn="primary" type="submit" name="behavior" value="allow">{{copy "question.send_answer"}}</button>{{else if .Question.CanAllow}}<button rst-btn="primary" type="submit" name="behavior" value="allow">{{copy "question.allow_once"}}</button>{{end}}<button rst-btn type="submit" name="behavior" value="deny">{{copy "question.deny"}}</button></form>{{end}}
diff --git a/internal/equipotest/questions_test.go b/internal/equipotest/questions_test.go
index 4ae8fd39..6a9e5161 100644
--- a/internal/equipotest/questions_test.go
+++ b/internal/equipotest/questions_test.go
@@ -5,6 +5,7 @@ import (
"amadan.net/oficina/equipo/internal/runnerproto"
"context"
"encoding/json"
+ "io"
"net/http/httptest"
"net/url"
"strings"
@@ -254,3 +255,80 @@ func TestQuestionValidatorRequired(t *testing.T) {
}
}
}
+
+func TestDirectStaleAnswerRevokedMember(t *testing.T) {
+ f, q := questionFixture(t)
+ a := runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"Blue"}}`)}
+ executionMust(t, f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, a))
+ mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", ownerAddress)
+ r := f.request()
+ r.RequestID = "direct-answer-poll"
+ result, err := f.x.Mutate(connectionContext, f.principal, "answers", r)
+ if err == nil && len(result.([]runnerproto.Question)) != 0 {
+ t.Fatal("revoked member answer delivered")
+ }
+}
+
+func TestClaudePermissionResponseBrowser(t *testing.T) {
+ f, q := questionFixture(t)
+ q.ID = "native"
+ q.PermissionID = "native"
+ q.Kind = "tool"
+ q.RawRequest = json.RawMessage(`{"id":"native","kind":"tool","direct":true,"provider":"claude","name":"Write","input":{"file_path":"/workspace/hello.txt","content":"hi"}}`)
+ request := f.request()
+ request.RequestID = "native"
+ request.Question = &q
+ _, err := f.x.Mutate(connectionContext, f.principal, "questions", request)
+ executionMust(t, err)
+ mail := &capturingMailer{}
+ router, err := equipo.RouterWithStore(f.d, testConfig(testOrigin), mail, nil, f.s)
+ executionMust(t, err)
+ server := httptest.NewServer(router)
+ t.Cleanup(server.Close)
+ client := signinClient(t, server.URL)
+ signinEmail(t, client, server.URL, testOrigin, mail, ownerAddress)
+ path := server.URL + "/tasks/" + f.a.TaskID + "/questions/native"
+ res, err := client.Get(path)
+ executionMust(t, err)
+ body, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ executionMust(t, err)
+ if res.StatusCode != 200 || !strings.Contains(string(body), "Allow once") {
+ t.Fatal("native permission has no approval control", res.StatusCode)
+ }
+ res = clientPost(t, client, path+"/answer", testOrigin, url.Values{"revision": {"1"}, "behavior": {"allow"}})
+ res.Body.Close()
+ if res.StatusCode != 303 {
+ t.Fatal("unchanged native permission not accepted", res.StatusCode)
+ }
+ var who string
+ executionMust(t, f.d.Writer().QueryRow("SELECT answered_by FROM questions WHERE id='native'").Scan(&who))
+ if who != ownerAddress {
+ t.Fatal("actor not session-derived", who)
+ }
+}
+
+func TestClaudePermissionResponseNoEscalation(t *testing.T) {
+ for _, raw := range []string{`{"id":"native","kind":"tool","direct":true,"provider":"claude","name":"publish","input":{}}`, `{"id":"native","kind":"tool","direct":true,"provider":"codex","name":"item/permissions/requestApproval","input":{"network":true}}`, `{"id":"native","kind":"tool","direct":false,"provider":"claude","name":"Write","input":{}}`} {
+ f, q := questionFixture(t)
+ q.ID = "native"
+ q.PermissionID = "native"
+ q.Kind = "tool"
+ q.RawRequest = json.RawMessage(raw)
+ request := f.request()
+ request.RequestID = "native"
+ request.Question = &q
+ _, err := f.x.Mutate(connectionContext, f.principal, "questions", request)
+ executionMust(t, err)
+ view, err := f.s.TaskView(connectionContext, ownerActor, f.a.TaskID)
+ executionMust(t, err)
+ for _, question := range view.Questions {
+ if question.ID == q.ID && question.CanAllow {
+ t.Fatal("unsafe permission control", raw)
+ }
+ }
+ if f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "allow"}) == nil {
+ t.Fatal("unsafe permission granted", raw)
+ }
+ }
+}
diff --git a/internal/runner/containment/mounts.go b/internal/runner/containment/mounts.go
index f784b6de..fed46660 100644
--- a/internal/runner/containment/mounts.go
+++ b/internal/runner/containment/mounts.go
@@ -160,6 +160,11 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error
}
targets[target] = true
}
+ if l.ToolSocket != "" {
+ if err = p.bindTool(l.ToolSocket); err != nil {
+ return nil, err
+ }
+ }
p.args = append(p.args, "--clearenv", "--setenv", "PATH", "/usr/bin:/bin:/opt", "--setenv", "HOME", "/home/runner", "--setenv", "TMPDIR", "/tmp", "--setenv", "LANG", "C.UTF-8")
allowed := map[string]bool{"LANG": true, "LC_ALL": true, "TERM": true, "CODEX_HOME": true, "CLAUDE_CONFIG_DIR": true, "CLAUDE_SECURESTORAGE_CONFIG_DIR": true, "CLAUDE_TMPDIR": true, "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": true, "DISABLE_AUTOUPDATER": true}
keys := make([]string, 0, len(l.Policy.Env))
diff --git a/internal/runner/containment/tool.go b/internal/runner/containment/tool.go
new file mode 100644
index 00000000..93c5128e
--- /dev/null
+++ b/internal/runner/containment/tool.go
@@ -0,0 +1,37 @@
+package containment
+
+import (
+ "golang.org/x/sys/unix"
+ "os"
+ "path/filepath"
+ "strconv"
+)
+
+// bindTool imports exactly the runner-created per-attempt endpoint. Its parent
+// and the authenticating broker stay outside the namespace.
+func (p *mounts) bindTool(path string) error {
+ if filepath.Base(path) != "equipo.sock" {
+ return errMount
+ }
+ parent, e := pin(filepath.Dir(path))
+ if e != nil {
+ return e
+ }
+ defer parent.Close()
+ var stat unix.Stat_t
+ if unix.Fstat(int(parent.Fd()), &stat) != nil || stat.Mode&0777 != 0700 || stat.Uid != uint32(os.Getuid()) {
+ return errMount
+ }
+ fd, e := unix.Openat(int(parent.Fd()), "equipo.sock", unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
+ if e != nil {
+ return e
+ }
+ f := os.NewFile(uintptr(fd), path)
+ if unix.Fstat(int(f.Fd()), &stat) != nil || stat.Mode&unix.S_IFMT != unix.S_IFSOCK || stat.Mode&0777 != 0600 || stat.Uid != uint32(os.Getuid()) {
+ f.Close()
+ return errMount
+ }
+ p.args = append(p.args, "--ro-bind-fd", strconv.Itoa(6+len(p.files)), "/tool/equipo.sock")
+ p.files = append(p.files, f)
+ return nil
+}
diff --git a/internal/runner/containment/tool_test.go b/internal/runner/containment/tool_test.go
new file mode 100644
index 00000000..50831ba4
--- /dev/null
+++ b/internal/runner/containment/tool_test.go
@@ -0,0 +1,63 @@
+package containment
+
+import (
+ "fmt"
+ "net"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestDirectToolMount(t *testing.T) {
+ dir := t.TempDir()
+ if e := os.Chmod(dir, 0700); e != nil {
+ t.Fatal(e)
+ }
+ fd, e := os.Open(dir)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer fd.Close()
+ path := filepath.Join(dir, "equipo.sock")
+ ln, e := net.ListenUnix("unix", &net.UnixAddr{Name: fmt.Sprintf("/proc/self/fd/%d/equipo.sock", fd.Fd()), Net: "unix"})
+ if e != nil {
+ t.Fatal(e)
+ }
+ ln.SetUnlinkOnClose(false)
+ defer ln.Close()
+ if e = os.Chmod(path, 0600); e != nil {
+ t.Fatal(e)
+ }
+ p := &mounts{}
+ defer p.close()
+ if e = p.bindTool(path); e != nil {
+ t.Fatal(e)
+ }
+ if len(p.files) != 1 || len(p.args) != 3 || p.args[0] != "--ro-bind-fd" || p.args[2] != "/tool/equipo.sock" {
+ t.Fatal("tool mount missing", p.args)
+ }
+ for _, change := range []string{"public", "symlink", "regular"} {
+ t.Run(change, func(t *testing.T) {
+ q := &mounts{}
+ defer q.close()
+ bad := path
+ switch change {
+ case "public":
+ os.Chmod(path, 0666)
+ defer os.Chmod(path, 0600)
+ case "symlink":
+ bad = filepath.Join(t.TempDir(), "equipo.sock")
+ os.Symlink(path, bad)
+ case "regular":
+ bad = filepath.Join(t.TempDir(), "equipo.sock")
+ os.WriteFile(bad, []byte("x"), 0600)
+ }
+ if e := os.Chmod(filepath.Dir(bad), 0700); e != nil {
+ t.Fatal(e)
+ }
+ if q.bindTool(bad) == nil {
+ t.Fatal("unsafe socket mount", change)
+ }
+ })
+ }
+}
diff --git a/internal/runner/direct_answer_capture.go b/internal/runner/direct_answer_capture.go
new file mode 100644
index 00000000..446b3e4a
--- /dev/null
+++ b/internal/runner/direct_answer_capture.go
@@ -0,0 +1,112 @@
+package runner
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+// WriteAnswer is a separate, durable path for replies in an admitted turn.
+func (c *captureInput) WriteAnswer(ctx context.Context, s provider.Session, turn string, raw []byte) (int, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.closed || c.ctx.Err() != nil || ctx.Err() != nil || c.launch.Selection.Provider != "codex" || s.Validate(c.launch) != nil || len(raw) > MaxFrameBytes+1 || !bytes.HasSuffix(raw, []byte{'\n'}) || !uniqueFrame(bytes.TrimSpace(raw)) {
+ return 0, runnerproto.ErrInvalid
+ }
+ var v struct {
+ ID json.RawMessage `json:"id"`
+ Method string `json:"method,omitempty"`
+ Params json.RawMessage `json:"params,omitempty"`
+ Result json.RawMessage `json:"result,omitempty"`
+ }
+ if runnerproto.DecodeLimit(bytes.NewReader(raw), &v, MaxFrameBytes) != nil || len(v.ID) == 0 || string(v.ID) == "null" {
+ return 0, runnerproto.ErrInvalid
+ }
+ var idString string
+ var idNumber int64
+ if json.Unmarshal(v.ID, &idString) != nil && json.Unmarshal(v.ID, &idNumber) != nil {
+ return 0, runnerproto.ErrInvalid
+ }
+ if v.Method == "turn/steer" {
+ var p struct {
+ Thread string `json:"threadId"`
+ Expected string `json:"expectedTurnId"`
+ Input []struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ } `json:"input"`
+ }
+ if len(v.Result) != 0 || runnerproto.DecodeLimit(bytes.NewReader(v.Params), &p, MaxFrameBytes) != nil || p.Thread != s.ID || p.Expected == "" || len(p.Input) != 1 || p.Input[0].Type != "text" || p.Input[0].Text == "" {
+ return 0, runnerproto.ErrInvalid
+ }
+ } else if v.Method == "" && len(v.Params) == 0 {
+ var r struct {
+ Action string `json:"action,omitempty"`
+ Content json.RawMessage `json:"content,omitempty"`
+ Meta json.RawMessage `json:"_meta,omitempty"`
+ Decision string `json:"decision,omitempty"`
+ Answers map[string]struct {
+ Answers []string `json:"answers"`
+ } `json:"answers,omitempty"`
+ }
+ if runnerproto.DecodeLimit(bytes.NewReader(v.Result), &r, MaxFrameBytes) != nil {
+ return 0, runnerproto.ErrInvalid
+ }
+ if r.Action != "" {
+ if (r.Action != "accept" && r.Action != "decline") || r.Decision != "" || len(r.Answers) != 0 || string(r.Meta) != "null" || (r.Action == "accept" && string(r.Content) != "{}") || (r.Action == "decline" && string(r.Content) != "null") {
+ return 0, runnerproto.ErrInvalid
+ }
+ } else if r.Decision != "" {
+ if (r.Decision != "accept" && r.Decision != "decline") || len(r.Answers) != 0 {
+ return 0, runnerproto.ErrInvalid
+ }
+ } else if len(r.Answers) == 0 {
+ return 0, runnerproto.ErrInvalid
+ }
+ } else {
+ return 0, runnerproto.ErrInvalid
+ }
+ if e := c.journal.AdmissionAllowed(ctx); e != nil {
+ return 0, e
+ }
+ key := runnerproto.EventHash([]any{"direct-wire", s.AttemptKey, turn, v.Method, v.ID})
+ hash := runnerproto.EventHash(json.RawMessage(bytes.TrimSpace(raw)))
+ tx, e := c.journal.db.BeginTx(ctx, nil)
+ if e != nil {
+ return 0, e
+ }
+ defer tx.Rollback()
+ var count int
+ if e = tx.QueryRowContext(ctx, `SELECT count(*) FROM direct_turns t JOIN direct_attempts a ON a.attempt=t.attempt WHERE t.attempt=? AND t.session=? AND t.turn=? AND t.state='dispatched' AND a.recovered=0`, s.AttemptKey, s.ID, turn).Scan(&count); e != nil || count != 1 {
+ return 0, runnerproto.ErrInvalid
+ }
+ if _, e = tx.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,?,'pending')", key, hash); e != nil {
+ return 0, runnerproto.ErrInvalid
+ }
+ if _, e = tx.ExecContext(ctx, "INSERT INTO direct_answer_scopes VALUES(?,?,?)", key, s.AttemptKey, turn); e != nil {
+ return 0, e
+ }
+ if e = tx.Commit(); e != nil {
+ return 0, c.journal.storageFailure(ctx, e)
+ }
+ if e = c.journal.currentDirectTurn(ctx, s, turn); e != nil {
+ return 0, e
+ }
+ n, e := c.input.Write(raw)
+ if e != nil || n != len(raw) {
+ c.closed = true
+ if e == nil {
+ e = io.ErrShortWrite
+ }
+ c.fail(e)
+ return n, e
+ }
+ if _, e = c.journal.db.ExecContext(ctx, "UPDATE journal_answers SET state='delivered' WHERE answer_key=? AND state='pending'", key); e != nil {
+ return n, c.journal.storageFailure(ctx, e)
+ }
+ return n, nil
+}
diff --git a/internal/runner/direct_questions.go b/internal/runner/direct_questions.go
new file mode 100644
index 00000000..83bdc7fe
--- /dev/null
+++ b/internal/runner/direct_questions.go
@@ -0,0 +1,212 @@
+package runner
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/codex"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+// DirectQuestionRelay uses the instance's durable question API through ask.
+// Current must revalidate that API's current question revision and answerer as
+// well as lease/fence authority. A saved answer alone never confers authority.
+type DirectQuestionRelay struct {
+ Binding ToolBinding
+ Proxy *ToolProxy
+ Launcher provider.Launcher
+ Current func(context.Context, runnerproto.Question) (time.Time, error)
+}
+
+func (r *DirectQuestionRelay) Handle(ctx context.Context, ev provider.Event, ask func(context.Context, runnerproto.Question) (runnerproto.QuestionAnswer, error)) error {
+ b := r.Binding
+ if r.Launcher == nil || b.Journal == nil || b.Current == nil || ev.Kind != "request" || ev.RequestID == "" || ev.SessionID != b.Session.ID || ev.TurnID != b.TurnID {
+ return runnerproto.ErrInvalid
+ }
+ if err := b.Current(ctx); err != nil {
+ return err
+ }
+ if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil {
+ return err
+ }
+ if b.Session.Provider == "codex" {
+ if _, _, e := codex.MCPApproval(ev); e == nil {
+ if r.Proxy == nil {
+ return runnerproto.ErrInvalid
+ }
+ authorize := func(ctx context.Context, original provider.Event) error {
+ if original.SessionID != ev.SessionID || original.TurnID != ev.TurnID || original.RequestID != ev.RequestID || (!bytes.Equal(original.Payload, ev.Payload) || !bytes.Equal(original.ToolCall, ev.ToolCall)) {
+ return runnerproto.ErrInvalid
+ }
+ name, args, e := codex.MCPApproval(original)
+ if e != nil {
+ return e
+ }
+ var fields map[string]json.RawMessage
+ if runnerproto.DecodeLimit(bytes.NewReader(args), &fields, maxToolFrame) != nil {
+ return runnerproto.ErrInvalid
+ }
+ var id string
+ if json.Unmarshal(fields["request_id"], &id) != nil {
+ return runnerproto.ErrInvalid
+ }
+ delete(fields, "request_id")
+ args, _ = json.Marshal(fields)
+ return r.Proxy.ValidateApproval(ctx, ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, Name: name, RequestID: id, Arguments: args})
+ }
+ if e = authorize(ctx, ev); e != nil {
+ return e
+ }
+ return r.Launcher.Respond(ctx, b.Session, provider.Answer{RequestID: ev.RequestID, TurnID: b.TurnID, Behavior: "allow", Authorize: authorize})
+ }
+ }
+ if ask == nil || r.Current == nil {
+ return runnerproto.ErrInvalid
+ }
+ q, e := DirectQuestionFromEvent(ev, b)
+ if e != nil {
+ return e
+ }
+ q.ExpiresAt, e = r.Current(ctx, q)
+ if e != nil || q.ExpiresAt.IsZero() || !time.Now().Before(q.ExpiresAt) {
+ return runnerproto.ErrInvalid
+ }
+ waitCtx, cancel := context.WithDeadline(ctx, q.ExpiresAt)
+ defer cancel()
+ answer, e := ask(waitCtx, q)
+ if e != nil {
+ return e
+ }
+ client := &directQuestionClient{launcher: r.Launcher, session: b.Session, turn: b.TurnID}
+ relay := QuestionRelay{Journal: b.Journal, Client: client, Agent: b.Agent, DirectSession: b.Session, TurnID: b.TurnID, Current: func(ctx context.Context, q runnerproto.Question) (time.Time, error) {
+ if e := b.Current(ctx); e != nil {
+ return time.Time{}, e
+ }
+ return r.Current(ctx, q)
+ }}
+ return relay.Deliver(waitCtx, q, answer)
+}
+
+type directQuestionClient struct {
+ launcher provider.Launcher
+ session provider.Session
+ turn string
+}
+
+func (c *directQuestionClient) Respond(ctx context.Context, _ paseo.Agent, a paseo.PermissionResponse) error {
+ return c.launcher.Respond(ctx, c.session, provider.Answer{RequestID: a.RequestID, TurnID: c.turn, Behavior: a.Behavior, Input: a.UpdatedInput})
+}
+func (c *directQuestionClient) Send(context.Context, paseo.Agent, string, string) error {
+ return runnerproto.ErrInvalid
+}
+
+func DirectQuestionFromEvent(ev provider.Event, b ToolBinding) (runnerproto.Question, error) {
+ q := runnerproto.Question{ID: runnerproto.EventHash([]any{b.InstanceID, b.TaskID, b.Attempt, b.Fence, ev.TurnID, ev.RequestID}), TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, ServerID: b.Agent.ServerID, AgentID: b.Agent.AgentID, SessionID: b.Session.ID, PermissionID: ev.RequestID, Kind: "tool", Revision: 1, ExpiresAt: b.LeaseDeadline}
+ if ev.Kind != "request" || ev.SessionID != b.Session.ID || ev.TurnID != b.TurnID || !uniqueFrame(ev.Payload) {
+ return q, runnerproto.ErrInvalid
+ }
+ name := ""
+ var input json.RawMessage
+ if b.Session.Provider == "claude" {
+ var p struct {
+ Tool string `json:"tool_name"`
+ Input json.RawMessage `json:"input"`
+ }
+ if runnerproto.DecodeLimit(bytes.NewReader(ev.Payload), &p, maxToolFrame) != nil {
+ return q, runnerproto.ErrInvalid
+ }
+ name = p.Tool
+ input = p.Input
+ if name == "AskUserQuestion" || name == "ask_person" {
+ q.Kind = "question"
+ }
+ } else if b.Session.Provider == "codex" {
+ var p struct {
+ Method string
+ Params json.RawMessage
+ }
+ if json.Unmarshal(ev.Payload, &p) != nil {
+ return q, runnerproto.ErrInvalid
+ }
+ name = p.Method
+ input = p.Params
+ if keys, e := codex.QuestionKeys(ev); e == nil {
+ q.Kind = "question"
+ name = "request_user_input"
+ questions := []any{}
+ for _, k := range keys {
+ questions = append(questions, map[string]string{"question": k, "header": k})
+ }
+ input, _ = json.Marshal(map[string]any{"questions": questions})
+ }
+ } else {
+ return q, runnerproto.ErrInvalid
+ }
+ q.RawRequest, _ = json.Marshal(map[string]any{"id": q.PermissionID, "kind": q.Kind, "provider": b.Session.Provider, "name": name, "input": input, "direct": true, "turn_id": b.TurnID, "request": json.RawMessage(ev.Payload)})
+ q.RawRequest = RedactJSON(q.RawRequest, nil)
+ return q, q.Validate()
+}
+
+// Ask returns a scoped MCP question's answer to that same tool call.
+func (r *DirectQuestionRelay) Ask(ctx context.Context, id string, args json.RawMessage, ask func(context.Context, runnerproto.Question) (runnerproto.QuestionAnswer, error)) (json.RawMessage, error) {
+ b := r.Binding
+ if b.Journal == nil || b.Current == nil || r.Current == nil || ask == nil || id == "" || validateToolArguments("ask_person", args) != nil {
+ return nil, runnerproto.ErrInvalid
+ }
+ var input PersonQuestion
+ _ = json.Unmarshal(args, &input)
+ permission := runnerproto.EventHash([]any{"ask", id, b.TurnID})
+ q := runnerproto.Question{ID: runnerproto.EventHash([]any{b.InstanceID, b.TaskID, b.Attempt, b.Fence, permission}), TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, ServerID: b.Agent.ServerID, AgentID: b.Agent.AgentID, SessionID: b.Session.ID, PermissionID: permission, Kind: "person", Revision: 1, ExpiresAt: b.LeaseDeadline}
+ q.RawRequest, _ = json.Marshal(map[string]any{"id": permission, "kind": "person", "question": input.Question})
+ if err := b.Current(ctx); err != nil {
+ return nil, err
+ }
+ if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil {
+ return nil, err
+ }
+ expiry, err := r.Current(ctx, q)
+ if err != nil || expiry.IsZero() || !time.Now().Before(expiry) {
+ return nil, runnerproto.ErrInvalid
+ }
+ ctx, cancel := context.WithDeadline(ctx, expiry)
+ defer cancel()
+ answer, err := ask(ctx, q)
+ if err != nil {
+ return nil, err
+ }
+ client := &scopedAnswerClient{}
+ relay := QuestionRelay{Journal: b.Journal, Agent: b.Agent, Client: client, DirectSession: b.Session, TurnID: b.TurnID, Current: func(ctx context.Context, q runnerproto.Question) (time.Time, error) {
+ if err := b.Current(ctx); err != nil {
+ return time.Time{}, err
+ }
+ return r.Current(ctx, q)
+ }}
+ if err = relay.Deliver(ctx, q, answer); err != nil {
+ return nil, err
+ }
+ if client.result == nil {
+ return nil, errDirectUncertain
+ }
+ return client.result, nil
+}
+
+type scopedAnswerClient struct{ result json.RawMessage }
+
+func (c *scopedAnswerClient) Respond(_ context.Context, _ paseo.Agent, a paseo.PermissionResponse) error {
+ if a.Behavior == "deny" {
+ c.result = json.RawMessage(`{"behavior":"deny"}`)
+ return nil
+ }
+ if a.Behavior != "allow" {
+ return runnerproto.ErrInvalid
+ }
+ c.result = bytes.Clone(a.UpdatedInput)
+ return nil
+}
+func (c *scopedAnswerClient) Send(context.Context, paseo.Agent, string, string) error {
+ return runnerproto.ErrInvalid
+}
diff --git a/internal/runner/direct_recovery.go b/internal/runner/direct_recovery.go
index e19e7506..21049e62 100644
--- a/internal/runner/direct_recovery.go
+++ b/internal/runner/direct_recovery.go
@@ -338,7 +338,7 @@ func (j *Journal) interruptDirect(ctx context.Context, attempt string, contained
if _, err = tx.ExecContext(ctx, "UPDATE direct_turns SET state='waiting_for_person',usage=NULL WHERE attempt=? AND state!='completed'", attempt); err != nil {
return err
}
- if _, err = tx.ExecContext(ctx, "UPDATE journal_answers SET state='invalid' WHERE state='pending'"); err != nil {
+ if _, err = tx.ExecContext(ctx, "UPDATE journal_answers SET state='invalid' WHERE state='pending' AND answer_key IN (SELECT answer_key FROM direct_answer_scopes WHERE attempt=?)", attempt); err != nil {
return err
}
return tx.Commit()
diff --git a/internal/runner/direct_recovery_test.go b/internal/runner/direct_recovery_test.go
index b4d490a6..9112ccee 100644
--- a/internal/runner/direct_recovery_test.go
+++ b/internal/runner/direct_recovery_test.go
@@ -165,7 +165,7 @@ func TestDirectJournalUpgrade(t *testing.T) {
defer j.Close()
var v int
mustJournal(t, j.db.QueryRow("PRAGMA user_version").Scan(&v))
- if v != 3 {
+ if v != 4 {
t.Fatalf("journal version %d", v)
}
events, err := j.Pending(ctx, 10)
diff --git a/internal/runner/direct_tools_test.go b/internal/runner/direct_tools_test.go
new file mode 100644
index 00000000..25bcf6e3
--- /dev/null
+++ b/internal/runner/direct_tools_test.go
@@ -0,0 +1,533 @@
+package runner
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func directToolFixture(t *testing.T) ToolBinding {
+ t.Helper()
+ j, _, s, _ := directFixture(t, "codex")
+ mustJournal(t, j.BeginTurn(context.Background(), s, directTurn()))
+ mustJournal(t, j.consumeTurn(context.Background(), s.AttemptKey, s.ID, "hello"))
+ return ToolBinding{Journal: j, Session: s, TurnID: "turn", InstanceID: "instance", TaskID: "task", Attempt: 1, Fence: 7, Tools: []string{"ask_person", "submit_candidate", "submit_review", "submit_reproduction"}, LeaseDeadline: time.Now().Add(time.Minute), Agent: paseo.Agent{Provider: "codex", ServerID: "direct", AgentID: s.AttemptKey, ProviderSessionID: s.ID}, Isolation: team.IsolationSnapshot{Status: "confined"}, Copy: ToolCopy{Accepted: "accepted", Rejected: "rejected"}, Current: func(context.Context) error { return nil }}
+}
+func TestDirectToolScope(t *testing.T) {
+ b := directToolFixture(t)
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ defer p.Close()
+ binary := filepath.Join(t.TempDir(), "equipo-tool-proxy")
+ build := exec.Command("go", "build", "-o", binary, "../../cmd/equipo-runner")
+ build.Env = append(os.Environ(), "CGO_ENABLED=0")
+ if out, e := build.CombinedOutput(); e != nil {
+ t.Fatalf("build: %v %s", e, out)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, binary, "--socket", p.SocketPath)
+ cmd.Env = []string{"PATH=/usr/bin:/bin"}
+ in, e := cmd.StdinPipe()
+ mustJournal(t, e)
+ out, e := cmd.StdoutPipe()
+ mustJournal(t, e)
+ mustJournal(t, cmd.Start())
+ t.Cleanup(func() {
+ if cmd.ProcessState == nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ }
+ })
+ enc := json.NewEncoder(in)
+ scan := bufio.NewScanner(out)
+ rpc := func(id int, method string, params any) map[string]any {
+ t.Helper()
+ mustJournal(t, enc.Encode(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}))
+ if !scan.Scan() {
+ t.Fatal("no helper reply", scan.Err())
+ }
+ var v map[string]any
+ mustJournal(t, json.Unmarshal(scan.Bytes(), &v))
+ return v
+ }
+ if rpc(1, "initialize", map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{}, "clientInfo": map[string]any{}})["error"] != nil {
+ t.Fatal("initialize")
+ }
+ tools := fmt.Sprint(rpc(2, "tools/list", map[string]any{}))
+ if strings.Contains(tools, "publish") || strings.Contains(tools, "attest") {
+ t.Fatal(tools)
+ }
+ args := []string{`{"request_id":"a","question":"Which?"}`, `{"request_id":"b","commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}`, `{"request_id":"c","candidate":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","decision":"approve","findings":[]}`, `{"request_id":"d","expected_symptom":"fails","files":[{"path":"x_test.go","bytes":"eA=="}],"test_names":[{"package":"./x","name":"TestX"}]}`}
+ for i, name := range b.Tools {
+ if v := rpc(3+i, "tools/call", map[string]any{"name": name, "arguments": json.RawMessage(args[i])}); v["error"] != nil {
+ t.Fatal(name, v)
+ }
+ rows, e := b.Journal.ToolSubmissions(ctx, 10)
+ mustJournal(t, e)
+ if len(rows) != 1 || rows[0].Fence != 7 || rows[0].Agent.ProviderSessionID != b.Session.ID {
+ t.Fatal(rows)
+ }
+ mustJournal(t, b.Journal.AckTool(ctx, rows[0]))
+ }
+ for i, name := range []string{"read_file", "publish", "attest_check", "ask_person"} {
+ a := json.RawMessage(`{"request_id":"evil","path":"/etc/passwd"}`)
+ if v := rpc(20+i, "tools/call", map[string]any{"name": name, "arguments": a}); v["error"] == nil {
+ t.Fatal("host authority", name)
+ }
+ }
+ in.Close()
+ mustJournal(t, cmd.Wait())
+}
+func TestToolProxyCannotExposeSecrets(t *testing.T) {
+ b := directToolFixture(t)
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ want := `{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}`
+ if string(p.MCP()) != want {
+ t.Fatal(string(p.MCP()))
+ }
+ if strings.Contains(string(p.MCP()), b.Journal.path) || strings.Contains(string(p.MCP()), "capability") {
+ t.Fatal("host secret exposed")
+ }
+ // A long host address is dialled through the verified parent fd by the helper.
+ if len(p.SocketPath) <= 107 {
+ t.Log("fixture address is short; separate long-path case covers fd binding")
+ }
+ mustJournal(t, p.Close())
+ mustJournal(t, p.Close())
+ if _, e := os.Stat(p.SocketPath); !os.IsNotExist(e) {
+ t.Fatal("proxy survived close", e)
+ }
+}
+func TestToolProxyLongPath(t *testing.T) {
+ b := directToolFixture(t)
+ path := filepath.Join(t.TempDir(), strings.Repeat("long", 30), "journal.db")
+ j, e := OpenJournal(context.Background(), path)
+ mustJournal(t, e)
+ defer j.Close()
+ // Proxy storage location is independent of the authenticated attempt journal.
+ p, e := openToolProxy(context.Background(), b, filepath.Dir(path))
+ mustJournal(t, e)
+ defer p.Close()
+ var out strings.Builder
+ input := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}` + "\n"
+ mustJournal(t, ServeToolProxy(context.Background(), strings.NewReader(input), &out, p.SocketPath))
+ if !strings.Contains(out.String(), "serverInfo") {
+ t.Fatal(out.String())
+ }
+}
+func TestCodexApprovalResponseBroker(t *testing.T) {
+ for _, change := range []string{"ok", "fence", "attempt", "tool", "arguments", "lost-lease", "execute-revalidate"} {
+ t.Run(change, func(t *testing.T) {
+ b := directToolFixture(t)
+ current := true
+ b.Current = func(context.Context) error {
+ if !current {
+ return runnerproto.ErrInvalid
+ }
+ return nil
+ }
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ defer p.Close()
+ q := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, Name: "ask_person", RequestID: "r", Arguments: json.RawMessage(`{"question":"Which?"}`)}
+ switch change {
+ case "fence":
+ q.Fence++
+ case "attempt":
+ q.Attempt++
+ case "tool":
+ q.Name = "publish"
+ case "arguments":
+ q.Arguments = json.RawMessage(`{"question":"Which?","command":"cat /etc/passwd"}`)
+ case "lost-lease":
+ current = false
+ }
+ e = p.ValidateApproval(context.Background(), q)
+ if change == "ok" || change == "execute-revalidate" {
+ mustJournal(t, e)
+ } else if e == nil {
+ t.Fatal("invalid approval", change)
+ }
+ if change == "execute-revalidate" {
+ current = false
+ if p.submit(context.Background(), q.Name, q.RequestID, q.Arguments) == nil {
+ t.Fatal("execution did not revalidate")
+ }
+ }
+ })
+ }
+}
+func TestDirectStaleAnswer(t *testing.T) {
+ for _, change := range []string{"cancel", "restart", "replaced-turn", "revoked-member", "replayed-changed-payload"} {
+ t.Run(change, func(t *testing.T) {
+ b := directToolFixture(t)
+ c := &answerClient{}
+ current := true
+ r := QuestionRelay{Journal: b.Journal, Client: c, Agent: b.Agent, DirectSession: b.Session, TurnID: b.TurnID, Current: func(context.Context, runnerproto.Question) (time.Time, error) {
+ if !current {
+ return time.Time{}, runnerproto.ErrInvalid
+ }
+ return b.LeaseDeadline, nil
+ }}
+ q := runnerproto.Question{ID: "q", TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, ServerID: b.Agent.ServerID, AgentID: b.Agent.AgentID, SessionID: b.Session.ID, PermissionID: "r", Kind: "person", Revision: 1, ExpiresAt: b.LeaseDeadline, RawRequest: json.RawMessage(`{"id":"r","kind":"person","question":"Which?"}`)}
+ a := runnerproto.QuestionAnswer{Behavior: "deny"}
+ switch change {
+ case "cancel":
+ mustJournal(t, b.Journal.interruptDirect(context.Background(), b.Session.AttemptKey, false))
+ case "restart":
+ _, e := b.Journal.RecoverDirect(context.Background())
+ mustJournal(t, e)
+ case "replaced-turn":
+ r.TurnID = "other"
+ case "revoked-member":
+ current = false
+ case "replayed-changed-payload":
+ mustJournal(t, r.Deliver(context.Background(), q, a))
+ q.RawRequest = json.RawMessage(`{"id":"r","kind":"person","question":"Changed?"}`)
+ }
+ before := len(c.responses)
+ if r.Deliver(context.Background(), q, a) == nil || len(c.responses) != before {
+ t.Fatal("stale answer delivered", change)
+ }
+ })
+ }
+}
+func TestDirectStaleAnswerCancelIsAttemptScoped(t *testing.T) {
+ b := directToolFixture(t)
+ ctx := context.Background()
+ var launchRaw, recordRaw []byte
+ mustJournal(t, b.Journal.db.QueryRow("SELECT launch,record FROM direct_attempts WHERE attempt='attempt'").Scan(&launchRaw, &recordRaw))
+ var launch provider.Launch
+ var record containment.Record
+ mustJournal(t, json.Unmarshal(launchRaw, &launch))
+ mustJournal(t, json.Unmarshal(recordRaw, &record))
+ launch.AttemptKey = "B"
+ record.AttemptKey = "B"
+ record.ID = strings.Repeat("b", 32)
+ mustJournal(t, b.Journal.recordDirectLaunch(ctx, launch, record))
+ sessionB := b.Session
+ sessionB.AttemptKey = "B"
+ sessionB.ID = "session-B"
+ turnB := provider.Turn{ID: "turn", AdmissionID: "admission-B", Prompt: "hello"}
+ mustJournal(t, b.Journal.BeginTurn(ctx, sessionB, turnB))
+ mustJournal(t, b.Journal.consumeTurn(ctx, "B", sessionB.ID, "hello"))
+ for _, a := range []string{"attempt", "B"} {
+ _, e := b.Journal.db.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,?,'pending')", a, "hash")
+ mustJournal(t, e)
+ _, e = b.Journal.db.ExecContext(ctx, "INSERT INTO direct_answer_scopes(answer_key,attempt,turn) VALUES(?,?,?)", a, a, "turn")
+ mustJournal(t, e)
+ }
+ mustJournal(t, b.Journal.interruptDirect(ctx, "attempt", false))
+ mustJournal(t, b.Journal.currentDirectTurn(ctx, sessionB, "turn"))
+ var state string
+ mustJournal(t, b.Journal.db.QueryRow("SELECT state FROM journal_answers WHERE answer_key='B'").Scan(&state))
+ if state != "pending" {
+ t.Fatal("attempt B answer invalidated by A", state)
+ }
+ mustJournal(t, b.Journal.db.QueryRow("SELECT state FROM journal_answers WHERE answer_key='attempt'").Scan(&state))
+ if state != "invalid" {
+ t.Fatal("A answer survived", state)
+ }
+}
+
+func TestDirectToolAnswerCapture(t *testing.T) {
+ j, l, s, p := directFixture(t, "codex")
+ ctx := context.Background()
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
+ input := &captureInput{journal: j, launch: l, input: p.Stdin(), ctx: ctx, fail: func(error) {}}
+ wire := []byte("{\"id\":7,\"result\":{\"decision\":\"decline\"}}\n")
+ if _, e := input.Write(wire); e == nil {
+ t.Fatal("ordinary stdin accepted uncorrelated reply")
+ }
+ if _, e := input.WriteAnswer(ctx, s, "turn", wire); e != nil {
+ t.Fatal("correlated answer rejected", e)
+ }
+ before := p.input.Len()
+ if _, e := input.WriteAnswer(ctx, s, "turn", wire); e == nil || p.input.Len() != before {
+ t.Fatal("answer replay transmitted")
+ }
+ for _, raw := range []string{"{\"id\":8,\"method\":\"turn/start\",\"params\":{}}\n", "{\"id\":8,\"result\":{\"decision\":{\"acceptWithExecpolicyAmendment\":{}}}}\n"} {
+ if _, e := input.WriteAnswer(ctx, s, "turn", []byte(raw)); e == nil {
+ t.Fatal("hidden turn or policy amendment", raw)
+ }
+ }
+ mustJournal(t, j.interruptDirect(ctx, s.AttemptKey, false))
+ if _, e := input.WriteAnswer(ctx, s, "turn", []byte("{\"id\":8,\"result\":{\"decision\":\"decline\"}}\n")); e == nil {
+ t.Fatal("cancelled answer sent")
+ }
+}
+
+type directAnswerLauncher struct {
+ provider.Launcher
+ answers []provider.Answer
+}
+
+func (l *directAnswerLauncher) Respond(ctx context.Context, s provider.Session, a provider.Answer) error {
+ l.answers = append(l.answers, a)
+ return nil
+}
+func TestCodexApprovalResponseRouting(t *testing.T) {
+ b := directToolFixture(t)
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ defer p.Close()
+ l := &directAnswerLauncher{}
+ relay := DirectQuestionRelay{Binding: b, Proxy: p, Launcher: l, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return b.LeaseDeadline, nil }}
+ for i, method := range []string{"mcpServer/elicitation/request", "item/commandExecution/requestApproval", "item/fileChange/requestApproval"} {
+ ev := provider.Event{Kind: "request", SessionID: b.Session.ID, TurnID: b.TurnID, RequestID: fmt.Sprint(i), Payload: json.RawMessage(fmt.Sprintf(`{"id":%d,"method":%q,"params":{"threadId":"session","turnId":"provider-turn","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, i, method))}
+ ev = pinnedRunnerMCP(ev)
+ asked := 0
+ mustJournal(t, relay.Handle(context.Background(), ev, func(ctx context.Context, q runnerproto.Question) (runnerproto.QuestionAnswer, error) {
+ asked++
+ if q.Validate() != nil || q.RawRequest == nil {
+ t.Fatal(q)
+ }
+ return runnerproto.QuestionAnswer{Behavior: "deny"}, nil
+ }))
+ if i == 0 {
+ if asked != 0 || l.answers[i].Behavior != "allow" || l.answers[i].Authorize == nil {
+ t.Fatal("Equipo MCP not validated", asked, l.answers)
+ }
+ } else if asked != 1 || l.answers[i].Behavior != "deny" {
+ t.Fatal("non-Equipo approval not relayed", asked, l.answers)
+ }
+ }
+}
+
+func TestToolProxyLifecycle(t *testing.T) {
+ for _, cause := range []string{"cancel", "lease", "restart", "pending"} {
+ t.Run(cause, func(t *testing.T) {
+ b := directToolFixture(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ var live atomic.Bool
+ live.Store(true)
+ b.Current = func(context.Context) error {
+ if !live.Load() {
+ return runnerproto.ErrInvalid
+ }
+ return nil
+ }
+ saved := b.Session
+ if cause == "pending" {
+ b.Session = provider.Session{}
+ b.TurnID = ""
+ }
+ p, e := OpenToolProxy(ctx, b)
+ mustJournal(t, e)
+ defer p.Close()
+ if cause == "pending" {
+ if p.submit(ctx, "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`)) == nil {
+ t.Fatal("unbound attempt accepted")
+ }
+ mustJournal(t, p.BindTurn(saved, "turn"))
+ mustJournal(t, p.submit(ctx, "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`)))
+ return
+ }
+ switch cause {
+ case "cancel":
+ cancel()
+ case "lease":
+ live.Store(false)
+ case "restart":
+ _, e = b.Journal.RecoverDirect(ctx)
+ mustJournal(t, e)
+ }
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ if _, e = os.Stat(p.SocketPath); os.IsNotExist(e) {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatal("invalid endpoint remained live", cause)
+ })
+ }
+}
+func TestCodexApprovalResponseChangedOriginal(t *testing.T) {
+ b := directToolFixture(t)
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ defer p.Close()
+ l := &directAnswerLauncher{}
+ relay := DirectQuestionRelay{Binding: b, Proxy: p, Launcher: l}
+ ev := provider.Event{Kind: "request", SessionID: b.Session.ID, TurnID: b.TurnID, RequestID: "7", Payload: json.RawMessage(`{"id":7,"method":"mcpServer/elicitation/request","params":{"threadId":"session","turnId":"provider-turn","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Original?"}}}`)}
+ ev = pinnedRunnerMCP(ev)
+ mustJournal(t, relay.Handle(context.Background(), ev, nil))
+ changed := ev
+ changed.Payload = json.RawMessage(strings.Replace(string(ev.Payload), "Original?", "Changed?", 1))
+ changed.ToolCall = json.RawMessage(strings.Replace(string(ev.ToolCall), "Original?", "Changed?", 1))
+ if l.answers[0].Authorize(context.Background(), changed) == nil {
+ t.Fatal("changed arguments approved")
+ }
+}
+
+func TestToolProxyCannotExposeSecretsHostileFrames(t *testing.T) {
+ b := directToolFixture(t)
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ defer p.Close()
+ for _, params := range []string{`{"name":"read_file","arguments":{"path":"/etc/passwd"}}`, `{"name":"publish","arguments":{"request_id":"r"}}`, `{"name":"ask_person","arguments":{"request_id":"r","question":"Hi?","fence":8}}`, `{"name":"ask_person","arguments":{"request_id":"r","question":"Hi?"},"capability":"steal"}`} {
+ var out strings.Builder
+ input := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}` + "\n" + `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":` + params + "}\n"
+ mustJournal(t, ServeToolProxy(context.Background(), strings.NewReader(input), &out, p.SocketPath))
+ if !strings.Contains(out.String(), `"error"`) || strings.Contains(out.String(), p.broker.capability.Secret) || strings.Contains(out.String(), b.Journal.path) {
+ t.Fatal("host authority leaked", out.String())
+ }
+ }
+}
+func TestDirectStaleAnswerTurnAssociation(t *testing.T) {
+ b := directToolFixture(t)
+ ctx := context.Background()
+ c := &answerClient{}
+ r := QuestionRelay{Journal: b.Journal, Client: c, Agent: b.Agent, DirectSession: b.Session, TurnID: b.TurnID, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return b.LeaseDeadline, nil }}
+ q := runnerproto.Question{ID: "q", TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, ServerID: b.Agent.ServerID, AgentID: b.Agent.AgentID, SessionID: b.Session.ID, PermissionID: "same-id", Kind: "person", Revision: 1, ExpiresAt: b.LeaseDeadline, RawRequest: json.RawMessage(`{"id":"same-id","kind":"person","question":"Hi?"}`)}
+ mustJournal(t, r.Deliver(ctx, q, runnerproto.QuestionAnswer{Behavior: "deny"}))
+ _, e := b.Journal.db.Exec("UPDATE direct_turns SET state='completed'")
+ mustJournal(t, e)
+ turn := provider.Turn{ID: "next", AdmissionID: "next", Prompt: "next"}
+ mustJournal(t, b.Journal.BeginTurn(ctx, b.Session, turn))
+ mustJournal(t, b.Journal.consumeTurn(ctx, b.Session.AttemptKey, b.Session.ID, "next"))
+ r.TurnID = "next"
+ if r.Deliver(ctx, q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil {
+ t.Fatal("previous turn answer reused in replacement turn")
+ }
+}
+
+func pinnedRunnerMCP(ev provider.Event) provider.Event {
+ var v map[string]any
+ _ = json.Unmarshal(ev.Payload, &v)
+ if v["method"] != "mcpServer/elicitation/request" {
+ return ev
+ }
+ p := v["params"].(map[string]any)
+ ev.ToolCall, _ = json.Marshal(map[string]any{"method": "item/started", "params": map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "item": map[string]any{"id": "item", "type": "mcpToolCall", "server": "equipo", "tool": p["tool"], "arguments": p["arguments"], "status": "inProgress"}}})
+ v["params"] = map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "serverName": "equipo", "mode": "form", "message": "fixture", "requestedSchema": map[string]any{"type": "object", "properties": map[string]any{}}, "_meta": map[string]any{"codex_approval_kind": "mcp_tool_call", "tool_params": p["arguments"]}}
+ ev.Payload, _ = json.Marshal(v)
+ return ev
+}
+
+func TestDirectToolScopedAskAnswer(t *testing.T) {
+ b := directToolFixture(t)
+ asked := 0
+ b.Ask = func(ctx context.Context, bound ToolBinding, id string, args json.RawMessage) (json.RawMessage, error) {
+ relay := DirectQuestionRelay{Binding: bound, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return bound.LeaseDeadline, nil }}
+ return relay.Ask(ctx, id, args, func(_ context.Context, q runnerproto.Question) (runnerproto.QuestionAnswer, error) {
+ asked++
+ if q.Kind != "person" || q.SessionID != bound.Session.ID {
+ t.Fatal(q)
+ }
+ return runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"answer":"blue"}}`)}, nil
+ })
+ }
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ defer p.Close()
+ input := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}` + "\n" + `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ask_person","arguments":{"request_id":"ask-1","question":"Which colour?"}}}` + "\n"
+ var out strings.Builder
+ mustJournal(t, ServeToolProxy(context.Background(), strings.NewReader(input), &out, p.SocketPath))
+ if !strings.Contains(out.String(), "blue") || asked != 1 {
+ t.Fatal("scoped answer not returned", out.String(), asked)
+ }
+}
+
+func TestToolProxyBindBeforeDispatch(t *testing.T) {
+ b := directToolFixture(t)
+ saved := b.Session
+ _, e := b.Journal.db.Exec("UPDATE direct_turns SET state='completed'")
+ mustJournal(t, e)
+ b.Session = provider.Session{}
+ b.TurnID = ""
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ defer p.Close()
+ mustJournal(t, p.BindTurn(saved, "next"))
+ turn := provider.Turn{ID: "next", AdmissionID: "next", Prompt: "next"}
+ mustJournal(t, b.Journal.BeginTurn(context.Background(), saved, turn))
+ mustJournal(t, b.Journal.consumeTurn(context.Background(), saved.AttemptKey, saved.ID, "next"))
+ mustJournal(t, p.submit(context.Background(), "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`)))
+}
+
+func TestCodexApprovalResponseIdempotency(t *testing.T) {
+ b := directToolFixture(t)
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ defer p.Close()
+ ctx := context.Background()
+ args := json.RawMessage(`{"question":"Original?"}`)
+ mustJournal(t, p.submit(ctx, "ask_person", "r", args))
+ q := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, Name: "ask_person", RequestID: "r", Arguments: args}
+ mustJournal(t, p.ValidateApproval(ctx, q))
+ q.Arguments = json.RawMessage(`{"question":"Changed?"}`)
+ if p.ValidateApproval(ctx, q) == nil {
+ t.Fatal("changed replay arguments approved")
+ }
+}
+func TestToolProxyBindingIdentity(t *testing.T) {
+ for _, field := range []string{"account", "model", "provider", "session"} {
+ t.Run(field, func(t *testing.T) {
+ b := directToolFixture(t)
+ switch field {
+ case "account":
+ b.Session.AccountID = "other"
+ case "model":
+ b.Session.Model = "other"
+ case "provider":
+ b.Session.Provider = "claude"
+ b.Agent.Provider = "claude"
+ case "session":
+ b.Agent.ProviderSessionID = "other"
+ }
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ defer p.Close()
+ if p.submit(context.Background(), "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`)) == nil {
+ t.Fatal("mismatched bound identity", field)
+ }
+ })
+ }
+}
+
+func TestCodexApprovalResponseToolAllowlist(t *testing.T) {
+ b := directToolFixture(t)
+ b.Tools = []string{"ask_person"}
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ defer p.Close()
+ q := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, Name: "submit_candidate", RequestID: "r", Arguments: json.RawMessage(`{"commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}`)}
+ if p.ValidateApproval(context.Background(), q) == nil {
+ t.Fatal("valid but unscoped tool approved")
+ }
+}
+
+func TestToolProxyRenewedLease(t *testing.T) {
+ b := directToolFixture(t)
+ b.LeaseDeadline = time.Now().Add(150 * time.Millisecond)
+ p, e := OpenToolProxy(context.Background(), b)
+ mustJournal(t, e)
+ defer p.Close()
+ mustJournal(t, p.RenewLease(context.Background(), time.Now().Add(time.Second)))
+ time.Sleep(200 * time.Millisecond)
+ mustJournal(t, p.submit(context.Background(), "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`)))
+ mustJournal(t, p.Close())
+ if p.RenewLease(context.Background(), time.Now().Add(time.Minute)) == nil {
+ t.Fatal("closed lease revived")
+ }
+}
diff --git a/internal/runner/journal.go b/internal/runner/journal.go
index 484eebed..5bd445ee 100644
--- a/internal/runner/journal.go
+++ b/internal/runner/journal.go
@@ -82,7 +82,7 @@ func OpenJournal(ctx context.Context, path string) (*Journal, error) {
db.SetMaxOpenConns(1)
j := &Journal{db: db, path: path, maxBytes: MaxJournalBytes}
var version int
- if err = db.QueryRowContext(ctx, "PRAGMA user_version").Scan(&version); err != nil || version > 3 {
+ if err = db.QueryRowContext(ctx, "PRAGMA user_version").Scan(&version); err != nil || version > 4 {
db.Close()
return nil, ErrJournal
}
@@ -116,6 +116,11 @@ func OpenJournal(ctx context.Context, path string) (*Journal, error) {
CREATE INDEX IF NOT EXISTS journal_events_direct_pending ON journal_events(json_extract(body,'$.agent_id')) WHERE acked=0;
DELETE FROM direct_frames WHERE pending=0;
PRAGMA user_version=3;`)
+ }
+ if err == nil && version < 4 {
+ _, err = tx.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS direct_answer_scopes(answer_key TEXT PRIMARY KEY,attempt TEXT NOT NULL,turn TEXT NOT NULL);
+ CREATE INDEX IF NOT EXISTS direct_answer_attempt ON direct_answer_scopes(attempt,turn);
+ PRAGMA user_version=4;`)
}
if err == nil {
_, err = tx.ExecContext(ctx, "UPDATE journal_streams SET ready=0")
diff --git a/internal/runner/journal_test.go b/internal/runner/journal_test.go
index e38dc601..953dc278 100644
--- a/internal/runner/journal_test.go
+++ b/internal/runner/journal_test.go
@@ -338,7 +338,7 @@ func TestRunnerJournalDurabilityConfiguration(t *testing.T) {
if syncLevel != 2 || mode != "delete" {
t.Fatal("journal writes are not durably synced", syncLevel, mode)
}
- _, err = j.db.Exec("PRAGMA user_version=4")
+ _, err = j.db.Exec("PRAGMA user_version=5")
mustJournal(t, err)
mustJournal(t, j.Close())
if other, err := OpenJournal(journalCtx, path); err == nil {
diff --git a/internal/runner/provider/answers.go b/internal/runner/provider/answers.go
new file mode 100644
index 00000000..afc37883
--- /dev/null
+++ b/internal/runner/provider/answers.go
@@ -0,0 +1,29 @@
+package provider
+
+import (
+ "bytes"
+ "encoding/json"
+ "io"
+ "strings"
+)
+
+// QuestionAnswers admits only a complete set of answers for the original keys.
+// Provider tool inputs, permissions and commands cannot be replaced by a reply.
+func QuestionAnswers(raw json.RawMessage, keys []string) (map[string]string, error) {
+ var v struct {
+ Answers map[string]string `json:"answers"`
+ }
+ d := json.NewDecoder(bytes.NewReader(raw))
+ d.DisallowUnknownFields()
+ if d.Decode(&v) != nil || d.Decode(new(any)) != io.EOF || len(keys) == 0 || len(v.Answers) != len(keys) {
+ return nil, ErrPolicy
+ }
+ seen := map[string]bool{}
+ for _, key := range keys {
+ if key == "" || seen[key] || strings.TrimSpace(v.Answers[key]) == "" || len(v.Answers[key]) > 8192 {
+ return nil, ErrPolicy
+ }
+ seen[key] = true
+ }
+ return v.Answers, nil
+}
diff --git a/internal/runner/provider/claude/answers.go b/internal/runner/provider/claude/answers.go
new file mode 100644
index 00000000..289363f6
--- /dev/null
+++ b/internal/runner/provider/claude/answers.go
@@ -0,0 +1,183 @@
+package claude
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/json"
+ "io"
+ "path/filepath"
+ "slices"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+type permissionRequest struct {
+ Tool string `json:"tool_name"`
+ Input json.RawMessage `json:"input"`
+}
+type pendingPermission struct {
+ request permissionRequest
+ turn string
+ reply chan json.RawMessage
+}
+
+// Permission is called only by the bound MCP endpoint. Respond resolves this
+// exact call; it never writes a user message to Claude's stdin.
+func (l *Launcher) Permission(ctx context.Context, session provider.Session, raw json.RawMessage) (json.RawMessage, error) {
+ var q permissionRequest
+ d := json.NewDecoder(bytes.NewReader(raw))
+ d.DisallowUnknownFields()
+ if !uniqueJSON(raw) || d.Decode(&q) != nil || d.Decode(new(any)) != io.EOF || q.Tool == "" || !uniqueJSON(q.Input) || len(raw) > MaxFrameBytes {
+ return nil, errProtocol
+ }
+ var input map[string]json.RawMessage
+ if json.Unmarshal(q.Input, &input) != nil || input == nil {
+ return nil, errProtocol
+ }
+ l.mu.Lock()
+ s, e := l.state(session)
+ if e != nil {
+ l.mu.Unlock()
+ return nil, e
+ }
+ if !s.active || s.closed || s.err != nil || s.ctx.Err() != nil || !s.attached {
+ l.mu.Unlock()
+ return nil, errNotReady
+ }
+ id := "permission:" + rand.Text()
+ p := &pendingPermission{request: q, turn: s.turn.ID, reply: make(chan json.RawMessage, 1)}
+ if s.permissions == nil {
+ s.permissions = map[string]*pendingPermission{}
+ }
+ if len(s.permissions) >= 64 {
+ l.mu.Unlock()
+ return nil, errNotReady
+ }
+ s.permissions[id] = p
+ ev := provider.Event{SessionID: session.ID, TurnID: s.turn.ID, RequestID: id, Kind: "request", Payload: bytes.Clone(raw)}
+ select {
+ case s.events <- ev:
+ default:
+ delete(s.permissions, id)
+ l.mu.Unlock()
+ return nil, errNotReady
+ }
+ l.mu.Unlock()
+ defer func() { l.mu.Lock(); delete(s.permissions, id); l.mu.Unlock() }()
+ select {
+ case reply := <-p.reply:
+ return reply, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-s.ctx.Done():
+ return nil, errNotReady
+ }
+}
+func permissionResult(q permissionRequest, a provider.Answer, policy provider.Policy) (json.RawMessage, error) {
+ if a.Behavior == "deny" && len(a.Input) == 0 {
+ return json.RawMessage(`{"behavior":"deny"}`), nil
+ }
+ if a.Behavior != "allow" {
+ return nil, provider.ErrPolicy
+ }
+ var input map[string]json.RawMessage
+ if json.Unmarshal(q.Input, &input) != nil || input == nil {
+ return nil, provider.ErrPolicy
+ }
+ if q.Tool == "AskUserQuestion" || q.Tool == "ask_person" {
+ var keys []string
+ if q.Tool == "ask_person" {
+ var text string
+ if json.Unmarshal(input["question"], &text) != nil || strings.TrimSpace(text) == "" {
+ return nil, provider.ErrPolicy
+ }
+ keys = []string{"answer"}
+ } else {
+ var questions []struct{ Question string }
+ if json.Unmarshal(input["questions"], &questions) != nil {
+ return nil, provider.ErrPolicy
+ }
+ for _, v := range questions {
+ keys = append(keys, v.Question)
+ }
+ }
+ if !uniqueJSON(a.Input) {
+ return nil, provider.ErrPolicy
+ }
+ answers, e := provider.QuestionAnswers(a.Input, keys)
+ if e != nil {
+ return nil, e
+ }
+ input["answers"], _ = json.Marshal(answers)
+ } else {
+ // Only the original native action can be allowed, under the unchanged policy.
+ if len(a.Input) != 0 || !slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep", "Bash"}, q.Tool) {
+ return nil, provider.ErrPolicy
+ }
+ var m manifest
+ if json.Unmarshal(policy.Manifest, &m) != nil || !slices.Contains(m.Tools, q.Tool) {
+ return nil, provider.ErrPolicy
+ }
+ fields := map[string][]string{
+ "Read": {"file_path", "offset", "limit", "pages"},
+ "Write": {"file_path", "content"},
+ "Edit": {"file_path", "old_string", "new_string", "replace_all"},
+ "Glob": {"pattern", "path"},
+ "Grep": {"pattern", "path", "glob", "output_mode", "-A", "-B", "-C", "context", "-n", "-i", "type", "head_limit", "offset", "multiline"},
+ "Bash": {"command", "description", "timeout", "run_in_background"},
+ }
+ for key := range input {
+ if !slices.Contains(fields[q.Tool], key) {
+ return nil, provider.ErrPolicy
+ }
+ }
+ for key := range input {
+ switch key {
+ case "dangerouslyDisableSandbox", "permissions", "sandbox", "permissionMode", "updatedPermissions":
+ return nil, provider.ErrPolicy
+ }
+ }
+ for _, key := range []string{"file_path", "path"} {
+ var path string
+ if v, ok := input[key]; ok {
+ if json.Unmarshal(v, &path) != nil {
+ return nil, provider.ErrPolicy
+ }
+ if !filepath.IsAbs(path) {
+ path = filepath.Join("/workspace", path)
+ }
+ path = filepath.Clean(path)
+ for _, deny := range m.DeniedPaths {
+ if path == deny || strings.HasPrefix(path, deny+"/") {
+ return nil, provider.ErrPolicy
+ }
+ }
+ }
+ }
+ }
+ return json.Marshal(map[string]any{"behavior": "allow", "updatedInput": input})
+}
+func (l *Launcher) respond(ctx context.Context, session provider.Session, a provider.Answer) error {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ s, e := l.state(session)
+ if e != nil {
+ return e
+ }
+ p := s.permissions[a.RequestID]
+ if p == nil || !s.active || s.closed || s.err != nil || ctx.Err() != nil || s.ctx.Err() != nil || a.TurnID != s.turn.ID || p.turn != a.TurnID {
+ return errNotReady
+ }
+ if e = s.lease.ValidatePolicy(ctx); e != nil {
+ return e
+ }
+ result, e := permissionResult(p.request, a, s.launch.Policy)
+ if e != nil {
+ return e
+ }
+ delete(s.permissions, a.RequestID)
+ p.reply <- result
+ return nil
+}
diff --git a/internal/runner/provider/claude/answers_test.go b/internal/runner/provider/claude/answers_test.go
new file mode 100644
index 00000000..6f30c32a
--- /dev/null
+++ b/internal/runner/provider/claude/answers_test.go
@@ -0,0 +1,112 @@
+package claude
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "context"
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestClaudePermissionResponse(t *testing.T) {
+ f := fixtureFor(t, "Engineering")
+ s, events := openFixture(t, f)
+ f.l.mu.Lock()
+ st, _ := f.l.state(s)
+ st.active = true
+ st.turn = provider.Turn{ID: "turn"}
+ f.l.mu.Unlock()
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ raw := json.RawMessage(`{"tool_name":"AskUserQuestion","input":{"questions":[{"question":"Which?","options":[{"label":"blue"}]}]}}`)
+ result := make(chan json.RawMessage, 1)
+ errs := make(chan error, 1)
+ go func() { v, e := f.l.Permission(ctx, s, raw); result <- v; errs <- e }()
+ var ev provider.Event
+ select {
+ case ev = <-events:
+ case <-ctx.Done():
+ t.Fatal("permission not relayed")
+ }
+ if ev.Kind != "request" || ev.RequestID == "" {
+ t.Fatal(ev)
+ }
+ for _, input := range []string{`{"answers":{"Which?":"blue"},"command":"evil"}`, `{"answers":{"Other?":"blue"}}`} {
+ if f.l.Respond(ctx, s, provider.Answer{TurnID: "turn", RequestID: ev.RequestID, Behavior: "allow", Input: json.RawMessage(input)}) == nil {
+ t.Fatal("widened answer accepted", input)
+ }
+ }
+ f.capture.mu.Lock()
+ before := f.capture.inputs
+ f.capture.mu.Unlock()
+ if e := f.l.Respond(ctx, s, provider.Answer{TurnID: "turn", RequestID: ev.RequestID, Behavior: "allow", Input: json.RawMessage(`{"answers":{"Which?":"blue"}}`)}); e != nil {
+ t.Fatal(e)
+ }
+ reply := <-result
+ if e := <-errs; e != nil {
+ t.Fatal(e)
+ }
+ var v struct {
+ Behavior string
+ UpdatedInput map[string]json.RawMessage
+ }
+ if json.Unmarshal(reply, &v) != nil || v.Behavior != "allow" || !strings.Contains(string(v.UpdatedInput["questions"]), "options") || !strings.Contains(string(v.UpdatedInput["answers"]), "blue") {
+ t.Fatal(string(reply))
+ }
+ f.capture.mu.Lock()
+ after := f.capture.inputs
+ f.capture.mu.Unlock()
+ if before != after {
+ t.Fatal("permission reply sent an ordinary prompt")
+ }
+ if f.l.Respond(ctx, s, provider.Answer{TurnID: "turn", RequestID: ev.RequestID, Behavior: "deny"}) == nil {
+ t.Fatal("replayed answer")
+ }
+ for _, name := range f.inputs.Tools {
+ if name == "AskUserQuestion" {
+ t.Fatal("built-in question added to specialist tools")
+ }
+ }
+}
+
+func TestClaudePermissionResponseNativePolicy(t *testing.T) {
+ f := fixtureFor(t, "Engineering")
+ original := permissionRequest{Tool: "Write", Input: json.RawMessage(`{"file_path":"/workspace/hello.txt","content":"hi"}`)}
+ reply, e := permissionResult(original, provider.Answer{Behavior: "allow"}, f.launch.Policy)
+ if e != nil || !strings.Contains(string(reply), `"content":"hi"`) {
+ t.Fatal("original input lost", string(reply), e)
+ }
+ for _, raw := range []string{`{"file_path":"/tool/equipo.sock","content":"hi"}`, `{"file_path":"/workspace/a","content":"hi","policyAmendment":true}`, `{"file_path":"/workspace/a","content":"hi","dangerouslyDisableSandbox":true}`} {
+ bad := original
+ bad.Input = json.RawMessage(raw)
+ if _, e := permissionResult(bad, provider.Answer{Behavior: "allow"}, f.launch.Policy); e == nil {
+ t.Fatal("native policy widened", raw)
+ }
+ }
+ if _, e := permissionResult(original, provider.Answer{Behavior: "allow", Input: json.RawMessage(`{"file_path":"/workspace/replaced"}`)}, f.launch.Policy); e == nil {
+ t.Fatal("native tool input replaced")
+ }
+ deny, e := permissionResult(original, provider.Answer{Behavior: "deny"}, f.launch.Policy)
+ if e != nil || string(deny) != `{"behavior":"deny"}` {
+ t.Fatal(string(deny), e)
+ }
+}
+
+func TestClaudePermissionResponseScopedMCPPolicy(t *testing.T) {
+ f := fixtureFor(t, "Engineering")
+ in := f.inputs
+ in.Tools = []string{"mcp__equipo__ask_person", "mcp__equipo__submit_candidate"}
+ got, e := PolicyInputs(f.lease.Binding(), in, "Engineering", "claude-haiku-5-5")
+ if e != nil {
+ t.Fatal(e)
+ }
+ var settings struct{ Permissions struct{ Allow []string } }
+ if json.Unmarshal(got.Settings, &settings) != nil || strings.Join(settings.Permissions.Allow, ",") != strings.Join(in.Tools, ",") {
+ t.Fatal("scoped MCP would fall through native permission hook", string(got.Settings))
+ }
+ in.Tools = []string{"mcp__equipo__publish"}
+ if _, e = PolicyInputs(f.lease.Binding(), in, "Engineering", "claude-haiku-5-5"); e == nil {
+ t.Fatal("unscoped MCP permission")
+ }
+}
diff --git a/internal/runner/provider/claude/launcher.go b/internal/runner/provider/claude/launcher.go
index 9e86a585..15311997 100644
--- a/internal/runner/provider/claude/launcher.go
+++ b/internal/runner/provider/claude/launcher.go
@@ -9,6 +9,7 @@ import (
"fmt"
"path/filepath"
"reflect"
+ "slices"
"sort"
"strings"
"sync"
@@ -34,6 +35,7 @@ type Launcher struct {
sessions map[string]*sessionState
}
type sessionState struct {
+ permissions map[string]*pendingPermission
session provider.Session
launch provider.Launch
base provider.Policy
@@ -112,7 +114,7 @@ func PolicyInputs(b provider.Binding, in provider.PolicyInputs, specialist, mode
}
tools := append(append([]string{}, native...), "mcp__equipo__permission")
for _, tool := range in.Tools {
- if !strings.HasPrefix(tool, "mcp__equipo__") || strings.ContainsAny(tool, "* ,\t\n") || tool == "mcp__equipo__permission" {
+ if !slices.Contains([]string{"mcp__equipo__ask_person", "mcp__equipo__submit_candidate", "mcp__equipo__submit_review", "mcp__equipo__submit_reproduction"}, tool) {
return in, provider.ErrPolicy
}
tools = append(tools, tool)
@@ -133,7 +135,7 @@ func PolicyInputs(b provider.Binding, in provider.PolicyInputs, specialist, mode
settings := map[string]any{
"disableAllHooks": true, "enabledPlugins": map[string]any{},
"sandbox": map[string]any{"enabled": true, "failIfUnavailable": true, "allowUnsandboxedCommands": false, "autoAllowBashIfSandboxed": false, "excludedCommands": []string{}, "filesystem": map[string]any{"denyRead": denied, "denyWrite": denied}, "network": map[string]any{"allowUnixSockets": []string{}}},
- "permissions": map[string]any{"deny": nativeDenies},
+ "permissions": map[string]any{"deny": nativeDenies, "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"]}}}`)
@@ -589,8 +591,8 @@ func (l *Launcher) StartTurn(ctx context.Context, s provider.Session, t provider
return nil
}
func argv(p provider.Policy) []string { var m manifest; json.Unmarshal(p.Manifest, &m); return m.Argv }
-func (l *Launcher) Respond(context.Context, provider.Session, provider.Answer) error {
- return errNotReady
+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()
diff --git a/internal/runner/provider/codex/answers.go b/internal/runner/provider/codex/answers.go
new file mode 100644
index 00000000..49dd2fc8
--- /dev/null
+++ b/internal/runner/provider/codex/answers.go
@@ -0,0 +1,223 @@
+package codex
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "sort"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+// QuestionKeys recognises both the pinned async representation and the schema
+// request. Other shapes can be displayed, but cannot be approved as questions.
+func QuestionKeys(ev provider.Event) ([]string, error) {
+ v, e := parse(ev.Payload)
+ if e != nil {
+ return nil, e
+ }
+ var p struct {
+ Questions []struct {
+ ID string `json:"id"`
+ }
+ Item struct {
+ Type, Delivery string
+ Questions []struct {
+ Title string `json:"title"`
+ }
+ }
+ }
+ if json.Unmarshal(v.Params, &p) != nil {
+ return nil, errProtocol
+ }
+ keys := []string{}
+ switch v.Method {
+ case "item/tool/requestUserInput":
+ for _, q := range p.Questions {
+ keys = append(keys, q.ID)
+ }
+ case "item/completed":
+ if p.Item.Type != "agentMessage" || p.Item.Delivery != "async" {
+ return nil, errProtocol
+ }
+ for _, q := range p.Item.Questions {
+ keys = append(keys, q.Title)
+ }
+ default:
+ return nil, errProtocol
+ }
+ if len(keys) == 0 || len(keys) > 32 {
+ return nil, errProtocol
+ }
+ seen := map[string]bool{}
+ for _, k := range keys {
+ if k == "" || seen[k] || strings.HasPrefix(k, "mcp_tool_call_approval_") {
+ return nil, errProtocol
+ }
+ seen[k] = true
+ }
+ return keys, nil
+}
+
+// MCPApproval keeps the provider's tool identity and arguments intact.
+func MCPApproval(ev provider.Event) (string, json.RawMessage, error) {
+ v, e := parse(ev.Payload)
+ if e != nil || v.Method != "mcpServer/elicitation/request" {
+ return "", nil, provider.ErrPolicy
+ }
+ var p struct {
+ ThreadID, TurnID, ServerName, Mode string
+ Meta struct {
+ Kind string `json:"codex_approval_kind"`
+ Arguments json.RawMessage `json:"tool_params"`
+ } `json:"_meta"`
+ RequestedSchema json.RawMessage
+ }
+ if json.Unmarshal(v.Params, &p) != nil || p.ServerName != "equipo" || p.Mode != "form" || p.Meta.Kind != "mcp_tool_call" || !uniqueJSON(p.Meta.Arguments) || !sameJSON(p.RequestedSchema, []byte(`{"type":"object","properties":{}}`)) {
+ return "", nil, provider.ErrPolicy
+ }
+ call, e := parse(ev.ToolCall)
+ if e != nil || call.Method != "item/started" {
+ return "", nil, provider.ErrPolicy
+ }
+ var c struct {
+ ThreadID, TurnID string
+ Item struct {
+ ID, Type, Server, Tool string
+ Arguments json.RawMessage
+ }
+ }
+ if json.Unmarshal(call.Params, &c) != nil || c.ThreadID != p.ThreadID || c.TurnID != p.TurnID || c.Item.ID == "" || c.Item.Type != "mcpToolCall" || c.Item.Server != p.ServerName || c.Item.Tool == "" || !sameJSON(c.Item.Arguments, p.Meta.Arguments) {
+ return "", nil, provider.ErrPolicy
+ }
+ return c.Item.Tool, c.Item.Arguments, nil
+}
+func (s *sessionState) correlateMCP(ev *provider.Event) {
+ for _, call := range s.mcpCalls {
+ candidate := *ev
+ candidate.ToolCall = call
+ if _, _, err := MCPApproval(candidate); err == nil {
+ if len(ev.ToolCall) > 0 {
+ ev.ToolCall = nil
+ return
+ } // Ambiguous calls cannot approve one another.
+ ev.ToolCall = call
+ }
+ }
+}
+
+func (l *Launcher) respond(ctx context.Context, session provider.Session, a provider.Answer) error {
+ s, e := l.state(session)
+ if e != nil {
+ return e
+ }
+ s.op.Lock()
+ defer s.op.Unlock()
+ s.mu.Lock()
+ ev, ok := s.requests[a.RequestID]
+ if !ok || !s.active || s.closed || s.err != nil || s.ctx.Err() != nil || ctx.Err() != nil || a.TurnID != s.turn.ID || ev.TurnID != a.TurnID {
+ s.mu.Unlock()
+ return errNotReady
+ }
+ providerTurn := s.providerTurn
+ s.mu.Unlock()
+ if e = s.lease.ValidatePolicy(ctx); e != nil {
+ return e
+ }
+ v, e := parse(ev.Payload)
+ if e != nil {
+ return e
+ }
+ var result any
+ steer := false
+ keys, keyErr := QuestionKeys(ev)
+ if keyErr == nil {
+ if a.Behavior != "allow" || !uniqueJSON(a.Input) {
+ return provider.ErrPolicy
+ }
+ answers, e := provider.QuestionAnswers(a.Input, keys)
+ if e != nil {
+ return e
+ }
+ if v.Method == "item/tool/requestUserInput" {
+ mapped := map[string]any{}
+ for k, v := range answers {
+ mapped[k] = map[string]any{"answers": []string{v}}
+ }
+ result = map[string]any{"answers": mapped}
+ } else {
+ steer = true
+ sort.Strings(keys)
+ lines := []string{}
+ for _, key := range keys {
+ lines = append(lines, fmt.Sprintf("%s: %s", key, answers[key]))
+ }
+ result = map[string]any{"threadId": session.ID, "expectedTurnId": providerTurn, "input": []any{map[string]any{"type": "text", "text": strings.Join(lines, "\n")}}}
+ }
+ } else {
+ if len(a.Input) != 0 {
+ return provider.ErrPolicy
+ }
+ switch v.Method {
+ case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "mcpServer/elicitation/request":
+ default:
+ return provider.ErrPolicy
+ }
+ decision := "decline"
+ if a.Behavior == "allow" {
+ // Native approval requests may escape the inner sandbox. No currently
+ // certified action schema proves otherwise, so only Equipo MCP can pass.
+ if _, _, e := MCPApproval(ev); e != nil || a.Authorize == nil {
+ return provider.ErrPolicy
+ }
+ if e = a.Authorize(ctx, ev); e != nil {
+ return e
+ }
+ decision = "accept"
+ } else if a.Behavior != "deny" {
+ return provider.ErrPolicy
+ }
+ result = map[string]any{"decision": decision}
+ if v.Method == "mcpServer/elicitation/request" {
+ var content any
+ if decision == "accept" {
+ content = map[string]any{}
+ }
+ result = map[string]any{"action": decision, "content": content, "_meta": nil}
+ }
+ }
+ if a.Behavior == "allow" && v.Method == "mcpServer/elicitation/request" {
+ s.mu.Lock()
+ current := ev
+ current.ToolCall = nil
+ s.correlateMCP(&current)
+ s.mu.Unlock()
+ if len(current.ToolCall) == 0 || !bytes.Equal(current.ToolCall, ev.ToolCall) {
+ return provider.ErrPolicy
+ }
+ }
+ // Reserve the one response before I/O. A lost write cannot be replayed.
+ s.mu.Lock()
+ if !s.active || s.closed || s.err != nil || s.providerTurn != providerTurn || s.turn.ID != a.TurnID {
+ s.mu.Unlock()
+ return errNotReady
+ }
+ delete(s.requests, a.RequestID)
+ s.mu.Unlock()
+ if steer {
+ raw, e := s.rpc.callAnswer(ctx, session, a.TurnID, marshal(result))
+ if e != nil {
+ return s.stop(e)
+ }
+ var response struct {
+ TurnID string `json:"turnId"`
+ }
+ if json.Unmarshal(raw, &response) != nil || response.TurnID != providerTurn {
+ return s.stop(provider.ErrIdentity)
+ }
+ return nil
+ }
+ return s.rpc.answer(ctx, session, a.TurnID, map[string]any{"id": json.RawMessage(a.RequestID), "result": result})
+}
diff --git a/internal/runner/provider/codex/answers_test.go b/internal/runner/provider/codex/answers_test.go
new file mode 100644
index 00000000..ea3fcef2
--- /dev/null
+++ b/internal/runner/provider/codex/answers_test.go
@@ -0,0 +1,252 @@
+package codex
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+)
+
+func answerFixture(t *testing.T) (*Launcher, *sessionState, *rpcInput, chan provider.Frame) {
+ t.Helper()
+ f := fixtureFor(t)
+ s, _ := openFixture(t, f)
+ st, e := f.l.state(s)
+ if e != nil {
+ t.Fatal(e)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ w := &rpcInput{sent: make(chan []byte, 16)}
+ frames := make(chan provider.Frame, 16)
+ rpc := newFrameRPC(ctx, &provider.Capture{Input: w, Frames: frames, Done: make(chan error, 1)}, st.handle)
+ st.mu.Lock()
+ original := st.rpc
+ st.rpc = rpc
+ st.active = true
+ st.turn = provider.Turn{ID: "local-turn"}
+ st.providerTurn = "provider-turn"
+ st.mu.Unlock()
+ t.Cleanup(func() { rpc.close(); <-rpc.done; original.close() })
+ return f.l, st, w, frames
+}
+func TestCodexApprovalResponse(t *testing.T) {
+ for _, method := range []string{"item/commandExecution/requestApproval", "item/fileChange/requestApproval", "mcpServer/elicitation/request"} {
+ t.Run(method, func(t *testing.T) {
+ l, s, w, _ := answerFixture(t)
+ ctx := context.Background()
+ raw := []byte(fmt.Sprintf(`{"id":7,"method":%q,"params":{"threadId":%q,"turnId":"provider-turn","itemId":"item","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, method, s.session.ID))
+ raw = pinnedMCPRequest(t, s, raw)
+ if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil {
+ t.Fatal(e)
+ }
+ // IDs are JSON values, not their display form.
+ if l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: `"7"`, Behavior: "deny"}) == nil {
+ t.Fatal("string ID answered numeric request")
+ }
+ for _, input := range []string{`{"decision":"acceptForSession"}`, `{"execpolicyAmendment":["curl"]}`, `{"permissions":{"network":true}}`} {
+ if l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: "7", Behavior: "allow", Input: json.RawMessage(input)}) == nil {
+ t.Fatal("policy amendment accepted", input)
+ }
+ }
+ if l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: "7", Behavior: "allow"}) == nil {
+ t.Fatal("approval without broker validation")
+ }
+ if e := l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: "7", Behavior: "deny"}); e != nil {
+ t.Fatal(e)
+ }
+ var reply struct {
+ ID json.RawMessage
+ Result map[string]any
+ }
+ if json.Unmarshal(<-w.sent, &reply) != nil || string(reply.ID) != "7" || reply.Result["decision"] != "decline" && reply.Result["action"] != "decline" {
+ t.Fatal(reply)
+ }
+ })
+ }
+}
+func TestCodexAsyncQuestionAnswer(t *testing.T) {
+ for _, mode := range []string{"async", "schema"} {
+ t.Run(mode, func(t *testing.T) {
+ l, s, w, frames := answerFixture(t)
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ raw := fmt.Sprintf(`{"method":"item/completed","params":{"threadId":%q,"turnId":"provider-turn","item":{"id":"message","type":"agentMessage","delivery":"async","questions":[{"title":"Greeting","options":["hi","bye"]}]}}}`, s.session.ID)
+ id := "async:message"
+ if mode == "schema" {
+ id = `"user-input"`
+ raw = fmt.Sprintf(`{"id":"user-input","method":"item/tool/requestUserInput","params":{"threadId":%q,"turnId":"provider-turn","itemId":"tool","questions":[{"id":"Greeting","header":"Greeting","question":"Which greeting?","options":[{"label":"hi"}]}]}}`, s.session.ID)
+ }
+ if e := s.handle(provider.Frame{Sequence: 99, Bytes: []byte(raw)}); e != nil {
+ t.Fatal(e)
+ }
+ a := provider.Answer{RequestID: id, TurnID: "local-turn", Behavior: "allow", Input: json.RawMessage(`{"answers":{"Greeting":"hi"}}`)}
+ bad := a
+ bad.TurnID = "replaced"
+ if l.Respond(ctx, s.session, bad) == nil {
+ t.Fatal("replaced turn answered")
+ }
+ result := make(chan error, 1)
+ go func() { result <- l.Respond(ctx, s.session, a) }()
+ var call struct {
+ ID json.RawMessage
+ Method string
+ Params struct{ ThreadID, ExpectedTurnID string }
+ Result struct {
+ Answers map[string]struct{ Answers []string }
+ }
+ }
+ var wire []byte
+ select {
+ case wire = <-w.sent:
+ case e := <-result:
+ t.Fatal("answer not transmitted", e)
+ case <-ctx.Done():
+ t.Fatal("answer timeout")
+ }
+ if json.Unmarshal(wire, &call) != nil {
+ t.Fatal("bad wire")
+ }
+ if mode == "async" {
+ if call.Method != "turn/steer" || call.Params.ExpectedTurnID != "provider-turn" || call.Params.ThreadID != s.session.ID {
+ t.Fatalf("wrong steer: %+v", call)
+ }
+ frames <- provider.Frame{Sequence: 100, Bytes: []byte(fmt.Sprintf(`{"id":%s,"result":{"turnId":"provider-turn"}}`, call.ID))}
+ } else if string(call.ID) != id || len(call.Result.Answers["Greeting"].Answers) != 1 {
+ t.Fatal("wrong schema answer", call)
+ }
+ if e := <-result; e != nil {
+ t.Fatal(e)
+ }
+ if l.Respond(ctx, s.session, a) == nil {
+ t.Fatal("answer replay")
+ }
+ s.mu.Lock()
+ s.active = false
+ s.mu.Unlock()
+ if l.Respond(ctx, s.session, a) == nil {
+ t.Fatal("completed turn follow-up without admission")
+ }
+ })
+ }
+}
+
+func TestCodexApprovalResponseValidatedMCP(t *testing.T) {
+ l, s, w, _ := answerFixture(t)
+ raw := []byte(fmt.Sprintf(`{"id":"mcp","method":"mcpServer/elicitation/request","params":{"threadId":%q,"turnId":"provider-turn","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, s.session.ID))
+ raw = pinnedMCPRequest(t, s, raw)
+ if e := s.handle(provider.Frame{Sequence: 100, Bytes: raw}); e != nil {
+ t.Fatal(e)
+ }
+ checked := 0
+ a := provider.Answer{TurnID: "local-turn", RequestID: `"mcp"`, Behavior: "allow", Authorize: func(_ context.Context, ev provider.Event) error {
+ checked++
+ if string(ev.Payload) != string(raw) {
+ t.Fatal("original request changed")
+ }
+ return nil
+ }}
+ if e := l.Respond(context.Background(), s.session, a); e != nil {
+ t.Fatal(e)
+ }
+ var reply struct {
+ ID string
+ Result struct{ Decision, Action string }
+ }
+ if json.Unmarshal(<-w.sent, &reply) != nil || reply.ID != "mcp" || reply.Result.Action != "accept" || checked != 1 {
+ t.Fatal(reply, checked)
+ }
+}
+func TestCodexApprovalResponseFixedMCPPolicy(t *testing.T) {
+ f := fixtureFor(t)
+ var cfg map[string]json.RawMessage
+ if json.Unmarshal(f.inputs.Settings, &cfg) != nil {
+ t.Fatal("settings")
+ }
+ var servers map[string]struct {
+ Command string
+ Args []string
+ }
+ if json.Unmarshal(cfg["mcp_servers"], &servers) != nil || len(servers) != 1 || servers["equipo"].Command != "/opt/equipo-tool-proxy" || fmt.Sprint(servers["equipo"].Args) != "[--socket /tool/equipo.sock]" {
+ t.Fatal("fixed MCP missing", string(cfg["mcp_servers"]))
+ }
+}
+
+func pinnedMCPRequest(t *testing.T, s *sessionState, raw []byte) []byte {
+ t.Helper()
+ var v map[string]any
+ if json.Unmarshal(raw, &v) != nil {
+ t.Fatal("request")
+ }
+ if v["method"] != "mcpServer/elicitation/request" {
+ return raw
+ }
+ p := v["params"].(map[string]any)
+ item := map[string]any{"method": "item/started", "params": map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "item": map[string]any{"id": "mcp-item", "type": "mcpToolCall", "server": "equipo", "tool": p["tool"], "arguments": p["arguments"], "status": "inProgress"}}}
+ if e := s.handle(provider.Frame{Sequence: 98, Bytes: marshal(item)}); e != nil {
+ t.Fatal(e)
+ }
+ v["params"] = map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "serverName": "equipo", "mode": "form", "message": "approval fixture", "requestedSchema": map[string]any{"type": "object", "properties": map[string]any{}}, "_meta": map[string]any{"codex_approval_kind": "mcp_tool_call", "tool_params": p["arguments"], "persist": []string{"session", "always"}}}
+ return marshal(v)
+}
+
+func TestCodexApprovalResponseResolvedRequest(t *testing.T) {
+ l, s, _, _ := answerFixture(t)
+ raw := []byte(fmt.Sprintf(`{"id":9,"method":"item/commandExecution/requestApproval","params":{"threadId":%q,"turnId":"provider-turn","itemId":"command"}}`, s.session.ID))
+ if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil {
+ t.Fatal(e)
+ }
+ resolved := []byte(fmt.Sprintf(`{"method":"serverRequest/resolved","params":{"threadId":%q,"requestId":9}}`, s.session.ID))
+ if e := s.handle(provider.Frame{Sequence: 100, Bytes: resolved}); e != nil {
+ t.Fatal(e)
+ }
+ if l.Respond(context.Background(), s.session, provider.Answer{RequestID: "9", TurnID: "local-turn", Behavior: "deny"}) == nil {
+ t.Fatal("resolved request answered")
+ }
+}
+func TestCodexApprovalResponseMCPCorrelation(t *testing.T) {
+ for _, change := range []string{"arguments", "server", "schema", "missing-item", "completed-item", "ambiguous"} {
+ t.Run(change, func(t *testing.T) {
+ l, s, _, _ := answerFixture(t)
+ raw := []byte(fmt.Sprintf(`{"id":7,"method":"mcpServer/elicitation/request","params":{"threadId":%q,"turnId":"provider-turn","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, s.session.ID))
+ raw = pinnedMCPRequest(t, s, raw)
+ switch change {
+ case "arguments":
+ raw = []byte(strings.Replace(string(raw), "Which?", "Changed?", 1))
+ case "server":
+ raw = []byte(strings.Replace(string(raw), `"serverName":"equipo"`, `"serverName":"other"`, 1))
+ case "schema":
+ raw = []byte(strings.Replace(string(raw), `"properties":{}`, `"properties":{"permissions":{"type":"string"}}`, 1))
+ case "missing-item":
+ s.mcpCalls = nil
+ case "ambiguous":
+ s.mcpCalls["other"] = s.mcpCalls["mcp-item"]
+ }
+ if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil {
+ t.Fatal(e)
+ }
+ if change == "completed-item" {
+ s.mu.Lock()
+ delete(s.mcpCalls, "mcp-item")
+ s.mu.Unlock()
+ }
+ if l.Respond(context.Background(), s.session, provider.Answer{RequestID: "7", TurnID: "local-turn", Behavior: "allow", Authorize: func(context.Context, provider.Event) error { return nil }}) == nil {
+ t.Fatal("uncorrelated MCP approved", change)
+ }
+ })
+ }
+}
+
+func TestCodexApprovalResponseNoQuestionFallback(t *testing.T) {
+ l, s, _, _ := answerFixture(t)
+ raw := []byte(fmt.Sprintf(`{"id":"fallback","method":"item/tool/requestUserInput","params":{"threadId":%q,"turnId":"provider-turn","itemId":"tool","questions":[{"id":"mcp_tool_call_approval_1","header":"Approve app tool call?","question":"Allow?","options":[{"label":"Always allow"}]}]}}`, s.session.ID))
+ if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil {
+ t.Fatal(e)
+ }
+ if l.Respond(context.Background(), s.session, provider.Answer{RequestID: `"fallback"`, TurnID: "local-turn", Behavior: "allow", Input: json.RawMessage(`{"answers":{"mcp_tool_call_approval_1":"Always allow"}}`)}) == nil {
+ t.Fatal("permission amendment through question fallback")
+ }
+}
diff --git a/internal/runner/provider/codex/events.go b/internal/runner/provider/codex/events.go
index ed6a28f1..8b510e47 100644
--- a/internal/runner/provider/codex/events.go
+++ b/internal/runner/provider/codex/events.go
@@ -58,7 +58,10 @@ func Decode(raw []byte) ([]provider.Event, error) {
TurnID string `json:"turnId"`
Thread struct{ ID string }
Turn struct{ ID, Status string }
- Item struct{ Type string }
+ Item struct {
+ Type, ID, Delivery string
+ Questions json.RawMessage
+ }
}
if json.Unmarshal(v.Params, &p) != nil {
return nil, errProtocol
@@ -116,6 +119,13 @@ func Decode(raw []byte) ([]provider.Event, error) {
if len(v.ID) > 0 {
request = string(v.ID)
} // JSON preserves string versus numeric server IDs.
+ if v.Method == "item/completed" && p.Item.Type == "agentMessage" && p.Item.Delivery == "async" && len(p.Item.Questions) > 0 && string(p.Item.Questions) != "null" {
+ if p.Item.ID == "" {
+ return nil, errProtocol
+ }
+ kind = "request"
+ request = "async:" + p.Item.ID
+ }
return []provider.Event{{SessionID: p.ThreadID, TurnID: p.TurnID, RequestID: request, Kind: kind, Payload: bytes.Clone(raw)}}, nil
}
func uniqueJSON(raw []byte) bool {
diff --git a/internal/runner/provider/codex/launcher.go b/internal/runner/provider/codex/launcher.go
index 1280ff2d..393feafc 100644
--- a/internal/runner/provider/codex/launcher.go
+++ b/internal/runner/provider/codex/launcher.go
@@ -36,6 +36,8 @@ type Launcher struct {
sessions map[string]*sessionState
}
type sessionState struct {
+ mcpCalls map[string]json.RawMessage
+ requests map[string]provider.Event
mu sync.Mutex
op sync.Mutex
session provider.Session
@@ -111,11 +113,18 @@ func PolicyInputs(b provider.Binding, in provider.PolicyInputs, model string) (p
settings := map[string]any{
"model": model, "model_provider": "openai", "approval_policy": "on-request", "approvals_reviewer": "user", "default_permissions": "equipo",
"permissions": map[string]any{"equipo": map[string]any{"filesystem": fs, "network": map[string]any{"enabled": false}}},
- "features": map[string]any{"apps": false, "multi_agent": false, "remote_control": false}, "mcp_servers": map[string]any{},
+ "features": map[string]any{"apps": false, "multi_agent": false, "remote_control": false, "tool_call_mcp_elicitation": true}, "mcp_servers": map[string]any{"equipo": map[string]any{"command": "/opt/equipo-tool-proxy", "args": []string{"--socket", "/tool/equipo.sock"}}},
+ }
+ for _, tool := range in.Tools {
+ switch tool {
+ case "mcp__equipo__ask_person", "mcp__equipo__submit_candidate", "mcp__equipo__submit_review", "mcp__equipo__submit_reproduction":
+ default:
+ return in, provider.ErrPolicy
+ }
}
in.ProviderVersion = Version
in.Settings = marshal(settings)
- in.MCP = json.RawMessage(`{}`)
+ in.MCP = json.RawMessage(`{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}`)
in.ThreadPolicy = marshal(map[string]any{"model": model, "modelProvider": "openai", "cwd": "/workspace", "approvalPolicy": "on-request", "approvalsReviewer": "user", "permissions": "equipo", "runtimeWorkspaceRoots": []string{"/workspace"}, "config": settings})
in.TurnPolicy = json.RawMessage(`{}`)
in.Argv = []string{"/opt/codex", "app-server", "--strict-config", "--listen", "stdio://"}
@@ -138,6 +147,12 @@ func toml(v any) string {
return "true"
}
return "false"
+ case []string:
+ values := make([]string, len(x))
+ for i, v := range x {
+ values[i] = strconv.Quote(v)
+ }
+ return "[" + strings.Join(values, ",") + "]"
case map[string]any:
keys := make([]string, 0, len(x))
for k := range x {
@@ -206,11 +221,14 @@ func (l *Launcher) validatePolicy(b provider.Binding, p provider.Policy) (provid
if !reflect.DeepEqual(in.Argv, want.Argv) || p.Env["CODEX_HOME"] != "/home/runner" {
return in, provider.ErrPolicy
}
- binary, helper := false, false
+ binary, helper, toolHelper := false, false, false
for _, f := range m.Files {
if f.Mount.Target == "/opt/codex" {
binary = f.SHA256 == l.digest
}
+ if f.Mount.Target == "/opt/equipo-tool-proxy" {
+ toolHelper = f.Mount.ReadOnly
+ }
if f.Mount.Target == "/opt/codex-code-mode-host" {
helper = f.SHA256 == l.hostDigest
}
@@ -218,10 +236,10 @@ func (l *Launcher) validatePolicy(b provider.Binding, p provider.Policy) (provid
return in, provider.ErrPolicy
}
}
- if !binary || !helper {
+ if !binary || !helper || !toolHelper {
return in, provider.ErrVersion
}
- if len(in.InstructionFiles) != 0 || len(in.Tools) != 0 {
+ if len(in.InstructionFiles) != 0 {
return in, provider.ErrPolicy
}
rebuilt, e := provider.BuildPolicy(b, in)
@@ -661,8 +679,8 @@ func (l *Launcher) StartTurn(ctx context.Context, session provider.Session, t pr
}
return currentErr
}
-func (l *Launcher) Respond(context.Context, provider.Session, provider.Answer) error {
- return errNotReady
+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, session provider.Session) error {
s, e := l.state(session)
@@ -737,9 +755,45 @@ func (s *sessionState) handle(frame provider.Frame) error {
} else if ev.Kind == "turn.completed" || ev.Kind == "turn.failed" || ev.Kind == "usage" || ev.Kind == "request" {
return errProtocol
}
+ var envelope struct {
+ Method string
+ Params struct {
+ RequestID json.RawMessage `json:"requestId"`
+ Item struct{ ID, Type string }
+ }
+ }
+ _ = json.Unmarshal(ev.Payload, &envelope)
+ if envelope.Method == "serverRequest/resolved" {
+ delete(s.requests, string(envelope.Params.RequestID))
+ }
+ if envelope.Params.Item.Type == "mcpToolCall" {
+ if envelope.Method == "item/started" {
+ if s.mcpCalls == nil {
+ s.mcpCalls = map[string]json.RawMessage{}
+ }
+ if len(s.mcpCalls) >= 64 {
+ return errProtocol
+ }
+ s.mcpCalls[envelope.Params.Item.ID] = bytes.Clone(ev.Payload)
+ } else if envelope.Method == "item/completed" {
+ delete(s.mcpCalls, envelope.Params.Item.ID)
+ }
+ }
+ if ev.Kind == "request" {
+ s.correlateMCP(&ev)
+ if s.requests == nil {
+ s.requests = map[string]provider.Event{}
+ }
+ if _, exists := s.requests[ev.RequestID]; exists || len(s.requests) >= 64 {
+ return errProtocol
+ }
+ s.requests[ev.RequestID] = ev
+ }
if ev.Kind == "turn.completed" || ev.Kind == "turn.failed" {
e = s.lease.EndTurn(context.Background())
s.active = false
+ s.requests = nil
+ s.mcpCalls = nil
if e != nil && !errors.Is(e, provider.ErrRefreshPending) {
return e
}
diff --git a/internal/runner/provider/codex/launcher_test.go b/internal/runner/provider/codex/launcher_test.go
index c4999c1d..ed3cf9e7 100644
--- a/internal/runner/provider/codex/launcher_test.go
+++ b/internal/runner/provider/codex/launcher_test.go
@@ -256,7 +256,7 @@ func fixtureFor(t *testing.T) *fixture {
os.Mkdir(work, 0700)
os.Mkdir(scratch, 0700)
files := []provider.Mount{}
- for _, name := range []string{"codex", "codex-code-mode-host"} {
+ for _, name := range []string{"codex", "codex-code-mode-host", "equipo-tool-proxy"} {
p := filepath.Join(root, name)
os.WriteFile(p, []byte(name), 0700)
files = append(files, provider.Mount{Source: p, Target: "/opt/" + name, ReadOnly: true})
@@ -739,7 +739,7 @@ func TestCodexPolicyShape(t *testing.T) {
t.Fatal("feature enabled", key)
}
}
- if len(config["mcp_servers"].(map[string]any)) != 0 {
+ if servers := config["mcp_servers"].(map[string]any); len(servers) != 1 || servers["equipo"] == nil {
t.Fatal("inherited MCP")
}
}
diff --git a/internal/runner/provider/codex/rpc.go b/internal/runner/provider/codex/rpc.go
index 96ec9f66..82de0a97 100644
--- a/internal/runner/provider/codex/rpc.go
+++ b/internal/runner/provider/codex/rpc.go
@@ -199,3 +199,76 @@ func (r *RPC) read() {
}
}
}
+
+// answer writes server replies separately from client-call correlation.
+func (r *RPC) answer(ctx context.Context, s provider.Session, turn string, v any) error {
+ raw, e := json.Marshal(v)
+ if e != nil || len(raw) > MaxFrameBytes {
+ return errProtocol
+ }
+ raw = append(raw, '\n')
+ r.writeMu.Lock()
+ defer r.writeMu.Unlock()
+ if ctx.Err() != nil || r.ctx.Err() != nil {
+ return errNotReady
+ }
+ stop := context.AfterFunc(ctx, func() { r.fail(ctx.Err()) })
+ defer stop()
+ var n int
+ if w, ok := r.cap.Input.(provider.AnswerWriter); ok {
+ n, e = w.WriteAnswer(ctx, s, turn, raw)
+ } else {
+ n, e = r.cap.Input.Write(raw)
+ }
+ if e != nil || n != len(raw) {
+ r.fail(io.ErrShortWrite)
+ return io.ErrShortWrite
+ }
+ return nil
+}
+func (r *RPC) callAnswer(ctx context.Context, s provider.Session, turn string, params json.RawMessage) (json.RawMessage, error) {
+ if !validSteer(params) {
+ return nil, provider.ErrPolicy
+ }
+ r.mu.Lock()
+ if r.err != nil {
+ e := r.err
+ r.mu.Unlock()
+ return nil, e
+ }
+ r.next++
+ id := fmt.Sprintf("equipo:%d", r.next)
+ key, _ := json.Marshal(id)
+ ch := make(chan reply, 1)
+ r.pending[string(key)] = ch
+ r.mu.Unlock()
+ if e := r.answer(ctx, s, turn, map[string]any{"id": id, "method": "turn/steer", "params": params}); e != nil {
+ return nil, e
+ }
+ select {
+ case v := <-ch:
+ return v.raw, v.err
+ case <-ctx.Done():
+ r.fail(ctx.Err())
+ return nil, ctx.Err()
+ case <-r.ctx.Done():
+ return nil, r.ctx.Err()
+ }
+}
+func validSteer(raw json.RawMessage) bool {
+ if !uniqueJSON(raw) {
+ return false
+ }
+ var p map[string]json.RawMessage
+ if json.Unmarshal(raw, &p) != nil || len(p) != 3 {
+ return false
+ }
+ for _, key := range []string{"threadId", "expectedTurnId"} {
+ var s string
+ if json.Unmarshal(p[key], &s) != nil || s == "" {
+ return false
+ }
+ }
+ var input []struct{ Type, Text string }
+ return json.Unmarshal(p["input"], &input) == nil && len(input) == 1 && input[0].Type == "text" && input[0].Text != ""
+}
diff --git a/internal/runner/provider/codex/testdata/answers-provenance.json b/internal/runner/provider/codex/testdata/answers-provenance.json
new file mode 100644
index 00000000..f849cd16
--- /dev/null
+++ b/internal/runner/provider/codex/testdata/answers-provenance.json
@@ -0,0 +1,22 @@
+{
+ "tag": "rust-v0.165.0",
+ "tree_sha": "360319d8dee62d87e2d59fc0c21805d79519cfed",
+ "schemas": {
+ "McpServerElicitationRequestParams": {
+ "source": "https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/app-server-protocol/schema/json/McpServerElicitationRequestParams.json",
+ "sha256": "5cbeb6bc702d2efa076da4c1dfb00672c970c1bad747031eb880b9ab907815c0"
+ },
+ "McpServerElicitationRequestResponse": {
+ "source": "https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/app-server-protocol/schema/json/McpServerElicitationRequestResponse.json",
+ "sha256": "792a012fdfe53ac211575a6c37ffbd492be848d15cb313d1bb4b534ade1f54ac"
+ },
+ "ToolRequestUserInputParams": {
+ "source": "https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/app-server-protocol/schema/json/ToolRequestUserInputParams.json",
+ "sha256": "fda15b62e7446105b59c8ed85c908abed2a47db70653e57c92c47a2f204fa77a"
+ },
+ "ToolRequestUserInputResponse": {
+ "source": "https://raw.githubusercontent.com/openai/codex/rust-v0.165.0/codex-rs/app-server-protocol/schema/json/ToolRequestUserInputResponse.json",
+ "sha256": "5073b245f741fa8ce62ec52e4dd1809b7831f9c4284c279a78abc9b171f8e3f2"
+ }
+ }
+}
diff --git a/internal/runner/provider/codex/testdata/schema-McpServerElicitationRequestParams.json b/internal/runner/provider/codex/testdata/schema-McpServerElicitationRequestParams.json
new file mode 100644
index 00000000..7fbc7e98
--- /dev/null
+++ b/internal/runner/provider/codex/testdata/schema-McpServerElicitationRequestParams.json
@@ -0,0 +1,651 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "definitions": {
+ "McpElicitationArrayType": {
+ "enum": [
+ "array"
+ ],
+ "type": "string"
+ },
+ "McpElicitationBooleanSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "default": {
+ "type": [
+ "boolean",
+ "null"
+ ]
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "title": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "$ref": "#/definitions/McpElicitationBooleanType"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ },
+ "McpElicitationBooleanType": {
+ "enum": [
+ "boolean"
+ ],
+ "type": "string"
+ },
+ "McpElicitationConstOption": {
+ "additionalProperties": false,
+ "properties": {
+ "const": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "const",
+ "title"
+ ],
+ "type": "object"
+ },
+ "McpElicitationEnumSchema": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/McpElicitationSingleSelectEnumSchema"
+ },
+ {
+ "$ref": "#/definitions/McpElicitationMultiSelectEnumSchema"
+ },
+ {
+ "$ref": "#/definitions/McpElicitationLegacyTitledEnumSchema"
+ }
+ ]
+ },
+ "McpElicitationLegacyTitledEnumSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "default": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "enum": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "enumNames": {
+ "items": {
+ "type": "string"
+ },
+ "type": [
+ "array",
+ "null"
+ ]
+ },
+ "title": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "$ref": "#/definitions/McpElicitationStringType"
+ }
+ },
+ "required": [
+ "enum",
+ "type"
+ ],
+ "type": "object"
+ },
+ "McpElicitationMultiSelectEnumSchema": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/McpElicitationUntitledMultiSelectEnumSchema"
+ },
+ {
+ "$ref": "#/definitions/McpElicitationTitledMultiSelectEnumSchema"
+ }
+ ]
+ },
+ "McpElicitationNumberSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "default": {
+ "format": "double",
+ "type": [
+ "number",
+ "null"
+ ]
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "maximum": {
+ "format": "double",
+ "type": [
+ "number",
+ "null"
+ ]
+ },
+ "minimum": {
+ "format": "double",
+ "type": [
+ "number",
+ "null"
+ ]
+ },
+ "title": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "$ref": "#/definitions/McpElicitationNumberType"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ },
+ "McpElicitationNumberType": {
+ "enum": [
+ "number",
+ "integer"
+ ],
+ "type": "string"
+ },
+ "McpElicitationObjectType": {
+ "enum": [
+ "object"
+ ],
+ "type": "string"
+ },
+ "McpElicitationPrimitiveSchema": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/McpElicitationEnumSchema"
+ },
+ {
+ "$ref": "#/definitions/McpElicitationStringSchema"
+ },
+ {
+ "$ref": "#/definitions/McpElicitationNumberSchema"
+ },
+ {
+ "$ref": "#/definitions/McpElicitationBooleanSchema"
+ }
+ ]
+ },
+ "McpElicitationSchema": {
+ "additionalProperties": false,
+ "description": "Typed form schema for MCP `elicitation/create` requests.\n\nThis matches the `requestedSchema` shape from the MCP 2025-11-25 `ElicitRequestFormParams` schema.",
+ "properties": {
+ "$schema": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "properties": {
+ "additionalProperties": {
+ "$ref": "#/definitions/McpElicitationPrimitiveSchema"
+ },
+ "type": "object"
+ },
+ "required": {
+ "items": {
+ "type": "string"
+ },
+ "type": [
+ "array",
+ "null"
+ ]
+ },
+ "type": {
+ "$ref": "#/definitions/McpElicitationObjectType"
+ }
+ },
+ "required": [
+ "properties",
+ "type"
+ ],
+ "type": "object"
+ },
+ "McpElicitationSingleSelectEnumSchema": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/McpElicitationUntitledSingleSelectEnumSchema"
+ },
+ {
+ "$ref": "#/definitions/McpElicitationTitledSingleSelectEnumSchema"
+ }
+ ]
+ },
+ "McpElicitationStringFormat": {
+ "enum": [
+ "email",
+ "uri",
+ "date",
+ "date-time"
+ ],
+ "type": "string"
+ },
+ "McpElicitationStringSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "default": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "format": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/McpElicitationStringFormat"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "maxLength": {
+ "format": "uint32",
+ "minimum": 0.0,
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "minLength": {
+ "format": "uint32",
+ "minimum": 0.0,
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "title": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "$ref": "#/definitions/McpElicitationStringType"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ },
+ "McpElicitationStringType": {
+ "enum": [
+ "string"
+ ],
+ "type": "string"
+ },
+ "McpElicitationTitledEnumItems": {
+ "additionalProperties": false,
+ "properties": {
+ "anyOf": {
+ "items": {
+ "$ref": "#/definitions/McpElicitationConstOption"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "anyOf"
+ ],
+ "type": "object"
+ },
+ "McpElicitationTitledMultiSelectEnumSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "default": {
+ "items": {
+ "type": "string"
+ },
+ "type": [
+ "array",
+ "null"
+ ]
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "items": {
+ "$ref": "#/definitions/McpElicitationTitledEnumItems"
+ },
+ "maxItems": {
+ "format": "uint64",
+ "minimum": 0.0,
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "minItems": {
+ "format": "uint64",
+ "minimum": 0.0,
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "title": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "$ref": "#/definitions/McpElicitationArrayType"
+ }
+ },
+ "required": [
+ "items",
+ "type"
+ ],
+ "type": "object"
+ },
+ "McpElicitationTitledSingleSelectEnumSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "default": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "oneOf": {
+ "items": {
+ "$ref": "#/definitions/McpElicitationConstOption"
+ },
+ "type": "array"
+ },
+ "title": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "$ref": "#/definitions/McpElicitationStringType"
+ }
+ },
+ "required": [
+ "oneOf",
+ "type"
+ ],
+ "type": "object"
+ },
+ "McpElicitationUntitledEnumItems": {
+ "additionalProperties": false,
+ "properties": {
+ "enum": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": {
+ "$ref": "#/definitions/McpElicitationStringType"
+ }
+ },
+ "required": [
+ "enum",
+ "type"
+ ],
+ "type": "object"
+ },
+ "McpElicitationUntitledMultiSelectEnumSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "default": {
+ "items": {
+ "type": "string"
+ },
+ "type": [
+ "array",
+ "null"
+ ]
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "items": {
+ "$ref": "#/definitions/McpElicitationUntitledEnumItems"
+ },
+ "maxItems": {
+ "format": "uint64",
+ "minimum": 0.0,
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "minItems": {
+ "format": "uint64",
+ "minimum": 0.0,
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "title": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "$ref": "#/definitions/McpElicitationArrayType"
+ }
+ },
+ "required": [
+ "items",
+ "type"
+ ],
+ "type": "object"
+ },
+ "McpElicitationUntitledSingleSelectEnumSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "default": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "enum": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "title": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "$ref": "#/definitions/McpElicitationStringType"
+ }
+ },
+ "required": [
+ "enum",
+ "type"
+ ],
+ "type": "object"
+ }
+ },
+ "oneOf": [
+ {
+ "properties": {
+ "_meta": true,
+ "message": {
+ "type": "string"
+ },
+ "mode": {
+ "enum": [
+ "form"
+ ],
+ "type": "string"
+ },
+ "requestedSchema": {
+ "$ref": "#/definitions/McpElicitationSchema"
+ }
+ },
+ "required": [
+ "message",
+ "mode",
+ "requestedSchema"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "_meta": true,
+ "message": {
+ "type": "string"
+ },
+ "mode": {
+ "enum": [
+ "openai/form"
+ ],
+ "type": "string"
+ },
+ "requestedSchema": true
+ },
+ "required": [
+ "message",
+ "mode",
+ "requestedSchema"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "_meta": true,
+ "message": {
+ "type": "string"
+ },
+ "mode": {
+ "enum": [
+ "openaiForm"
+ ],
+ "type": "string"
+ },
+ "requestedSchema": true
+ },
+ "required": [
+ "message",
+ "mode",
+ "requestedSchema"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "_meta": true,
+ "elicitationId": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ },
+ "mode": {
+ "enum": [
+ "url"
+ ],
+ "type": "string"
+ },
+ "url": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "elicitationId",
+ "message",
+ "mode",
+ "url"
+ ],
+ "type": "object"
+ }
+ ],
+ "properties": {
+ "serverName": {
+ "type": "string"
+ },
+ "threadId": {
+ "type": "string"
+ },
+ "turnId": {
+ "description": "Active Codex turn when this elicitation was observed, if app-server could correlate one.\n\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.",
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "serverName",
+ "threadId"
+ ],
+ "title": "McpServerElicitationRequestParams",
+ "type": "object"
+}
\ No newline at end of file
diff --git a/internal/runner/provider/codex/testdata/schema-McpServerElicitationRequestResponse.json b/internal/runner/provider/codex/testdata/schema-McpServerElicitationRequestResponse.json
new file mode 100644
index 00000000..13390a06
--- /dev/null
+++ b/internal/runner/provider/codex/testdata/schema-McpServerElicitationRequestResponse.json
@@ -0,0 +1,29 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "definitions": {
+ "McpServerElicitationAction": {
+ "enum": [
+ "accept",
+ "decline",
+ "cancel"
+ ],
+ "type": "string"
+ }
+ },
+ "properties": {
+ "_meta": {
+ "description": "Optional client metadata for form-mode action handling."
+ },
+ "action": {
+ "$ref": "#/definitions/McpServerElicitationAction"
+ },
+ "content": {
+ "description": "Structured user input for accepted elicitations, mirroring RMCP `CreateElicitationResult`.\n\nThis is nullable because decline/cancel responses have no content."
+ }
+ },
+ "required": [
+ "action"
+ ],
+ "title": "McpServerElicitationRequestResponse",
+ "type": "object"
+}
\ No newline at end of file
diff --git a/internal/runner/provider/codex/testdata/schema-ToolRequestUserInputParams.json b/internal/runner/provider/codex/testdata/schema-ToolRequestUserInputParams.json
new file mode 100644
index 00000000..04ee2de6
--- /dev/null
+++ b/internal/runner/provider/codex/testdata/schema-ToolRequestUserInputParams.json
@@ -0,0 +1,98 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "definitions": {
+ "ToolRequestUserInputOption": {
+ "description": "EXPERIMENTAL. Defines a single selectable option for request_user_input.",
+ "properties": {
+ "description": {
+ "type": "string"
+ },
+ "label": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "description",
+ "label"
+ ],
+ "type": "object"
+ },
+ "ToolRequestUserInputQuestion": {
+ "description": "EXPERIMENTAL. Represents one request_user_input question and its required options.",
+ "properties": {
+ "header": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "isOther": {
+ "default": false,
+ "type": "boolean"
+ },
+ "isSecret": {
+ "default": false,
+ "type": "boolean"
+ },
+ "options": {
+ "items": {
+ "$ref": "#/definitions/ToolRequestUserInputOption"
+ },
+ "type": [
+ "array",
+ "null"
+ ]
+ },
+ "question": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "header",
+ "id",
+ "question"
+ ],
+ "type": "object"
+ }
+ },
+ "description": "EXPERIMENTAL. Params sent with a request_user_input event.",
+ "properties": {
+ "autoResolutionMs": {
+ "default": null,
+ "description": "@deprecated Use `isBlocking` to decide whether the request should block.",
+ "format": "uint64",
+ "minimum": 0.0,
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "isBlocking": {
+ "type": "boolean"
+ },
+ "itemId": {
+ "type": "string"
+ },
+ "questions": {
+ "items": {
+ "$ref": "#/definitions/ToolRequestUserInputQuestion"
+ },
+ "type": "array"
+ },
+ "threadId": {
+ "type": "string"
+ },
+ "turnId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "isBlocking",
+ "itemId",
+ "questions",
+ "threadId",
+ "turnId"
+ ],
+ "title": "ToolRequestUserInputParams",
+ "type": "object"
+}
\ No newline at end of file
diff --git a/internal/runner/provider/codex/testdata/schema-ToolRequestUserInputResponse.json b/internal/runner/provider/codex/testdata/schema-ToolRequestUserInputResponse.json
new file mode 100644
index 00000000..3fd6fbc3
--- /dev/null
+++ b/internal/runner/provider/codex/testdata/schema-ToolRequestUserInputResponse.json
@@ -0,0 +1,34 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "definitions": {
+ "ToolRequestUserInputAnswer": {
+ "description": "EXPERIMENTAL. Captures a user's answer to a request_user_input question.",
+ "properties": {
+ "answers": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "answers"
+ ],
+ "type": "object"
+ }
+ },
+ "description": "EXPERIMENTAL. Response payload mapping question ids to answers.",
+ "properties": {
+ "answers": {
+ "additionalProperties": {
+ "$ref": "#/definitions/ToolRequestUserInputAnswer"
+ },
+ "type": "object"
+ }
+ },
+ "required": [
+ "answers"
+ ],
+ "title": "ToolRequestUserInputResponse",
+ "type": "object"
+}
\ No newline at end of file
diff --git a/internal/runner/provider/types.go b/internal/runner/provider/types.go
index 4b6678b2..5f9719b1 100644
--- a/internal/runner/provider/types.go
+++ b/internal/runner/provider/types.go
@@ -51,6 +51,8 @@ type Policy struct {
}
type Launch struct {
+ // ToolSocket is the runner-created per-attempt endpoint, pinned by containment.
+ ToolSocket string
AttemptKey, Workspace, ResumeSessionID string
Selection Selection
Binding Binding
@@ -68,12 +70,18 @@ type Turn struct {
}
type Answer struct {
+ // Authorize is supplied by the runner for an Equipo MCP approval. The adapter
+ // passes the captured original request; model payloads cannot supply callbacks.
+ Authorize func(context.Context, Event) error `json:"-"`
+
RequestID, TurnID, Behavior string
Input json.RawMessage
}
type Event struct {
- Sequence int64 `json:"capture_sequence,omitempty"`
+ // ToolCall is the captured item/started frame correlated by the adapter.
+ ToolCall json.RawMessage `json:",omitempty"`
+ Sequence int64 `json:"capture_sequence,omitempty"`
SessionID, TurnID, RequestID, Kind string
Payload json.RawMessage
}
@@ -179,3 +187,9 @@ type TurnBarrier interface {
type SessionBinding interface {
BindSession(context.Context, Session) error
}
+
+// AnswerWriter journals a correlated answer before sending it. It does not
+// consume a new turn admission and refuses writes outside the active turn.
+type AnswerWriter interface {
+ WriteAnswer(context.Context, Session, string, []byte) (int, error)
+}
diff --git a/internal/runner/questions.go b/internal/runner/questions.go
index 7821e77a..b0d5c51f 100644
--- a/internal/runner/questions.go
+++ b/internal/runner/questions.go
@@ -2,6 +2,7 @@ package runner
import (
"amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/runnerproto"
"context"
"database/sql"
@@ -65,9 +66,11 @@ func QuestionFromEvent(e paseo.Event, id, task string, secrets []string) (runner
// QuestionRelay records delivery intent before Respond. A lost reply remains
// uncertain; it cannot trigger an automatic second response or a new turn.
type QuestionRelay struct {
- Journal *Journal
- Client QuestionClient
- Agent paseo.Agent
+ DirectSession provider.Session
+ TurnID string
+ Journal *Journal
+ Client QuestionClient
+ Agent paseo.Agent
// Current returns the trusted current lease bound, capped by the attempt deadline.
Current func(context.Context, runnerproto.Question) (time.Time, error)
}
@@ -76,6 +79,14 @@ func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, ans
if r.Journal == nil || r.Client == nil || r.Current == nil || q.Attempt <= 0 || q.Fence <= 0 || q.ExpiresAt.IsZero() || q.Validate() != nil || q.ValidateAnswer(answer) != nil {
return runnerproto.ErrInvalid
}
+ if r.DirectSession.AttemptKey != "" {
+ if q.SessionID != r.DirectSession.ID || q.AgentID != r.DirectSession.AttemptKey {
+ return runnerproto.ErrInvalid
+ }
+ if err := r.Journal.currentDirectTurn(ctx, r.DirectSession, r.TurnID); err != nil {
+ return err
+ }
+ }
var err error
q.ExpiresAt, err = r.Current(ctx, q)
if err != nil {
@@ -97,6 +108,12 @@ func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, ans
var old, state string
err = tx.QueryRowContext(ctx, "SELECT content_hash,state FROM journal_answers WHERE answer_key=?", key).Scan(&old, &state)
if err == nil {
+ if r.DirectSession.AttemptKey != "" {
+ var attempt, turn string
+ if err := tx.QueryRowContext(ctx, "SELECT attempt,turn FROM direct_answer_scopes WHERE answer_key=?", key).Scan(&attempt, &turn); err != nil || attempt != r.DirectSession.AttemptKey || turn != r.TurnID {
+ return runnerproto.ErrInvalid
+ }
+ }
if old != hash {
return runnerproto.ErrInvalid
}
@@ -116,6 +133,11 @@ func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, ans
tx.Rollback()
return r.Journal.storageFailure(ctx, err)
}
+ if r.DirectSession.AttemptKey != "" {
+ if _, err = tx.ExecContext(ctx, "INSERT INTO direct_answer_scopes(answer_key,attempt,turn) VALUES(?,?,?)", key, r.DirectSession.AttemptKey, r.TurnID); err != nil {
+ return err
+ }
+ }
if err = tx.Commit(); err != nil {
return r.Journal.storageFailure(ctx, err)
}
@@ -123,10 +145,19 @@ func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, ans
if err != nil {
return err
}
+ if r.DirectSession.AttemptKey != "" {
+ if err := r.Journal.currentDirectTurn(ctx, r.DirectSession, r.TurnID); err != nil {
+ return err
+ }
+ var state string
+ if err := r.Journal.db.QueryRowContext(ctx, "SELECT state FROM journal_answers WHERE answer_key=?", key).Scan(&state); err != nil || state != "pending" {
+ return runnerproto.ErrInvalid
+ }
+ }
if err = DeliverAnswer(ctx, r.Client, r.Agent, q, answer); err != nil {
return err
}
- if _, err = r.Journal.db.ExecContext(ctx, "UPDATE journal_answers SET state='delivered' WHERE answer_key=?", key); err != nil {
+ if _, err = r.Journal.db.ExecContext(ctx, "UPDATE journal_answers SET state='delivered' WHERE answer_key=? AND state='pending'", key); err != nil {
return r.Journal.storageFailure(ctx, err)
}
return nil
diff --git a/internal/runner/tool_journal.go b/internal/runner/tool_journal.go
index 50d54e25..c1a6c44a 100644
--- a/internal/runner/tool_journal.go
+++ b/internal/runner/tool_journal.go
@@ -148,3 +148,22 @@ func (j *Journal) finishTools(ctx context.Context, c RunClaim, outcome string) e
}
return tx.Commit()
}
+
+// validateToolReplay applies the same immutable request key before automatic
+// approval that appendTool enforces again when the endpoint executes the call.
+func (j *Journal) validateToolReplay(ctx context.Context, v ToolSubmission) error {
+ key := runnerproto.EventHash([]any{v.InstanceID, v.TaskID, v.Attempt, v.Fence, v.RequestID})
+ hash := runnerproto.EventHash([]any{v.Name, runnerproto.EventHash(json.RawMessage(v.Arguments)), v.Agent})
+ var old string
+ err := j.db.QueryRowContext(ctx, "SELECT content_hash FROM journal_tools WHERE request_key=?", key).Scan(&old)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return j.storageFailure(ctx, err)
+ }
+ if old != hash {
+ return runnerproto.ErrInvalid
+ }
+ return nil
+}
diff --git a/internal/runner/tool_proxy.go b/internal/runner/tool_proxy.go
new file mode 100644
index 00000000..3875e025
--- /dev/null
+++ b/internal/runner/tool_proxy.go
@@ -0,0 +1,395 @@
+package runner
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "path/filepath"
+ "slices"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+const directMCP = `{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}`
+
+// ToolProxy exposes MCP only. The authenticating broker and its capability stay
+// in the runner; neither is written into the mounted endpoint directory.
+type ToolProxy struct {
+ SocketPath string
+ broker *AttemptSocket
+ listener *net.UnixListener
+ ctx context.Context
+ cancel context.CancelFunc
+ workers sync.WaitGroup
+ once sync.Once
+ directory string
+}
+
+func OpenToolProxy(ctx context.Context, b ToolBinding) (*ToolProxy, error) {
+ if b.Journal == nil {
+ return nil, runnerproto.ErrInvalid
+ }
+ return openToolProxy(ctx, b, filepath.Dir(b.Journal.path))
+}
+func openToolProxy(ctx context.Context, b ToolBinding, root string) (*ToolProxy, error) {
+ if b.Journal == nil || b.Current == nil || b.InstanceID == "" || b.TaskID == "" || b.Attempt <= 0 || b.Fence <= 0 || b.Isolation.Status != "confined" || b.Copy.Accepted == "" || b.Copy.Rejected == "" || len(b.Tools) == 0 || !time.Now().Before(b.LeaseDeadline) {
+ return nil, runnerproto.ErrInvalid
+ }
+ for _, name := range b.Tools {
+ if !slices.Contains([]string{"ask_person", "submit_candidate", "submit_review", "submit_reproduction"}, name) {
+ return nil, runnerproto.ErrInvalid
+ }
+ }
+ if err := b.Current(ctx); err != nil {
+ return nil, err
+ }
+ parent, err := openPrivateDir(root)
+ if err != nil {
+ return nil, err
+ }
+ parent.Close()
+ dir, err := os.MkdirTemp(root, "tool-")
+ if err != nil {
+ return nil, err
+ }
+ ok := false
+ defer func() {
+ if !ok {
+ os.Remove(filepath.Join(dir, "equipo.sock"))
+ os.Remove(dir)
+ }
+ }()
+ fd, err := openPrivateDir(dir)
+ if err != nil {
+ return nil, err
+ }
+ defer fd.Close()
+ path := filepath.Join(dir, "equipo.sock")
+ listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: fmt.Sprintf("/proc/self/fd/%d/equipo.sock", fd.Fd()), Net: "unix"})
+ if err != nil {
+ return nil, err
+ }
+ listener.SetUnlinkOnClose(false)
+ if err = os.Chmod(path, 0600); err != nil {
+ listener.Close()
+ return nil, err
+ }
+ ctx, cancel := context.WithCancel(ctx)
+ b.Tools = slices.Clone(b.Tools)
+ broker := &AttemptSocket{pending: b.Session.AttemptKey == "", binding: b, done: make(chan struct{}), capability: toolCapability{Secret: rand.Text() + rand.Text(), Copy: b.Copy, Tools: b.Tools, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence}}
+ p := &ToolProxy{SocketPath: path, broker: broker, listener: listener, ctx: ctx, cancel: cancel, directory: dir}
+ p.workers.Add(2)
+ go p.accept()
+ // Cancellation closes all connections and permanently invalidates the broker.
+ context.AfterFunc(ctx, func() { _ = p.Close() })
+ go func() {
+ defer p.workers.Done()
+ tick := time.NewTicker(100 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-tick.C:
+ broker.mu.Lock()
+ b := broker.binding
+ err := b.Current(ctx)
+ if !time.Now().Before(b.LeaseDeadline) {
+ err = runnerproto.ErrInvalid
+ }
+ if err == nil && b.Session.AttemptKey != "" {
+ var recovered int
+ err = b.Journal.db.QueryRowContext(ctx, "SELECT recovered FROM direct_attempts WHERE attempt=?", b.Session.AttemptKey).Scan(&recovered)
+ if recovered != 0 {
+ err = runnerproto.ErrInvalid
+ }
+ }
+ broker.mu.Unlock()
+ if err != nil {
+ cancel()
+ return
+ }
+ }
+ }
+ }()
+ ok = true
+ return p, nil
+}
+
+// BindTurn is called by the trusted supervisor after session identity and turn
+// identity is durable, before StartTurn writes its prompt. Calls still require
+// durable dispatch. Binding never changes the task, fence or tools.
+func (p *ToolProxy) BindTurn(session provider.Session, turn string) error {
+ s := p.broker
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.invalid || p.ctx.Err() != nil || s.binding.Agent.Provider != session.Provider {
+ return runnerproto.ErrInvalid
+ }
+ if s.binding.Session.AttemptKey != "" && s.binding.Session != session {
+ return runnerproto.ErrInvalid
+ }
+ if err := s.binding.Current(p.ctx); err != nil {
+ return err
+ }
+ var saved string
+ var recovered int
+ if turn == "" {
+ return runnerproto.ErrInvalid
+ }
+ if err := s.binding.Journal.db.QueryRowContext(p.ctx, "SELECT session,recovered FROM direct_attempts WHERE attempt=?", session.AttemptKey).Scan(&saved, &recovered); err != nil || saved != session.ID || recovered != 0 {
+ return runnerproto.ErrInvalid
+ }
+ if s.binding.TurnID != "" && s.binding.TurnID != turn {
+ var active int
+ if err := s.binding.Journal.db.QueryRowContext(p.ctx, "SELECT count(*) FROM direct_turns WHERE attempt=? AND state IN ('intent','dispatched')", session.AttemptKey).Scan(&active); err != nil || active != 0 {
+ return runnerproto.ErrInvalid
+ }
+ }
+ s.binding.Session = session
+ s.binding.TurnID = turn
+ s.binding.Agent.AgentID = session.AttemptKey
+ s.binding.Agent.ProviderSessionID = session.ID
+ s.pending = false
+ return nil
+}
+
+// RenewLease accepts only the supervisor's trusted monotonic renewal.
+func (p *ToolProxy) RenewLease(ctx context.Context, deadline time.Time) error {
+ return p.broker.RenewLease(ctx, deadline)
+}
+
+func (p *ToolProxy) MCP() json.RawMessage { return json.RawMessage(directMCP) }
+func (p *ToolProxy) Close() error {
+ p.once.Do(func() { p.cancel(); p.broker.Invalidate(); p.listener.Close() })
+ p.workers.Wait()
+ if err := os.Remove(p.SocketPath); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ if err := os.Remove(p.directory); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ return nil
+}
+func (p *ToolProxy) accept() {
+ defer p.workers.Done()
+ for {
+ conn, err := p.listener.AcceptUnix()
+ if err != nil {
+ return
+ }
+ p.workers.Add(1)
+ go func() {
+ defer p.workers.Done()
+ defer conn.Close()
+ stop := context.AfterFunc(p.ctx, func() { conn.Close() })
+ defer stop()
+ if !toolPeer(conn) {
+ return
+ }
+ // Bound each client to the lease and an idle frame interval.
+ input := &proxyReader{conn: conn}
+ _ = serveTools(p.ctx, input, conn, func() (toolCapability, error) {
+ p.broker.mu.Lock()
+ defer p.broker.mu.Unlock()
+ if p.broker.invalid || p.ctx.Err() != nil {
+ return toolCapability{}, runnerproto.ErrInvalid
+ }
+ if err := p.broker.binding.Current(p.ctx); err != nil {
+ p.broker.invalidateLocked()
+ return toolCapability{}, err
+ }
+ return p.broker.capability, nil
+ }, func(q toolRequest) (any, error) {
+ if e := p.submit(p.ctx, q.Name, q.RequestID, q.Arguments); e != nil {
+ return nil, e
+ }
+ p.broker.mu.Lock()
+ bound := p.broker.binding
+ p.broker.mu.Unlock()
+ if q.Name == "ask_person" && bound.Ask != nil {
+ answer, e := bound.Ask(p.ctx, bound, q.RequestID, q.Arguments)
+ if e != nil {
+ return nil, e
+ }
+ p.broker.mu.Lock()
+ defer p.broker.mu.Unlock()
+ if bound.Session != p.broker.binding.Session || bound.TurnID != p.broker.binding.TurnID {
+ return nil, runnerproto.ErrInvalid
+ }
+ if e = p.broker.current(p.ctx); e != nil {
+ return nil, e
+ }
+ return map[string]any{"content": []any{map[string]string{"type": "text", "text": string(answer)}}}, nil
+ }
+ return nil, nil
+ }, p.permission())
+ }()
+ }
+}
+
+type proxyReader struct{ conn net.Conn }
+
+func (r *proxyReader) Read(b []byte) (int, error) {
+ _ = r.conn.SetReadDeadline(time.Now().Add(30 * time.Second))
+ return r.conn.Read(b)
+}
+func (p *ToolProxy) permission() func(context.Context, json.RawMessage) (json.RawMessage, error) {
+ if p.broker.binding.Permission == nil {
+ return nil
+ }
+ return func(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) {
+ p.broker.mu.Lock()
+ err := p.broker.current(ctx)
+ fn := p.broker.binding.Permission
+ session, turn := p.broker.binding.Session, p.broker.binding.TurnID
+ p.broker.mu.Unlock()
+ if err != nil {
+ return nil, err
+ }
+ result, err := fn(ctx, raw)
+ if err != nil {
+ return nil, err
+ }
+ p.broker.mu.Lock()
+ defer p.broker.mu.Unlock()
+ if session != p.broker.binding.Session || turn != p.broker.binding.TurnID {
+ return nil, runnerproto.ErrInvalid
+ }
+ if err = p.broker.current(ctx); err != nil {
+ return nil, err
+ }
+ return result, nil
+ }
+}
+func (p *ToolProxy) submit(ctx context.Context, name, id string, args json.RawMessage) error {
+ p.broker.mu.Lock()
+ b := p.broker.binding
+ cap := p.broker.capability
+ p.broker.mu.Unlock()
+ return p.broker.submit(ctx, toolRequest{Capability: cap.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, RequestID: id, Name: name, Arguments: args})
+}
+
+// ValidateApproval does not execute a tool. The eventual socket call repeats
+// every validation and uses the existing durable submission idempotency key.
+func (p *ToolProxy) ValidateApproval(ctx context.Context, q ToolSubmission) error {
+ s := p.broker
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ b := s.binding
+ if q.InstanceID != b.InstanceID || q.TaskID != b.TaskID || q.Attempt != b.Attempt || q.Fence != b.Fence || q.Agent != b.Agent || !slices.Contains(b.Tools, q.Name) || q.RequestID == "" || len(q.RequestID) > 256 {
+ return runnerproto.ErrInvalid
+ }
+ if err := validateToolArguments(q.Name, q.Arguments); err != nil {
+ return err
+ }
+ if err := b.Journal.validateToolReplay(ctx, q); err != nil {
+ return err
+ }
+ return s.current(ctx)
+}
+func (s *AttemptSocket) current(ctx context.Context) error {
+ if ctx.Err() != nil || s.invalid || s.pending || !time.Now().Before(s.binding.LeaseDeadline) {
+ return runnerproto.ErrInvalid
+ }
+ b := s.binding
+ if err := b.Current(ctx); err != nil {
+ return err
+ }
+ if b.Session.AttemptKey != "" {
+ if b.Agent.AgentID != b.Session.AttemptKey || b.Agent.ProviderSessionID != b.Session.ID || b.Agent.Provider != b.Session.Provider {
+ return runnerproto.ErrInvalid
+ }
+ if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil {
+ return err
+ }
+ }
+ return b.Journal.AdmissionAllowed(ctx)
+}
+func (j *Journal) currentDirectTurn(ctx context.Context, s provider.Session, turn string) error {
+ if s.ID == "" || s.AttemptKey == "" || turn == "" {
+ return runnerproto.ErrInvalid
+ }
+ var count int
+ if err := j.db.QueryRowContext(ctx, `SELECT count(*) FROM direct_turns t JOIN direct_attempts a ON a.attempt=t.attempt WHERE t.attempt=? AND t.session=? AND t.turn=? AND t.state='dispatched' AND a.recovered=0 AND a.session=?`, s.AttemptKey, s.ID, turn, s.ID).Scan(&count); err != nil {
+ return err
+ }
+ if count != 1 {
+ return runnerproto.ErrInvalid
+ }
+ var raw []byte
+ var launch provider.Launch
+ if err := j.db.QueryRowContext(ctx, "SELECT launch FROM direct_attempts WHERE attempt=?", s.AttemptKey).Scan(&raw); err != nil {
+ return err
+ }
+ if json.Unmarshal(raw, &launch) != nil || s.Validate(launch) != nil {
+ return runnerproto.ErrInvalid
+ }
+ return nil
+}
+
+// ServeToolProxy is the fixed binary's stdio mode. It knows only an endpoint.
+func ServeToolProxy(ctx context.Context, input io.Reader, output io.Writer, path string) error {
+ if !filepath.IsAbs(path) || filepath.Clean(path) != path {
+ return runnerproto.ErrInvalid
+ }
+ // Inside the namespace /tool is an immutable mount. On the host, verify its
+ // private parent and use the open fd so long paths never need truncation.
+ dialPath := path
+ var parent *os.File
+ if path != "/tool/equipo.sock" {
+ var err error
+ parent, err = openPrivateDir(filepath.Dir(path))
+ if err != nil {
+ return err
+ }
+ defer parent.Close()
+ dialPath = fmt.Sprintf("/proc/self/fd/%d/%s", parent.Fd(), filepath.Base(path))
+ }
+ conn, err := (&net.Dialer{}).DialContext(ctx, "unix", dialPath)
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+ stop := context.AfterFunc(ctx, func() { conn.Close() })
+ defer stop()
+ reader := bufio.NewReaderSize(input, maxToolFrame+1)
+ replies := bufio.NewReaderSize(conn, maxToolFrame+1)
+ for {
+ if _, err = reader.Peek(1); err == io.EOF {
+ return nil
+ } else if err != nil {
+ return err
+ }
+ raw, err := readToolFrame(reader)
+ if err != nil {
+ return err
+ }
+ var q mcpRequest
+ if runnerproto.DecodeLimit(bytes.NewReader(raw), &q, maxToolFrame) != nil || q.JSONRPC != "2.0" {
+ return runnerproto.ErrInvalid
+ }
+ if _, err = conn.Write(append(raw, '\n')); err != nil {
+ return err
+ }
+ if len(q.ID) == 0 {
+ continue
+ }
+ reply, err := readToolFrame(replies)
+ if err != nil {
+ return err
+ }
+ if _, err = output.Write(append(reply, '\n')); err != nil {
+ return err
+ }
+ }
+}
diff --git a/internal/runner/tool_socket.go b/internal/runner/tool_socket.go
index b8b80b30..413de452 100644
--- a/internal/runner/tool_socket.go
+++ b/internal/runner/tool_socket.go
@@ -18,6 +18,7 @@ import (
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/runnerproto"
"golang.org/x/sys/unix"
)
@@ -25,6 +26,14 @@ import (
const maxToolFrame = 64 << 10
type ToolBinding struct {
+ // Ask returns only an authenticated answer to the bound scoped question.
+ Ask func(context.Context, ToolBinding, string, json.RawMessage) (json.RawMessage, error)
+
+ Session provider.Session
+ TurnID string
+ // Permission is the trusted adapter's MCP permission handler, never model code.
+ Permission func(context.Context, json.RawMessage) (json.RawMessage, error)
+
ReadPolicy paseo.ReadPolicy
Copy ToolCopy
InstanceID, TaskID string
@@ -254,7 +263,9 @@ func (s *AttemptSocket) invalidateLocked() {
if !s.invalid {
s.invalid = true
close(s.done)
- s.listener.Close()
+ if s.listener != nil {
+ s.listener.Close()
+ }
}
}
@@ -326,11 +337,17 @@ func (s *AttemptSocket) submit(ctx context.Context, q toolRequest) error {
if subtle.ConstantTimeCompare([]byte(q.Capability), []byte(s.capability.Secret)) != 1 || q.InstanceID != b.InstanceID || q.TaskID != b.TaskID || q.Attempt != b.Attempt || q.Fence != b.Fence || !slices.Contains(b.Tools, q.Name) || q.RequestID == "" || len(q.RequestID) > 256 {
return runnerproto.ErrInvalid
}
- if s.pending || s.invalid || !time.Now().Before(b.LeaseDeadline) {
+ if s.pending {
+ if s.listener != nil {
+ s.invalidateLocked()
+ }
+ return runnerproto.ErrInvalid
+ }
+ if s.invalid || !time.Now().Before(b.LeaseDeadline) {
s.invalidateLocked()
return runnerproto.ErrInvalid
}
- if err := b.Current(ctx); err != nil {
+ if err := s.current(ctx); err != nil {
s.invalidateLocked()
return err
}
diff --git a/internal/runner/tools.go b/internal/runner/tools.go
index 915388fb..34ddefcb 100644
--- a/internal/runner/tools.go
+++ b/internal/runner/tools.go
@@ -105,6 +105,13 @@ func ServeTools(ctx context.Context, input io.Reader, output io.Writer, socketPa
if _, err := readToolCapability(capabilityPath); err != nil {
return err
}
+ return serveTools(ctx, input, output, func() (toolCapability, error) { return readToolCapability(capabilityPath) }, func(q toolRequest) (any, error) {
+ err := callToolSocket(ctx, socketPath, q)
+ return nil, err
+ }, nil)
+}
+
+func serveTools(ctx context.Context, input io.Reader, output io.Writer, capability func() (toolCapability, error), call func(toolRequest) (any, error), permission func(context.Context, json.RawMessage) (json.RawMessage, error)) error {
reader := bufio.NewReaderSize(input, maxToolFrame+1)
encoder := json.NewEncoder(output)
initialized := false
@@ -135,7 +142,7 @@ func ServeTools(ctx context.Context, input io.Reader, output io.Writer, socketPa
default:
return runnerproto.ErrInvalid
}
- cap, err := readToolCapability(capabilityPath)
+ cap, err := capability()
if err != nil {
return err
}
@@ -163,7 +170,11 @@ func ServeTools(ctx context.Context, input io.Reader, output io.Writer, socketPa
err = runnerproto.ErrInvalid
break
}
- result = map[string]any{"tools": toolSchemas(cap.Tools, cap.Copy)}
+ schemas := toolSchemas(cap.Tools, cap.Copy)
+ if permission != nil {
+ schemas = append(schemas, map[string]any{"name": "permission", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{"tool_name": map[string]string{"type": "string"}, "input": map[string]string{"type": "object"}}, "required": []string{"tool_name", "input"}, "additionalProperties": false}})
+ }
+ result = map[string]any{"tools": schemas}
case "tools/call":
if !initialized {
err = runnerproto.ErrInvalid
@@ -174,7 +185,20 @@ func ServeTools(ctx context.Context, input io.Reader, output io.Writer, socketPa
Meta json.RawMessage `json:"_meta,omitempty"`
Arguments map[string]json.RawMessage `json:"arguments"`
}
- if runnerproto.DecodeLimit(bytes.NewReader(q.Params), &params, maxToolFrame) != nil || !slices.Contains(cap.Tools, params.Name) {
+ if runnerproto.DecodeLimit(bytes.NewReader(q.Params), &params, maxToolFrame) != nil {
+ err = runnerproto.ErrInvalid
+ break
+ }
+ if params.Name == "permission" && permission != nil {
+ raw, _ := json.Marshal(params.Arguments)
+ var answer json.RawMessage
+ answer, err = permission(ctx, raw)
+ if err == nil {
+ result = map[string]any{"content": []any{map[string]string{"type": "text", "text": string(answer)}}}
+ }
+ break
+ }
+ if !slices.Contains(cap.Tools, params.Name) {
err = runnerproto.ErrInvalid
break
}
@@ -192,8 +216,8 @@ func ServeTools(ctx context.Context, input io.Reader, output io.Writer, socketPa
if err = validateToolArguments(params.Name, args); err != nil {
break
}
- err = callToolSocket(ctx, socketPath, toolRequest{Capability: cap.Secret, InstanceID: cap.InstanceID, TaskID: cap.TaskID, Attempt: cap.Attempt, Fence: cap.Fence, RequestID: requestID, Name: params.Name, Arguments: args})
- if err == nil {
+ result, err = call(toolRequest{Capability: cap.Secret, InstanceID: cap.InstanceID, TaskID: cap.TaskID, Attempt: cap.Attempt, Fence: cap.Fence, RequestID: requestID, Name: params.Name, Arguments: args})
+ if err == nil && result == nil {
result = map[string]any{"content": []any{map[string]string{"type": "text", "text": cap.Copy.Accepted}}}
}
default:
diff --git a/internal/runnerproto/questions.go b/internal/runnerproto/questions.go
index 8016045c..bce051c2 100644
--- a/internal/runnerproto/questions.go
+++ b/internal/runnerproto/questions.go
@@ -69,6 +69,23 @@ func (a QuestionAnswer) Validate(kind string) error {
// ValidateAnswer permits only the pinned structured question adapters. Unknown
// provider shapes can be retained without turning them into an approval.
func (q Question) ValidateAnswer(a QuestionAnswer) error {
+ // A direct Claude native approval permits the unchanged action only. The
+ // adapter separately checks the original input against its certified policy.
+ if q.Kind == "tool" && a.Behavior == "allow" && len(a.UpdatedInput) == 0 {
+ var raw struct {
+ Direct bool
+ Provider, Name string
+ Input json.RawMessage
+ }
+ if DecodeLimit(bytes.NewReader(q.RawRequest), new(map[string]any), MaxEventBytes) != nil || json.Unmarshal(q.RawRequest, &raw) != nil {
+ return ErrInvalid
+ }
+ if raw.Direct && raw.Provider == "claude" && slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep", "Bash"}, raw.Name) {
+ return nil
+ }
+ return ErrInvalid
+ }
+
if a.Validate(q.Kind) != nil {
return ErrInvalid
}
@@ -94,13 +111,26 @@ func (q Question) ValidateAnswer(a QuestionAnswer) error {
Provider string `json:"provider"`
Name string `json:"name"`
Input struct {
+ Question string `json:"question"`
Questions []struct {
Question string `json:"question"`
Header string `json:"header"`
} `json:"questions"`
} `json:"input"`
}
- if json.Unmarshal(q.RawRequest, &raw) != nil || len(raw.Input.Questions) == 0 {
+ if json.Unmarshal(q.RawRequest, &raw) != nil {
+ return ErrInvalid
+ }
+ if raw.Provider == "claude" && raw.Name == "ask_person" {
+ var input struct {
+ Answers map[string]string `json:"answers"`
+ }
+ if strings.TrimSpace(raw.Input.Question) == "" || json.Unmarshal(a.UpdatedInput, &input) != nil || len(input.Answers) != 1 || strings.TrimSpace(input.Answers["answer"]) == "" {
+ return ErrInvalid
+ }
+ return nil
+ }
+ if len(raw.Input.Questions) == 0 {
return ErrInvalid
}
if (raw.Provider != "claude" || raw.Name != "AskUserQuestion") && (raw.Provider != "codex" || raw.Name != "request_user_input") {