From 43406d468dbecf0cb9191c046d0ce31cbe9d0ea1 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:07:25 -0600 Subject: [PATCH] fix(core): give each Code Mode call its own ID (#64324) --- packages/core/src/codemode/tool.ts | 9 +++++- packages/core/src/permission.ts | 25 +++++++++++++--- packages/core/test/lib/permission.ts | 2 +- packages/core/test/mcp-attach.test.ts | 3 +- packages/core/test/mcp.test.ts | 12 ++++---- packages/core/test/permission.test.ts | 16 ++++++++++ packages/core/test/plugin/fixture.ts | 1 + .../test/plugin/permission-assert.test.ts | 1 + packages/core/test/tool-execute.test.ts | 29 ++++++++++++++++-- packages/core/test/tool-registry.test.ts | 30 +++++++++++++++++++ 10 files changed, 113 insertions(+), 15 deletions(-) diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index 4976c40ef3b..5c947af5f73 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -11,7 +11,9 @@ import type { Namespace as ToolNamespace, Result, } from "@opencode/schema/tool" -import { Clock, Context, Effect, Ref, Schema, Semaphore } from "effect" +import { Identifier } from "@opencode/schema/identifier" +import { CallID } from "@opencode/schema/tool" +import { Clock, Context, Effect, Ref, Schema, Scope, Semaphore } from "effect" import { toSessionError } from "../session/to-session-error.js" import { definition, normalizedName } from "../tool/runtime.js" import { Permission } from "../permission.js" @@ -127,9 +129,14 @@ export const create = ( executeTool: (name, tool, input) => Effect.gen(function* () { const index = yield* Ref.getAndUpdate(callIndex, (index) => index + 1) + // Its own ID, so plugin hooks and traces can tell the program's calls apart. It has no row, so + // until the program ends its permission requests show on this call's. + const id = CallID.make(`call_${Identifier.ascending()}`) + yield* permission.nested(id, context.id).pipe(Scope.provide(scope)) // The program sees the same failure text the model gets for a direct call. const executed = yield* executeTool(name, tool, input, { ...context, + id, // Progress replaces the execute call's own, so an inner tool's updates would hide the call rows. progress: () => Effect.void, // A stop is the execute call's to handle: a nested call never fails it with its own error. diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index b78a674d277..319a8b2075d 100644 --- a/packages/core/src/permission.ts +++ b/packages/core/src/permission.ts @@ -1,7 +1,7 @@ export * as Permission from "./permission.js" import { makeLocationNode } from "@opencode/util/effect/app-node" -import { Context, Deferred, Effect, Layer, Schema } from "effect" +import { Context, Deferred, Effect, Layer, Schema, Scope } from "effect" import { Permission } from "@opencode/schema/permission" import type { Tool } from "@opencode/schema/tool" import { Bus } from "./bus.js" @@ -119,6 +119,11 @@ export interface Interface { readonly get: (id: ID) => Effect.Effect readonly forSession: (sessionID: SessionSchema.ID) => Effect.Effect> readonly list: () => Effect.Effect> + /** + * Marks `call` as made by `parent`, such as a call inside a Code Mode program. It has an ID of its own but no row, + * so until the scope closes, requests naming it as their source show on `parent`'s row. + */ + readonly nested: (call: Tool.CallID, parent: Tool.CallID) => Effect.Effect } export class Service extends Context.Service()("@opencode/Permission") {} @@ -139,6 +144,7 @@ const layer = Layer.effect( const saved = yield* PermissionSaved.Service const hooks = yield* PluginHooks.Service const pending = new Map() + const parents = new Map() let closed = false const close = Effect.gen(function* () { @@ -181,6 +187,17 @@ const layer = Layer.effect( return rules.filter((rule) => Wildcard.match(input.action, rule.action)) } + const nested: Interface["nested"] = (call, parent) => + Effect.acquireRelease( + Effect.sync(() => void parents.set(call, parent)), + () => Effect.sync(() => void parents.delete(call)), + ) + + function row(source: AssertInput["source"]) { + const parent = source && parents.get(source.id) + return parent ? { ...source, id: parent } : source + } + const evaluateInput = Effect.fnUntraced(function* (input: AssertInput) { const rules = yield* configured(input.sessionID, input.agent) if (denied(input, rules)) return { effect: "deny" as const, rules } @@ -193,7 +210,7 @@ const layer = Layer.effect( action: input.action, resources: input.resources, metadata: input.metadata, - source: input.source, + source: row(input.source), effect, }) const unattended = yield* Unattended @@ -221,7 +238,7 @@ const layer = Layer.effect( metadata: input.metadata && Object.fromEntries(Object.entries(input.metadata).filter(([, value]) => value !== undefined)), - source: input.source, + source: row(input.source), message, } } @@ -377,7 +394,7 @@ const layer = Layer.effect( return Array.from(pending.values(), (item) => item.request).filter((request) => request.sessionID === sessionID) }) - return Service.of({ ask, assert, assertNotDenied, allows, reply, get, forSession, list, close }) + return Service.of({ ask, assert, assertNotDenied, allows, reply, get, forSession, list, nested, close }) }), ) diff --git a/packages/core/test/lib/permission.ts b/packages/core/test/lib/permission.ts index 447c778da8b..2b6cfeeb5ee 100644 --- a/packages/core/test/lib/permission.ts +++ b/packages/core/test/lib/permission.ts @@ -2,7 +2,7 @@ import { Permission } from "@opencode/core/permission" import { Effect, Layer } from "effect" export const permissionLayer = (overrides: Partial = {}) => - Layer.mock(Permission.Service, { close: Effect.void, ...overrides }) + Layer.mock(Permission.Service, { close: Effect.void, nested: () => Effect.void, ...overrides }) export const permissionService = (overrides: Partial = {}) => Effect.runSync( diff --git a/packages/core/test/mcp-attach.test.ts b/packages/core/test/mcp-attach.test.ts index 44825d0147f..51094d629af 100644 --- a/packages/core/test/mcp-attach.test.ts +++ b/packages/core/test/mcp-attach.test.ts @@ -21,6 +21,7 @@ import { hostEnvironmentLayer } from "./fixture/environment" import { tempLocationLayer } from "./fixture/location" import { testEffect } from "./lib/effect" import { imagePassthrough } from "./lib/image" +import { permissionLayer } from "./lib/permission" import { executeTool, toolIdentity } from "./lib/tool" // Attached clients are never OAuth integrations. @@ -48,7 +49,7 @@ const it = testEffect( }), ), Credential.node.replace(Layer.mock(Credential.Service, {})), - Permission.node.replace(Layer.mock(Permission.Service, { assert: () => Effect.void })), + Permission.node.replace(permissionLayer({ assert: () => Effect.void })), Image.node.replace(imagePassthrough), ]), ) diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts index 8718c6634a9..6aee3e77fb9 100644 --- a/packages/core/test/mcp.test.ts +++ b/packages/core/test/mcp.test.ts @@ -77,6 +77,7 @@ import { isRecord } from "@opencode/util/record" import { CrossSpawnSpawner } from "@opencode/util/cross-spawn-spawner" import { advance, drain } from "./lib/clock" import { testEffect } from "./lib/effect" +import { permissionLayer } from "./lib/permission" import { registerIntegrationPolicy, setOrganizationPolicy } from "./fixture/policy" import { location } from "./fixture/location" import { host } from "./plugin/host" @@ -619,7 +620,7 @@ const mcp = Layer.mock(Mcp.Service, { } satisfies Mcp.ToolResult }), }) -const permissions = Layer.mock(Permission.Service, { +const permissions = permissionLayer({ assert: (input) => Effect.gen(function* () { if (!assertion) return yield* Effect.die("Permission test is not initialized") @@ -1787,7 +1788,8 @@ it.live("discovers and reads MCP resources through Code Mode", () => metadata: { server: "resources", uri: "docs://readme" }, sessionID, agent: toolIdentity.agent, - source: { type: "tool", messageID: toolIdentity.messageID, id: "call_resource" }, + // The call's own ID. The real service shows the request on the execute call's row. + source: { type: "tool", messageID: toolIdentity.messageID, id: expect.not.stringMatching(/^call_resource$/) }, }) server.state.contents = [{ uri: "docs://readme", text: "line\n".repeat(20_000), mimeType: "text/plain" }] @@ -2683,7 +2685,7 @@ testEffect(Layer.empty).live("preserves plugin transforms through MCP catalog up Effect.provide( Layer.fresh( AppNodeBuilder.build(LayerNode.group([Tool.node, McpTool.node, Bus.node]), [ - ...toolNodeReplacements(Layer.mock(Permission.Service, { assert: () => Effect.void })), + ...toolNodeReplacements(permissionLayer({ assert: () => Effect.void })), Mcp.node.replace( Layer.mock(Mcp.Service, { awaitStartup: () => Effect.void, @@ -2734,7 +2736,7 @@ testEffect(Layer.empty).effect("coalesces queued MCP tool notifications after in }).pipe( Effect.provide( AppNodeBuilder.build(LayerNode.group([Tool.node, McpTool.node, Bus.node]), [ - ...toolNodeReplacements(Layer.mock(Permission.Service, { assert: () => Effect.void })), + ...toolNodeReplacements(permissionLayer({ assert: () => Effect.void })), Mcp.node.replace( Layer.mock(Mcp.Service, { awaitStartup: () => Effect.void, @@ -3069,7 +3071,7 @@ it.effect("waits for permission before calling an MCP tool", () => source: { type: "tool", messageID: toolIdentity.messageID, - id: "call_mcp_permission", + id: expect.not.stringMatching(/^call_mcp_permission$/), }, }) expect(calls).toBe(0) diff --git a/packages/core/test/permission.test.ts b/packages/core/test/permission.test.ts index 8d42e5b54a9..49db52d5917 100644 --- a/packages/core/test/permission.test.ts +++ b/packages/core/test/permission.test.ts @@ -16,6 +16,7 @@ import { Session } from "@opencode/core/session" import { SessionTable } from "@opencode/core/session/sql" import { SessionStore } from "@opencode/core/session/store" import { ShellParse } from "@opencode/core/shell/parse" +import { Tool } from "@opencode/core/tool" import { eq } from "drizzle-orm" import { location } from "./fixture/location" import { testEffect } from "./lib/effect" @@ -320,6 +321,21 @@ describe("Permission", () => { }), ) + it.effect("shows a nested call's request on its parent's row until the scope closes", () => + Effect.gen(function* () { + yield* setup() + const service = yield* Permission.Service + const source = { type: "tool" as const, messageID: "msg_test", id: "call_child" } + const ask = (id: string) => service.ask(assertion({ id: Permission.ID.create(id), source })) + yield* service + .nested(Tool.CallID.make("call_child"), Tool.CallID.make("call_parent")) + .pipe(Effect.andThen(ask("per_nested")), Effect.scoped) + yield* ask("per_after") + expect((yield* service.get(Permission.ID.create("per_nested")))?.source).toEqual({ ...source, id: "call_parent" }) + expect((yield* service.get(Permission.ID.create("per_after")))?.source).toEqual(source) + }), + ) + it.effect("drops undefined metadata values so pending requests encode as JSON", () => Effect.gen(function* () { yield* setup() diff --git a/packages/core/test/plugin/fixture.ts b/packages/core/test/plugin/fixture.ts index f7907490690..a8d6dd316ca 100644 --- a/packages/core/test/plugin/fixture.ts +++ b/packages/core/test/plugin/fixture.ts @@ -90,6 +90,7 @@ const permissionLayer = Layer.succeed( get: () => Effect.succeed(undefined), forSession: () => Effect.succeed([]), list: () => Effect.succeed([]), + nested: () => Effect.void, }), ) diff --git a/packages/core/test/plugin/permission-assert.test.ts b/packages/core/test/plugin/permission-assert.test.ts index 3a4d2baa2bc..17079e78c37 100644 --- a/packages/core/test/plugin/permission-assert.test.ts +++ b/packages/core/test/plugin/permission-assert.test.ts @@ -32,6 +32,7 @@ const permission = Layer.succeed( get: () => Effect.succeed(undefined), forSession: () => Effect.succeed([]), list: () => Effect.succeed([]), + nested: () => Effect.void, }), ) diff --git a/packages/core/test/tool-execute.test.ts b/packages/core/test/tool-execute.test.ts index b5d7880129b..2dcfa983d8b 100644 --- a/packages/core/test/tool-execute.test.ts +++ b/packages/core/test/tool-execute.test.ts @@ -418,6 +418,29 @@ test("execute supports callable namespace tools", async () => { expect(result.content).toEqual([{ type: "text", text: '["admin","created"]' }]) }) +test("each call in a program gets its own ID and is marked as nested in execute", async () => { + const ids: string[] = [] + const nested: Array<[string, string]> = [] + const input = Schema.Struct({}) + const record = { + name: "record", + description: "Record the call", + input, + execute: (_, context) => Effect.sync(() => ids.push(context.id)).pipe(Effect.as({ content: "ok" })), + } satisfies Info + await Effect.runPromise( + createCodeMode( + new Map([["record", record]]), + permissionService({ + nested: (call, parent) => Effect.sync(() => void nested.push([call, parent])), + }), + ).execute({ code: "await Promise.all([tools.record({}), tools.record({})])" }, context), + ) + expect(new Set(ids).size).toBe(2) + expect(ids).not.toContain(context.id) + expect(nested.toSorted()).toEqual(ids.toSorted().map((id) => [id, context.id])) +}) + test("executions share the prepared runtime of an inventory while keeping per-call state", async () => { let conversions = 0 const echo: Info = { @@ -437,7 +460,7 @@ test("executions share the prepared runtime of an inventory while keeping per-ca }, }, }, - execute: (input, context) => Effect.succeed({ content: `${context.id}:${(input as { value: string }).value}` }), + execute: (input) => Effect.succeed({ content: (input as { value: string }).value }), } const inventory = { tools: new Map([["echo", echo]]) } const codeMode = CodeModeTool.create(inventory, (_, tool, input, context) => execute(tool, input, context), allowAll) @@ -457,14 +480,14 @@ test("executions share the prepared runtime of an inventory while keeping per-ca expect(CodeModeTool.catalog(inventory).tools).toHaveLength(1) expect(results).toEqual( ["first", "second"].map((id) => ({ - output: `${id}:${id}`, + output: id, progress: [{ toolCalls: [{ tool: "echo", status: "running", input: { value: id } }] }], })), ) expect( (await Effect.runPromise(codeMode.execute({ code: 'return await tools.echo({ value: "x" })' }, context))).output .output, - ).toBe("call_execute:x") + ).toBe("x") expect(conversions).toBe(1) await Effect.runPromise( diff --git a/packages/core/test/tool-registry.test.ts b/packages/core/test/tool-registry.test.ts index 2a62821caa4..a0231be18ba 100644 --- a/packages/core/test/tool-registry.test.ts +++ b/packages/core/test/tool-registry.test.ts @@ -962,6 +962,36 @@ describe("Tool", () => { ) }) + it.effect("hooks see one ID per call inside a Code Mode program", () => + Effect.gen(function* () { + const service = yield* Tool.Service + const hooks = yield* PluginHooks.Service + yield* transform(service, { echo: make() }) + const before: string[] = [] + const after: string[] = [] + yield* hooks.register("tool", "execute.before", (event) => + Effect.sync(() => void (event.tool === "echo" && before.push(event.id))), + ) + yield* hooks.register("tool", "execute.after", (event) => + Effect.sync(() => void (event.tool === "echo" && after.push(event.id))), + ) + const snapshot = yield* service.snapshot() + yield* snapshot.execute({ + sessionID, + ...identity, + call: { + type: "tool-call", + id: "call-program", + name: "execute", + input: { code: 'await Promise.all([tools.echo({ text: "a" }), tools.echo({ text: "b" })])' }, + }, + }) + expect(new Set(before).size).toBe(2) + expect(before).not.toContain("call-program") + expect(after.toSorted()).toEqual(before.toSorted()) + }), + ) + it.effect("normalizes image tool output once and drops unresizable images", () => Effect.gen(function* () { const service = yield* Tool.Service