diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index cd1bdc9044a5..d2145b70293f 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -284,8 +284,23 @@ 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" }, + { action: "shell *", resource: "*", effect: "allow" }, + ], + }, ], }; +const listAgents = [out("agent.list", ""), reply("agent.list", agentList)]; const supervisedRules = [ { action: "shell", resource: "*", effect: "ask" }, { action: "edit", resource: "*", effect: "ask" }, @@ -893,7 +908,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 +925,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" }, @@ -1504,6 +1522,93 @@ 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 { runtime, thread } = yield* resumed([ + ...backgroundLaunch(CHILD, { + ...childCreated(CHILD), + agent: "review", + permissions: t3Rules, + }), + 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("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" }, + { action: "shell *", resource: "*", effect: "allow" }, + { action: "shell", resource: "*", 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([ @@ -1696,6 +1801,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), ] @@ -1902,7 +2008,29 @@ 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), + ], + }, + { + // 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", ""), + reply("agent.list", { + 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 }) => Effect.gen(function* () { const again = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-again" }; const { runtime, thread } = yield* resumed([ @@ -1921,8 +2049,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...again, metadata: { sessionID: CHILD, status: "running" }, }), - 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, @@ -2326,6 +2453,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" }], @@ -2712,6 +2840,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/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 4204f275fd8d..53d22562c4a9 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 0072f9d1897b..d6b4b0726842 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"; @@ -438,19 +439,84 @@ 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. 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"); + return agentRules + .slice(start) + .flatMap((entry) => + entry.effect === "deny" + ? [entry] + : policy.runtimeMode === "full-access" + ? [{ ...entry, effect: "allow" as const }] + : [ + entry, + ...caps + .filter((own) => actionMatches(entry.action, own.action, caseless)) + .map((own) => ({ ...own, resource: entry.resource })), + ], + ); +}; + +// 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) => + 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; + 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, 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")] : []), @@ -797,6 +863,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; @@ -840,6 +907,9 @@ 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>>(); + // 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) => @@ -2117,8 +2187,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 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, 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 }), @@ -3782,6 +3856,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()) { @@ -3962,11 +4038,7 @@ 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 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,23 +4056,34 @@ 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 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; + }); + const pathsFor = Effect.fnUntraced(function* ( + directory: string, + agents: ReadonlyArray, + ) { + const known = (yield* agentsIn(directory)) ?? new Map>(); 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); } } 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, + thread: Pick, policy: RulesPolicy, appThreadId: string | null, ) { @@ -4009,11 +4092,20 @@ 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) ?? [], + caseless, + ); return sessionRules( policy, paths, policy.runtimeMode === "full-access" ? [] : thread.grants, appThreadId === null ? null : yield* mcpServerNameFor(appThreadId), + limits, ); }); @@ -4698,7 +4790,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, );