mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-18 07:12:47 +03:00
feat(plugin): allow tool call repair before lookup (#45453)
This commit is contained in:
committed by
GitHub
Unverified
parent
ff5b5d00f9
commit
e288e0fc4d
@@ -358,15 +358,10 @@ export const layer = Layer.effect(
|
||||
? { webSocket: transport.bind(session.id) }
|
||||
: {}),
|
||||
}
|
||||
const executeTool: Prepared["executeTool"] = (input) => {
|
||||
const tool = hooked.get(input.call.name)
|
||||
// A registered tool absent from the hooked set was removed or renamed by a hook.
|
||||
if (!tool && registry.has(input.call.name))
|
||||
return new Tool.Error({ message: `Tool is not available for this request: ${input.call.name}` })
|
||||
return tools
|
||||
.execute(tool ? { ...input, call: { ...input.call, name: tool.name } } : input)
|
||||
const executeTool: Prepared["executeTool"] = (input) =>
|
||||
tools
|
||||
.execute({ ...input, definitions: hooked })
|
||||
.pipe(Effect.catchCauseFilter(declineDefect, (decline) => Effect.fail(decline)))
|
||||
}
|
||||
return {
|
||||
request,
|
||||
options,
|
||||
|
||||
+32
-26
@@ -49,6 +49,8 @@ export interface Snapshot {
|
||||
readonly messageID: SessionMessage.ID
|
||||
readonly call: ToolCall
|
||||
readonly progress?: (update: Tool.Metadata) => Effect.Effect<void>
|
||||
/** Surviving request definitions, keyed by the names advertised after session context hooks. */
|
||||
readonly definitions?: ReadonlyMap<string, ToolDefinition>
|
||||
}) => Effect.Effect<Tool.Result & { readonly content: ReadonlyArray<Tool.Content> }, Tool.Error>
|
||||
}
|
||||
|
||||
@@ -90,23 +92,23 @@ const layer = Layer.effect(
|
||||
]
|
||||
})
|
||||
|
||||
const beforeExecute = (name: string, input: unknown, context: Tool.Context) =>
|
||||
hooks.trigger("tool", "execute.before", {
|
||||
tool: name,
|
||||
sessionID: context.sessionID,
|
||||
agent: context.agent,
|
||||
messageID: context.messageID,
|
||||
id: context.id,
|
||||
input,
|
||||
})
|
||||
|
||||
const executeTool = Effect.fn("Tool.execute")(function* (
|
||||
tool: Tool.Info,
|
||||
name: string,
|
||||
input: unknown,
|
||||
context: Tool.Context,
|
||||
) {
|
||||
const beforeEvent: PluginHooks.Domains["tool"]["execute.before"] = {
|
||||
tool: name,
|
||||
inputSchema: definition(tool).inputSchema,
|
||||
sessionID: context.sessionID,
|
||||
agent: context.agent,
|
||||
messageID: context.messageID,
|
||||
id: context.id,
|
||||
input,
|
||||
}
|
||||
yield* hooks.trigger("tool", "execute.before", beforeEvent)
|
||||
const execution = yield* execute(tool, beforeEvent.input, context).pipe(
|
||||
const execution = yield* execute(tool, input, context).pipe(
|
||||
Effect.map((value) => ({ value })),
|
||||
Effect.catchTag("Tool.Error", (failure) => Effect.succeed({ failure })),
|
||||
)
|
||||
@@ -116,7 +118,7 @@ const layer = Layer.effect(
|
||||
agent: context.agent,
|
||||
messageID: context.messageID,
|
||||
id: context.id,
|
||||
input: beforeEvent.input,
|
||||
input,
|
||||
}
|
||||
if ("failure" in execution) {
|
||||
const afterEvent: PluginHooks.Domains["tool"]["execute.after"] = {
|
||||
@@ -212,7 +214,11 @@ const layer = Layer.effect(
|
||||
const executeRule = rules.findLast((rule) => Wildcard.match("execute", rule.action))
|
||||
const codemodeEnabled = executeRule?.resource !== "*" || executeRule.effect !== "deny"
|
||||
const codemodeTool = codemodeEnabled
|
||||
? CodeModeTool.create(codemode, (name, tool, input, context) => executeTool(tool, name, input, context))
|
||||
? CodeModeTool.create(codemode, (name, tool, input, context) =>
|
||||
beforeExecute(name, input, context).pipe(
|
||||
Effect.flatMap((event) => executeTool(tool, name, event.input, context)),
|
||||
),
|
||||
)
|
||||
: undefined
|
||||
const codeModeCatalog = codemodeEnabled ? CodeModeTool.catalog(codemode) : undefined
|
||||
return {
|
||||
@@ -223,13 +229,7 @@ const layer = Layer.effect(
|
||||
.map(([, tool]) => definition(tool)),
|
||||
...(codemodeTool ? [definition(codemodeTool)] : []),
|
||||
],
|
||||
execute: (input: {
|
||||
readonly sessionID: SessionSchema.ID
|
||||
readonly agent: Agent.ID
|
||||
readonly messageID: SessionMessage.ID
|
||||
readonly call: ToolCall
|
||||
readonly progress?: (update: Tool.Metadata) => Effect.Effect<void>
|
||||
}) => {
|
||||
execute: Effect.fnUntraced(function* (input: Parameters<Snapshot["execute"]>[0]) {
|
||||
const context: Tool.Context = {
|
||||
sessionID: input.sessionID,
|
||||
agent: input.agent,
|
||||
@@ -237,12 +237,18 @@ const layer = Layer.effect(
|
||||
id: Tool.CallID.make(input.call.id),
|
||||
progress: input.progress ?? (() => Effect.void),
|
||||
}
|
||||
if (input.call.name === "execute" && codemodeTool)
|
||||
return executeTool(codemodeTool, input.call.name, input.call.input, context)
|
||||
const tool = direct.get(input.call.name)
|
||||
if (tool) return executeTool(tool, input.call.name, input.call.input, context)
|
||||
return new Tool.Error({ message: `Unknown tool: ${input.call.name}` })
|
||||
},
|
||||
const event = yield* beforeExecute(input.call.name, input.call.input, context)
|
||||
const requested = input.definitions?.get(event.tool)
|
||||
// Preserve session context removal and alias resolution, now after the repair hook.
|
||||
if (!requested && input.definitions && (direct.has(event.tool) || codemodeTool?.name === event.tool))
|
||||
return yield* new Tool.Error({ message: `Tool is not available for this request: ${event.tool}` })
|
||||
const name = requested?.name ?? event.tool
|
||||
if (name === "execute" && codemodeTool)
|
||||
return yield* executeTool(codemodeTool, name, event.input, context)
|
||||
const tool = direct.get(name)
|
||||
if (tool) return yield* executeTool(tool, name, event.input, context)
|
||||
return yield* new Tool.Error({ message: `Unknown tool: ${name}` })
|
||||
}),
|
||||
}
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -580,7 +580,7 @@ describe("Plugin", () => {
|
||||
const registry = yield* Tool.Service
|
||||
const executed: unknown[] = []
|
||||
const seen: {
|
||||
before?: { input: unknown; inputSchema: unknown }
|
||||
before?: { input: unknown; tool: string }
|
||||
after?: { input: unknown; status: string; content: unknown; metadata: unknown }
|
||||
} = {}
|
||||
|
||||
@@ -605,7 +605,9 @@ describe("Plugin", () => {
|
||||
yield* ctx.tool
|
||||
.hook("execute.before", (event) =>
|
||||
Effect.sync(() => {
|
||||
seen.before = { input: event.input, inputSchema: event.inputSchema }
|
||||
expect(event).not.toHaveProperty("inputSchema")
|
||||
seen.before = { input: event.input, tool: event.tool }
|
||||
event.tool = "echo"
|
||||
event.input = { text: "before-mutated" }
|
||||
}),
|
||||
)
|
||||
@@ -648,17 +650,12 @@ describe("Plugin", () => {
|
||||
sessionID: Session.ID.make("ses_hooks"),
|
||||
agent: Agent.ID.make("build"),
|
||||
messageID: SessionMessage.ID.make("msg_hooks"),
|
||||
call: { type: "tool-call", id: "call-hooks", name: "echo", input: { text: "original" } },
|
||||
call: { type: "tool-call", id: "call-hooks", name: "misspelled", input: { text: "original" } },
|
||||
})
|
||||
|
||||
expect(seen.before).toEqual({
|
||||
input: { text: "original" },
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { text: { type: "string" } },
|
||||
required: ["text"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
tool: "misspelled",
|
||||
})
|
||||
expect(executed).toEqual([{ text: "before-mutated" }])
|
||||
expect(seen.after).toEqual({
|
||||
@@ -712,7 +709,7 @@ describe("Plugin", () => {
|
||||
sessionID: Session.ID.make("ses_hook_reject"),
|
||||
agent: Agent.ID.make("build"),
|
||||
messageID: SessionMessage.ID.make("msg_hook_reject"),
|
||||
call: { type: "tool-call", id: "call-hook-reject", name: "echo", input: { text: "original" } },
|
||||
call: { type: "tool-call", id: "call-hook-reject", name: "missing", input: { text: "original" } },
|
||||
})
|
||||
.pipe(Effect.flip)
|
||||
|
||||
|
||||
@@ -611,6 +611,11 @@ describe("fromPromise", () => {
|
||||
},
|
||||
})
|
||||
})
|
||||
await ctx.tool.hook("execute.before", (event) => {
|
||||
expect(event.tool).toBe("helllo")
|
||||
expect(event).not.toHaveProperty("inputSchema")
|
||||
event.tool = "hello"
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
@@ -624,7 +629,7 @@ describe("fromPromise", () => {
|
||||
agent: Agent.ID.make("build"),
|
||||
messageID: SessionMessage.ID.make("msg_promise_tool"),
|
||||
progress: (update) => Effect.sync(() => progress.push(update)),
|
||||
call: { type: "tool-call", id: "call_promise_tool", name: "hello", input: { name: "world" } },
|
||||
call: { type: "tool-call", id: "call_promise_tool", name: "helllo", input: { name: "world" } },
|
||||
}),
|
||||
).toMatchObject({
|
||||
output: "Hello, world!",
|
||||
|
||||
@@ -6,6 +6,10 @@ import { Image } from "@opencode-ai/core/image"
|
||||
import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { SessionMessage } from "@opencode-ai/core/session/message"
|
||||
import { SessionModelRequest } from "@opencode-ai/core/session/model-request"
|
||||
import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
|
||||
import { LanguageModel } from "@opencode-ai/ai"
|
||||
import { route } from "@opencode-ai/ai/protocols/openai-chat"
|
||||
import { State } from "@opencode-ai/core/state"
|
||||
import { Tool } from "@opencode-ai/core/tool"
|
||||
import type { Info } from "@opencode-ai/schema/tool"
|
||||
@@ -38,7 +42,9 @@ const imageStore = Layer.mock(Image.Service, {
|
||||
})
|
||||
},
|
||||
})
|
||||
const registryLayer = AppNodeBuilder.build(LayerNode.group([Tool.node, PluginHooks.node]), [[Image.node, imageStore]])
|
||||
const registryLayer = AppNodeBuilder.build(LayerNode.group([Tool.node, PluginHooks.node, SessionModelRequest.node]), [
|
||||
[Image.node, imageStore],
|
||||
])
|
||||
const it = testEffect(registryLayer)
|
||||
const identity = {
|
||||
agent: Agent.ID.make("build"),
|
||||
@@ -86,6 +92,116 @@ describe("Tool", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("repairs names and inputs before lookup using the captured request tool set", () =>
|
||||
Effect.gen(function* () {
|
||||
const service = yield* Tool.Service
|
||||
const hooks = yield* PluginHooks.Service
|
||||
yield* transform(service, { echo: constant("captured"), hidden: make() }, { codemode: false })
|
||||
const snapshot = yield* service.snapshot()
|
||||
const modelRequests = yield* SessionModelRequest.Service
|
||||
yield* hooks.register("session", "context", (event) =>
|
||||
Effect.sync(() => {
|
||||
const echo = event.tools.echo
|
||||
if (!echo) throw new Error("Expected echo definition")
|
||||
event.tools.alias = echo
|
||||
delete event.tools.echo
|
||||
delete event.tools.hidden
|
||||
}),
|
||||
)
|
||||
const prepared = yield* modelRequests.prepare({
|
||||
scope: {
|
||||
session: Schema.decodeUnknownSync(Session.Info)({
|
||||
id: sessionID,
|
||||
projectID: "project",
|
||||
location: { directory: "/test" },
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: 0, updated: 0 },
|
||||
}),
|
||||
agentID: identity.agent,
|
||||
model: SessionRunnerModel.resolved(LanguageModel.make({ id: "test", provider: "test", route }), {
|
||||
capabilities: { tools: true, input: ["text"], output: ["text"] },
|
||||
cost: [],
|
||||
limit: { context: 200_000, output: 32_000 },
|
||||
}),
|
||||
tools: snapshot,
|
||||
},
|
||||
transcript: { system: [], messages: [] },
|
||||
})
|
||||
expect(prepared.request.tools.map((tool) => tool.name)).toEqual(["execute", "alias"])
|
||||
yield* transform(service, { echo: constant("new") }, { codemode: false })
|
||||
const before: string[] = []
|
||||
const after: string[] = []
|
||||
yield* hooks.register("tool", "execute.before", (event) =>
|
||||
Effect.sync(() => {
|
||||
expect(event).not.toHaveProperty("inputSchema")
|
||||
before.push(event.tool)
|
||||
event.tool = event.tool === "typo" ? "alias" : event.tool
|
||||
event.input = { text: "corrected" }
|
||||
}),
|
||||
)
|
||||
yield* hooks.register("tool", "execute.after", (event) =>
|
||||
Effect.sync(() => {
|
||||
after.push(event.tool)
|
||||
expect(event.input).toEqual({ text: "corrected" })
|
||||
}),
|
||||
)
|
||||
expect((yield* prepared.executeTool(call("typo"))).output).toEqual({ text: "captured" })
|
||||
expect(before).toEqual(["typo"])
|
||||
expect(after).toEqual(["echo"])
|
||||
expect(yield* prepared.executeTool(call("hidden")).pipe(Effect.flip)).toMatchObject({
|
||||
message: "Tool is not available for this request: hidden",
|
||||
})
|
||||
expect(yield* prepared.executeTool(call("echo")).pipe(Effect.flip)).toMatchObject({
|
||||
message: "Tool is not available for this request: echo",
|
||||
})
|
||||
expect(yield* prepared.executeTool(call("missing")).pipe(Effect.flip)).toMatchObject({
|
||||
message: "Unknown tool: missing",
|
||||
})
|
||||
expect(before).toEqual(["typo", "hidden", "echo", "missing"])
|
||||
expect(after).toEqual(["echo"])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("hooks execute and known Code Mode calls once but leaves unknown interpreter paths unchanged", () =>
|
||||
Effect.gen(function* () {
|
||||
const service = yield* Tool.Service
|
||||
const hooks = yield* PluginHooks.Service
|
||||
yield* transform(service, { echo: make() })
|
||||
const seen: string[] = []
|
||||
yield* hooks.register("tool", "execute.before", (event) =>
|
||||
Effect.sync(() => {
|
||||
seen.push(event.tool)
|
||||
expect(event).not.toHaveProperty("inputSchema")
|
||||
if (event.tool === "run_code") event.tool = "execute"
|
||||
}),
|
||||
)
|
||||
const snapshot = yield* service.snapshot()
|
||||
const known = yield* snapshot.execute({
|
||||
...call("run_code"),
|
||||
call: {
|
||||
type: "tool-call",
|
||||
id: "known",
|
||||
name: "run_code",
|
||||
input: { code: 'return await tools.echo({ text: "hello" })' },
|
||||
},
|
||||
})
|
||||
expect(known.output).toMatchObject({ output: '{\n "text": "hello"\n}' })
|
||||
expect(seen).toEqual(["run_code", "echo"])
|
||||
const unknown = yield* snapshot.execute({
|
||||
...call("execute"),
|
||||
call: {
|
||||
type: "tool-call",
|
||||
id: "unknown",
|
||||
name: "execute",
|
||||
input: { code: "return await tools.missing({})" },
|
||||
},
|
||||
})
|
||||
expect(unknown.output).toMatchObject({ error: true })
|
||||
expect(seen).toEqual(["run_code", "echo", "execute"])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("replays mutations on refreshed sources and restores tools on disposal and scope cleanup", () =>
|
||||
Effect.gen(function* () {
|
||||
const service = yield* Tool.Service
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Tool } from "@opencode-ai/schema/tool"
|
||||
import type { Agent } from "@opencode-ai/schema/agent"
|
||||
import type { Session } from "@opencode-ai/schema/session"
|
||||
import type { SessionMessage } from "@opencode-ai/schema/session-message"
|
||||
import type { Effect, JsonSchema, Types } from "effect"
|
||||
import type { Effect, Types } from "effect"
|
||||
import type { Hooks, Transform } from "./registration.js"
|
||||
|
||||
export interface ToolDraft {
|
||||
@@ -18,8 +18,7 @@ export interface ToolDraft {
|
||||
|
||||
export interface ToolHooks {
|
||||
readonly "execute.before": {
|
||||
readonly tool: string
|
||||
readonly inputSchema: JsonSchema.JsonSchema
|
||||
tool: string
|
||||
readonly sessionID: Session.ID
|
||||
readonly agent: Agent.ID
|
||||
readonly messageID: SessionMessage.ID
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Tool } from "@opencode-ai/schema/tool"
|
||||
import type { Agent } from "@opencode-ai/schema/agent"
|
||||
import type { Session } from "@opencode-ai/schema/session"
|
||||
import type { SessionMessage } from "@opencode-ai/schema/session-message"
|
||||
import type { JsonSchema, Types } from "effect"
|
||||
import type { Types } from "effect"
|
||||
import type { Hooks, Transform } from "./registration.js"
|
||||
|
||||
export interface ToolContext extends Omit<Tool.Context, "progress"> {
|
||||
@@ -35,8 +35,7 @@ interface ToolDraft {
|
||||
|
||||
interface ToolHooks {
|
||||
readonly "execute.before": {
|
||||
readonly tool: string
|
||||
readonly inputSchema: JsonSchema.JsonSchema
|
||||
tool: string
|
||||
readonly sessionID: Session.ID
|
||||
readonly agent: Agent.ID
|
||||
readonly messageID: SessionMessage.ID
|
||||
|
||||
Reference in New Issue
Block a user