From c53d620db2f33cf54dd3a50ff036b552311bbaac Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 15:00:00 +0000 Subject: [PATCH 1/8] test(server): OpenCode subagents keep their own agent denies (#38100) Fails on main: T3 writes its mode rules onto an OpenCode 2 subagent session without the subagent's agent denies, so an agent with edit: deny can write. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index cd1bdc9044a5..ff57e423470b 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -1527,6 +1527,90 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + // regression: #38100 a subagent's own agent denies were overridden by T3's session rules + it.effect.each(["full-access", "approval-required"] as const)( + "keeps a subagent's own agent denies in the rules T3 writes to it (%s)", + (mode) => + Effect.gen(function* () { + const editDeny = { action: "edit", resource: "*", effect: "deny" }; + const agents = { + ...agentList, + data: [ + ...agentList.data, + { + id: "review", + name: "Review", + request: { settings: {}, headers: {}, body: {} }, + description: "Reviews changes", + mode: "subagent", + hidden: false, + permissions: [{ action: "*", resource: "*", effect: "allow" }, editDeny], + }, + ], + }; + const launch = backgroundLaunch(CHILD).map((entry) => + entry.type === "emit_inbound" && + (entry.frame as { event?: { type?: string } }).event?.type === "session.created" + ? event("session.created", { ...childCreated(CHILD), agent: "review" }) + : entry, + ); + const supervised = mode === "approval-required"; + const { runtime, thread } = yield* resumed([ + ...launch, + event("session.execution.succeeded", { sessionID: SESSION }), + out("agent.list", ""), + reply("agent.list", agents), + ...(supervised + ? [ + out("session.update", { sessionID: SESSION, permissions: supervisedRules }), + reply("session.update", null), + ] + : []), + out("session.update", { + sessionID: CHILD, + permissions: [ + ...(supervised ? supervisedRules.slice(0, 3) : t3Rules.slice(0, 1)), + editDeny, + ...mcpRules, + ], + }), + reply("session.update", null), + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.succeeded", { sessionID: SESSION }), + ]); + const firstEnded = yield* Deferred.make(); + const ended = yield* runtime.events.pipe( + Stream.filter( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "turn.terminal" } + > => event.type === "turn.terminal", + ), + Stream.tap(() => Deferred.succeed(firstEnded, undefined)), + Stream.take(2), + Stream.runCollect, + Effect.forkScoped, + ); + yield* runtime.startTurn(withLineage(thread)); + yield* Deferred.await(firstEnded); + yield* runtime.startTurn({ + ...withLineage(thread), + runId: RunId.make("run:opencode2-adapter:2"), + runOrdinal: 2, + providerTurnOrdinal: 2, + attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"), + runtimePolicy: policy(mode), + }); + assert.deepEqual( + [...(yield* Fiber.join(ended))].map((terminal) => terminal.status), + ["completed", "completed"], + ); + }), + ); + it.effect("gives a background subagent the rules of a mode changed while it runs", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ From 93aa080f5ac618da08a7356fd5c5e05c9f10551b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 15:33:27 +0000 Subject: [PATCH 2/8] fix(opencode): subagents launched from T3 Code keep their agent's denies OpenCode 2 copies the parent session's rules into each child session it creates and applies them after the child agent's own rules, so T3's mode rules (`* allow` in Full access, `edit: ask` when supervised) overrode a subagent's denies. Rewriting the child's rules afterwards is too late: OpenCode prompts the child without waiting for T3. T3's sessions now ask before each subagent launch. T3 answers that request itself, and before it approves it sets the parent's rules to ask for everything, so the child is created asking for everything too. Until the child's own rules are written, T3 answers each of its requests from the agent's rules plus the thread's mode. The rules T3 then writes to a subagent session carry the agent's rules from its first deny on, in every mode, and the parent goes back to its normal rules. Fixes pingdotgg/t3code#38100 Co-Authored-By: Claude Fable 5.2 --- .../Adapters/OpenCode2AdapterV2.test.ts | 136 ++++++++- .../src/server/v2/adapter.ts | 287 +++++++++++++++--- packages/provider-opencode/src/testing.ts | 2 +- 3 files changed, 376 insertions(+), 49 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index ff57e423470b..cd59514b3e2b 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -50,6 +50,7 @@ import { OPENCODE_2_STILL_STOPPING, OPENCODE_PROVIDER, t3McpServerName, + wildcardMatch, } from "@t3tools/provider-opencode/testing"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { openCode2ReplayRuntime } from "./OpenCode2AdapterV2.testkit.ts"; @@ -98,7 +99,8 @@ const mcpRules = [ { action: "t3-code-*", resource: "*", effect: "deny" }, { action: "t3-code-thread_opencode2-adapter_*", resource: "*", effect: "allow" }, ]; -const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, ...mcpRules]; +const launchGate = { action: "subagent", resource: "*", effect: "ask" }; +const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, launchGate, ...mcpRules]; const TITLE = "Prime check"; const sessionInfo = (overrides: Record = {}) => ({ id: SESSION, @@ -284,13 +286,28 @@ const agentList = { hidden: false, permissions: [{ action: "*", resource: "*", effect: "allow" }, ...buildPaths], }, + { + id: "general", + name: "General", + request: { settings: {}, headers: {}, body: {} }, + description: "A general subagent.", + mode: "subagent", + hidden: false, + permissions: [{ action: "*", resource: "*", effect: "allow" }], + }, ], }; +// A subagent's rules carry its agent's denies, so writing them reads the agents once per directory. +const listsAgents: ReadonlyArray = [ + out("agent.list", ""), + reply("agent.list", agentList), +]; const supervisedRules = [ { action: "shell", resource: "*", effect: "ask" }, { action: "edit", resource: "*", effect: "ask" }, { action: "external_directory", resource: "*", effect: "ask" }, ...buildPaths, + launchGate, ...mcpRules, ]; @@ -1611,6 +1628,106 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect("holds a subagent to its agent's denies from the moment OpenCode creates it", () => + Effect.gen(function* () { + const editDeny = { action: "edit", resource: "*", effect: "deny" }; + const askAll = { action: "*", resource: "*", effect: "ask" }; + const window = [t3Rules[0], askAll, ...mcpRules]; + const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-review" }; + const asked = (sessionID: string, id: string, action: string, resource: string) => + event("permission.asked", { + id, + sessionID, + action, + resources: [resource], + save: [resource], + source: { type: "tool", messageID: "msg_assistant", id: tool.id }, + }); + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.started", { sessionID: SESSION }), + event("session.tool.input.started", { ...tool, name: "subagent" }), + event("session.tool.called", { + ...tool, + name: "subagent", + input: { agent: "review", description: "Review", prompt: "write t.txt" }, + executed: false, + }), + // OpenCode asks before it creates the child, which copies the parent's rules as they are then. + asked(SESSION, "per_launch", "subagent", "review"), + out("agent.list", ""), + reply("agent.list", { + ...agentList, + data: [ + ...agentList.data, + { + ...agentList.data[1], + id: "review", + permissions: [{ action: "*", resource: "*", effect: "allow" }, editDeny], + }, + ], + }), + out("session.update", { sessionID: SESSION, permissions: window }), + reply("session.update", null), + out("permission.reply", { sessionID: SESSION, requestID: "per_launch", decision: "once" }), + reply("permission.reply", null), + event("session.created", { + ...childCreated(CHILD), + agent: "review", + permissions: window, + }), + // The child's first step runs before T3 can write its rules; its agent's deny still holds. + asked(CHILD, "per_edit", "edit", "t.txt"), + out("permission.reply", { + sessionID: CHILD, + requestID: "per_edit", + decision: "reject", + message: "The review agent's permissions do not allow edit here.", + }), + reply("permission.reply", null), + asked(CHILD, "per_read", "read", "t.txt"), + out("permission.reply", { sessionID: CHILD, requestID: "per_read", decision: "once" }), + reply("permission.reply", null), + event("session.tool.progress", { + ...tool, + metadata: { sessionID: CHILD, status: "running" }, + }), + out("session.update", { + sessionID: CHILD, + permissions: [t3Rules[0], editDeny, ...mcpRules], + }), + reply("session.update", null), + out("session.update", { sessionID: SESSION, permissions: t3Rules }), + reply("session.update", null), + event("session.execution.succeeded", { sessionID: SESSION }), + ]); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.startTurn(withLineage(thread)); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + }), + ); + + it("matches rule patterns the way OpenCode does", () => { + for (const [value, pattern, matches] of [ + ["edit", "*", true], + ["edit", "edit", true], + ["edit", "edi", false], + ["t3-code-thread_x_read", "t3-code-*", true], + ["src/a.ts", "src/*.ts", true], + ["src/a.tsx", "src/*.ts", false], + ["a.ts", "?.ts", true], + ["git status", "git *", true], + ["git", "git *", true], + ["github", "git *", false], + ["a(b).ts", "a(b).ts", true], + ["C:\\work\\a.ts", "C:/work/*", true], + ["a".repeat(2000), `${"*a".repeat(1000)}b`, false], + ] as const) { + assert.equal(wildcardMatch(value, pattern), matches, `${value} ~ ${pattern}`); + } + }); + it.effect("gives a background subagent the rules of a mode changed while it runs", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ @@ -1780,6 +1897,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { // The adapter writes a child's rules only when they changed. ...(writesRules ? [ + ...listsAgents, out("session.update", { sessionID: CHILD, permissions: "" }), reply("session.update", null), ] @@ -2005,6 +2123,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...again, metadata: { sessionID: CHILD, status: "running" }, }), + ...listsAgents, out("session.update", { sessionID: CHILD, permissions: "" }), reply("session.update", null), // The child fails while the joined call is still the foreground one. @@ -2410,6 +2529,13 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...toolOf(SESSION, "call-other"), metadata: { sessionID: OTHER, status: "running" }, }), + // A session called as a subagent stops asking before launches of its own. + ...listsAgents, + out("session.update", { + sessionID: OTHER, + permissions: t3Rules.filter((entry) => entry !== launchGate), + }), + reply("session.update", null), event("session.tool.success", { ...toolOf(SESSION, "call-other"), content: [{ type: "text", text: "OTHER_OK" }], @@ -2796,7 +2922,11 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { [ ...backgroundLaunch(CHILD), event("session.execution.succeeded", { sessionID: SESSION }), - out("session.update", { sessionID: CHILD, permissions: t3Rules }), + ...listsAgents, + out("session.update", { + sessionID: CHILD, + permissions: t3Rules.filter((entry) => entry !== launchGate), + }), reply("session.update", null), out("session.prompt", { sessionID: SESSION, text: "" }), reply("session.prompt", { @@ -5340,6 +5470,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { sessionInfo({ permissions: [ { action: "*", resource: "*", effect: "allow" }, + launchGate, { action: "t3-code-*", resource: "*", effect: "deny" }, { action: `${server}_*`, resource: "*", effect: "allow" }, ], @@ -6932,6 +7063,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { sessionID: FORK, permissions: [ { action: "*", resource: "*", effect: "allow" }, + launchGate, { action: "t3-code-*", resource: "*", effect: "deny" }, { action: "t3-code-thread_opencode2-adapter_fork_*", resource: "*", effect: "allow" }, ], diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 0072f9d1897b..1c2bb52ef3b8 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"; @@ -356,6 +357,10 @@ interface ThreadState { rules: ReadonlyArray | undefined; policy: RulesPolicy; readonly grants: Array; + /** Subagent calls T3 let through whose child is not attached yet; while any is, the session's rules ask for everything. */ + readonly launching: Set; + /** Ran under a launch window (a parent this turn, a child since birth): requests it raised can arrive after it closed. */ + windowed: boolean; readonly calls: Map; subagent: | { @@ -412,6 +417,7 @@ interface PendingRequest { readonly action: string; readonly resources: ReadonlyArray; readonly save: ReadonlyArray; + readonly toolId: string | undefined; } | { readonly type: "form"; readonly id: string; readonly form: NativeForm }; } @@ -438,11 +444,70 @@ const mcpRules = (mcpServerName: string | null): ReadonlyArray => { action: `${mcpServerName}_*`, resource: "*", effect: "allow" }, ]; +const globMatch = (input: string, pattern: string) => { + let at = 0; + let next = 0; + let star = -1; + let resume = 0; + while (at < input.length) { + if (pattern[next] === "*") { + star = next++; + resume = at; + } else if (next < pattern.length && (pattern[next] === "?" || pattern[next] === input[at])) { + at++; + next++; + } else if (star >= 0) { + next = star + 1; + at = ++resume; + } else { + return false; + } + } + while (pattern[next] === "*") next++; + return next === pattern.length; +}; + +// OpenCode's Wildcard.match without a regex: `*` is any text, `?` one character, a trailing ` *` is optional. +export const wildcardMatch = (value: string, glob: string, windows = false): boolean => { + const fold = (text: string) => { + const slashed = text.replaceAll("\\", "/"); + return windows ? slashed.toLowerCase() : slashed; + }; + const input = fold(value); + const pattern = fold(glob); + return ( + globMatch(input, pattern) || (pattern.endsWith(" *") && globMatch(input, pattern.slice(0, -2))) + ); +}; + +// OpenCode's Permission.evaluate: the last matching rule decides, and no match asks. +const effectOf = ( + action: string, + resource: string, + rules: ReadonlyArray, + windows: boolean, +): Rule["effect"] => + rules.findLast( + (entry) => + wildcardMatch(action, entry.action, windows) && + wildcardMatch(resource, entry.resource, windows), + )?.effect ?? "ask"; + +const SUBAGENT = "subagent"; +// OpenCode copies a parent's session rules into the child it creates and applies them after the +// child agent's own, so a parent asks T3 before each launch and asks for everything while it runs. +const LAUNCH_GATE = rule(SUBAGENT, "ask"); +const LAUNCH_WINDOW = rule("*", "ask"); +const isLaunchWindow = (entry: Rule) => + entry.action === "*" && entry.resource === "*" && entry.effect === "ask"; + const sessionRules = ( policy: RulesPolicy, paths: ReadonlyArray, grants: ReadonlyArray, mcpServerName: string | null, + own: ReadonlyArray = [], + launch?: Rule, ): ReadonlyArray => [ ...(policy.runtimeMode === "full-access" ? [rule("*", "allow")] @@ -455,6 +520,8 @@ const sessionRules = ( // Plan edits are re-allowed only for plan paths; free-tier sessions refuse denied shell/read. ...(policy.interactionMode === "plan" ? [rule("edit", "deny")] : []), ...paths, + ...own, + ...(launch === undefined ? [] : [launch]), ...mcpRules(mcpServerName), ]; @@ -547,6 +614,21 @@ const agentPaths = (rules: ReadonlyArray) => (entry.action === "edit" || entry.action === "external_directory"), ); +/** A subagent's rules from its first deny on: its denies outrank T3's mode, and what it re-allows after them follows the mode. */ +const agentDenies = (rules: ReadonlyArray, policy: RulesPolicy): ReadonlyArray => { + const first = rules.findIndex((entry) => entry.effect === "deny"); + if (first < 0) return []; + const mode = sessionRules(policy, [], [], null); + return rules.slice(first).map((entry) => { + if (entry.effect === "deny" || agentPaths([entry]).length > 0) return entry; + const effects = mode + .filter((moded) => moded.action === "*" || wildcardMatch(moded.action, entry.action)) + .map((moded) => moded.effect); + const effect = (["deny", "ask", "allow"] as const).find((kind) => effects.includes(kind)); + return effect === undefined ? entry : { ...entry, effect }; + }); +}; + const ref = (nativeId: string, strength: "strong" | "weak" = "strong") => ({ driver: OPENCODE_PROVIDER, nativeId, @@ -915,6 +997,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr rules: undefined, policy: input.runtimePolicy, grants: [], + launching: new Set(), + windowed: false, calls: new Map(), subagent, wakes: [], @@ -2117,13 +2201,15 @@ 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 child sessions may retain old mode rules, and a new one is born asking for everything. + if (child.rules?.some(isLaunchWindow) === true) child.windowed = true; + if (info === undefined || child.windowed) { yield* writeRules(child, rootOf(call.state).policy).pipe( Effect.timeout(REQUEST_REPLY_TIMEOUT), Effect.ignore({ log: true }), ); } + yield* closeLaunch(call.state, call.toolId); }); const settleCall: ( @@ -2132,6 +2218,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr result?: string, ) => Effect.Effect = Effect.fnUntraced(function* (call, status, result) { if (!isOrchestrationV2WorkActive(call.status)) return; + yield* closeLaunch(call.state, call.toolId); call.status = status; call.completedAt = yield* DateTime.now; if (result !== undefined) call.result = result; @@ -2620,13 +2707,21 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }); const onPermissionAsked = Effect.fnUntraced(function* (data: Permission.Request) { + if (yield* settleLaunchAsk(data)) return; const turn = threads.get(data.sessionID)?.active; const toolName = data.source === undefined ? undefined : turn?.tools.get(data.source.id)?.name; const save = data.save ?? []; yield* showRequest( data.sessionID, - { type: "permission", id: data.id, action: data.action, resources: data.resources, save }, + { + type: "permission", + id: data.id, + action: data.action, + resources: data.resources, + save, + toolId: data.source?.id, + }, { type: "approval_request", requestKind: openCodePermissionRequestKind(data.action, toolName), @@ -3962,63 +4057,82 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr contextWindows.has(directoryOf(cwd)) ? Effect.void : readModels(directoryOf(cwd)); yield* readModels(session.cwd); + const windows = (yield* HostProcess.Platform) === "win32"; const agentRules = new Map>>(); - const pathsFor = Effect.fnUntraced(function* ( - directory: string, - agents: ReadonlyArray, - ) { - let known = agentRules.get(directory); - if (known === undefined) { - // A fresh server lists no agents for its first moments, like its models. - const listed = yield* client.agent.list({ location: { directory } }).pipe( - Effect.repeat({ - until: (list) => list.data.length > 0, - schedule: Schedule.spaced("250 millis"), - }), - Effect.timeout("5 seconds"), - Effect.tapCause((cause) => - Effect.logWarning( - "Could not list OpenCode agents; their path rules are skipped.", - cause, - ).pipe(Effect.annotateLogs({ errorTag: causeErrorTag(cause) })), + const agentsIn = Effect.fnUntraced(function* (directory: string, subagent?: string) { + const known = agentRules.get(directory); + // A subagent the cached list lacks was added since; its denies must not be skipped. + if (known !== undefined && (subagent === undefined || known.has(subagent))) return known; + // A fresh server lists no agents for its first moments, like its models. + const listed = yield* client.agent.list({ location: { directory } }).pipe( + Effect.repeat({ + until: (list) => list.data.length > 0, + schedule: Schedule.spaced("250 millis"), + }), + Effect.timeout("5 seconds"), + Effect.tapCause((cause) => + Effect.logWarning("Could not list OpenCode agents; their rules are skipped.", cause).pipe( + Effect.annotateLogs({ errorTag: causeErrorTag(cause) }), ), - Effect.option, - ); - if (listed._tag === "None") return []; - known = new Map( - listed.value.data.map((agent) => [agent.id, agentPaths(agent.permissions)]), - ); - agentRules.set(directory, known); - } - const paths = new Map(); - for (const agent of agents) { - for (const entry of known.get(agent) ?? []) { - paths.set(`${entry.action}\u0000${entry.resource}`, entry); - } - } - return [...paths.values()]; + ), + Effect.option, + ); + if (listed._tag === "None") return undefined; + const agents = new Map(listed.value.data.map((agent) => [agent.id, agent.permissions])); + agentRules.set(directory, agents); + return agents; }); const rulesFor = Effect.fnUntraced(function* ( - thread: Pick, + thread: Pick & { + readonly child: boolean; + readonly launch?: Rule | undefined; + }, policy: RulesPolicy, appThreadId: string | null, ) { const plan = policy.interactionMode === "plan"; - const paths = - policy.runtimeMode === "full-access" && !plan - ? [] - : yield* pathsFor(thread.directory, plan ? [thread.agent, "plan"] : [thread.agent]); + const full = policy.runtimeMode === "full-access"; + const agents = + full && !plan && !thread.child + ? undefined + : yield* agentsIn(thread.directory, thread.child ? thread.agent : undefined); + // Rules written without a subagent's denies would let it do what its agent forbids. + if (thread.child && agents?.has(thread.agent) !== true) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: OPENCODE_PROVIDER, + detail: "Could not read the OpenCode agents a subagent's rules depend on", + }); + } + const paths = new Map(); + for (const agent of plan ? [thread.agent, "plan"] : full ? [] : [thread.agent]) { + for (const entry of agentPaths(agents?.get(agent) ?? [])) { + paths.set(`${entry.action}\u0000${entry.resource}`, entry); + } + } return sessionRules( policy, - paths, - policy.runtimeMode === "full-access" ? [] : thread.grants, + [...paths.values()], + full ? [] : thread.grants, appThreadId === null ? null : yield* mcpServerNameFor(appThreadId), + thread.child ? agentDenies(agents?.get(thread.agent) ?? [], policy) : [], + thread.launch, ); }); const writeRules = Effect.fnUntraced(function* (state: ThreadState, policy: RulesPolicy) { - const rules = yield* rulesFor(state, policy, rootOf(state).providerThread.appThreadId); + const child = state.subagent !== undefined; + const rules = yield* rulesFor( + { + directory: state.directory, + agent: state.agent, + grants: state.grants, + child, + launch: child ? undefined : state.launching.size > 0 ? LAUNCH_WINDOW : LAUNCH_GATE, + }, + policy, + rootOf(state).providerThread.appThreadId, + ); if (!sameRules(state.rules, rules)) { yield* client.session.update({ sessionID: Session.ID.make(state.sessionId), @@ -4029,6 +4143,77 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr state.policy = policy; }); + const openLaunch = (state: ThreadState, key: string) => { + state.launching.add(key); + state.windowed = true; + return writeRules(state, state.policy).pipe( + Effect.timeout(REQUEST_REPLY_TIMEOUT), + Effect.as(true), + Effect.catchCause((cause) => + Effect.logWarning("Could not prepare an OpenCode session for a subagent.", cause).pipe( + Effect.map(() => { + state.launching.delete(key); + return false; + }), + ), + ), + ); + }; + + const closeLaunch = (state: ThreadState, key: string) => + state.launching.delete(key) && state.launching.size === 0 + ? writeRules(state, state.policy).pipe( + Effect.timeout(REQUEST_REPLY_TIMEOUT), + Effect.ignore({ log: true }), + ) + : Effect.void; + + /** Answers what a launch gate or window made OpenCode ask, as the asking session's own rules decide it. */ + const settleLaunchAsk = Effect.fnUntraced(function* (data: Permission.Request) { + const state = threads.get(data.sessionID); + const born = announced.get(data.sessionID); + const owner = ownerOf(data.sessionID); + if (owner === undefined) return false; + const root = rootOf(owner); + const gated = data.action === SUBAGENT && state === root; + const windowed = + state?.windowed === true || (state?.rules ?? born?.permissions)?.some(isLaunchWindow); + if (!gated && windowed !== true) return false; + const directory = state?.directory ?? owner.directory; + const agent = state?.agent ?? born?.agent ?? "build"; + const own = (yield* agentsIn(directory, state === root ? undefined : agent))?.get(agent); + const session = yield* rulesFor( + { directory, agent, grants: state?.grants ?? [], child: state !== root }, + root.policy, + root.providerThread.appThreadId, + ).pipe(Effect.option); + const effects = + own === undefined || session._tag === "None" + ? ["deny" as const] + : data.resources.map((resource) => + effectOf(data.action, resource, [...own, ...session.value], windows), + ); + if (!effects.includes("deny") && effects.includes("ask")) return false; + const allowed = + !effects.includes("deny") && + (!gated || (yield* openLaunch(root, data.source?.id ?? data.id))); + yield* client.permission + .reply({ + sessionID: Session.ID.make(data.sessionID), + requestID: Permission.ID.make(data.id), + decision: allowed ? "once" : "reject", + ...(allowed + ? {} + : { message: `The ${agent} agent's permissions do not allow ${data.action} here.` }), + }) + .pipe( + Effect.catchTags(permissionGone), + Effect.timeout(REQUEST_REPLY_TIMEOUT), + Effect.ignore({ log: true }), + ); + return true; + }); + const writeTitle = Effect.fnUntraced(function* (state: ThreadState, title: string) { const next = title.trim(); // An empty title asks OpenCode to generate one. @@ -4698,7 +4883,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: [], child: false, launch: LAUNCH_GATE }, policy, threadInput.threadId, ); @@ -4887,6 +5072,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr state.agent = agent; } // Refresh stale mode rules; running subagent updates are best effort because they outlive this turn. + state.launching.clear(); + state.windowed = false; yield* writeRules(state, turnInput.runtimePolicy); yield* writeTitle(state, turnInput.appThread.title).pipe( Effect.timeout(REQUEST_REPLY_TIMEOUT), @@ -5221,6 +5408,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* writeRules(state, rootOf(state).policy).pipe(Effect.ignore({ log: true })); } const sessionID = Session.ID.make(entry.sessionId); + // A subagent launch the user approves still needs its window before OpenCode creates the child. + const approved = + decision !== undefined && + approves(decision) && + (native.type !== "permission" || + native.action !== SUBAGENT || + asker.subagent !== undefined || + (yield* openLaunch(asker, native.toolId ?? native.id))); if (native.type === "permission" && decision === "decline") { yield* client.session .synthetic({ @@ -5237,7 +5432,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr .reply({ sessionID, requestID: Permission.ID.make(native.id), - decision: decision !== undefined && approves(decision) ? "once" : "reject", + decision: approved ? "once" : "reject", ...(decision === "decline" ? { message: DECLINED } : {}), }) .pipe(Effect.catchTags(permissionGone)), diff --git a/packages/provider-opencode/src/testing.ts b/packages/provider-opencode/src/testing.ts index d9d079c708d8..9e3d64e41370 100644 --- a/packages/provider-opencode/src/testing.ts +++ b/packages/provider-opencode/src/testing.ts @@ -3,4 +3,4 @@ export { OPENCODE_PROVIDER, OPENCODE_SDK_PROTOCOL, } from "./server/adapter.ts"; -export { OPENCODE_2_STILL_STOPPING, t3McpServerName } from "./server/v2/adapter.ts"; +export { OPENCODE_2_STILL_STOPPING, t3McpServerName, wildcardMatch } from "./server/v2/adapter.ts"; From 10e87d88fbc821c70b06ac8c52971c489d8f8deb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 15:53:03 +0000 Subject: [PATCH 3/8] fix(opencode): root sessions carry no allow rule for a subagent to inherit The launch gate added earlier asked before each subagent launch, but OpenCode evaluates a project's saved approvals after session rules, so a saved "always allow" for the subagent skipped the ask and the child inherited the root's `* allow` over its agent's deny again. No ask can be made to hold against a saved approval; only a deny can. So the gate is gone and T3 no longer writes an allow to a root session at all. `* allow` is dropped and every other allow (accept-edits, session grants, an agent's path allows) is written as an ask, which leaves a new subagent nothing that outranks its agent's denies. T3 answers each permission request from the rules it enforces: allowed ones are approved, ones the asking agent denies are refused, and the rest go to the user as before. Refs pingdotgg/t3code#38100 Co-Authored-By: Claude Fable 5.2 --- .../Adapters/OpenCode2AdapterV2.test.ts | 86 ++++------ .../src/server/v2/adapter.ts | 154 ++++++------------ 2 files changed, 84 insertions(+), 156 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index cd59514b3e2b..ce6aa3f681bc 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -99,13 +99,14 @@ const mcpRules = [ { action: "t3-code-*", resource: "*", effect: "deny" }, { action: "t3-code-thread_opencode2-adapter_*", resource: "*", effect: "allow" }, ]; -const launchGate = { action: "subagent", resource: "*", effect: "ask" }; -const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, launchGate, ...mcpRules]; +// What full access gives a subagent session; a root session is written no allow for one to inherit. +const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, ...mcpRules]; +const rootRules = mcpRules; const TITLE = "Prime check"; const sessionInfo = (overrides: Record = {}) => ({ id: SESSION, title: TITLE, - permissions: t3Rules, + permissions: rootRules, projectID: "global", model: { id: "big-pickle", providerID: "opencode", variant: "default" }, cost: 0, @@ -306,8 +307,7 @@ const supervisedRules = [ { action: "shell", resource: "*", effect: "ask" }, { action: "edit", resource: "*", effect: "ask" }, { action: "external_directory", resource: "*", effect: "ask" }, - ...buildPaths, - launchGate, + ...buildPaths.map((entry) => ({ ...entry, effect: "ask" })), ...mcpRules, ]; @@ -1628,34 +1628,36 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); - it.effect("holds a subagent to its agent's denies from the moment OpenCode creates it", () => + it.effect("answers a new subagent's requests from its agent's rules before writing any", () => Effect.gen(function* () { const editDeny = { action: "edit", resource: "*", effect: "deny" }; - const askAll = { action: "*", resource: "*", effect: "ask" }; - const window = [t3Rules[0], askAll, ...mcpRules]; const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-review" }; - const asked = (sessionID: string, id: string, action: string, resource: string) => + const asked = (id: string, action: string, sessionID = CHILD) => event("permission.asked", { id, sessionID, action, - resources: [resource], - save: [resource], + resources: ["t.txt"], + save: ["t.txt"], source: { type: "tool", messageID: "msg_assistant", id: tool.id }, }); const { runtime, thread } = yield* resumed([ out("session.prompt", { sessionID: SESSION, text: "" }), promptAccepted, event("session.execution.started", { sessionID: SESSION }), + // Full access is T3's answer to each request, not an allow the root session carries. + asked("per_shell", "shell", SESSION), + out("permission.reply", { sessionID: SESSION, requestID: "per_shell", decision: "once" }), + reply("permission.reply", null), event("session.tool.input.started", { ...tool, name: "subagent" }), - event("session.tool.called", { - ...tool, - name: "subagent", - input: { agent: "review", description: "Review", prompt: "write t.txt" }, - executed: false, + // The child copies the root's rules, which hold no allow to outrank its agent's deny. + event("session.created", { + ...childCreated(CHILD), + agent: "review", + permissions: rootRules, }), - // OpenCode asks before it creates the child, which copies the parent's rules as they are then. - asked(SESSION, "per_launch", "subagent", "review"), + // An ask left in a child's rules by an earlier mode would outrank the deny; T3 still refuses. + asked("per_edit", "edit"), out("agent.list", ""), reply("agent.list", { ...agentList, @@ -1664,21 +1666,10 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { { ...agentList.data[1], id: "review", - permissions: [{ action: "*", resource: "*", effect: "allow" }, editDeny], + permissions: [{ action: "read", resource: "*", effect: "ask" }, editDeny], }, ], }), - out("session.update", { sessionID: SESSION, permissions: window }), - reply("session.update", null), - out("permission.reply", { sessionID: SESSION, requestID: "per_launch", decision: "once" }), - reply("permission.reply", null), - event("session.created", { - ...childCreated(CHILD), - agent: "review", - permissions: window, - }), - // The child's first step runs before T3 can write its rules; its agent's deny still holds. - asked(CHILD, "per_edit", "edit", "t.txt"), out("permission.reply", { sessionID: CHILD, requestID: "per_edit", @@ -1686,20 +1677,10 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { message: "The review agent's permissions do not allow edit here.", }), reply("permission.reply", null), - asked(CHILD, "per_read", "read", "t.txt"), + // Full access answers what the agent only asks about. + asked("per_read", "read"), out("permission.reply", { sessionID: CHILD, requestID: "per_read", decision: "once" }), reply("permission.reply", null), - event("session.tool.progress", { - ...tool, - metadata: { sessionID: CHILD, status: "running" }, - }), - out("session.update", { - sessionID: CHILD, - permissions: [t3Rules[0], editDeny, ...mcpRules], - }), - reply("session.update", null), - out("session.update", { sessionID: SESSION, permissions: t3Rules }), - reply("session.update", null), event("session.execution.succeeded", { sessionID: SESSION }), ]); const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); @@ -2533,7 +2514,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...listsAgents, out("session.update", { sessionID: OTHER, - permissions: t3Rules.filter((entry) => entry !== launchGate), + permissions: t3Rules, }), reply("session.update", null), event("session.tool.success", { @@ -2925,7 +2906,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...listsAgents, out("session.update", { sessionID: CHILD, - permissions: t3Rules.filter((entry) => entry !== launchGate), + permissions: t3Rules, }), reply("session.update", null), out("session.prompt", { sessionID: SESSION, text: "" }), @@ -3067,7 +3048,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ), ...noOpenRequests, - out("session.update", { sessionID: SESSION, permissions: t3Rules }), + out("session.update", { sessionID: SESSION, permissions: rootRules }), reply("session.update", null), ]); yield* runtime.resumeThread({ @@ -3331,7 +3312,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { sessionID: SESSION, permissions: [ ...supervisedRules.slice(0, 3), - { action: "shell", resource: "echo *", effect: "allow" }, + { action: "shell", resource: "echo *", effect: "ask" }, ...supervisedRules.slice(3), ], }), @@ -4299,6 +4280,8 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { reply("session.form.reply", null), ], { + // Full access answers a subagent's requests itself; a supervised thread shows them. + supervised: true, beforeResponse: (path) => path === `/api/session/${CHILD}/form` ? Deferred.succeed(reading, undefined).pipe(Effect.andThen(Deferred.await(resume))) @@ -4326,7 +4309,10 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ), Effect.forkScoped, ); - yield* runtime.startTurn(withLineage(thread)); + yield* runtime.startTurn({ + ...withLineage(thread), + runtimePolicy: policy("approval-required"), + }); yield* Deferred.await(reading); const stopping = yield* runtime .interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId }) @@ -5469,8 +5455,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { "session.get", sessionInfo({ permissions: [ - { action: "*", resource: "*", effect: "allow" }, - launchGate, { action: "t3-code-*", resource: "*", effect: "deny" }, { action: `${server}_*`, resource: "*", effect: "allow" }, ], @@ -6210,7 +6194,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { out("session.create", { location: { directory: custom }, model: { providerID: "opencode", id: "big-pickle" }, - permissions: t3Rules, + permissions: rootRules, }), replyData("session.create", sessionInfo({ location: { directory: custom } })), out("session.prompt", { sessionID: SESSION, text: "" }), @@ -7062,8 +7046,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { out("session.update", { sessionID: FORK, permissions: [ - { action: "*", resource: "*", effect: "allow" }, - launchGate, { action: "t3-code-*", resource: "*", effect: "deny" }, { action: "t3-code-thread_opencode2-adapter_fork_*", resource: "*", effect: "allow" }, ], diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 1c2bb52ef3b8..f7c5c56e48df 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -357,10 +357,6 @@ interface ThreadState { rules: ReadonlyArray | undefined; policy: RulesPolicy; readonly grants: Array; - /** Subagent calls T3 let through whose child is not attached yet; while any is, the session's rules ask for everything. */ - readonly launching: Set; - /** Ran under a launch window (a parent this turn, a child since birth): requests it raised can arrive after it closed. */ - windowed: boolean; readonly calls: Map; subagent: | { @@ -417,7 +413,6 @@ interface PendingRequest { readonly action: string; readonly resources: ReadonlyArray; readonly save: ReadonlyArray; - readonly toolId: string | undefined; } | { readonly type: "form"; readonly id: string; readonly form: NativeForm }; } @@ -493,13 +488,17 @@ const effectOf = ( wildcardMatch(resource, entry.resource, windows), )?.effect ?? "ask"; -const SUBAGENT = "subagent"; -// OpenCode copies a parent's session rules into the child it creates and applies them after the -// child agent's own, so a parent asks T3 before each launch and asks for everything while it runs. -const LAUNCH_GATE = rule(SUBAGENT, "ask"); -const LAUNCH_WINDOW = rule("*", "ask"); -const isLaunchWindow = (entry: Rule) => - entry.action === "*" && entry.resource === "*" && entry.effect === "ask"; +// OpenCode copies a root session's rules into each subagent session it creates and applies them +// after the subagent agent's own, where saved approvals can still outrank an ask but never a deny. +// So a root session is never written an allow: each becomes an ask that T3 answers from `rules`. +const inheritable = (rules: ReadonlyArray) => + rules.flatMap((entry): ReadonlyArray => + entry.effect !== "allow" + ? [entry] + : entry.action === "*" && entry.resource === "*" + ? [] + : [{ ...entry, effect: "ask" }], + ); const sessionRules = ( policy: RulesPolicy, @@ -507,7 +506,6 @@ const sessionRules = ( grants: ReadonlyArray, mcpServerName: string | null, own: ReadonlyArray = [], - launch?: Rule, ): ReadonlyArray => [ ...(policy.runtimeMode === "full-access" ? [rule("*", "allow")] @@ -521,7 +519,6 @@ const sessionRules = ( ...(policy.interactionMode === "plan" ? [rule("edit", "deny")] : []), ...paths, ...own, - ...(launch === undefined ? [] : [launch]), ...mcpRules(mcpServerName), ]; @@ -997,8 +994,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr rules: undefined, policy: input.runtimePolicy, grants: [], - launching: new Set(), - windowed: false, calls: new Map(), subagent, wakes: [], @@ -2201,15 +2196,13 @@ 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, and a new one is born asking for everything. - if (child.rules?.some(isLaunchWindow) === true) child.windowed = true; - if (info === undefined || child.windowed) { + // Reused child sessions may retain old mode rules; refresh policy as soon as the call identifies them. + if (info === undefined) { yield* writeRules(child, rootOf(call.state).policy).pipe( Effect.timeout(REQUEST_REPLY_TIMEOUT), Effect.ignore({ log: true }), ); } - yield* closeLaunch(call.state, call.toolId); }); const settleCall: ( @@ -2218,7 +2211,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr result?: string, ) => Effect.Effect = Effect.fnUntraced(function* (call, status, result) { if (!isOrchestrationV2WorkActive(call.status)) return; - yield* closeLaunch(call.state, call.toolId); call.status = status; call.completedAt = yield* DateTime.now; if (result !== undefined) call.result = result; @@ -2707,21 +2699,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }); const onPermissionAsked = Effect.fnUntraced(function* (data: Permission.Request) { - if (yield* settleLaunchAsk(data)) return; const turn = threads.get(data.sessionID)?.active; const toolName = data.source === undefined ? undefined : turn?.tools.get(data.source.id)?.name; const save = data.save ?? []; yield* showRequest( data.sessionID, - { - type: "permission", - id: data.id, - action: data.action, - resources: data.resources, - save, - toolId: data.source?.id, - }, + { type: "permission", id: data.id, action: data.action, resources: data.resources, save }, { type: "approval_request", requestKind: openCodePermissionRequestKind(data.action, toolName), @@ -2791,6 +2775,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } const state = ownerOf(asking); if (state === undefined) return; + if (asked.type === "permission" && (yield* settleAsk(asked.request))) return; const target = requestTurn(asking); if (target !== undefined && !target.turn.awaitingStart) { if (asked.type === "permission") return yield* onPermissionAsked(asked.request); @@ -4084,10 +4069,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }); const rulesFor = Effect.fnUntraced(function* ( - thread: Pick & { - readonly child: boolean; - readonly launch?: Rule | undefined; - }, + thread: Pick & { readonly child: boolean }, policy: RulesPolicy, appThreadId: string | null, ) { @@ -4110,26 +4092,24 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr paths.set(`${entry.action}\u0000${entry.resource}`, entry); } } - return sessionRules( + const rules = sessionRules( policy, [...paths.values()], full ? [] : thread.grants, - appThreadId === null ? null : yield* mcpServerNameFor(appThreadId), + null, thread.child ? agentDenies(agents?.get(thread.agent) ?? [], policy) : [], - thread.launch, ); + const mcp = mcpRules(appThreadId === null ? null : yield* mcpServerNameFor(appThreadId)); + // `rules` is what T3 enforces; `written` is what the OpenCode session is given. + return { + rules: [...rules, ...mcp], + written: [...(thread.child ? rules : inheritable(rules)), ...mcp], + }; }); const writeRules = Effect.fnUntraced(function* (state: ThreadState, policy: RulesPolicy) { - const child = state.subagent !== undefined; - const rules = yield* rulesFor( - { - directory: state.directory, - agent: state.agent, - grants: state.grants, - child, - launch: child ? undefined : state.launching.size > 0 ? LAUNCH_WINDOW : LAUNCH_GATE, - }, + const { written: rules } = yield* rulesFor( + { ...state, child: state.subagent !== undefined }, policy, rootOf(state).providerThread.appThreadId, ); @@ -4143,68 +4123,44 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr state.policy = policy; }); - const openLaunch = (state: ThreadState, key: string) => { - state.launching.add(key); - state.windowed = true; - return writeRules(state, state.policy).pipe( - Effect.timeout(REQUEST_REPLY_TIMEOUT), - Effect.as(true), - Effect.catchCause((cause) => - Effect.logWarning("Could not prepare an OpenCode session for a subagent.", cause).pipe( - Effect.map(() => { - state.launching.delete(key); - return false; - }), - ), - ), - ); - }; - - const closeLaunch = (state: ThreadState, key: string) => - state.launching.delete(key) && state.launching.size === 0 - ? writeRules(state, state.policy).pipe( - Effect.timeout(REQUEST_REPLY_TIMEOUT), - Effect.ignore({ log: true }), - ) - : Effect.void; - - /** Answers what a launch gate or window made OpenCode ask, as the asking session's own rules decide it. */ - const settleLaunchAsk = Effect.fnUntraced(function* (data: Permission.Request) { + /** Answers a request the thread's rules already decide; one they leave open goes to the user. */ + const settleAsk = Effect.fnUntraced(function* (data: Permission.Request) { const state = threads.get(data.sessionID); - const born = announced.get(data.sessionID); const owner = ownerOf(data.sessionID); if (owner === undefined) return false; const root = rootOf(owner); - const gated = data.action === SUBAGENT && state === root; - const windowed = - state?.windowed === true || (state?.rules ?? born?.permissions)?.some(isLaunchWindow); - if (!gated && windowed !== true) return false; + const child = state !== root; const directory = state?.directory ?? owner.directory; - const agent = state?.agent ?? born?.agent ?? "build"; - const own = (yield* agentsIn(directory, state === root ? undefined : agent))?.get(agent); + const agent = state?.agent ?? announced.get(data.sessionID)?.agent ?? "build"; const session = yield* rulesFor( - { directory, agent, grants: state?.grants ?? [], child: state !== root }, + { directory, agent, grants: state?.grants ?? [], child }, root.policy, root.providerThread.appThreadId, ).pipe(Effect.option); + // A full-access root's rules open with an allow for everything, which outranks its agent's rules. + const rules = session._tag === "None" ? undefined : session.value.rules; + const own = + child || rules?.[0]?.action !== "*" + ? (yield* agentsIn(directory, child ? agent : undefined))?.get(agent) + : []; + // A subagent whose agent rules cannot be read is refused; a root's request goes to the user. + if (!child && (own === undefined || rules === undefined)) return false; const effects = - own === undefined || session._tag === "None" + own === undefined || rules === undefined ? ["deny" as const] : data.resources.map((resource) => - effectOf(data.action, resource, [...own, ...session.value], windows), + effectOf(data.action, resource, [...own, ...rules], windows), ); - if (!effects.includes("deny") && effects.includes("ask")) return false; - const allowed = - !effects.includes("deny") && - (!gated || (yield* openLaunch(root, data.source?.id ?? data.id))); + const denied = effects.includes("deny"); + if (!denied && (effects.length === 0 || effects.includes("ask"))) return false; yield* client.permission .reply({ sessionID: Session.ID.make(data.sessionID), requestID: Permission.ID.make(data.id), - decision: allowed ? "once" : "reject", - ...(allowed - ? {} - : { message: `The ${agent} agent's permissions do not allow ${data.action} here.` }), + decision: denied ? "reject" : "once", + ...(denied + ? { message: `The ${agent} agent's permissions do not allow ${data.action} here.` } + : {}), }) .pipe( Effect.catchTags(permissionGone), @@ -4882,8 +4838,8 @@ 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: [], child: false, launch: LAUNCH_GATE }, + const { written: permissions } = yield* rulesFor( + { directory, agent: "build", grants: [], child: false }, policy, threadInput.threadId, ); @@ -5072,8 +5028,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr state.agent = agent; } // Refresh stale mode rules; running subagent updates are best effort because they outlive this turn. - state.launching.clear(); - state.windowed = false; yield* writeRules(state, turnInput.runtimePolicy); yield* writeTitle(state, turnInput.appThread.title).pipe( Effect.timeout(REQUEST_REPLY_TIMEOUT), @@ -5408,14 +5362,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* writeRules(state, rootOf(state).policy).pipe(Effect.ignore({ log: true })); } const sessionID = Session.ID.make(entry.sessionId); - // A subagent launch the user approves still needs its window before OpenCode creates the child. - const approved = - decision !== undefined && - approves(decision) && - (native.type !== "permission" || - native.action !== SUBAGENT || - asker.subagent !== undefined || - (yield* openLaunch(asker, native.toolId ?? native.id))); if (native.type === "permission" && decision === "decline") { yield* client.session .synthetic({ @@ -5432,7 +5378,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr .reply({ sessionID, requestID: Permission.ID.make(native.id), - decision: approved ? "once" : "reject", + decision: decision !== undefined && approves(decision) ? "once" : "reject", ...(decision === "decline" ? { message: DECLINED } : {}), }) .pipe(Effect.catchTags(permissionGone)), From 4eed327336081d6ef97178185c58b87adc214641 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 16:06:25 +0000 Subject: [PATCH 4/8] fix(opencode): a subagent session is written none of its agent's denies OpenCode copies permissions from whichever session launches a subagent, not only from the root. Writing a subagent's own agent denies into its session therefore applied them to the subagents it launched, so a nested writer under a read-only coordinator was denied edits its agent allows. Every session, root or subagent, is now written the same agent-neutral rules: no allow and no agent denies. The asking agent's denies are applied only where T3 answers a permission request. The regression test asserted the denies in the rules written to the subagent; it now asserts they are absent there and that the subagent's denied request is refused. Refs pingdotgg/t3code#38100 Co-Authored-By: Claude Fable 5.2 --- .../Adapters/OpenCode2AdapterV2.test.ts | 51 ++++++++----------- .../src/server/v2/adapter.ts | 51 +++++++------------ 2 files changed, 39 insertions(+), 63 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index ce6aa3f681bc..5c00c9e1618d 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -99,8 +99,7 @@ const mcpRules = [ { action: "t3-code-*", resource: "*", effect: "deny" }, { action: "t3-code-thread_opencode2-adapter_*", resource: "*", effect: "allow" }, ]; -// What full access gives a subagent session; a root session is written no allow for one to inherit. -const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, ...mcpRules]; +// Full access is T3's answer to each request: no session is written an allow a subagent could inherit. const rootRules = mcpRules; const TITLE = "Prime check"; const sessionInfo = (overrides: Record = {}) => ({ @@ -298,11 +297,6 @@ const agentList = { }, ], }; -// A subagent's rules carry its agent's denies, so writing them reads the agents once per directory. -const listsAgents: ReadonlyArray = [ - out("agent.list", ""), - reply("agent.list", agentList), -]; const supervisedRules = [ { action: "shell", resource: "*", effect: "ask" }, { action: "edit", resource: "*", effect: "ask" }, @@ -1546,7 +1540,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { // regression: #38100 a subagent's own agent denies were overridden by T3's session rules it.effect.each(["full-access", "approval-required"] as const)( - "keeps a subagent's own agent denies in the rules T3 writes to it (%s)", + "holds a subagent to its own agent's denies without writing them to its session (%s)", (mode) => Effect.gen(function* () { const editDeny = { action: "edit", resource: "*", effect: "deny" }; @@ -1565,6 +1559,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, ], }; + const listsAgents = [out("agent.list", ""), reply("agent.list", agents)]; const launch = backgroundLaunch(CHILD).map((entry) => entry.type === "emit_inbound" && (entry.frame as { event?: { type?: string } }).event?.type === "session.created" @@ -1575,25 +1570,36 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { const { runtime, thread } = yield* resumed([ ...launch, event("session.execution.succeeded", { sessionID: SESSION }), - out("agent.list", ""), - reply("agent.list", agents), ...(supervised ? [ + ...listsAgents, out("session.update", { sessionID: SESSION, permissions: supervisedRules }), reply("session.update", null), ] : []), + // Rules a subagent's own subagents would copy: no allow, and none of its agent's denies. out("session.update", { sessionID: CHILD, - permissions: [ - ...(supervised ? supervisedRules.slice(0, 3) : t3Rules.slice(0, 1)), - editDeny, - ...mcpRules, - ], + permissions: supervised ? [...supervisedRules.slice(0, 3), ...mcpRules] : rootRules, }), reply("session.update", null), out("session.prompt", { sessionID: SESSION, text: "" }), promptAccepted, + event("permission.asked", { + id: "per_edit", + sessionID: CHILD, + action: "edit", + resources: ["from-review.txt"], + save: ["*"], + }), + ...(supervised ? [] : listsAgents), + out("permission.reply", { + sessionID: CHILD, + requestID: "per_edit", + decision: "reject", + message: "The review agent's permissions do not allow edit here.", + }), + reply("permission.reply", null), event("session.execution.succeeded", { sessionID: SESSION }), ]); const firstEnded = yield* Deferred.make(); @@ -1878,7 +1884,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { // The adapter writes a child's rules only when they changed. ...(writesRules ? [ - ...listsAgents, out("session.update", { sessionID: CHILD, permissions: "" }), reply("session.update", null), ] @@ -2104,7 +2109,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...again, metadata: { sessionID: CHILD, status: "running" }, }), - ...listsAgents, out("session.update", { sessionID: CHILD, permissions: "" }), reply("session.update", null), // The child fails while the joined call is still the foreground one. @@ -2510,13 +2514,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...toolOf(SESSION, "call-other"), metadata: { sessionID: OTHER, status: "running" }, }), - // A session called as a subagent stops asking before launches of its own. - ...listsAgents, - out("session.update", { - sessionID: OTHER, - permissions: t3Rules, - }), - reply("session.update", null), event("session.tool.success", { ...toolOf(SESSION, "call-other"), content: [{ type: "text", text: "OTHER_OK" }], @@ -2903,11 +2900,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { [ ...backgroundLaunch(CHILD), event("session.execution.succeeded", { sessionID: SESSION }), - ...listsAgents, - out("session.update", { - sessionID: CHILD, - permissions: t3Rules, - }), + out("session.update", { sessionID: CHILD, permissions: rootRules }), reply("session.update", null), out("session.prompt", { sessionID: SESSION, text: "" }), reply("session.prompt", { diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index f7c5c56e48df..09595f6d8f05 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -488,9 +488,9 @@ const effectOf = ( wildcardMatch(resource, entry.resource, windows), )?.effect ?? "ask"; -// OpenCode copies a root session's rules into each subagent session it creates and applies them -// after the subagent agent's own, where saved approvals can still outrank an ask but never a deny. -// So a root session is never written an allow: each becomes an ask that T3 answers from `rules`. +// OpenCode copies a session's rules into each subagent session it creates and applies them after +// that subagent's own agent rules, where saved approvals can outrank an ask but never a deny. +// So no session is written an allow or an agent's denies: allows become asks T3 answers itself. const inheritable = (rules: ReadonlyArray) => rules.flatMap((entry): ReadonlyArray => entry.effect !== "allow" @@ -504,8 +504,6 @@ const sessionRules = ( policy: RulesPolicy, paths: ReadonlyArray, grants: ReadonlyArray, - mcpServerName: string | null, - own: ReadonlyArray = [], ): ReadonlyArray => [ ...(policy.runtimeMode === "full-access" ? [rule("*", "allow")] @@ -518,8 +516,6 @@ const sessionRules = ( // Plan edits are re-allowed only for plan paths; free-tier sessions refuse denied shell/read. ...(policy.interactionMode === "plan" ? [rule("edit", "deny")] : []), ...paths, - ...own, - ...mcpRules(mcpServerName), ]; const sameRules = (left: ReadonlyArray | undefined, right: ReadonlyArray) => @@ -615,7 +611,7 @@ const agentPaths = (rules: ReadonlyArray) => const agentDenies = (rules: ReadonlyArray, policy: RulesPolicy): ReadonlyArray => { const first = rules.findIndex((entry) => entry.effect === "deny"); if (first < 0) return []; - const mode = sessionRules(policy, [], [], null); + const mode = sessionRules(policy, [], []); return rules.slice(first).map((entry) => { if (entry.effect === "deny" || agentPaths([entry]).length > 0) return entry; const effects = mode @@ -4076,35 +4072,19 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const plan = policy.interactionMode === "plan"; const full = policy.runtimeMode === "full-access"; const agents = - full && !plan && !thread.child + full && !plan ? undefined : yield* agentsIn(thread.directory, thread.child ? thread.agent : undefined); - // Rules written without a subagent's denies would let it do what its agent forbids. - if (thread.child && agents?.has(thread.agent) !== true) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver: OPENCODE_PROVIDER, - detail: "Could not read the OpenCode agents a subagent's rules depend on", - }); - } const paths = new Map(); for (const agent of plan ? [thread.agent, "plan"] : full ? [] : [thread.agent]) { for (const entry of agentPaths(agents?.get(agent) ?? [])) { paths.set(`${entry.action}\u0000${entry.resource}`, entry); } } - const rules = sessionRules( - policy, - [...paths.values()], - full ? [] : thread.grants, - null, - thread.child ? agentDenies(agents?.get(thread.agent) ?? [], policy) : [], - ); + const rules = sessionRules(policy, [...paths.values()], full ? [] : thread.grants); const mcp = mcpRules(appThreadId === null ? null : yield* mcpServerNameFor(appThreadId)); - // `rules` is what T3 enforces; `written` is what the OpenCode session is given. - return { - rules: [...rules, ...mcp], - written: [...(thread.child ? rules : inheritable(rules)), ...mcp], - }; + // T3 enforces `rules` then `mcp`; `written` is what the OpenCode session is given. + return { rules, mcp, written: [...inheritable(rules), ...mcp] }; }); const writeRules = Effect.fnUntraced(function* (state: ThreadState, policy: RulesPolicy) { @@ -4138,19 +4118,22 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr root.providerThread.appThreadId, ).pipe(Effect.option); // A full-access root's rules open with an allow for everything, which outranks its agent's rules. - const rules = session._tag === "None" ? undefined : session.value.rules; + const rules = session._tag === "None" ? undefined : session.value; const own = - child || rules?.[0]?.action !== "*" + child || rules?.rules[0]?.action !== "*" ? (yield* agentsIn(directory, child ? agent : undefined))?.get(agent) : []; // A subagent whose agent rules cannot be read is refused; a root's request goes to the user. if (!child && (own === undefined || rules === undefined)) return false; - const effects = + // A subagent's own denies outrank the mode here only, never in rules its own subagents would copy. + const enforced = own === undefined || rules === undefined + ? undefined + : [...own, ...rules.rules, ...(child ? agentDenies(own, root.policy) : []), ...rules.mcp]; + const effects = + enforced === undefined ? ["deny" as const] - : data.resources.map((resource) => - effectOf(data.action, resource, [...own, ...rules], windows), - ); + : data.resources.map((resource) => effectOf(data.action, resource, enforced, windows)); const denied = effects.includes("deny"); if (!denied && (effects.length === 0 || effects.includes("ask"))) return false; yield* client.permission From 979e778cbdf478ab561ea26b1eb7156e12335f46 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 16:34:22 +0000 Subject: [PATCH 5/8] fix(opencode): answer permission requests only for live runs, and deliver the answer Follow-ups to answering OpenCode permission requests from T3's rules: - A request left by an execution T3 gave up on is stopped before the rules are consulted, as it was before, instead of being approved. - A failed or timed-out reply is no longer swallowed: an approval that did not arrive goes to the user, and an undelivered refusal ends the turn. - A subagent's own agent rules decide a deny on their own; otherwise the mode's rules apply on top of them. The earlier rewrite of the agent's rules turned `* allow` after a deny into `* deny` in plan mode. The orchestrator integration scripts and the recorded fork transcript expected the old `* allow` rule lists and are updated to the rules now written. Refs pingdotgg/t3code#38100 Co-Authored-By: Claude Fable 5.2 --- ...penCode2OrchestratorV2.integration.test.ts | 14 ++-- .../opencode2_fork/opencode_transcript.ndjson | 2 +- .../src/server/v2/adapter.ts | 72 ++++++++----------- 3 files changed, 37 insertions(+), 51 deletions(-) diff --git a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts index 8681ce4333cb..73ae3b42e57e 100644 --- a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts +++ b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts @@ -65,9 +65,10 @@ const mcpRules = (name: string) => [ { action: "t3-code-*", resource: "*", effect: "deny" }, { action: `t3-code-thread_${name}_*`, resource: "*", effect: "allow" }, ]; -const FULL_ACCESS = [{ action: "*", resource: "*", effect: "allow" }]; - -const t3Rules = (name: string) => [...FULL_ACCESS, ...mcpRules(name)]; +// A session is written no allow a subagent could inherit: T3 answers what the rules would allow. +const t3Rules = mcpRules; +const asks = (rules: ReadonlyArray<{ action: string; resource: string }>) => + rules.map((entry) => ({ ...entry, effect: "ask" })); const BUILD_PATHS = [ { @@ -111,16 +112,15 @@ const agentList = (directory: string) => ({ const autoEditRules = (name: string) => [ { action: "shell", resource: "*", effect: "ask" }, - { action: "edit", resource: "*", effect: "allow" }, + { action: "edit", resource: "*", effect: "ask" }, { action: "external_directory", resource: "*", effect: "ask" }, - ...BUILD_PATHS, + ...asks(BUILD_PATHS), ...mcpRules(name), ]; const planRules = (name: string) => [ - { action: "*", resource: "*", effect: "allow" }, { action: "edit", resource: "*", effect: "deny" }, - ...PLAN_PATHS, + ...asks(PLAN_PATHS), ...mcpRules(name), ]; diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_fork/opencode_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_fork/opencode_transcript.ndjson index a483f04813b3..613375719c14 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_fork/opencode_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_fork/opencode_transcript.ndjson @@ -49,7 +49,7 @@ {"type": "emit_inbound", "label": "message.list.synthetic.response", "frame": {"type": "sdk.response", "operation": "message.list", "data": {"data": [], "cursor": {}}}} {"type": "expect_outbound", "label": "session.fork", "frame": {"type": "session.fork", "input": {"sessionID": "ses_f1484ea8affe5aTo8CcgbGIszj", "before": "msg_0eb7b1f9f001g95Bduh3bi8syS"}}} {"type": "emit_inbound", "label": "session.fork.response", "frame": {"type": "sdk.response", "operation": "session.fork", "data": {"data": {"id": "ses_f1484db83ffeLGtrRCFimo1H0e", "fork": {"sessionID": "ses_f1484ea8affe5aTo8CcgbGIszj", "boundary": {"type": "before", "messageID": "msg_0eb7b1f9f001g95Bduh3bi8syS"}}, "projectID": "global", "model": {"id": "big-pickle", "providerID": "opencode", "variant": "default"}, "cost": 0, "tokens": {"input": 0, "output": 0, "reasoning": 0, "cache": {"read": 0, "write": 0}}, "time": {"created": 1790657111165, "updated": 1790657111165}, "title": "spike fork (fork #1)", "location": {"directory": ""}, "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "subagent", "resource": "*", "effect": "deny"}]}}}} -{"type": "expect_outbound", "label": "session.update", "frame": {"type": "session.update", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "t3-code-*", "resource": "*", "effect": "deny"}, {"action": "t3-code-thread_opencode2-fork_target_*", "resource": "*", "effect": "allow"}]}}} +{"type": "expect_outbound", "label": "session.update", "frame": {"type": "session.update", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "permissions": [{"action": "t3-code-*", "resource": "*", "effect": "deny"}, {"action": "t3-code-thread_opencode2-fork_target_*", "resource": "*", "effect": "allow"}]}}} {"type": "emit_inbound", "label": "session.update.response", "frame": {"type": "sdk.response", "operation": "session.update", "data": null}} {"type": "emit_inbound", "label": "session.forked", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7b247d001fXzFroPg5P0bps", "created": 1790657111165, "type": "session.forked", "location": {"directory": ""}, "data": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "parentID": "ses_f1484ea8affe5aTo8CcgbGIszj", "boundary": {"type": "before", "messageID": "msg_0eb7b1f9f001g95Bduh3bi8syS"}, "instructions": {"core/environment": "db4a793a05fec32fdfa985a3432125a86d6cb42debc8b9ee8f6a99fbfcf2f93b", "core/date": "bf08b8486572ab3eef677a3c9ee12468e411ae41a8f4d2fb6cf02a6ca73f1986", "core/codemode": "616a7ad8b8e40e8a71eab238dfbbe9eaf0f4a9e6fdad853226d075bfe602e1e6", "core/skill-guidance": "0d001919496102654717308c72635523bf7c3cd99c81e058cc79f2947104f9a5"}, "instructionEntries": []}, "durable": {"aggregateID": "ses_f1484db83ffeLGtrRCFimo1H0e", "seq": 0, "version": 2}}}} {"type": "expect_outbound", "label": "session.update.title", "frame": {"type": "session.update", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "title": ""}}} diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 09595f6d8f05..f3c42cbe8c52 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -607,21 +607,6 @@ const agentPaths = (rules: ReadonlyArray) => (entry.action === "edit" || entry.action === "external_directory"), ); -/** A subagent's rules from its first deny on: its denies outrank T3's mode, and what it re-allows after them follows the mode. */ -const agentDenies = (rules: ReadonlyArray, policy: RulesPolicy): ReadonlyArray => { - const first = rules.findIndex((entry) => entry.effect === "deny"); - if (first < 0) return []; - const mode = sessionRules(policy, [], []); - return rules.slice(first).map((entry) => { - if (entry.effect === "deny" || agentPaths([entry]).length > 0) return entry; - const effects = mode - .filter((moded) => moded.action === "*" || wildcardMatch(moded.action, entry.action)) - .map((moded) => moded.effect); - const effect = (["deny", "ask", "allow"] as const).find((kind) => effects.includes(kind)); - return effect === undefined ? entry : { ...entry, effect }; - }); -}; - const ref = (nativeId: string, strength: "strong" | "weak" = "strong") => ({ driver: OPENCODE_PROVIDER, nativeId, @@ -2771,20 +2756,21 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } const state = ownerOf(asking); if (state === undefined) return; - if (asked.type === "permission" && (yield* settleAsk(asked.request))) return; const target = requestTurn(asking); - if (target !== undefined && !target.turn.awaitingStart) { - if (asked.type === "permission") return yield* onPermissionAsked(asked.request); - return yield* onFormCreated(asked.form); - } - if (state.unsettled || state.active?.awaitingStart === true) { - yield* stopStaleRequest( + const live = target !== undefined && !target.turn.awaitingStart; + // A request left by an execution T3 gave up on is stopped, never answered from the rules. + if (!live && (state.unsettled || state.active?.awaitingStart === true)) { + return yield* stopStaleRequest( asking, asked.type === "permission" ? { type: "permission", id: asked.request.id } : { type: "form", id: asked.form.id }, ); } + if (asked.type === "permission" && (yield* settleAsk(asked.request))) return; + if (!live) return; + if (asked.type === "permission") return yield* onPermissionAsked(asked.request); + return yield* onFormCreated(asked.form); }); const sessionOfEvent = (event: OpenCode2Client.OpenCode2StreamEvent) => @@ -4126,31 +4112,31 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr // A subagent whose agent rules cannot be read is refused; a root's request goes to the user. if (!child && (own === undefined || rules === undefined)) return false; // A subagent's own denies outrank the mode here only, never in rules its own subagents would copy. - const enforced = - own === undefined || rules === undefined - ? undefined - : [...own, ...rules.rules, ...(child ? agentDenies(own, root.policy) : []), ...rules.mcp]; const effects = - enforced === undefined + own === undefined || rules === undefined ? ["deny" as const] - : data.resources.map((resource) => effectOf(data.action, resource, enforced, windows)); + : data.resources.map((resource) => + child && effectOf(data.action, resource, own, windows) === "deny" + ? "deny" + : effectOf(data.action, resource, [...own, ...rules.rules, ...rules.mcp], windows), + ); const denied = effects.includes("deny"); if (!denied && (effects.length === 0 || effects.includes("ask"))) return false; - yield* client.permission - .reply({ - sessionID: Session.ID.make(data.sessionID), - requestID: Permission.ID.make(data.id), - decision: denied ? "reject" : "once", - ...(denied - ? { message: `The ${agent} agent's permissions do not allow ${data.action} here.` } - : {}), - }) - .pipe( - Effect.catchTags(permissionGone), - Effect.timeout(REQUEST_REPLY_TIMEOUT), - Effect.ignore({ log: true }), - ); - return true; + const delivered = yield* deliver( + client.permission + .reply({ + sessionID: Session.ID.make(data.sessionID), + requestID: Permission.ID.make(data.id), + decision: denied ? "reject" : "once", + ...(denied + ? { message: `The ${agent} agent's permissions do not allow ${data.action} here.` } + : {}), + }) + .pipe(Effect.catchTags(permissionGone)), + ); + // An approval that did not arrive goes to the user; a refusal must not become approvable. + if (!delivered && denied) yield* abandonRequest(state ?? owner, "permission reply failed"); + return delivered || denied; }); const writeTitle = Effect.fnUntraced(function* (state: ThreadState, title: string) { From 1cff2bd6a5f20f23c66b2ba584142671595531db Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 16:56:37 +0000 Subject: [PATCH 6/8] fix(opencode): leave provider-raised permission requests to the user T3 approved any request its rules allow. A request OpenCode raises on its own, such as one a permission hook turns into an ask, reached the user before and was now approved silently. T3 answers a request only when the rules it wrote, or the agent's own, are what made OpenCode ask. The agents read for those answers are cached per directory; the cache is dropped on reconnect so a restarted server's changed agent rules are read again. Refs pingdotgg/t3code#38100 Co-Authored-By: Claude Fable 5.2 --- .../Adapters/OpenCode2AdapterV2.test.ts | 14 +++++++++----- .../provider-opencode/src/server/v2/adapter.ts | 18 +++++++++++++----- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 5c00c9e1618d..7c4f26aeca2f 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -297,6 +297,11 @@ const agentList = { }, ], }; +// A reconnect drops the cached agents, so the next request answered from their rules reads them again. +const relistsAgents: ReadonlyArray = [ + out("agent.list", ""), + reply("agent.list", agentList), +]; const supervisedRules = [ { action: "shell", resource: "*", effect: "ask" }, { action: "edit", resource: "*", effect: "ask" }, @@ -1651,10 +1656,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { out("session.prompt", { sessionID: SESSION, text: "" }), promptAccepted, event("session.execution.started", { sessionID: SESSION }), - // Full access is T3's answer to each request, not an allow the root session carries. - asked("per_shell", "shell", SESSION), - out("permission.reply", { sessionID: SESSION, requestID: "per_shell", decision: "once" }), - reply("permission.reply", null), event("session.tool.input.started", { ...tool, name: "subagent" }), // The child copies the root's rules, which hold no allow to outrank its agent's deny. event("session.created", { @@ -3975,9 +3976,10 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...(source === "stream" ? [ event("permission.asked", shellAsk.data, "late-permission"), + ...relistsAgents, event("form.created", { form: colorForm }), ] - : []), + : relistsAgents), out("permission.reply", { sessionID: SESSION, requestID: shellAsk.data.id, @@ -4413,6 +4415,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { promptAccepted, ...reconnected({ [SESSION]: { type: "running" } }), ...openRequests([shellAsk.data]), + ...relistsAgents, out("permission.reply", { sessionID: SESSION, requestID: shellAsk.data.id, @@ -6041,6 +6044,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...(streamed ? { time: { created: 2, streamed: 3 } } : {}), }), ...openRequests([shellAsk.data]), + ...relistsAgents, event("session.execution.succeeded", { sessionID: SESSION }, "finish"), ], { supervised: true, replayGate: gate }, diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index f3c42cbe8c52..7f3274fcb5fb 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -3834,6 +3834,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const previous = currentScope; connection = next; client = next.client; + // A restarted server may have reloaded its agents; rules answered from a stale copy could allow a new deny. + agentRules.clear(); nativeGoalSupport = supportsNativeGoals(); session = { ...session, @@ -4103,12 +4105,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr root.policy, root.providerThread.appThreadId, ).pipe(Effect.option); - // A full-access root's rules open with an allow for everything, which outranks its agent's rules. const rules = session._tag === "None" ? undefined : session.value; - const own = - child || rules?.rules[0]?.action !== "*" - ? (yield* agentsIn(directory, child ? agent : undefined))?.get(agent) - : []; + const own = (yield* agentsIn(directory, child ? agent : undefined))?.get(agent); // A subagent whose agent rules cannot be read is refused; a root's request goes to the user. if (!child && (own === undefined || rules === undefined)) return false; // A subagent's own denies outrank the mode here only, never in rules its own subagents would copy. @@ -4122,6 +4120,16 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ); const denied = effects.includes("deny"); if (!denied && (effects.length === 0 || effects.includes("ask"))) return false; + // The rules OpenCode holds would have allowed this, so something of its own asked: the user decides. + const written = [...(own ?? []), ...(rules?.written ?? [])]; + if ( + !denied && + data.resources.every( + (resource) => effectOf(data.action, resource, written, windows) === "allow", + ) + ) { + return false; + } const delivered = yield* deliver( client.permission .reply({ From a5a0d4bffd44c576c491074be65963c7c0cb9446 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 17:01:00 +0000 Subject: [PATCH 7/8] fix(opencode): decide permission requests under both path matchings for external servers OpenCode matches rule patterns case-insensitively on Windows. T3 used its own host's platform, which is wrong for a server it did not start. A deny on such a server could miss under the host's matching and the request be approved. For an external server T3 now evaluates both matchings and takes the stricter result. Refs pingdotgg/t3code#38100 Co-Authored-By: Claude Fable 5.2 --- .../provider-opencode/src/server/v2/adapter.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 7f3274fcb5fb..afe0c3a49f4f 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4026,7 +4026,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr contextWindows.has(directoryOf(cwd)) ? Effect.void : readModels(directoryOf(cwd)); yield* readModels(session.cwd); - const windows = (yield* HostProcess.Platform) === "win32"; + const hostWindows = (yield* HostProcess.Platform) === "win32"; + // A server T3 did not start may run on another platform, so both of OpenCode's matchings must agree. + const decide = (action: string, resource: string, rules: ReadonlyArray) => { + const effects = (connection.external ? [false, true] : [hostWindows]).map((windows) => + effectOf(action, resource, rules, windows), + ); + return effects.includes("deny") ? "deny" : effects.includes("ask") ? "ask" : "allow"; + }; const agentRules = new Map>>(); const agentsIn = Effect.fnUntraced(function* (directory: string, subagent?: string) { const known = agentRules.get(directory); @@ -4114,9 +4121,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr own === undefined || rules === undefined ? ["deny" as const] : data.resources.map((resource) => - child && effectOf(data.action, resource, own, windows) === "deny" + child && decide(data.action, resource, own) === "deny" ? "deny" - : effectOf(data.action, resource, [...own, ...rules.rules, ...rules.mcp], windows), + : decide(data.action, resource, [...own, ...rules.rules, ...rules.mcp]), ); const denied = effects.includes("deny"); if (!denied && (effects.length === 0 || effects.includes("ask"))) return false; @@ -4124,9 +4131,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const written = [...(own ?? []), ...(rules?.written ?? [])]; if ( !denied && - data.resources.every( - (resource) => effectOf(data.action, resource, written, windows) === "allow", - ) + data.resources.every((resource) => decide(data.action, resource, written) === "allow") ) { return false; } From a06797da700c70c867bf94180f9b45236359b7d4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 17:03:56 +0000 Subject: [PATCH 8/8] fix(opencode): declare the agent rules cache before the event stream starts A stream that dropped before the first model read finished reached the reconnect path, which clears the cache, before the cache was declared. Refs pingdotgg/t3code#38100 Co-Authored-By: Claude Fable 5.2 --- packages/provider-opencode/src/server/v2/adapter.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index afe0c3a49f4f..bf18d23c3824 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -928,6 +928,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const events = yield* Queue.unbounded(); const threads = new Map(); const childOwners = new Map(); + // Declared before the event stream starts: an early reconnect clears it. + const agentRules = new Map>>(); const announced = new Map["data"]>(); const strays = new Map(); const busy = new Set(); @@ -4034,7 +4036,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ); return effects.includes("deny") ? "deny" : effects.includes("ask") ? "ask" : "allow"; }; - const agentRules = new Map>>(); const agentsIn = Effect.fnUntraced(function* (directory: string, subagent?: string) { const known = agentRules.get(directory); // A subagent the cached list lacks was added since; its denies must not be skipped.