mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 00:03:13 +03:00
fix(core): give each Code Mode call its own ID (#64324)
This commit is contained in:
committed by
GitHub
Unverified
parent
9f807c7777
commit
43406d468d
@@ -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.
|
||||
|
||||
@@ -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<Request | undefined>
|
||||
readonly forSession: (sessionID: SessionSchema.ID) => Effect.Effect<ReadonlyArray<Request>>
|
||||
readonly list: () => Effect.Effect<ReadonlyArray<Request>>
|
||||
/**
|
||||
* 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<void, never, Scope.Scope>
|
||||
}
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/Permission") {}
|
||||
@@ -139,6 +144,7 @@ const layer = Layer.effect(
|
||||
const saved = yield* PermissionSaved.Service
|
||||
const hooks = yield* PluginHooks.Service
|
||||
const pending = new Map<ID, Pending>()
|
||||
const parents = new Map<string, Tool.CallID>()
|
||||
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 })
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Permission } from "@opencode/core/permission"
|
||||
import { Effect, Layer } from "effect"
|
||||
|
||||
export const permissionLayer = (overrides: Partial<Permission.Interface> = {}) =>
|
||||
Layer.mock(Permission.Service, { close: Effect.void, ...overrides })
|
||||
Layer.mock(Permission.Service, { close: Effect.void, nested: () => Effect.void, ...overrides })
|
||||
|
||||
export const permissionService = (overrides: Partial<Permission.Interface> = {}) =>
|
||||
Effect.runSync(
|
||||
|
||||
@@ -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),
|
||||
]),
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -90,6 +90,7 @@ const permissionLayer = Layer.succeed(
|
||||
get: () => Effect.succeed(undefined),
|
||||
forSession: () => Effect.succeed([]),
|
||||
list: () => Effect.succeed([]),
|
||||
nested: () => Effect.void,
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ const permission = Layer.succeed(
|
||||
get: () => Effect.succeed(undefined),
|
||||
forSession: () => Effect.succeed([]),
|
||||
list: () => Effect.succeed([]),
|
||||
nested: () => Effect.void,
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -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<typeof input>
|
||||
await Effect.runPromise(
|
||||
createCodeMode(
|
||||
new Map<string, Info>([["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<unknown>(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(
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user