From 41d2fad54920cb363282d7d5424fe969617fbd62 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 12:08:22 +0000 Subject: [PATCH 01/10] test(opencode): subagents keep their agent's denies under inherited Full access rules OpenCode 2 copies a parent session's rules into each child session, and session rules are checked after agent rules. T3's Full access catch-all allow therefore overrides a subagent's own denies. Fails on main. Refs #38100 Co-Authored-By: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index cd1bdc9044a5c..446433a3237b6 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -1504,6 +1504,57 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + // OpenCode copies the parent's session rules into a child, and session rules outrank agent rules. + it.effect("keeps a subagent's own agent denies under the Full access rules it inherits", () => + Effect.gen(function* () { + const editDeny = { action: "edit", resource: "*", effect: "deny" }; + const launch = backgroundLaunch(CHILD).map((entry) => + entry.type === "emit_inbound" && + entry.frame.type === "sdk.event" && + entry.frame.event.type === "session.created" + ? event("session.created", { + ...childCreated(CHILD), + agent: "review", + permissions: t3Rules, + }) + : entry, + ); + const { runtime, thread } = yield* resumed([ + ...launch, + out("agent.list", ""), + reply("agent.list", { + ...agentList, + data: [ + ...agentList.data, + { + ...agentList.data[0]!, + id: "review", + name: "review", + mode: "subagent", + permissions: [{ action: "*", resource: "*", effect: "allow" }, editDeny], + }, + ], + }), + out("session.update", { + sessionID: CHILD, + permissions: [t3Rules[0], editDeny, ...mcpRules], + }), + reply("session.update", null), + out("session.interrupt", { sessionID: SESSION }), + reply("session.interrupt", { interrupted: true }), + event("session.execution.interrupted", { sessionID: SESSION }), + ]); + const watch = yield* watchBackgroundTurn(runtime); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.attached; + yield* runtime.interruptTurn({ + providerThread: thread, + providerTurnId: yield* providerTurnId, + }); + assert.equal((yield* watch.terminal)?.status, "interrupted"); + }), + ); + it.effect("stops background subagents on a user Stop", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ From f72a6c93d1096aa2f2a3758392148c8e61d6e229 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 12:40:40 +0000 Subject: [PATCH 02/10] fix(opencode): subagents keep their own agent's denies OpenCode 2 copies a parent session's permission rules into each child session, and session rules are checked after agent rules. T3's Full access catch-all allow (or Supervised edit: ask) therefore overrode a subagent's own denies, so read-only agents like explore or a custom review agent could write files. When a child session reports inherited rules, rewrite them: T3's policy, then the subagent's own rules from its first deny on, with later allows and asks capped by T3's policy so they never loosen it. Fixes #38100 Co-Authored-By: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 29 ++++---- .../src/server/v2/adapter.ts | 69 +++++++++++++------ 2 files changed, 64 insertions(+), 34 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 446433a3237b6..311338f41220a 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -286,6 +286,7 @@ const agentList = { }, ], }; +const listAgents = [out("agent.list", ""), reply("agent.list", agentList)]; const supervisedRules = [ { action: "shell", resource: "*", effect: "ask" }, { action: "edit", resource: "*", effect: "ask" }, @@ -893,7 +894,10 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { agent: "general", model: { id: "big-pickle", providerID: "opencode", variant: "default" }, }); - const backgroundLaunch = (child: string): ReadonlyArray => { + const backgroundLaunch = ( + child: string, + created: Record = childCreated(child), + ): ReadonlyArray => { const call = "call-background"; const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: call }; return [ @@ -907,7 +911,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { input: { description: "Sleep", prompt: "sleep", background: true }, executed: false, }), - event("session.created", childCreated(child)), + event("session.created", created), event("session.tool.progress", { ...tool, metadata: { sessionID: child, status: "running" }, @@ -1508,19 +1512,12 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { it.effect("keeps a subagent's own agent denies under the Full access rules it inherits", () => Effect.gen(function* () { const editDeny = { action: "edit", resource: "*", effect: "deny" }; - const launch = backgroundLaunch(CHILD).map((entry) => - entry.type === "emit_inbound" && - entry.frame.type === "sdk.event" && - entry.frame.event.type === "session.created" - ? event("session.created", { - ...childCreated(CHILD), - agent: "review", - permissions: t3Rules, - }) - : entry, - ); const { runtime, thread } = yield* resumed([ - ...launch, + ...backgroundLaunch(CHILD, { + ...childCreated(CHILD), + agent: "review", + permissions: t3Rules, + }), out("agent.list", ""), reply("agent.list", { ...agentList, @@ -1747,6 +1744,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { // The adapter writes a child's rules only when they changed. ...(writesRules ? [ + ...listAgents, out("session.update", { sessionID: CHILD, permissions: "" }), reply("session.update", null), ] @@ -1972,6 +1970,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...again, metadata: { sessionID: CHILD, status: "running" }, }), + ...listAgents, out("session.update", { sessionID: CHILD, permissions: "" }), reply("session.update", null), // The child fails while the joined call is still the foreground one. @@ -2377,6 +2376,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...toolOf(SESSION, "call-other"), metadata: { sessionID: OTHER, status: "running" }, }), + ...listAgents, event("session.tool.success", { ...toolOf(SESSION, "call-other"), content: [{ type: "text", text: "OTHER_OK" }], @@ -2763,6 +2763,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { [ ...backgroundLaunch(CHILD), event("session.execution.succeeded", { sessionID: SESSION }), + ...listAgents, out("session.update", { sessionID: CHILD, permissions: t3Rules }), reply("session.update", null), out("session.prompt", { sessionID: SESSION, text: "" }), diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 0072f9d1897b7..4a567300f8184 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -438,19 +438,41 @@ const mcpRules = (mcpServerName: string | null): ReadonlyArray => { action: `${mcpServerName}_*`, resource: "*", effect: "allow" }, ]; +const policyRules = (policy: RulesPolicy): ReadonlyArray => + policy.runtimeMode === "full-access" + ? [rule("*", "allow")] + : [ + rule("shell", "ask"), + rule("edit", policy.runtimeMode === "auto-accept-edits" ? "allow" : "ask"), + rule("external_directory", "ask"), + ]; + +// A child session inherits its parent's rules, which outrank agent rules; repeat the agent's own +// restrictions after them. Its later allows and asks never loosen T3's policy. +const agentLimits = (policy: RulesPolicy, agentRules: ReadonlyArray): ReadonlyArray => { + const start = agentRules.findIndex((entry) => entry.effect === "deny"); + if (start === -1) return []; + const base = policyRules(policy); + return agentRules + .slice(start) + .flatMap((entry) => + entry.effect === "deny" + ? [entry] + : policy.runtimeMode === "full-access" + ? [{ ...entry, effect: "allow" as const }] + : [entry, ...base.filter((own) => entry.action === "*" || own.action === entry.action)], + ); +}; + const sessionRules = ( policy: RulesPolicy, paths: ReadonlyArray, grants: ReadonlyArray, mcpServerName: string | null, + limits: ReadonlyArray = [], ): ReadonlyArray => [ - ...(policy.runtimeMode === "full-access" - ? [rule("*", "allow")] - : [ - rule("shell", "ask"), - rule("edit", policy.runtimeMode === "auto-accept-edits" ? "allow" : "ask"), - rule("external_directory", "ask"), - ]), + ...policyRules(policy), + ...limits, ...grants, // Plan edits are re-allowed only for plan paths; free-tier sessions refuse denied shell/read. ...(policy.interactionMode === "plan" ? [rule("edit", "deny")] : []), @@ -2117,8 +2139,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* emit({ type: "app_thread.created", driver, appThread }); yield* emitProviderThread(child); yield* emitSubagent(call); - // Reused child sessions may retain old mode rules; refresh policy as soon as the call identifies them. - if (info === undefined) { + // Reused children may keep old mode rules, and new ones copy their parent's; rewrite both. + if (info === undefined || info.permissions !== undefined) { yield* writeRules(child, rootOf(call.state).policy).pipe( Effect.timeout(REQUEST_REPLY_TIMEOUT), Effect.ignore({ log: true }), @@ -3963,10 +3985,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* readModels(session.cwd); const agentRules = new Map>>(); - const pathsFor = Effect.fnUntraced(function* ( - directory: string, - agents: ReadonlyArray, - ) { + const agentsIn = Effect.fnUntraced(function* (directory: string) { let known = agentRules.get(directory); if (known === undefined) { // A fresh server lists no agents for its first moments, like its models. @@ -3984,15 +4003,20 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ), Effect.option, ); - if (listed._tag === "None") return []; - known = new Map( - listed.value.data.map((agent) => [agent.id, agentPaths(agent.permissions)]), - ); + if (listed._tag === "None") return new Map>(); + known = new Map(listed.value.data.map((agent) => [agent.id, agent.permissions])); agentRules.set(directory, known); } + return known; + }); + const pathsFor = Effect.fnUntraced(function* ( + directory: string, + agents: ReadonlyArray, + ) { + const known = yield* agentsIn(directory); const paths = new Map(); for (const agent of agents) { - for (const entry of known.get(agent) ?? []) { + for (const entry of agentPaths(known.get(agent) ?? [])) { paths.set(`${entry.action}\u0000${entry.resource}`, entry); } } @@ -4000,7 +4024,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }); const rulesFor = Effect.fnUntraced(function* ( - thread: Pick, + thread: Pick, policy: RulesPolicy, appThreadId: string | null, ) { @@ -4009,11 +4033,16 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr policy.runtimeMode === "full-access" && !plan ? [] : yield* pathsFor(thread.directory, plan ? [thread.agent, "plan"] : [thread.agent]); + const limits = + thread.subagent === undefined + ? [] + : agentLimits(policy, (yield* agentsIn(thread.directory)).get(thread.agent) ?? []); return sessionRules( policy, paths, policy.runtimeMode === "full-access" ? [] : thread.grants, appThreadId === null ? null : yield* mcpServerNameFor(appThreadId), + limits, ); }); @@ -4698,7 +4727,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const directory = threadInput.runtimePolicy.cwd ?? host.paths.cwd; const policy = threadInput.runtimePolicy; const permissions = yield* rulesFor( - { directory, agent: "build", grants: [] }, + { directory, agent: "build", grants: [], subagent: undefined }, policy, threadInput.threadId, ); From 64d608d11625efa82dc6827de748214a33d3f5dc Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 13:14:41 +0000 Subject: [PATCH 03/10] fix(opencode): rewrite a new subagent's rules only when its agent denies something A child announced with inherited rules was always rewritten, which also added T3's MCP rules to children whose agent restricts nothing and broke the recorded nested-background replay. Rewrite only when the agent has its own denies; record the agent.list call that check makes in the fixture. Co-Authored-By: Claude Opus 5.5 --- .../opencode_transcript.ndjson | 2 ++ packages/provider-opencode/src/server/v2/adapter.ts | 13 +++++++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_nested_background/opencode_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_nested_background/opencode_transcript.ndjson index 4204f275fd8dc..53d22562c4a92 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_nested_background/opencode_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_nested_background/opencode_transcript.ndjson @@ -38,6 +38,8 @@ {"type": "emit_inbound", "label": "session.step.streamed", "frame": {"type": "sdk.event", "event": {"id": "evt_0f73f91d5001vrzflyt1WQFGva", "created": 1790854533589, "type": "session.step.streamed", "location": {"directory": ""}, "data": {"sessionID": "ses_f08c08821ffefFAD3sMjkyP0Fd", "assistantMessageID": "msg_0f73f7b54001L2fnmF6VSokmbn"}, "durable": {"aggregateID": "ses_f08c08821ffefFAD3sMjkyP0Fd", "seq": 11, "version": 1}}}} {"type": "emit_inbound", "label": "session.created.2", "frame": {"type": "sdk.event", "event": {"id": "evt_0f73f91dd001BBDOI1lGk77sTL", "created": 1790854533597, "type": "session.created", "location": {"directory": ""}, "data": {"sessionID": "ses_f08c06e25ffeF0asx24ydmo3oy", "slug": "kind-forest", "version": "2.0.18", "projectID": "3b9597874c088ee0849b0d68c211296e47876139", "parentID": "ses_f08c08821ffefFAD3sMjkyP0Fd", "location": {"directory": ""}, "subpath": "", "title": "Chain subagents with background", "agent": "general", "permissions": [{"action": "*", "resource": "*", "effect": "allow"}], "model": {"id": "deepseek/deepseek-v4-flash", "providerID": "openrouter", "variant": "default"}}, "durable": {"aggregateID": "ses_f08c06e25ffeF0asx24ydmo3oy", "seq": 0, "version": 1}}}} {"type": "emit_inbound", "label": "session.tool.progress", "frame": {"type": "sdk.event", "event": {"id": "evt_0f73f91e00015k1c4ULxR6t2Sb", "created": 1790854533600, "type": "session.tool.progress", "location": {"directory": ""}, "data": {"sessionID": "ses_f08c08821ffefFAD3sMjkyP0Fd", "assistantMessageID": "msg_0f73f7b54001L2fnmF6VSokmbn", "id": "call_3d90a8b7d44c49f6ae053fd7", "metadata": {"sessionID": "ses_f08c06e25ffeF0asx24ydmo3oy", "status": "running"}}}}} +{"type": "expect_outbound", "label": "agent.list", "frame": {"type": "agent.list", "input": {"location[directory]": ""}}} +{"type": "emit_inbound", "label": "agent.list.response", "frame": {"type": "sdk.response", "operation": "agent.list", "data": {"location": {"directory": ""}, "data": [{"id": "build", "name": "Build", "request": {"settings": {}, "headers": {}, "body": {}}, "description": "The default agent. Executes tools based on configured permissions.", "mode": "primary", "hidden": false, "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "external_directory", "resource": "*", "effect": "ask"}, {"action": "read", "resource": "*.env", "effect": "ask"}, {"action": "read", "resource": "*.env.*", "effect": "ask"}, {"action": "read", "resource": "*.env.example", "effect": "allow"}, {"action": "external_directory", "resource": "/data/opencode/shell/*/*", "effect": "allow"}, {"action": "external_directory", "resource": "/data/opencode/tool-output/*", "effect": "allow"}, {"action": "external_directory", "resource": "/tmp/opencode/*", "effect": "allow"}, {"action": "external_directory", "resource": "/config/opencode/*", "effect": "allow"}, {"action": "question", "resource": "*", "effect": "allow"}]}, {"id": "plan", "name": "Plan", "request": {"settings": {}, "headers": {}, "body": {}}, "description": "Read-only agent for exploring the codebase and planning work before implementation.", "mode": "primary", "hidden": false, "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "external_directory", "resource": "*", "effect": "ask"}, {"action": "read", "resource": "*.env", "effect": "ask"}, {"action": "read", "resource": "*.env.*", "effect": "ask"}, {"action": "read", "resource": "*.env.example", "effect": "allow"}, {"action": "external_directory", "resource": "/data/opencode/shell/*/*", "effect": "allow"}, {"action": "external_directory", "resource": "/data/opencode/tool-output/*", "effect": "allow"}, {"action": "external_directory", "resource": "/tmp/opencode/*", "effect": "allow"}, {"action": "external_directory", "resource": "/config/opencode/*", "effect": "allow"}, {"action": "question", "resource": "*", "effect": "allow"}, {"action": "edit", "resource": "*", "effect": "deny"}, {"action": "edit", "resource": "/.opencode/plan/*", "effect": "allow"}, {"action": "external_directory", "resource": "/.opencode/plan/*", "effect": "allow"}]}]}}} {"type": "emit_inbound", "label": "session.inbox.enqueued.2", "frame": {"type": "sdk.event", "event": {"id": "evt_0f73f91e200143nPcVfCFMVD3q", "created": 1790854533602, "type": "session.inbox.enqueued", "location": {"directory": ""}, "data": {"inboxID": "msg_0f73f91e0002lgRNb7FtMzcoQu", "sessionID": "ses_f08c06e25ffeF0asx24ydmo3oy", "item": {"type": "user", "payload": {"text": "You are a subagent spawned by another session.\nUse the subagent tool with background set to true to delegate to the general subagent with the prompt: Run the shell command `sleep 25` with the shell tool, then reply exactly GRANDCHILD_OK. As soon as it is launched, reply exactly MIDDLE_OK and end your turn without waiting for it."}, "delivery": "steer"}}, "durable": {"aggregateID": "ses_f08c06e25ffeF0asx24ydmo3oy", "seq": 1, "version": 1}}}} {"type": "emit_inbound", "label": "session.execution.started.2", "frame": {"type": "sdk.event", "event": {"id": "evt_0f73f91e4001B2I7Jd3RFqZj5q", "created": 1790854533604, "type": "session.execution.started", "data": {"sessionID": "ses_f08c06e25ffeF0asx24ydmo3oy"}, "durable": {"aggregateID": "ses_f08c06e25ffeF0asx24ydmo3oy", "seq": 2, "version": 1}}}} {"type": "emit_inbound", "label": "session.instructions.updated.2", "frame": {"type": "sdk.event", "event": {"id": "evt_0f73f91ee001ixy9HSfoqk0dfn", "created": 1790854533614, "metadata": {"instructions": {"initial": true}}, "type": "session.instructions.updated", "location": {"directory": ""}, "data": {"sessionID": "ses_f08c06e25ffeF0asx24ydmo3oy", "delta": {"core/environment": "1c986c3eac0f6ca81397ee564526171942f29600037576981dd43f39f8d186fa", "core/date": "9d407747420cc512794008e266cb494f38764d6dcf796660ba21354b97d331f9", "core/codemode": "616a7ad8b8e40e8a71eab238dfbbe9eaf0f4a9e6fdad853226d075bfe602e1e6", "core/skill-guidance": "0d001919496102654717308c72635523bf7c3cd99c81e058cc79f2947104f9a5"}}, "durable": {"aggregateID": "ses_f08c06e25ffeF0asx24ydmo3oy", "seq": 3, "version": 2}}}} diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 4a567300f8184..b4c12eefe0f61 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -2139,8 +2139,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* emit({ type: "app_thread.created", driver, appThread }); yield* emitProviderThread(child); yield* emitSubagent(call); - // Reused children may keep old mode rules, and new ones copy their parent's; rewrite both. - if (info === undefined || info.permissions !== undefined) { + // Reused children may keep old mode rules, and new ones copy their parent's, which outrank + // their agent's own denies; rewrite both. + if ( + info === undefined || + (info.permissions !== undefined && (yield* hasAgentLimits(child))) + ) { yield* writeRules(child, rootOf(call.state).policy).pipe( Effect.timeout(REQUEST_REPLY_TIMEOUT), Effect.ignore({ log: true }), @@ -4023,6 +4027,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr return [...paths.values()]; }); + const hasAgentLimits = Effect.fnUntraced(function* (thread: ThreadState) { + const own = (yield* agentsIn(thread.directory)).get(thread.agent) ?? []; + return own.some((entry) => entry.effect === "deny"); + }); + const rulesFor = Effect.fnUntraced(function* ( thread: Pick, policy: RulesPolicy, From 55d111b6af40bb88ebf5f3089df3e916ae74ef18 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 13:19:36 +0000 Subject: [PATCH 04/10] fix(opencode): cap a subagent's allows only within their own scope T3's approval caps after a subagent's allow were appended with a `*` resource and matched the allow's action by equality. A scoped allow (`edit src/** allow`) then reopened the agent's broader deny, and a glob action (`e*`) escaped the cap. Caps now take the allow's resource, match its action as OpenCode's glob, and only restrict (never an `allow` cap). Co-Authored-By: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 54 +++++++++++++++++++ .../src/server/v2/adapter.ts | 18 ++++++- 2 files changed, 70 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 311338f41220a..bbb864b304aa7 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -284,6 +284,19 @@ const agentList = { hidden: false, permissions: [{ action: "*", resource: "*", effect: "allow" }, ...buildPaths], }, + { + id: "reader", + name: "Reader", + request: { settings: {}, headers: {}, body: {} }, + description: "Reads anything, edits only src.", + mode: "subagent", + hidden: false, + permissions: [ + { action: "*", resource: "*", effect: "allow" }, + { action: "*", resource: "*", effect: "deny" }, + { action: "e*", resource: "src/**", effect: "allow" }, + ], + }, ], }; const listAgents = [out("agent.list", ""), reply("agent.list", agentList)]; @@ -1552,6 +1565,47 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect("keeps a subagent's own agent denies and T3's asks under Supervised rules", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed( + [ + ...backgroundLaunch(CHILD, { + ...childCreated(CHILD), + agent: "reader", + permissions: supervisedRules, + }), + out("session.update", { + sessionID: CHILD, + permissions: [ + ...supervisedRules.slice(0, 3), + { action: "*", resource: "*", effect: "deny" }, + { action: "e*", resource: "src/**", effect: "allow" }, + { action: "edit", resource: "src/**", effect: "ask" }, + { action: "external_directory", resource: "src/**", effect: "ask" }, + ...mcpRules, + ], + }), + reply("session.update", null), + out("session.interrupt", { sessionID: SESSION }), + reply("session.interrupt", { interrupted: true }), + event("session.execution.interrupted", { sessionID: SESSION }), + ], + { supervised: true }, + ); + const watch = yield* watchBackgroundTurn(runtime); + yield* runtime.startTurn({ + ...withLineage(thread), + runtimePolicy: policy("approval-required"), + }); + yield* watch.attached; + yield* runtime.interruptTurn({ + providerThread: thread, + providerTurnId: yield* providerTurnId, + }); + assert.equal((yield* watch.terminal)?.status, "interrupted"); + }), + ); + it.effect("stops background subagents on a user Stop", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index b4c12eefe0f61..ff27f23cdab87 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -452,7 +452,7 @@ const policyRules = (policy: RulesPolicy): ReadonlyArray => const agentLimits = (policy: RulesPolicy, agentRules: ReadonlyArray): ReadonlyArray => { const start = agentRules.findIndex((entry) => entry.effect === "deny"); if (start === -1) return []; - const base = policyRules(policy); + const caps = policyRules(policy).filter((own) => own.effect !== "allow"); return agentRules .slice(start) .flatMap((entry) => @@ -460,10 +460,24 @@ const agentLimits = (policy: RulesPolicy, agentRules: ReadonlyArray): Read ? [entry] : policy.runtimeMode === "full-access" ? [{ ...entry, effect: "allow" as const }] - : [entry, ...base.filter((own) => entry.action === "*" || own.action === entry.action)], + : [ + entry, + ...caps + .filter((own) => actionPattern(entry.action).test(own.action)) + .map((own) => ({ ...own, resource: entry.resource })), + ], ); }; +// OpenCode matches rule actions as globs: `*` is any run, `?` one character. +const actionPattern = (pattern: string) => + new RegExp( + `^${pattern + .replaceAll(/[.+^${}()|[\]\\]/g, "\\$&") + .replaceAll("*", ".*") + .replaceAll("?", ".")}$`, + ); + const sessionRules = ( policy: RulesPolicy, paths: ReadonlyArray, From 139ee4e3e60b2c1b06350e59664615722921f7d0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 13:37:21 +0000 Subject: [PATCH 05/10] fix(opencode): match subagent rule actions without case on Windows OpenCode's Wildcard.match ignores case on Windows, so an agent allow like `E* src/** allow` covers edit there; the approval cap must match the same way. Also say plainly that an agent's own path allows skip approval, as they already do for root sessions. Co-Authored-By: Claude Opus 5.5 --- .../src/server/v2/adapter.ts | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index ff27f23cdab87..d498cf6678558 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -73,6 +73,7 @@ import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender"; import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; import { compareSemverVersions } from "@t3tools/shared/semver"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3tools/shared/model"; import { causeErrorTag } from "@t3tools/shared/observability"; @@ -448,8 +449,13 @@ const policyRules = (policy: RulesPolicy): ReadonlyArray => ]; // A child session inherits its parent's rules, which outrank agent rules; repeat the agent's own -// restrictions after them. Its later allows and asks never loosen T3's policy. -const agentLimits = (policy: RulesPolicy, agentRules: ReadonlyArray): ReadonlyArray => { +// restrictions after them. T3's approval asks still cover its later allows, except its own +// path allows, which skip approval as they do for root sessions. +const agentLimits = ( + policy: RulesPolicy, + agentRules: ReadonlyArray, + caseless: boolean, +): ReadonlyArray => { const start = agentRules.findIndex((entry) => entry.effect === "deny"); if (start === -1) return []; const caps = policyRules(policy).filter((own) => own.effect !== "allow"); @@ -463,19 +469,20 @@ const agentLimits = (policy: RulesPolicy, agentRules: ReadonlyArray): Read : [ entry, ...caps - .filter((own) => actionPattern(entry.action).test(own.action)) + .filter((own) => actionPattern(entry.action, caseless).test(own.action)) .map((own) => ({ ...own, resource: entry.resource })), ], ); }; -// OpenCode matches rule actions as globs: `*` is any run, `?` one character. -const actionPattern = (pattern: string) => +// Mirrors OpenCode's Wildcard.match: `*` is any run, `?` one character, no case on Windows. +const actionPattern = (pattern: string, caseless: boolean) => new RegExp( `^${pattern .replaceAll(/[.+^${}()|[\]\\]/g, "\\$&") .replaceAll("*", ".*") .replaceAll("?", ".")}$`, + caseless ? "si" : "s", ); const sessionRules = ( @@ -833,6 +840,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const server = yield* OpenCode2Server.OpenCode2Server; const idAllocator = yield* IdAllocator.IdAllocatorV2; const host = yield* ProviderHost.ProviderHost; + const caseless = (yield* HostProcess.Platform) === "win32"; const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const fileSystem = yield* FileSystem.FileSystem; const paths = yield* Path.Path; @@ -4059,7 +4067,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const limits = thread.subagent === undefined ? [] - : agentLimits(policy, (yield* agentsIn(thread.directory)).get(thread.agent) ?? []); + : agentLimits( + policy, + (yield* agentsIn(thread.directory)).get(thread.agent) ?? [], + caseless, + ); return sessionRules( policy, paths, From 9edaaa414917b932693749bf8f70c07f2d57db4b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 13:44:12 +0000 Subject: [PATCH 06/10] fix(opencode): keep a subagent's rules while its agent's rules cannot be read A rules refresh for a subagent while agent.list failed wrote T3's policy without the agent's own denies. Leave the child's rules as they are and retry on the next refresh instead. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 26 ++++++++++++++++--- .../src/server/v2/adapter.ts | 10 ++++--- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index bbb864b304aa7..3813faf5d6a72 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -2005,7 +2005,27 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ); // regression: #21979 a failed background subagent pinned its thread as busy - it.effect("settles the background call a foreground call joined to a failed child", () => + it.effect.each([ + { + name: "", + rules: [ + ...listAgents, + out("session.update", { sessionID: CHILD, permissions: "" }), + reply("session.update", null), + ], + }, + { + // Rewriting without the agent's rules would drop its own denies. + name: " while its agent's rules cannot be read", + rules: [ + out("agent.list", ""), + reply("agent.list", { + status: 502, + body: { _tag: "UnknownError", message: "bad gateway" }, + }), + ], + }, + ])("settles the background call a foreground call joined to a failed child$name", ({ rules }) => Effect.gen(function* () { const again = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-again" }; const { runtime, thread } = yield* resumed([ @@ -2024,9 +2044,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...again, metadata: { sessionID: CHILD, status: "running" }, }), - ...listAgents, - out("session.update", { sessionID: CHILD, permissions: "" }), - reply("session.update", null), + ...rules, // The child fails while the joined call is still the foreground one. event("session.execution.failed", { sessionID: CHILD, diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index d498cf6678558..bd697bd50d2a2 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4029,7 +4029,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ), Effect.option, ); - if (listed._tag === "None") return new Map>(); + if (listed._tag === "None") return undefined; known = new Map(listed.value.data.map((agent) => [agent.id, agent.permissions])); agentRules.set(directory, known); } @@ -4039,7 +4039,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr directory: string, agents: ReadonlyArray, ) { - const known = yield* agentsIn(directory); + const known = (yield* agentsIn(directory)) ?? new Map>(); const paths = new Map(); for (const agent of agents) { for (const entry of agentPaths(known.get(agent) ?? [])) { @@ -4050,7 +4050,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }); const hasAgentLimits = Effect.fnUntraced(function* (thread: ThreadState) { - const own = (yield* agentsIn(thread.directory)).get(thread.agent) ?? []; + const own = (yield* agentsIn(thread.directory))?.get(thread.agent) ?? []; return own.some((entry) => entry.effect === "deny"); }); @@ -4069,7 +4069,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ? [] : agentLimits( policy, - (yield* agentsIn(thread.directory)).get(thread.agent) ?? [], + (yield* agentsIn(thread.directory))?.get(thread.agent) ?? [], caseless, ); return sessionRules( @@ -4082,6 +4082,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }); const writeRules = Effect.fnUntraced(function* (state: ThreadState, policy: RulesPolicy) { + // Without its agent's rules a subagent would lose its own denies; keep its rules for a retry. + if (state.subagent !== undefined && (yield* agentsIn(state.directory)) === undefined) return; const rules = yield* rulesFor(state, policy, rootOf(state).providerThread.appThreadId); if (!sameRules(state.rules, rules)) { yield* client.session.update({ From 17f7b7cbb9880d180d6f9f1e3380b14645217f7d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 14:00:12 +0000 Subject: [PATCH 07/10] fix(opencode): match subagent rule actions without a backtracking regex Agent config is untrusted, and a glob with many `*` compiled to `.*` runs backtracked polynomially on T3's event loop. Match by resuming from the last `*` instead, bounded by pattern length times action length, with the same results. Co-Authored-By: Claude Opus 5.5 --- .../src/server/v2/adapter.ts | 36 ++++++++++++++----- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index bd697bd50d2a2..121f7a9ff2abd 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -469,21 +469,39 @@ const agentLimits = ( : [ entry, ...caps - .filter((own) => actionPattern(entry.action, caseless).test(own.action)) + .filter((own) => actionMatches(entry.action, own.action, caseless)) .map((own) => ({ ...own, resource: entry.resource })), ], ); }; // Mirrors OpenCode's Wildcard.match: `*` is any run, `?` one character, no case on Windows. -const actionPattern = (pattern: string, caseless: boolean) => - new RegExp( - `^${pattern - .replaceAll(/[.+^${}()|[\]\\]/g, "\\$&") - .replaceAll("*", ".*") - .replaceAll("?", ".")}$`, - caseless ? "si" : "s", - ); +// Agent config is untrusted; a backtracking RegExp stalls the event loop on runs of `*`, while +// resuming only from the last `*` keeps this within pattern length times action length. +const actionMatches = (pattern: string, action: string, caseless: boolean) => { + const glob = caseless ? pattern.toLowerCase() : pattern; + const name = caseless ? action.toLowerCase() : action; + let at = 0; + let of = 0; + let star = -1; + let resume = 0; + while (of < name.length) { + if (glob[at] === "?" || (glob[at] !== "*" && glob[at] === name[of])) { + at += 1; + of += 1; + } else if (glob[at] === "*") { + star = at; + at += 1; + resume = of; + } else if (star !== -1) { + at = star + 1; + resume += 1; + of = resume; + } else return false; + } + while (glob[at] === "*") at += 1; + return at === glob.length; +}; const sessionRules = ( policy: RulesPolicy, From 6b99e0f90645b3990d2d52d9ca5b123de1469765 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 14:09:39 +0000 Subject: [PATCH 08/10] fix(opencode): treat a trailing ` *` in a subagent rule action as optional OpenCode's Wildcard.match lets `shell *` cover bare `shell`, so such an agent allow escaped T3's Supervised shell ask. Match it the same way, once, as OpenCode does. Co-Authored-By: Claude Opus 5.5 --- .../orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts | 3 +++ packages/provider-opencode/src/server/v2/adapter.ts | 9 +++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 3813faf5d6a72..fadc440f0648b 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -295,6 +295,7 @@ const agentList = { { action: "*", resource: "*", effect: "allow" }, { action: "*", resource: "*", effect: "deny" }, { action: "e*", resource: "src/**", effect: "allow" }, + { action: "shell *", resource: "*", effect: "allow" }, ], }, ], @@ -1582,6 +1583,8 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { { action: "e*", resource: "src/**", effect: "allow" }, { action: "edit", resource: "src/**", effect: "ask" }, { action: "external_directory", resource: "src/**", effect: "ask" }, + { action: "shell *", resource: "*", effect: "allow" }, + { action: "shell", resource: "*", effect: "ask" }, ...mcpRules, ], }), diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 121f7a9ff2abd..dd48ce75ba510 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -475,10 +475,15 @@ const agentLimits = ( ); }; -// Mirrors OpenCode's Wildcard.match: `*` is any run, `?` one character, no case on Windows. +// Mirrors OpenCode's Wildcard.match: `*` is any run, `?` one character, a trailing ` *` is +// optional, no case on Windows. // Agent config is untrusted; a backtracking RegExp stalls the event loop on runs of `*`, while // resuming only from the last `*` keeps this within pattern length times action length. -const actionMatches = (pattern: string, action: string, caseless: boolean) => { +const actionMatches = (pattern: string, action: string, caseless: boolean) => + globMatches(pattern, action, caseless) || + (pattern.endsWith(" *") && globMatches(pattern.slice(0, -2), action, caseless)); + +const globMatches = (pattern: string, action: string, caseless: boolean) => { const glob = caseless ? pattern.toLowerCase() : pattern; const name = caseless ? action.toLowerCase() : action; let at = 0; From 984f11c0fa06da0486022eddac9424953047c093 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 14:14:35 +0000 Subject: [PATCH 09/10] fix(opencode): list agents again after OpenCode reconnects A restarted OpenCode server may have reloaded agent config, so cached agent rules could miss a subagent's new denies. Clear them on reconnect. Co-Authored-By: Claude Opus 5.5 --- packages/provider-opencode/src/server/v2/adapter.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index dd48ce75ba510..d3cacca6ec984 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -907,6 +907,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const sessionScope = yield* Effect.scope; // Project config changes model limits; key by directory because this runtime serves all instance threads. const contextWindows = new Map>(); + const agentRules = new Map>>(); const modelVariants = new Map>>(); const directoryOf = (cwd: string | null | undefined) => cwd ?? host.paths.cwd; const windowOf = (cwd: string | null | undefined, model: string) => @@ -3853,6 +3854,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }; currentScope = scope; yield* Scope.close(previous, Exit.void); + // A restarted server may have reloaded agent config; list agents again. + agentRules.clear(); // A restarted server forgot T3's MCP servers; the next turn adds them again. // The gap may have started a pending prompt unseen, so none may set a later wake's boundary. for (const state of threads.values()) { @@ -4033,7 +4036,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr contextWindows.has(directoryOf(cwd)) ? Effect.void : readModels(directoryOf(cwd)); yield* readModels(session.cwd); - const agentRules = new Map>>(); const agentsIn = Effect.fnUntraced(function* (directory: string) { let known = agentRules.get(directory); if (known === undefined) { From 44bd8235b7dd2208b37a99cf7979d804a8194bec Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 14:21:13 +0000 Subject: [PATCH 10/10] fix(opencode): always apply the chosen policy to a subagent Skipping a subagent's rules write while agent.list failed could leave a running child on Full access after a switch to Supervised. Always write the policy; when listing fails, use the last listing of that directory, which now survives reconnects. Co-Authored-By: Claude Opus 5.5 --- .../orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts | 4 +++- packages/provider-opencode/src/server/v2/adapter.ts | 7 ++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index fadc440f0648b..d2145b70293fa 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -2018,7 +2018,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ], }, { - // Rewriting without the agent's rules would drop its own denies. + // The chosen policy still applies when OpenCode cannot list the subagent's agent. name: " while its agent's rules cannot be read", rules: [ out("agent.list", ""), @@ -2026,6 +2026,8 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { status: 502, body: { _tag: "UnknownError", message: "bad gateway" }, }), + out("session.update", { sessionID: CHILD, permissions: t3Rules }), + reply("session.update", null), ], }, ])("settles the background call a foreground call joined to a failed child$name", ({ rules }) => diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index d3cacca6ec984..d6b4b0726842e 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -908,6 +908,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr // Project config changes model limits; key by directory because this runtime serves all instance threads. const contextWindows = new Map>(); const agentRules = new Map>>(); + // The last listing per directory, kept across reconnects for when a new listing fails. + const lastAgentRules = new Map>>(); const modelVariants = new Map>>(); const directoryOf = (cwd: string | null | undefined) => cwd ?? host.paths.cwd; const windowOf = (cwd: string | null | undefined, model: string) => @@ -4054,9 +4056,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ), Effect.option, ); - if (listed._tag === "None") return undefined; + if (listed._tag === "None") return lastAgentRules.get(directory); known = new Map(listed.value.data.map((agent) => [agent.id, agent.permissions])); agentRules.set(directory, known); + lastAgentRules.set(directory, known); } return known; }); @@ -4107,8 +4110,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }); const writeRules = Effect.fnUntraced(function* (state: ThreadState, policy: RulesPolicy) { - // Without its agent's rules a subagent would lose its own denies; keep its rules for a retry. - if (state.subagent !== undefined && (yield* agentsIn(state.directory)) === undefined) return; const rules = yield* rulesFor(state, policy, rootOf(state).providerThread.appThreadId); if (!sameRules(state.rules, rules)) { yield* client.session.update({