diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index cd1bdc9044a5..7c4f26aeca2f 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,12 +99,13 @@ const mcpRules = [ { action: "t3-code-*", resource: "*", effect: "deny" }, { action: "t3-code-thread_opencode2-adapter_*", resource: "*", effect: "allow" }, ]; -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 = {}) => ({ id: SESSION, title: TITLE, - permissions: t3Rules, + permissions: rootRules, projectID: "global", model: { id: "big-pickle", providerID: "opencode", variant: "default" }, cost: 0, @@ -284,13 +286,27 @@ 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 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" }, { action: "external_directory", resource: "*", effect: "ask" }, - ...buildPaths, + ...buildPaths.map((entry) => ({ ...entry, effect: "ask" })), ...mcpRules, ]; @@ -1527,6 +1543,179 @@ 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)( + "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" }; + 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 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" + ? 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 }), + ...(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), ...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(); + 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("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 tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-review" }; + const asked = (id: string, action: string, sessionID = CHILD) => + event("permission.asked", { + id, + sessionID, + action, + 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 }), + 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", { + ...childCreated(CHILD), + agent: "review", + permissions: rootRules, + }), + // 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, + data: [ + ...agentList.data, + { + ...agentList.data[1], + id: "review", + permissions: [{ action: "read", resource: "*", effect: "ask" }, editDeny], + }, + ], + }), + 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), + // 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.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([ @@ -2712,7 +2901,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { [ ...backgroundLaunch(CHILD), event("session.execution.succeeded", { sessionID: SESSION }), - 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", { @@ -2853,7 +3042,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({ @@ -3117,7 +3306,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), ], }), @@ -3787,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, @@ -4085,6 +4275,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))) @@ -4112,7 +4304,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 }) @@ -4220,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, @@ -5255,7 +5451,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { "session.get", sessionInfo({ permissions: [ - { action: "*", resource: "*", effect: "allow" }, { action: "t3-code-*", resource: "*", effect: "deny" }, { action: `${server}_*`, resource: "*", effect: "allow" }, ], @@ -5849,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 }, @@ -5995,7 +6191,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: "" }), @@ -6847,7 +7043,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { out("session.update", { sessionID: FORK, permissions: [ - { action: "*", resource: "*", effect: "allow" }, { action: "t3-code-*", resource: "*", effect: "deny" }, { action: "t3-code-thread_opencode2-adapter_fork_*", resource: "*", effect: "allow" }, ], 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 0072f9d1897b..bf18d23c3824 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,11 +439,71 @@ 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"; + +// 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" + ? [entry] + : entry.action === "*" && entry.resource === "*" + ? [] + : [{ ...entry, effect: "ask" }], + ); + const sessionRules = ( policy: RulesPolicy, paths: ReadonlyArray, grants: ReadonlyArray, - mcpServerName: string | null, ): ReadonlyArray => [ ...(policy.runtimeMode === "full-access" ? [rule("*", "allow")] @@ -455,7 +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, - ...mcpRules(mcpServerName), ]; const sameRules = (left: ReadonlyArray | undefined, right: ReadonlyArray) => @@ -868,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(); @@ -2697,18 +2759,20 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const state = ownerOf(asking); if (state === undefined) 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) => @@ -3772,6 +3836,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, @@ -3962,63 +4028,67 @@ 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, - ) { - 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 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 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 }, 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]); - return sessionRules( - policy, - paths, - policy.runtimeMode === "full-access" ? [] : thread.grants, - appThreadId === null ? null : yield* mcpServerNameFor(appThreadId), - ); + const full = policy.runtimeMode === "full-access"; + const agents = + full && !plan + ? undefined + : yield* agentsIn(thread.directory, thread.child ? thread.agent : undefined); + 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); + const mcp = mcpRules(appThreadId === null ? null : yield* mcpServerNameFor(appThreadId)); + // 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) { - const rules = yield* rulesFor(state, policy, rootOf(state).providerThread.appThreadId); + const { written: rules } = yield* rulesFor( + { ...state, child: state.subagent !== undefined }, + policy, + rootOf(state).providerThread.appThreadId, + ); if (!sameRules(state.rules, rules)) { yield* client.session.update({ sessionID: Session.ID.make(state.sessionId), @@ -4029,6 +4099,60 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr state.policy = policy; }); + /** 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 owner = ownerOf(data.sessionID); + if (owner === undefined) return false; + const root = rootOf(owner); + const child = state !== root; + const directory = state?.directory ?? owner.directory; + const agent = state?.agent ?? announced.get(data.sessionID)?.agent ?? "build"; + const session = yield* rulesFor( + { directory, agent, grants: state?.grants ?? [], child }, + root.policy, + root.providerThread.appThreadId, + ).pipe(Effect.option); + const rules = session._tag === "None" ? undefined : session.value; + 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. + const effects = + own === undefined || rules === undefined + ? ["deny" as const] + : data.resources.map((resource) => + child && decide(data.action, resource, own) === "deny" + ? "deny" + : decide(data.action, resource, [...own, ...rules.rules, ...rules.mcp]), + ); + 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) => decide(data.action, resource, written) === "allow") + ) { + return false; + } + 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) { const next = title.trim(); // An empty title asks OpenCode to generate one. @@ -4697,8 +4821,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: [] }, + const { written: permissions } = yield* rulesFor( + { directory, agent: "build", grants: [], child: false }, policy, threadInput.threadId, ); 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";