diff --git a/packages/core/src/automation/code.ts b/packages/core/src/automation/code.ts index a8fab6789f1..fbebf720b53 100644 --- a/packages/core/src/automation/code.ts +++ b/packages/core/src/automation/code.ts @@ -11,6 +11,7 @@ import type { SessionMessage } from "../session/message.js" import type { SessionSchema } from "../session/schema.js" import { Tool } from "../tool.js" import { McpTool } from "../tool/mcp.js" +import { defaultCodeMode } from "../tool/runtime.js" import { Wildcard } from "../util/wildcard.js" import { type Invocation, matchesAuthor } from "./author.js" import type { AutomationEvent } from "./event.js" @@ -134,9 +135,7 @@ const resolveTools = Effect.fnUntraced(function* (paths: ReadonlyArray) const registered = yield* tools.list() const actions = new Set() for (const path of paths) { - const found = registered.find( - (item) => item.options?.codemode !== false && CodeModeTool.qualifiedName(item) === path, - ) + const found = registered.find((item) => defaultCodeMode(item) && CodeModeTool.qualifiedName(item) === path) if (!found) return yield* Effect.fail(`Unknown Code Mode tool: ${path}`) actions.add(found.options?.permission ?? found.id) } diff --git a/packages/core/src/codemode/instructions.ts b/packages/core/src/codemode/instructions.ts index d368e12ac51..ec2c3c50741 100644 --- a/packages/core/src/codemode/instructions.ts +++ b/packages/core/src/codemode/instructions.ts @@ -158,7 +158,8 @@ export const make = (inventory?: CodeModeCatalog.Inventory): Instructions.List = // Rendered once, against the inventory that produced `current`, and stored with the update. changed: (previous, current) => update(previous, current, inventory === undefined ? () => undefined : CodeModeCatalog.lookup(inventory)), - removed: () => "Code Mode tools are no longer available. Do not use any previously listed Code Mode tools.", + removed: () => + "The `execute` tool is no longer available. Permitted tools are now available as direct tool calls.", }, }) } diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index 4534660baa1..6df923a6f75 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -163,6 +163,7 @@ export const create = ( const executed = yield* executeTool(name, tool, input, { ...context, id, + codemode: true, // 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. @@ -258,12 +259,14 @@ function progressHooks(record: (update: (items: Array) => Array { + const codemode = registration.options?.codemode + const pinned = typeof codemode === "object" && codemode !== null ? codemode.pinned : undefined + return (pinned ?? registration.options?.pinned) === true +} + export const catalog = (inventory: Inventory) => { - const pinned = new Set( - Array.from(inventory.tools.values()) - .filter((registration) => registration.options?.pinned === true) - .map(qualifiedName), - ) + const pinned = new Set(Array.from(inventory.tools.values()).filter(isPinned).map(qualifiedName)) const root: CatalogNode = { children: new Map() } for (const namespace of inventory.namespaces?.values() ?? []) getNode(root, namespace.name).namespace = namespace for (const tool of runtime(inventory).catalog) @@ -353,7 +356,7 @@ function inventoryTools(inventory: Inventory) { const root: ToolNode = { children: new Map() } for (const namespace of inventory.namespaces?.values() ?? []) getNode(root, namespace.name).namespace = namespace for (const [name, registration] of inventory.tools) { - const child = definition(registration) + const child = definition(registration, true) getNode(root, qualifiedName(registration)).tool = Tool.make({ description: child.description, input: child.inputSchema, diff --git a/packages/core/src/mcp/instructions.ts b/packages/core/src/mcp/instructions.ts index d8d0871f4b4..0c5733c0335 100644 --- a/packages/core/src/mcp/instructions.ts +++ b/packages/core/src/mcp/instructions.ts @@ -2,8 +2,10 @@ export * as McpInstructions from "./instructions.js" import { makeLocationNode } from "@opencode/util/effect/app-node" import { Context, Effect, Layer, Schema } from "effect" -import { Permission } from "../permission.js" +import type { CodeModeCatalog } from "../codemode/catalog.js" +import type { Tool } from "../tool.js" import { McpTool } from "../tool/mcp.js" +import { normalizedName } from "../tool/runtime.js" import { Mcp } from "./index.js" import { Instructions } from "../instructions/index.js" @@ -42,9 +44,19 @@ const update = Instructions.listUpdate({ }, }) +function catalogPaths( + items: ReadonlyArray, + prefix = "", +): ReadonlyArray { + return items.flatMap((item) => { + const path = prefix ? `${prefix}.${item.name}` : item.name + return item.type === "tool" ? [path] : catalogPaths(item.tools, path) + }) +} + export interface Interface { - /** Lists server instructions reachable under the given ruleset; callers pass the merged agent and Session permissions. */ - readonly load: (permissions: Permission.Ruleset) => Effect.Effect + /** Lists instructions for MCP servers that have at least one tool in the Session's tool snapshot. */ + readonly load: (tools: Pick) => Effect.Effect } export class Service extends Context.Service()("@opencode/McpInstructions") {} @@ -55,7 +67,7 @@ export const layer = Layer.effect( const mcp = yield* Mcp.Service return Service.of({ - load: Effect.fn("McpInstructions.load")(function* (permissions) { + load: Effect.fn("McpInstructions.load")(function* (snapshot) { const source = (value: ReadonlyArray | Instructions.Removed) => Instructions.make>({ key: Instructions.Key.make("core/mcp-guidance"), @@ -70,22 +82,18 @@ export const layer = Layer.effect( const [instructions, tools] = yield* Effect.all([mcp.instructions(), mcp.tools()], { concurrency: "unbounded", }) - const canExecute = Permission.evaluate("execute", "*", permissions).effect !== "deny" + const direct = new Set(snapshot.definitions.map((tool) => tool.name)) + const codemode = new Set(snapshot.codeModeCatalog ? catalogPaths(snapshot.codeModeCatalog.tools) : []) // Instructions are useful only when this Session can reach at least one server tool. const visible = instructions .flatMap((item) => { + const namespace = McpTool.namespace(item.server) const owned = tools.filter((tool) => tool.server === item.server) - // Without execute, Code Mode server tools are exposed directly. - const codemode = canExecute && owned[0]?.codemode !== false - if ( - !owned.some( - (tool) => - Permission.evaluate(McpTool.name(tool.server, tool.name), "*", permissions).effect !== "deny", - ) - ) - return [] + const inCodeMode = owned.some((tool) => codemode.has(`${namespace}.${normalizedName({ name: tool.name })}`)) + const inDirect = owned.some((tool) => direct.has(McpTool.name(item.server, tool.name))) + if (!inCodeMode && !inDirect) return [] return [ - codemode + inCodeMode ? { server: item.server, instructions: item.instructions } : { server: item.server, instructions: item.instructions, codemode: false as const }, ] diff --git a/packages/core/src/plugin/internal.ts b/packages/core/src/plugin/internal.ts index 988343b8189..68cf5437b23 100644 --- a/packages/core/src/plugin/internal.ts +++ b/packages/core/src/plugin/internal.ts @@ -262,7 +262,6 @@ const pre = [ ...ProviderPlugins, ...WebSearchPlugins, PatchTool.Plugin, - // Render model prompts after the patch plugin selects the available editing tools. ...OptimizePlugin.Plugins, VerbosityPlugin.Plugin, IdentityPlugin.Plugin, diff --git a/packages/core/src/plugin/optimize.ts b/packages/core/src/plugin/optimize.ts index 10c2d063a05..8dabad0484e 100644 --- a/packages/core/src/plugin/optimize.ts +++ b/packages/core/src/plugin/optimize.ts @@ -29,25 +29,6 @@ export const AnthropicPlugin = make( "append", ) -// Both OpenAIToolsPlugin and AnthropicToolsPlugin are disabled intentionally until we can figure out a good ux for displaying -// heavy grep/glob usage done via shell or other mechanisms - -export const OpenAIToolsPlugin = make("opencode.optimize.openai.tools", (model, tools) => { - const ids = [model.id, model.modelID, model.family].join(" ").toLowerCase() - if (!ids.includes("gpt")) return undefined - delete tools.grep - delete tools.glob - return undefined -}) - -export const AnthropicToolsPlugin = make("opencode.optimize.anthropic.tools", (model, tools) => { - const ids = [model.id, model.modelID, model.family].join(" ").toLowerCase() - if (!ids.includes("claude")) return undefined - delete tools.grep - delete tools.glob - return undefined -}) - export const KimiPlugin = make("opencode.prompt.kimi", (model) => model.id.toLowerCase().includes("kimi") ? PROMPT_KIMI : undefined, ) @@ -77,7 +58,7 @@ export const resolveModel = (ctx: Context, event: SessionHooks["context"]) => function make( id: string, - optimize: (model: Model.Info, tools: SessionHooks["context"]["tools"]) => string | undefined, + optimize: (model: Model.Info) => string | undefined, mode: "override" | "append" = "override", ) { return define({ @@ -86,8 +67,7 @@ function make( const hook = (event: SessionHooks["context"]) => Effect.gen(function* () { const model = yield* resolveModel(ctx, event) - // Curate tools before rendering their guidance, including for agents with a custom system prompt. - const template = optimize(model, event.tools) + const template = optimize(model) if (!template) return if ((yield* ctx.agent.get({ agentID: event.agent })).data.system) return const system = event.system[0] diff --git a/packages/core/src/plugin/provider/opencode-watches.ts b/packages/core/src/plugin/provider/opencode-watches.ts index e951b475831..ad8b34bddb3 100644 --- a/packages/core/src/plugin/provider/opencode-watches.ts +++ b/packages/core/src/plugin/provider/opencode-watches.ts @@ -282,7 +282,7 @@ export const make = Effect.fnUntraced(function* (ctx: Context, http: HttpClient. ), }), output: Watch, - options: { namespace, codemode: true, pinned: true }, + options: { namespace, codemode: { pinned: true } }, execute: (input, context) => Effect.gen(function* () { // A link or shorthand, or one event type of a server with its arguments; never both. diff --git a/packages/core/src/plugin/tool-input-repair.ts b/packages/core/src/plugin/tool-input-repair.ts index c2e1f03b362..e9532b08bcb 100644 --- a/packages/core/src/plugin/tool-input-repair.ts +++ b/packages/core/src/plugin/tool-input-repair.ts @@ -30,20 +30,19 @@ export const Plugin = define({ const aliased = new Map() yield* ctx.tool.hook("execute.before", (event) => Effect.gen(function* () { - // The outer Code Mode tool is built per snapshot rather than registered, so it cannot be - // looked up here. Its `{ code }` input is trivial; the tools it calls are repaired normally. + // The outer Code Mode tool is built per snapshot rather than registered; its `{ code }` + // input is trivial, and the tools it calls are repaired normally. if (event.tool === "execute") return - const tools = yield* ctx.tool.list() - const alias = aliases.get(event.tool) - const tool = - tools.find((tool) => tool.id === event.tool) ?? - (alias === undefined ? undefined : tools.find((tool) => tool.id === alias)) + const alias = event.info ? undefined : aliases.get(event.tool) + const aliasedTool = + alias === undefined ? undefined : (yield* ctx.tool.list()).find((tool) => tool.id === alias) + const tool = event.info ?? aliasedTool if (!tool) return - if (tool.id !== event.tool) { + if (aliasedTool) { aliased.set(event.id, event.tool) - event.tool = tool.id + event.tool = aliasedTool.id } - const schema = definition(tool).inputSchema + const schema = definition(tool, event.codemode).inputSchema if (schema.type !== "object") return event.input = repair(event.input, schema, schema, 0) }), diff --git a/packages/core/src/session/context.ts b/packages/core/src/session/context.ts index bd55a9a06aa..76633c2e7bd 100644 --- a/packages/core/src/session/context.ts +++ b/packages/core/src/session/context.ts @@ -12,6 +12,7 @@ import { Environment } from "../environment/index.js" import { FileAccess } from "../file-access.js" import { FileMutation } from "../file-mutation.js" import { FileWrite } from "../file-write.js" +import { Flag } from "../flag.js" import { makeLocationNode } from "@opencode/util/effect/app-node" import { InstructionDiscovery } from "../instruction-discovery.js" import { Instructions } from "../instructions/index.js" @@ -22,6 +23,8 @@ import { McpTool } from "../tool/mcp.js" import { ReferenceInstructions } from "../reference/instructions.js" import { SkillInstructions } from "../skill/instructions.js" import { Tool } from "../tool.js" +import { modelTools } from "../tool/model-policy.js" +import { WebSearch } from "../websearch.js" import { AgentNotFoundError } from "./error.js" import { SessionHistory } from "./history.js" import { InstructionEntry } from "./instruction-entry.js" @@ -86,6 +89,7 @@ const layer = Layer.effect( const db = (yield* Database.Service).db const discovery = yield* InstructionDiscovery.Service const entries = yield* InstructionEntry.Service + const flags = yield* Flag.Service const location = yield* Location.Service const mcpInstructions = yield* McpInstructions.Service const mcpTools = yield* McpTool.Service @@ -95,7 +99,8 @@ const layer = Layer.effect( const skillInstructions = yield* SkillInstructions.Service const store = yield* SessionStore.Service const registry = yield* Tool.Service - const codeMode = yield* CodeModeTool.services + const services = yield* CodeModeTool.services + const websearch = yield* WebSearch.Service const resolveModel = ( session: SessionSchema.Info, @@ -150,14 +155,27 @@ const layer = Layer.effect( if (!agent.info) return yield* new AgentNotFoundError({ sessionID: session.id, agent: session.agent ?? agent.id }) // Session permissions narrow discovery the same way they narrow the tool snapshot. const permissions = Permission.merge(agent.info.permissions, session.permissions ?? []) + const [selected, hasWebSearch, fullCodeMode] = yield* Effect.all( + [ + models.select(session, model.available).pipe(Effect.orElseSucceed(() => undefined)), + websearch.available(), + flags.enabled("full_codemode"), + ], + { concurrency: "unbounded" }, + ) + const fallbackRef = session.model ?? agent.info.model + const policyModel = selected?.info ?? (fallbackRef && Model.Info.default(fallbackRef.providerID, fallbackRef.id)) + const tools = yield* registry.snapshot(permissions, { + services, + tools: modelTools({ model: policyModel, websearch: hasWebSearch, fullCodeMode }), + }) const loaded = yield* Effect.all( { - tools: registry.snapshot(permissions, codeMode), builtins: builtins.load(), discovery: discovery.load(), skills: skillInstructions.load(permissions), references: referenceInstructions.load(), - mcp: mcpInstructions.load(permissions), + mcp: mcpInstructions.load(tools), entries: entries.load(sessionID), }, { concurrency: "unbounded" }, @@ -169,7 +187,7 @@ const layer = Layer.effect( // prompt-cache prefix: user-level catalog and guidance, then project instructions, then // the date and environment, which vary by day and directory. instructions: Instructions.combine([ - CodeModeInstructions.make(loaded.tools.codeModeCatalog), + CodeModeInstructions.make(tools.codeModeCatalog), loaded.mcp, loaded.references, loaded.skills, @@ -177,7 +195,7 @@ const layer = Layer.effect( loaded.builtins, loaded.entries, ]), - tools: loaded.tools, + tools, } }) @@ -229,6 +247,7 @@ export const node = makeLocationNode({ FileAccess.node, FileMutation.node, FileWrite.node, + Flag.node, InstructionBuiltIns.node, InstructionDiscovery.node, InstructionEntry.node, @@ -241,5 +260,6 @@ export const node = makeLocationNode({ SessionStore.node, SkillInstructions.node, Tool.node, + WebSearch.node, ], }) diff --git a/packages/core/src/session/runner/model.ts b/packages/core/src/session/runner/model.ts index 918b20680bc..c725cba6429 100644 --- a/packages/core/src/session/runner/model.ts +++ b/packages/core/src/session/runner/model.ts @@ -36,6 +36,13 @@ export type Error = ModelNotSelectedError | ModelUnavailableError | ModelResolve export type Resolved = ModelResolver.Resolved export interface Interface { + readonly select: ( + session: SessionSchema.Info, + available: () => Effect.Effect>, + ) => Effect.Effect< + { readonly info: Model.Info; readonly variant: Model.VariantID | undefined }, + ModelNotSelectedError | ModelUnavailableError + > /** Availability is sampled lazily for each explicitly selected model resolution. */ readonly resolve: ( session: SessionSchema.Info, @@ -99,6 +106,7 @@ const layer = Layer.effect( return yield* new ModelNotSelectedError({ sessionID: session.id }) }) return Service.of({ + select, resolve: Effect.fn("SessionRunnerModel.resolve")(function* (session, available, request) { const selected = yield* select(session, available) const ref = Model.Ref.make({ diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index a8e586a9d66..e31f047ed0b 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -1,10 +1,11 @@ export * as Tool from "./tool.js" export { CallID, Content, Error, FileContent, TextContent } from "@opencode/schema/tool" -export type { Context, Metadata, Namespace, Options, Result } from "@opencode/schema/tool" +export type { Context, Info, Metadata, Namespace, Options, Result } from "@opencode/schema/tool" import { ToolDefinition, type ToolCall } from "@opencode/ai/effect" import type { CodeMode } from "@opencode/codemode" import { Tool } from "@opencode/schema/tool" +import { isRecord } from "@opencode/util/record" import { Context, Effect, Layer, Ref, Result, Schema, SchemaIssue, Types } from "effect" import { makeLocationNode } from "@opencode/util/effect/app-node" import type { Agent } from "./agent.js" @@ -18,7 +19,14 @@ import { PluginHooks } from "./plugin/hooks.js" import { SessionMessage } from "./session/message.js" import { SessionSchema } from "./session/schema.js" import { State } from "./state.js" -import { definition, effectiveName, execute, normalizedName, normalizeContent } from "./tool/runtime.js" +import { + defaultCodeMode, + definition, + effectiveName, + execute, + normalizedName, + normalizeContent, +} from "./tool/runtime.js" import { Wildcard } from "./util/wildcard.js" export class RegistrationError extends Schema.TaggedError()("Tool.RegistrationError", { @@ -26,33 +34,49 @@ export class RegistrationError extends Schema.TaggedError()(" message: Schema.String, }) {} +type RegisteredTool = Tool.Info & { readonly id: string } + export interface Editor { - readonly list: () => readonly (Tool.Info & { readonly id: string })[] - readonly get: (id: string) => (Tool.Info & { readonly id: string }) | undefined + readonly list: () => readonly RegisteredTool[] + readonly get: (id: string) => RegisteredTool | undefined readonly namespace: (namespace: Tool.Namespace) => void - readonly add: (tool: Tool.Info) => void + readonly add: < + Input extends Tool.ValueSchema = Tool.ValueSchema, + Output extends Tool.ValueSchema | undefined = undefined, + CMInput extends Tool.ValueSchema = Input, + CMOutput extends Tool.ValueSchema | undefined = Output, + >( + tool: Tool.Info, + ) => void readonly update: (id: string, update: (tool: Types.Mutable) => void) => void readonly remove: (id: string) => void } type Data = { - tools: Map + tools: Map // Converted once at registration; schemas cannot change without re-registering the tool. definitions: Map namespaces: Map errors: { kind: "tool" | "namespace"; name: string; namespace?: string; error: RegistrationError }[] } -export interface Interface extends State.Transformable { - readonly list: () => Effect.Effect> +export interface Policy { + readonly hidden?: ReadonlySet + readonly direct?: ReadonlySet +} + +export interface SnapshotOptions { /** - * With `full_codemode`, Code Mode gets the experimental `path` and `Bun` globals, which act through `codeMode`: the + * With `full_codemode`, Code Mode gets the experimental `path` and `Bun` globals, which act through `services`: the * session's Location and file services. */ - readonly snapshot: ( - permissions?: Permission.Ruleset, - codeMode?: Context.Context, - ) => Effect.Effect + readonly services?: Context.Context + readonly tools?: Policy +} + +export interface Interface extends State.Transformable { + readonly list: () => Effect.Effect> + readonly snapshot: (permissions?: Permission.Ruleset, options?: SnapshotOptions) => Effect.Effect /** * Runs a Code Mode program with no model step over only the Code Mode tools named in `tools` (still subject to * whole-tool permission filtering and each tool's own executor policy), with no `fetch`. @@ -130,9 +154,11 @@ const layer = Layer.effect( ] }) - const beforeExecute = (name: string, input: unknown, context: Tool.Context) => + const beforeExecute = (name: string, info: Tool.Info | undefined, input: unknown, context: Tool.Context) => hooks.trigger("tool", "execute.before", { tool: name, + ...(info === undefined ? {} : { info }), + codemode: context.codemode === true, sessionID: context.sessionID, agent: context.agent, messageID: context.messageID, @@ -158,6 +184,8 @@ const layer = Layer.effect( ) const base = { tool: name, + info: tool, + codemode: context.codemode === true, sessionID: context.sessionID, agent: context.agent, messageID: context.messageID, @@ -199,22 +227,19 @@ const layer = Layer.effect( input: unknown, context: Tool.Context, ) { - const event = yield* beforeExecute(name, input, context) + const event = yield* beforeExecute(name, tool, input, context) const selected = event.tool === name ? tool : tools.get(event.tool) if (!selected) return yield* new Tool.Error({ message: `Tool is not available for this request: ${event.tool}` }) return yield* executeTool(selected, event.tool, event.input, context) }) - let catalog: - | { - data: Data - names: string - full: boolean - inventory: CodeModeTool.Inventory - value: CodeModeCatalog.Inventory - definition: ToolDefinition - } - | undefined + type CachedCatalog = { + readonly inventory: CodeModeTool.Inventory + readonly value: CodeModeCatalog.Inventory + readonly definition: ToolDefinition + } + let catalogData: Data | undefined + const catalogs = new Map() const state = State.create({ name: "tool", initial: () => ({ @@ -236,18 +261,21 @@ const layer = Layer.effect( }, add: (tool) => { const id = effectiveName(tool) - commit(editor, id, { ...tool, id, options: tool.options && { ...tool.options } }) + commit(editor, id, { ...tool, id }) }, update: (id, update) => { const current = editor.tools.get(id) if (!current) return - const tool = { ...current, options: current.options && { ...current.options } } - update(tool) - tool.name = current.name - tool.id = id - if (tool.options?.namespace !== current.options?.namespace) - tool.options = { ...tool.options, namespace: current.options?.namespace } - commit(editor, id, tool) + const draft: Types.Mutable = { + ...current, + options: cloneOptions(current.options), + } + update(draft) + draft.name = current.name + draft.id = id + if (draft.options?.namespace !== current.options?.namespace) + draft.options = { ...draft.options, namespace: current.options?.namespace } + commit(editor, id, draft) }, remove: (id) => { editor.tools.delete(id) @@ -255,7 +283,8 @@ const layer = Layer.effect( }, }), notify: (value) => { - catalog = undefined + catalogData = undefined + catalogs.clear() return Effect.forEach( value.errors, ({ kind, name, namespace, error }) => @@ -273,57 +302,73 @@ const layer = Layer.effect( transform: state.transform, reload: state.reload, list: () => Effect.sync(() => Array.from(state.get().tools.values())), - snapshot: Effect.fn("Tool.snapshot")((permissions, codeMode) => - Effect.map(flags.enabled("full_codemode"), (enabled) => { - const full = enabled && codeMode !== undefined - const data = state.get() - const active = new Map() + snapshot: Effect.fn("Tool.snapshot")((permissions, options) => + Effect.gen(function* () { const rules = permissions ?? [] - for (const [name, tool] of data.tools) { - if (whollyDisabled(tool.options?.permission ?? name, rules)) continue - active.set(name, tool) - } - const codeModeEnabled = !whollyDisabled("execute", rules) // Without Code Mode its tools would be unreachable, so expose them as direct tools instead. - const direct = codeModeEnabled - ? new Map(Array.from(active).filter(([, tool]) => tool.options?.codemode === false)) - : active - const codeModeTools = new Map(Array.from(active).filter(([, tool]) => tool.options?.codemode !== false)) - const names = Array.from(codeModeTools.keys()).join("\0") - // Discovery is immutable for a registry revision and visible tool set. Keep executors - // fresh, but share the inventory, whose prepared runtime and much larger rendered catalog - // are cached by identity, and the execute tool's definition across steps. - const cached = - catalog?.data === data && catalog.names === names && catalog.full === full ? catalog : undefined - const codeModeInventory = cached?.inventory ?? { tools: codeModeTools, namespaces: data.namespaces } - const codeModeTool = codeModeEnabled - ? CodeModeTool.create( - codeModeInventory, - (name, tool, input, context) => run(codeModeInventory.tools, tool, name, input, context), - permission, - full ? codeMode : undefined, - ) - : undefined - const codeModeCatalog = !codeModeEnabled - ? undefined - : (cached?.value ?? CodeModeTool.catalog(codeModeInventory)) - const codeModeDefinition = codeModeTool && (cached?.definition ?? definition(codeModeTool)) - if (codeModeCatalog && codeModeDefinition) - catalog = { - data, - names, - full, - inventory: codeModeInventory, - value: codeModeCatalog, - definition: codeModeDefinition, + const codeModeEnabled = !whollyDisabled("execute", rules) + const full = codeModeEnabled && options?.services !== undefined && (yield* flags.enabled("full_codemode")) + const data = state.get() + if (catalogData !== data) { + catalogData = data + catalogs.clear() + } + const hidden = options?.tools?.hidden + const keepDirect = options?.tools?.direct + const direct = new Map() + const codemodeEntries: Array<[string, Tool.Info]> = [] + for (const [name, tool] of data.tools) { + if (hidden?.has(name)) continue + if (whollyDisabled(tool.options?.permission ?? name, rules)) continue + if (codeModeEnabled && defaultCodeMode(tool) && !keepDirect?.has(name)) { + codemodeEntries.push([name, tool]) + continue } + direct.set(name, tool) + } + const codemode = !codeModeEnabled + ? undefined + : (() => { + const key = `${full ? "1" : "0"}\0${codemodeEntries.map(([name]) => name).join("\0")}` + // Discovery is immutable for a registry revision and visible tool set. Keep executors + // fresh, but share the inventory, whose prepared runtime and much larger rendered catalog + // are cached by identity, and the execute tool's definition across steps. + const cached = catalogs.get(key) + if (cached) { + catalogs.delete(key) + catalogs.set(key, cached) + } + const inventory = cached?.inventory ?? { + tools: new Map(codemodeEntries), + namespaces: data.namespaces, + } + const tool = CodeModeTool.create( + inventory, + (name, item, input, context) => run(inventory.tools, item, name, input, context), + permission, + full ? options.services : undefined, + ) + const entry = cached ?? { + inventory, + value: CodeModeTool.catalog(inventory), + definition: definition(tool), + } + if (!cached) { + if (catalogs.size >= CATALOG_CACHE_LIMIT) { + const oldest = catalogs.keys().next().value + if (oldest !== undefined) catalogs.delete(oldest) + } + catalogs.set(key, entry) + } + return { tool, catalog: entry.value, definition: entry.definition } + })() return { - ...(codeModeCatalog === undefined ? {} : { codeModeCatalog }), + ...(codemode === undefined ? {} : { codeModeCatalog: codemode.catalog }), definitions: [ ...Array.from(direct) .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) .map(([name]) => data.definitions.get(name)!), - ...(codeModeDefinition ? [codeModeDefinition] : []), + ...(codemode ? [codemode.definition] : []), ], execute: Effect.fnUntraced(function* (input: Parameters[0]) { const context: Tool.Context = { @@ -334,14 +379,16 @@ const layer = Layer.effect( progress: input.progress ?? (() => Effect.void), cancel: input.cancel, } - const event = yield* beforeExecute(input.call.name, input.call.input, context) + const initialName = input.definitions?.get(input.call.name)?.name ?? input.call.name + const initial = initialName === "execute" && codemode ? codemode.tool : direct.get(initialName) + const event = yield* beforeExecute(input.call.name, initial, 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)) + if (!requested && input.definitions && (direct.has(event.tool) || codemode?.tool.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) { - const run = (ctx: Tool.Context) => executeTool(codeModeTool, name, event.input, ctx) + if (name === "execute" && codemode) { + const run = (ctx: Tool.Context) => executeTool(codemode.tool, name, event.input, ctx) const background = yield* CodeModeJob.Current return yield* background ? background(context, run) : run(context) } @@ -367,7 +414,7 @@ const layer = Layer.effect( const tools = new Map( Array.from(data.tools).filter( ([name, tool]) => - tool.options?.codemode !== false && + defaultCodeMode(tool) && allowed.has(CodeModeTool.qualifiedName(tool)) && !whollyDisabled(tool.options?.permission ?? name, input.permissions), ), @@ -384,6 +431,7 @@ const layer = Layer.effect( const context: Tool.Context = { ...input.context, id: Tool.CallID.make(`call_${input.context.messageID}_${index}`), + codemode: true, } return yield* run(tools, tool, name, toolInput, context) }), @@ -393,11 +441,21 @@ const layer = Layer.effect( }), ) +const cloneOptions = (options: Tool.Options | undefined): Tool.Options | undefined => + options && { + ...options, + ...(isRecord(options.codemode) ? { codemode: { ...options.codemode } } : {}), + } + /** Store a valid tool under its effective name, or record why it was skipped. */ -function commit(editor: Data, id: string, input: Tool.Info & { readonly id: string }) { +function commit(editor: Data, id: string, input: RegisteredTool) { // JavaScript plugins may leave out `input` for a tool that takes none. - const tool = input.input === undefined || input.input === null ? { ...input, input: {} } : input - const registered = register(tool) + const tool = { + ...input, + input: input.input === undefined || input.input === null ? {} : input.input, + options: cloneOptions(input.options), + } + const registered = register(id, tool) if (Result.isFailure(registered)) { editor.errors.push({ kind: "tool", @@ -416,6 +474,8 @@ const whollyDisabled = (action: string, rules: Permission.Ruleset) => { return rule?.resource === "*" && rule.effect === "deny" } +const CATALOG_CACHE_LIMIT = 5 + const formatSchemaIssue = SchemaIssue.makeFormatterDefault() function schemaMakeError(error: unknown) { @@ -423,7 +483,9 @@ function schemaMakeError(error: unknown) { return error instanceof Error ? error.message : String(error) } -function register(tool: Tool.Info): Result.Result { +const isSchemaValue = (value: unknown) => (typeof value === "object" && value !== null) || typeof value === "function" + +function register(id: string, tool: Tool.Info): Result.Result { const namespace = tool.options?.namespace if (namespace !== undefined) { const error = namespaceError(namespace) @@ -432,19 +494,39 @@ function register(tool: Tool.Info): Result.Result ToolDefinition.make(definition(tool)), catch: (error) => new RegistrationError({ name: id, message: `Invalid tool definition ${id}: ${schemaMakeError(error)}` }), }) + if (Result.isFailure(direct)) return Result.fail(direct.failure) + const codemode = tool.options?.codemode + if (codemode === undefined || typeof codemode === "boolean") return direct + if (!isRecord(codemode)) + return Result.fail( + new RegistrationError({ + name: id, + message: `Invalid tool definition ${id}: options.codemode must be a boolean or object`, + }), + ) + if (codemode.input !== undefined && !isSchemaValue(codemode.input)) + return Result.fail( + new RegistrationError({ name: id, message: `Invalid tool definition ${id}: input must be a schema` }), + ) + const overridden = Result.try({ + try: () => ToolDefinition.make(definition(tool, true)), + catch: (error) => + new RegistrationError({ name: id, message: `Invalid tool definition ${id}: ${schemaMakeError(error)}` }), + }) + if (Result.isFailure(overridden)) return Result.fail(overridden.failure) + return direct } function namespaceError(name: string) { diff --git a/packages/core/src/tool/AGENTS.md b/packages/core/src/tool/AGENTS.md index 5c7b9ffdeec..107f9226492 100644 --- a/packages/core/src/tool/AGENTS.md +++ b/packages/core/src/tool/AGENTS.md @@ -59,3 +59,13 @@ Tool filtering is catalog visibility, not execution authorization. A call still Built-ins return complete tool responses. `Tool.Snapshot.execute` is the local execution boundary. Generic output bounding is applied by the Session runner after execution. Producer capture remains local to producers. Shell stores combined process output in its backing file and returns a bounded tail with the full-output path when truncated. + +## Model tool policy + +`tool/model-policy.ts` (`modelTools`) decides, per model, which tools are hidden and which tools that allow Code Mode stay direct. `Tool.snapshot` in `src/tool.ts` applies it: a tool is inside Code Mode only when Code Mode is enabled, `defaultCodeMode` in `tool/runtime.ts` allows it (`options.codemode !== false`), and the policy doesn't keep it direct. The built-in registrations in `tool/plugin/` decide which tools allow Code Mode. + +The team docs site mirrors this logic in an interactive page: https://anoma.ly/team/abattoir/projects/opencode/model-tools (repo `anomalyco/abattoir`). When you change `modelTools`, the placement check in `Tool.snapshot`, `defaultCodeMode`, or a built-in's `codemode` option, update the page in the same change: + +- `src/guides/oc-model-tools.ts` holds a hand-copied version of `modelTools` and the snapshot placement, plus the `MODELS` and `TOOLS` example lists. Keep the copy identical to the code here. +- `content/projects/opencode/model-tools.md` has the page text; update it if a rule changes. +- Open a PR into Abattoir's `dev` branch. diff --git a/packages/core/src/tool/model-policy.ts b/packages/core/src/tool/model-policy.ts new file mode 100644 index 00000000000..262948ea651 --- /dev/null +++ b/packages/core/src/tool/model-policy.ts @@ -0,0 +1,73 @@ +import type { Model } from "@opencode/schema/model" + +const codeModeBuiltIns = ["read", "write", "edit", "patch", "shell", "websearch"] as const + +export interface ModelTools { + readonly hidden: Set + readonly direct: Set +} + +export function modelTools(input: { + readonly model?: Model.Info + readonly websearch: boolean + readonly fullCodeMode: boolean +}): ModelTools { + const hidden = new Set() + const direct = new Set() + if (!input.websearch) hidden.add("websearch") + if (!input.model) { + if (input.fullCodeMode) { + for (const name of codeModeBuiltIns) { + if (!hidden.has(name)) direct.add(name) + } + } + return { hidden, direct } + } + + const id = input.model.id.toLowerCase() + const modelID = input.model.modelID.toLowerCase() + const gpt = gptMode(id, modelID) + if (gpt === "patch") { + hidden.add("edit") + hidden.add("write") + } else { + hidden.add("patch") + } + + if (!input.fullCodeMode) return { hidden, direct } + + if (gpt !== undefined || isAnthropic(input.model, id, modelID)) { + hidden.add("glob") + hidden.add("grep") + hidden.add("webfetch") + return { hidden, direct } + } + + for (const name of codeModeBuiltIns) { + if (!hidden.has(name)) direct.add(name) + } + return { hidden, direct } +} + +function gptMode(id: string, modelID: string): "patch" | "edit" | undefined { + if (!id.includes("gpt") && !modelID.includes("gpt")) return undefined + const usePatch = + (id.includes("gpt-") || modelID.includes("gpt-")) && + !id.includes("oss") && + !modelID.includes("oss") && + !id.includes("gpt-4") && + !modelID.includes("gpt-4") + return usePatch ? "patch" : "edit" +} + +function isAnthropic(model: Model.Info, id: string, modelID: string) { + return ( + model.providerID === "anthropic" || + model.providerID === "claude-agent" || + model.canonical === "anthropic" || + model.canonical === "claude-agent" || + id.includes("claude") || + modelID.includes("claude") || + Boolean(model.family?.toLowerCase().includes("claude")) + ) +} diff --git a/packages/core/src/tool/plugin/edit.ts b/packages/core/src/tool/plugin/edit.ts index 949fc767bef..f1fc6c308ff 100644 --- a/packages/core/src/tool/plugin/edit.ts +++ b/packages/core/src/tool/plugin/edit.ts @@ -120,7 +120,9 @@ const withRegionEndings = (region: string, replacement: string, fallback: string const after = replacement.split("\n") const key = (line: string) => normalizeForMatch(line.trimEnd()) const source = alignLines(before.map(key), after.map(key)) - return after.map((line, index) => (index === after.length - 1 ? line : line + (endings[source[index]!] ?? fallback))).join("") + return after + .map((line, index) => (index === after.length - 1 ? line : line + (endings[source[index]!] ?? fallback))) + .join("") } /** @@ -273,7 +275,14 @@ export const Plugin = { editor.add({ name, options: flags.resolve(loaded.entries).full_codemode.enabled - ? { codemode: true, pinned: true, permission: "edit" } + ? { + codemode: { + pinned: true, + description: + "Edit a file by replacing `oldString` with `newString` (must differ). Preserve exact indentation without line-number prefixes. Use `\\n` for line breaks; existing LF/CRLF endings are preserved unless `oldString` and `newString` differ only in `\\r`. `oldString` must match once unless `replaceAll` is true; add context to disambiguate.", + }, + permission: "edit", + } : { codemode: false, permission: "edit" }, description: "Edit the contents of a file by finding and replacing exact text. When editing text from Read output, preserve the exact indentation (tabs or spaces) and omit the line-number prefix, such as `1: `. Never include the prefix in oldString or newString. Write line breaks as \\n; the file's existing CRLF or LF line endings are matched and preserved. To change line endings themselves, make oldString and newString differ only in \\r; that edit applies to the exact bytes. If there is no exact match, the edit retries while ignoring typographic quote, dash, and space variants, then trailing whitespace on each line. The edit fails if oldString is not found. By default, oldString must identify a UNIQUE location. Multiple matches FAIL unless replaceAll is true. Add more surrounding context to disambiguate, or set replaceAll to true to replace every occurrence. Use replaceAll when the change should apply to every occurrence, such as renaming a variable.", diff --git a/packages/core/src/tool/plugin/glob.ts b/packages/core/src/tool/plugin/glob.ts index e27d2e63ab4..ff3e20c4c99 100644 --- a/packages/core/src/tool/plugin/glob.ts +++ b/packages/core/src/tool/plugin/glob.ts @@ -6,10 +6,7 @@ import { Effect, Schema } from "effect" import path from "path" import { toolFailure } from "../runtime.js" import { ToolSearch } from "../search.js" -import { Config } from "../../config.js" -import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js" import { Environment } from "../../environment/index.js" -import { Flag } from "../../flag.js" import { FileSystem } from "../../filesystem.js" import { Location } from "../../location.js" import { FileAccess } from "../../file-access.js" @@ -55,14 +52,9 @@ export const Plugin = { const location = yield* Location.Service const access = yield* FileAccess.Service const permission = yield* Permission.Service - const config = yield* Config.Service - // Internal plugins are not re-run on config changes, so reload the tool transform instead. - const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload()) - const flags = yield* Flag.Service yield* ctx.tool - .transform((editor) => { - if (flags.resolve(loaded.entries).full_codemode.enabled) return + .transform((editor) => editor.add({ name, options: { codemode: false }, @@ -119,8 +111,8 @@ export const Plugin = { : toolFailure(`Unable to find files matching ${input.pattern}`)(error), ), ), - }) - }) + }), + ) .pipe(Effect.orDie) }), } diff --git a/packages/core/src/tool/plugin/grep.ts b/packages/core/src/tool/plugin/grep.ts index 31468559419..6caebdc01c0 100644 --- a/packages/core/src/tool/plugin/grep.ts +++ b/packages/core/src/tool/plugin/grep.ts @@ -4,10 +4,7 @@ import type { Context } from "@opencode/plugin/effect/plugin" import { ToolFailure } from "@opencode/ai/effect" import { Effect, Schema } from "effect" import path from "path" -import { Config } from "../../config.js" -import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js" import { Environment } from "../../environment/index.js" -import { Flag } from "../../flag.js" import { FileSystem } from "../../filesystem.js" import { Location } from "../../location.js" import { FileAccess } from "../../file-access.js" @@ -73,14 +70,9 @@ export const Plugin = { const location = yield* Location.Service const access = yield* FileAccess.Service const permission = yield* Permission.Service - const config = yield* Config.Service - // Internal plugins are not re-run on config changes, so reload the tool transform instead. - const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload()) - const flags = yield* Flag.Service yield* ctx.tool - .transform((editor) => { - if (flags.resolve(loaded.entries).full_codemode.enabled) return + .transform((editor) => editor.add({ name, options: { codemode: false }, @@ -153,8 +145,8 @@ export const Plugin = { return new ToolFailure({ message: `Unable to grep for ${input.pattern}`, error }) }), ), - }) - }) + }), + ) .pipe(Effect.orDie) }), } diff --git a/packages/core/src/tool/plugin/opencode.ts b/packages/core/src/tool/plugin/opencode.ts index bfd091e1cdb..821cfd05844 100644 --- a/packages/core/src/tool/plugin/opencode.ts +++ b/packages/core/src/tool/plugin/opencode.ts @@ -100,11 +100,13 @@ export const Plugin = { const permission = yield* Permission.Service const hook = (event: SessionHooks["context"]) => Effect.sync(() => { - event.system.push( - SystemPart.make( - "When you create a worktree outside the current working directory and intend to use it as your primary working directory, consider using `execute` to call `tools.opencode.session_move` and make the worktree the session's working directory.", - ), - ) + const text = + "execute" in event.tools + ? "When you create a worktree outside the current working directory and intend to use it as your primary working directory, consider using `execute` to call `tools.opencode.session_move` and make the worktree the session's working directory." + : "opencode_session_move" in event.tools + ? "When you create a worktree outside the current working directory and intend to use it as your primary working directory, consider calling `opencode_session_move` to make the worktree the session's working directory." + : undefined + if (text) event.system.push(SystemPart.make(text)) }) yield* ctx.session.hook("context", hook) yield* ctx.session.hook("compaction", hook) @@ -142,7 +144,7 @@ export const Plugin = { "Move a session to another directory, or omit sessionID to move the current session. The current session moves at the next safe boundary; do not run destination-dependent tools in the same execute call.", input: MoveInput, output: MoveOutput, - options: { namespace: "opencode", codemode: true, pinned: true }, + options: { namespace: "opencode", codemode: { pinned: true } }, execute: (input, context) => Effect.gen(function* () { const sessionID = input.sessionID ?? context.sessionID @@ -178,7 +180,7 @@ export const Plugin = { description: "Create a named worktree. Returns its directory.", input: WorktreeCreateInput, output: Worktree.Info, - options: { namespace: "opencode", codemode: true, pinned: true }, + options: { namespace: "opencode", codemode: { pinned: true } }, execute: (input) => ctx.worktree.create({ projectID: ctx.location.project.id, name: input.name }).pipe( Effect.map((output) => ({ output, content: `Created worktree in ${output.directory}.` })), @@ -192,7 +194,7 @@ export const Plugin = { description: "List a repository's worktrees.", input: Schema.Struct({}), output: Schema.Struct({ worktrees: Worktree.List }), - options: { namespace: "opencode", codemode: true, pinned: true }, + options: { namespace: "opencode", codemode: { pinned: true } }, execute: () => ctx.worktree.list({ projectID: ctx.location.project.id }).pipe( Effect.map((worktrees) => ({ output: { worktrees } })), @@ -205,7 +207,7 @@ export const Plugin = { "Remove a worktree. The repository location selects configuration; directory identifies the worktree to remove.", input: WorktreeRemoveInput, output: WorktreeRemoveOutput, - options: { namespace: "opencode", codemode: true, pinned: true, permission: "edit" }, + options: { namespace: "opencode", codemode: { pinned: true }, permission: "edit" }, execute: (input, context) => Effect.gen(function* () { // Removing a worktree deletes files, so it requires the same approval as editing them. @@ -227,9 +229,7 @@ export const Plugin = { output: { directory: target.absolute, removed: true }, content: `Removed worktree ${target.absolute}.`, } - }).pipe( - Effect.mapError(toolFailure(`Unable to remove worktree ${input.directory}`)), - ), + }).pipe(Effect.mapError(toolFailure(`Unable to remove worktree ${input.directory}`))), }) draft.add({ name: "models", diff --git a/packages/core/src/tool/plugin/patch.ts b/packages/core/src/tool/plugin/patch.ts index 8b58eaa3bb5..d6e1a85c782 100644 --- a/packages/core/src/tool/plugin/patch.ts +++ b/packages/core/src/tool/plugin/patch.ts @@ -1,7 +1,6 @@ export * as PatchTool from "./patch.js" import type { Context } from "@opencode/plugin/effect/plugin" -import type { SessionHooks } from "@opencode/plugin/effect/session" import { ToolFailure } from "@opencode/ai/effect" import { FileDiff } from "@opencode/schema/file-diff" import { Effect, Result, Schema } from "effect" @@ -69,7 +68,14 @@ export const Plugin = { editor.add({ name, options: flags.resolve(loaded.entries).full_codemode.enabled - ? { codemode: true, pinned: true, permission: "edit" } + ? { + codemode: { + pinned: true, + description: + "Apply multi-file edits inside `*** Begin Patch` ... `*** End Patch`. Start each operation with `*** Add File: ` (every content line prefixed with `+`), `*** Delete File: `, or `*** Update File: ` (optional `*** Move to: `, then `@@ [context]` hunks with space/`-`/`+` line prefixes).", + }, + permission: "edit", + } : { codemode: false, permission: "edit" }, description: DESCRIPTION, input: Input, @@ -296,21 +302,6 @@ export const Plugin = { }), ) .pipe(Effect.orDie) - - const hook = (event: SessionHooks["context"]) => - Effect.sync(() => { - const usePatch = - event.model.id.includes("gpt-") && !event.model.id.includes("oss") && !event.model.id.includes("gpt-4") - if (usePatch) { - delete event.tools.edit - delete event.tools.write - return - } - delete event.tools.patch - }) - yield* ctx.session.hook("context", hook) - yield* ctx.session.hook("compaction", hook) - yield* ctx.session.hook("generate", hook) }), } diff --git a/packages/core/src/tool/plugin/read.ts b/packages/core/src/tool/plugin/read.ts index d9e1bdce34e..6dd81a4b663 100644 --- a/packages/core/src/tool/plugin/read.ts +++ b/packages/core/src/tool/plugin/read.ts @@ -32,6 +32,15 @@ const LocationInput = Schema.Struct({ export const Input = LocationInput type Missing = { input: string; requested: FileAccess.Target; context: FileAccess.Invocation } +const description = (codemode: boolean) => + [ + "Read the contents of a file or directory. Supports text files, images, and PDFs.", + codemode + ? "Reading an image or PDF automatically attaches it to the execute result, even if the program doesn't return or print the media reference." + : "Each text line is prefixed by its 1-based line number as : . The prefix is for reference and is not part of the file content. Directory entries are returned one per line.", + "Use offset and limit to read large files or directories in sections. Prefer one larger read over many small slices, and use grep to find specific content in large files.", + ].join(" ") + export const Plugin = { id: "opencode.tool.read", effect: Effect.fn("ReadTool.Plugin")(function* (ctx: Context) { @@ -49,22 +58,13 @@ export const Plugin = { const discovery = yield* InstructionDiscovery.Service yield* ctx.tool - .transform((editor) => { - const codeMode = flags.resolve(loaded.entries).full_codemode.enabled + .transform((editor) => editor.add({ name, - options: codeMode ? { codemode: true, pinned: true } : { codemode: false }, - description: [ - "Read the contents of a file or directory. Supports text files, images, and PDFs.", - ...(codeMode - ? [ - "Reading an image or PDF automatically attaches it to the execute result, even if the program doesn't return or print the media reference.", - ] - : [ - "Each text line is prefixed by its 1-based line number as : . The prefix is for reference and is not part of the file content. Directory entries are returned one per line.", - ]), - "Use offset and limit to read large files or directories in sections. Prefer one larger read over many small slices, and use grep to find specific content in large files.", - ].join(" "), + options: flags.resolve(loaded.entries).full_codemode.enabled + ? { codemode: { pinned: true, description: description(true) } } + : { codemode: false }, + description: description(false), input: Input, output: ReadToolFileSystem.Output, execute: (input, context) => { @@ -198,8 +198,8 @@ export const Plugin = { }), ) }, - }) - }) + }), + ) .pipe(Effect.orDie) const alternatePath = Effect.fn("ReadTool.alternatePath")(function* (absolute: string) { diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index 72b51319b59..39d2eb2888a 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -373,21 +373,27 @@ export const Plugin = { }) yield* ctx.tool - .transform((editor) => { - const codeMode = flags.resolve(loaded.entries).full_codemode.enabled + .transform((editor) => editor.add({ name, - // With full_codemode, shell is called as `tools.shell` inside `execute` instead of as a direct tool, and is - // pinned so the Code Mode catalog always lists it, however many other tools there are. - options: codeMode ? { codemode: true, pinned: true } : { codemode: false }, - description: description(undefined, codeMode), - input: codeMode ? CodeModeInput : Input, + // With full_codemode, shell is allowed in Code Mode and pinned so the catalog always lists it. + options: flags.resolve(loaded.entries).full_codemode.enabled + ? { + codemode: { + pinned: true, + description: description(undefined, true), + input: CodeModeInput, + }, + } + : { codemode: false }, + description: description(), + input: Input, output: StructuredOutput, execute: (input, context) => { // Code Mode input has no background parameter. const background = "background" in input && input.background === true // A foreground timeout of 0 falls back to the default, so a call can't block until the command exits. - const foreground = input.timeout || (codeMode ? CODE_MODE_TIMEOUT_MS : DEFAULT_TIMEOUT_MS) + const foreground = input.timeout || (context.codemode ? CODE_MODE_TIMEOUT_MS : DEFAULT_TIMEOUT_MS) const timeout = background ? (input.timeout ?? 0) : foreground let finalTimeout = timeout // Uninterruptible from spawning to blocking, so an interrupt cannot orphan a started command. @@ -514,8 +520,8 @@ export const Plugin = { Effect.mapError(toolFailure(`Unable to execute command: ${input.command}`)), ) }, - }) - }) + }), + ) .pipe(Effect.orDie) const hook = (event: SessionHooks["context"]) => diff --git a/packages/core/src/tool/plugin/webfetch.ts b/packages/core/src/tool/plugin/webfetch.ts index 39543dd19dd..465e95bcb82 100644 --- a/packages/core/src/tool/plugin/webfetch.ts +++ b/packages/core/src/tool/plugin/webfetch.ts @@ -5,9 +5,6 @@ import { ToolFailure } from "@opencode/ai/effect" import { Duration, Effect, Schema } from "effect" import { FetchHttpClient, HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http" import { Parser } from "htmlparser2" -import { Config } from "../../config.js" -import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js" -import { Flag } from "../../flag.js" import { Mime } from "../../mime.js" import { Permission } from "../../permission.js" import { convertHTMLToMarkdown, MAX_MARKDOWN_BYTES } from "../html-markdown.js" @@ -131,15 +128,9 @@ export const Plugin = { effect: Effect.fn("WebFetchTool.Plugin")(function* (ctx: Context) { const http = yield* HttpClient.HttpClient const permission = yield* Permission.Service - const config = yield* Config.Service - // Internal plugins are not re-run on config changes, so reload the tool transform instead. - const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload()) - const flags = yield* Flag.Service yield* ctx.tool - .transform((editor) => { - // Code Mode programs have a `fetch` global that checks the same webfetch permission rules. - if (flags.resolve(loaded.entries).full_codemode.enabled) return + .transform((editor) => editor.add({ name, options: { codemode: false }, @@ -195,8 +186,8 @@ export const Plugin = { }) return { output: { contentType, output }, content: output, metadata: { contentType } } }).pipe(Effect.mapError((error) => new ToolFailure({ message: `Unable to fetch ${input.url}`, error }))), - }) - }) + }), + ) .pipe(Effect.orDie) }), } diff --git a/packages/core/src/tool/plugin/websearch.ts b/packages/core/src/tool/plugin/websearch.ts index 5c28858d1cf..426cc4e2784 100644 --- a/packages/core/src/tool/plugin/websearch.ts +++ b/packages/core/src/tool/plugin/websearch.ts @@ -1,7 +1,6 @@ export * as WebSearchTool from "./websearch.js" import type { Context } from "@opencode/plugin/effect/plugin" -import type { SessionHooks } from "@opencode/plugin/effect/session" import { ToolFailure } from "@opencode/ai/effect" import { Effect, Schema, Semaphore } from "effect" import { HttpClientError } from "effect/http" @@ -190,18 +189,5 @@ export const Plugin = { }), ) .pipe(Effect.orDie) - - const hook = (event: SessionHooks["context"]) => - Effect.gen(function* () { - const disabled = yield* websearch.default().pipe( - Effect.as(false), - Effect.catchTag("WebSearch.Disabled", () => Effect.succeed(true)), - ) - // Policy can remove every provider, and the model shouldn't be offered a tool that can't search. - if (disabled || (yield* websearch.providers()).length === 0) delete event.tools[name] - }) - yield* ctx.session.hook("context", hook) - yield* ctx.session.hook("compaction", hook) - yield* ctx.session.hook("generate", hook) }), } diff --git a/packages/core/src/tool/plugin/write.ts b/packages/core/src/tool/plugin/write.ts index 882ef22d69a..2f73e558d0c 100644 --- a/packages/core/src/tool/plugin/write.ts +++ b/packages/core/src/tool/plugin/write.ts @@ -45,7 +45,14 @@ export const Plugin = { editor.add({ name, options: flags.resolve(loaded.entries).full_codemode.enabled - ? { codemode: true, pinned: true, permission: "edit" } + ? { + codemode: { + pinned: true, + description: + "Create a new file or overwrite an existing file on the local filesystem, creating missing parent directories automatically. Prefer `edit` for partial changes to existing files.", + }, + permission: "edit", + } : { codemode: false, permission: "edit" }, description: "Writes a file to the local filesystem, overwriting if one exists.\n\nMissing parent directories are created automatically.\n\nUse this tool to create new files or overwrite existing files. For partial changes, use the edit tool instead.", diff --git a/packages/core/src/tool/runtime.ts b/packages/core/src/tool/runtime.ts index b6f034601fd..80af44053a5 100644 --- a/packages/core/src/tool/runtime.ts +++ b/packages/core/src/tool/runtime.ts @@ -19,18 +19,28 @@ export const codecFor = (schema: JsonSchema.JsonSchema) => { return codec } -export const definition = (tool: Tool.Info): ToolDefinition => ({ - type: "tool", - name: effectiveName(tool), - description: tool.description, - inputSchema: inputJsonSchema(tool.input), - ...(tool.freeform && { freeform: tool.freeform }), - ...(tool.output === undefined ? {} : { outputSchema: outputJsonSchema(tool.output) }), -}) +const codemodeOverrides = (tool: Tool.Info, codemode: boolean) => + codemode && typeof tool.options?.codemode === "object" && tool.options.codemode !== null + ? tool.options.codemode + : undefined + +export const definition = (tool: Tool.Info, codemode = false): ToolDefinition => { + const overrides = codemodeOverrides(tool, codemode) + const output = overrides?.output ?? tool.output + return { + type: "tool", + name: effectiveName(tool), + description: overrides?.description ?? tool.description, + inputSchema: inputJsonSchema(overrides?.input ?? tool.input), + ...(tool.freeform && { freeform: tool.freeform }), + ...(output === undefined ? {} : { outputSchema: outputJsonSchema(output) }), + } +} export const execute = (tool: Tool.Info, input: unknown, context: Tool.Context) => Effect.gen(function* () { - const decoded = yield* decodeInput(tool, input) + const overrides = codemodeOverrides(tool, context.codemode === true) + const decoded = yield* decodeInput(tool, overrides?.input ?? tool.input, input) // Tool implementations declare `Tool.Error` but plugins can fail with anything at // runtime. A foreign typed failure would slip past every `catchTag("Tool.Error")` // downstream and leave its call permanently unsettled, so the declared contract is @@ -45,7 +55,8 @@ export const execute = (tool: Tool.Info, input: unknown, context: Tool }), ), ) - if (tool.output === undefined) { + const outputSchema = overrides?.output ?? tool.output + if (outputSchema === undefined) { if ("output" in result) return yield* Effect.die("Tool result declared output without an output schema") return { output: undefined, @@ -54,7 +65,7 @@ export const execute = (tool: Tool.Info, input: unknown, context: Tool } } if (!("output" in result)) return yield* new Tool.Error({ message: "Tool did not return its declared output" }) - const output = yield* encodeOutput(tool.output, result.output) + const output = yield* encodeOutput(outputSchema, result.output) return { output, content: normalizeContent(result.content, output), @@ -62,9 +73,9 @@ export const execute = (tool: Tool.Info, input: unknown, context: Tool } }) -const decodeInput = (tool: Tool.Info, value: unknown) => +const decodeInput = (tool: Pick, schema: Tool.ValueSchema, value: unknown) => Effect.gen(function* () { - const result = yield* validateInput(tool.input, value) + const result = yield* validateInput(schema, value) if (result.issues) return yield* new Tool.Error({ message: formatInputIssues(effectiveName(tool), result.issues, value) }) return result.value @@ -135,7 +146,7 @@ const encodeOutput = (schema: Tool.ValueSchema, value: unknown) => { } const isStandardSchema = (schema: Tool.ValueSchema): schema is StandardSchemaV1 => - typeof schema === "object" && schema !== null && "~standard" in schema + (typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema const isStandardJSONSchema = ( schema: StandardSchemaV1, @@ -293,6 +304,8 @@ export const effectiveName = (tool: Pick) => ? normalizedName(tool) : `${tool.options.namespace.replaceAll(".", "_")}_${normalizedName(tool)}` +export const defaultCodeMode = (tool: Pick) => tool.options?.codemode !== false + /** For `Effect.mapError`: keep a `ToolFailure` as is, wrap anything else with `message`. */ export const toolFailure = (message: string) => (error: unknown) => error instanceof ToolFailure ? error : new ToolFailure({ message, error }) diff --git a/packages/core/src/websearch.ts b/packages/core/src/websearch.ts index eeb59373050..94bc1694c8b 100644 --- a/packages/core/src/websearch.ts +++ b/packages/core/src/websearch.ts @@ -55,6 +55,7 @@ export class RequestError extends Schema.TaggedError()("WebSearch. export type Error = ProviderRequiredError | ProviderNotFoundError | DisabledError | RequestError export interface Interface extends State.Transformable { + readonly available: () => Effect.Effect readonly providers: () => Effect.Effect readonly default: () => Effect.Effect readonly select: (selection: Selection) => Effect.Effect @@ -171,6 +172,10 @@ const layer = Layer.effect( return Service.of({ transform: state.transform, reload: state.reload, + available: Effect.fn("WebSearch.available")(function* () { + if (state.get().providers.size === 0) return false + return (yield* selection()) !== false + }), providers: Effect.fn("WebSearch.providers")(function* () { return providers(state.get()) }), diff --git a/packages/core/test/boot-work.test.ts b/packages/core/test/boot-work.test.ts index 1f2636c8fa0..209954c4e22 100644 --- a/packages/core/test/boot-work.test.ts +++ b/packages/core/test/boot-work.test.ts @@ -121,6 +121,7 @@ const it = testEffect( LayerNodePlatform.llmClient.replace(llmLayer), SessionRunnerModel.node.replace( Layer.succeed(SessionRunnerModel.Service, { + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed( SessionRunnerModel.resolved( diff --git a/packages/core/test/codemode.test.ts b/packages/core/test/codemode.test.ts index 417ee9b807b..0c0d4150163 100644 --- a/packages/core/test/codemode.test.ts +++ b/packages/core/test/codemode.test.ts @@ -25,7 +25,7 @@ describe("CodeMode", () => { description: "Echo text", input: Schema.Struct({ text: Schema.String }), output: Schema.String, - options: { pinned: true }, + options: { codemode: { pinned: true } }, execute: ({ text }) => Effect.succeed({ output: text }), }) }) diff --git a/packages/core/test/codemode/instructions.test.ts b/packages/core/test/codemode/instructions.test.ts index 58c62af6054..aa5553d38c7 100644 --- a/packages/core/test/codemode/instructions.test.ts +++ b/packages/core/test/codemode/instructions.test.ts @@ -66,7 +66,7 @@ describe("CodeModeInstructions", () => { ) expect(yield* readUpdate(CodeModeInstructions.make(), initialized)).toMatchObject({ - text: "Code Mode tools are no longer available. Do not use any previously listed Code Mode tools.", + text: "The `execute` tool is no longer available. Permitted tools are now available as direct tool calls.", }) }), ) diff --git a/packages/core/test/config/command-subagent.test.ts b/packages/core/test/config/command-subagent.test.ts index 318b63cbf27..19a53ac1e24 100644 --- a/packages/core/test/config/command-subagent.test.ts +++ b/packages/core/test/config/command-subagent.test.ts @@ -32,6 +32,7 @@ const it = testEffect( LayerNodePlatform.llmClient.replace(llmLayer), SessionRunnerModel.node.replace( Layer.succeed(SessionRunnerModel.Service, { + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: (session) => Effect.succeed( SessionRunnerModel.resolved( diff --git a/packages/core/test/fixture/policy.ts b/packages/core/test/fixture/policy.ts index 09c6387a756..d97865d9b28 100644 --- a/packages/core/test/fixture/policy.ts +++ b/packages/core/test/fixture/policy.ts @@ -85,6 +85,7 @@ export const registerIntegrationPolicy = Effect.fn(function* (input: { Effect.provideService( WebSearch.Service, WebSearch.Service.of({ + available: () => Effect.die("unused WebSearch.available"), providers: () => Effect.die("unused WebSearch.providers"), default: () => Effect.die("unused WebSearch.default"), select: () => Effect.die("unused WebSearch.select"), diff --git a/packages/core/test/lib/tool.ts b/packages/core/test/lib/tool.ts index ad95a5c6221..7813a1a9be2 100644 --- a/packages/core/test/lib/tool.ts +++ b/packages/core/test/lib/tool.ts @@ -88,8 +88,9 @@ export interface ToolExecution { export const executeTool = ( registry: Tool.Interface, input: Parameters[0], + options?: Tool.SnapshotOptions, ): Effect.Effect => - registry.snapshot().pipe( + registry.snapshot(undefined, options).pipe( Effect.flatMap((tools) => tools.execute(input)), Effect.map((result) => ({ status: "completed" as const, ...result }) satisfies ToolExecution), Effect.catchTag("Tool.Error", (error) => diff --git a/packages/core/test/mcp-instructions.test.ts b/packages/core/test/mcp-instructions.test.ts index dda4467ff73..129c677f908 100644 --- a/packages/core/test/mcp-instructions.test.ts +++ b/packages/core/test/mcp-instructions.test.ts @@ -1,11 +1,17 @@ import { describe, expect } from "bun:test" import { Effect, Layer } from "effect" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { Location } from "@opencode/core/location" import { Mcp } from "@opencode/core/mcp/index" import { McpInstructions } from "@opencode/core/mcp/instructions" +import { Permission } from "@opencode/core/permission" +import { AbsolutePath } from "@opencode/core/schema" +import { Tool } from "@opencode/core/tool" import { McpTool } from "@opencode/core/tool/mcp" +import { LayerNode } from "@opencode/util/effect/layer-node" import { it } from "./lib/effect" import { readInitial, readUpdate } from "./lib/instructions" +import { toolNodeReplacements } from "./lib/tool" const instructions = (server: string, text: string) => ({ server: Mcp.ServerName.make(server), instructions: text }) satisfies Mcp.ServerInstructions @@ -15,25 +21,43 @@ const tool = (server: string, name = "search") => ({ server: Mcp.ServerName.make(server), name, inputSchema: schema }) satisfies Mcp.Tool const layer = (catalog: () => Mcp.ServerInstructions[], tools: () => Mcp.Tool[]) => - AppNodeBuilder.build(McpInstructions.node, [ + AppNodeBuilder.build(LayerNode.group([McpInstructions.node, McpTool.node, Tool.node]), [ + ...toolNodeReplacements(), + Location.node.replace(Location.boundNode({ directory: AbsolutePath.make("/project") })), Mcp.node.replace( Layer.mock(Mcp.Service, { + awaitStartup: () => Effect.void, instructions: () => Effect.succeed(catalog()), tools: () => Effect.succeed(tools()), }), ), ]) +const load = (permissions: Permission.Ruleset = []) => + Effect.gen(function* () { + const mcpTools = yield* McpTool.Service + const registry = yield* Tool.Service + const service = yield* McpInstructions.Service + yield* mcpTools.flush + return yield* service.load(yield* registry.snapshot(permissions)) + }) + describe("McpInstructions", () => { - it.effect("renders instructions for servers with at least one permitted tool", () => + it.effect("renders instructions for servers with at least one reachable snapshot tool", () => Effect.gen(function* () { - const service = yield* McpInstructions.Service - const generation = yield* service - .load([ - { action: McpTool.name("alpha", "restricted"), resource: "*", effect: "deny" }, - { action: McpTool.name("hidden", "search"), resource: "*", effect: "deny" }, - ]) - .pipe(Effect.flatMap(readInitial)) + const registry = yield* Tool.Service + const mcpTools = yield* McpTool.Service + yield* mcpTools.flush + yield* registry.transform((editor) => editor.remove(McpTool.name("removed", "search"))) + + const generation = yield* load([ + { action: "*", resource: "*", effect: "deny" }, + // Scoped allow keeps alpha_search in the snapshot (not whollyDisabled), while hidden_search stays denied. + { action: McpTool.name("alpha", "search"), resource: "https://example.com/*", effect: "allow" }, + { action: McpTool.name("beta", "search"), resource: "*", effect: "allow" }, + { action: McpTool.name("removed", "search"), resource: "*", effect: "allow" }, + { action: "execute", resource: "*", effect: "allow" }, + ]).pipe(Effect.flatMap(readInitial)) expect(generation.text).toBe( [ @@ -57,20 +81,20 @@ describe("McpInstructions", () => { instructions("beta", "Beta instructions"), instructions("unused", "No tools"), instructions("hidden", "Denied tool"), + instructions("removed", "Removed by transform"), instructions("alpha", "Alpha line one\nAlpha line two"), ], - () => [tool("alpha"), tool("alpha", "restricted"), tool("beta"), tool("hidden")], + () => [tool("alpha"), tool("alpha", "restricted"), tool("beta"), tool("hidden"), tool("removed")], ), ), ), ) - it.effect("lists Code Mode servers as direct tools when the agent cannot use execute", () => + it.effect("lists Code Mode servers as direct tools when the snapshot has no Code Mode catalog", () => Effect.gen(function* () { - const service = yield* McpInstructions.Service - const generation = yield* service - .load([{ action: "execute", resource: "*", effect: "deny" }]) - .pipe(Effect.flatMap(readInitial)) + const generation = yield* load([{ action: "execute", resource: "*", effect: "deny" }]).pipe( + Effect.flatMap(readInitial), + ) expect(generation.text).toBe( [ @@ -91,12 +115,11 @@ describe("McpInstructions", () => { ), ) - it.effect("keeps MCP instructions when Code Mode is disabled and execute is denied", () => + it.effect("keeps MCP instructions when Code Mode is disabled for the server and execute is denied", () => Effect.gen(function* () { - const service = yield* McpInstructions.Service - const generation = yield* service - .load([{ action: "execute", resource: "*", effect: "deny" }]) - .pipe(Effect.flatMap(readInitial)) + const generation = yield* load([{ action: "execute", resource: "*", effect: "deny" }]).pipe( + Effect.flatMap(readInitial), + ) expect(generation.text).toBe( [ @@ -127,11 +150,10 @@ describe("McpInstructions", () => { it.effect("replaces a server entry when Code Mode is disabled for it", () => { let tools: Mcp.Tool[] = [tool("alpha")] return Effect.gen(function* () { - const service = yield* McpInstructions.Service - const initialized = yield* service.load([]).pipe(Effect.flatMap(readInitial)) + const initialized = yield* load().pipe(Effect.flatMap(readInitial)) tools = [{ ...tool("alpha"), codemode: false }] - const changed = yield* readUpdate(yield* service.load([]), initialized) + const changed = yield* readUpdate(yield* load(), initialized) expect(changed.text).toBe( [ "The following MCP server instructions have changed. Each entry replaces the previously listed server with the same name:", @@ -154,11 +176,10 @@ describe("McpInstructions", () => { let catalog = [instructions("alpha", "Alpha instructions")] const tools = [tool("alpha"), tool("beta")] return Effect.gen(function* () { - const service = yield* McpInstructions.Service - const initialized = yield* service.load([]).pipe(Effect.flatMap(readInitial)) + const initialized = yield* load().pipe(Effect.flatMap(readInitial)) catalog = [instructions("alpha", "Alpha instructions"), instructions("beta", "Beta instructions")] - const added = yield* readUpdate(yield* service.load([]), initialized) + const added = yield* readUpdate(yield* load(), initialized) expect(added.text).toBe( [ "New MCP server instructions are available in addition to those previously listed:", @@ -170,7 +191,7 @@ describe("McpInstructions", () => { ) catalog = [instructions("alpha", "Updated alpha"), instructions("beta", "Beta instructions")] - const changed = yield* readUpdate(yield* service.load([]), added) + const changed = yield* readUpdate(yield* load(), added) expect(changed.text).toBe( [ "The following MCP server instructions have changed. Each entry replaces the previously listed server with the same name:", @@ -182,13 +203,11 @@ describe("McpInstructions", () => { ) catalog = [instructions("beta", "Beta instructions")] - const removed = yield* readUpdate(yield* service.load([]), changed) + const removed = yield* readUpdate(yield* load(), changed) expect(removed.text).toBe("Instructions for the following MCP servers are no longer available: alpha.") catalog = [] - expect((yield* readUpdate(yield* service.load([]), removed)).text).toBe( - "MCP server instructions are no longer available.", - ) + expect((yield* readUpdate(yield* load(), removed)).text).toBe("MCP server instructions are no longer available.") }).pipe( Effect.provide( layer( diff --git a/packages/core/test/plugin/goal.test.ts b/packages/core/test/plugin/goal.test.ts index 73bdb518e3b..fe927eeedc8 100644 --- a/packages/core/test/plugin/goal.test.ts +++ b/packages/core/test/plugin/goal.test.ts @@ -36,6 +36,7 @@ const it = testEffect( LayerNodePlatform.llmClient.replace(llmLayer), SessionRunnerModel.node.replace( Layer.succeed(SessionRunnerModel.Service, { + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed( SessionRunnerModel.resolved( diff --git a/packages/core/test/plugin/optimize.test.ts b/packages/core/test/plugin/optimize.test.ts index 85c3a8054b6..5a31df8d9a8 100644 --- a/packages/core/test/plugin/optimize.test.ts +++ b/packages/core/test/plugin/optimize.test.ts @@ -157,70 +157,6 @@ describe("OptimizePlugin", () => { }), ) - it.effect("curates search tools across providers without changing editing tools", () => - Effect.gen(function* () { - const hooks = yield* PluginHooks.Service - const pluginHost = yield* makeHost - yield* OptimizePlugin.OpenAIToolsPlugin.effect(pluginHost) - yield* OptimizePlugin.AnthropicToolsPlugin.effect(pluginHost) - const cases = [ - ["openai", "gpt-5", ["edit", "patch", "read", "shell", "write"]], - ["openrouter", "openai/gpt-6-astra", ["edit", "patch", "read", "shell", "write"]], - ["azure", "GPT-4.1", ["edit", "patch", "read", "shell", "write"]], - ["groq", "openai/gpt-oss-120b", ["edit", "patch", "read", "shell", "write"]], - ["anthropic", "claude-opus-4-8", ["edit", "patch", "read", "shell", "write"]], - ["amazon-bedrock", "us.anthropic.Claude-sonnet-4-6", ["edit", "patch", "read", "shell", "write"]], - ["github-copilot", "claude-sonnet-4.6", ["edit", "patch", "read", "shell", "write"]], - ["google", "gemini-2.5-pro", ["edit", "glob", "grep", "patch", "read", "shell", "write"]], - ["moonshotai", "kimi-k2", ["edit", "glob", "grep", "patch", "read", "shell", "write"]], - ["openai", "o3", ["edit", "glob", "grep", "patch", "read", "shell", "write"]], - ["anthropic", "other-model", ["edit", "glob", "grep", "patch", "read", "shell", "write"]], - ] as const - - yield* Effect.forEach( - cases, - ([providerID, id, tools]) => - Effect.gen(function* () { - const event = { - ...context(id), - model: Model.Ref.make({ providerID: Provider.ID.make(providerID), id: Model.ID.make(id) }), - } - yield* hooks.trigger("session", "context", event) - expect(Object.keys(event.tools).sort()).toEqual([...tools]) - expect(event.system.map((part) => part.text)).toEqual([fallback]) - }), - { discard: true }, - ) - }), - ) - - it.effect("can disable OpenAI tool optimization while retaining its prompt and Anthropic tool optimization", () => - Effect.gen(function* () { - const hooks = yield* PluginHooks.Service - const pluginHost = yield* makeHost - yield* OptimizePlugin.OpenAIPlugin.effect(pluginHost) - yield* OptimizePlugin.AnthropicToolsPlugin.effect(pluginHost) - yield* Effect.scoped( - Effect.gen(function* () { - yield* OptimizePlugin.OpenAIToolsPlugin.effect(pluginHost) - const event = context("gpt-5") - yield* hooks.trigger("session", "context", event) - expect(event.system[0]?.text).toBe(SessionSystemPrompt.render(PROMPT_GPT, Object.keys(event.tools))) - expect(Object.keys(event.tools).sort()).toEqual(["edit", "patch", "read", "shell", "write"]) - }), - ) - - const event = context("gpt-5") - yield* hooks.trigger("session", "context", event) - expect(event.system[0]?.text).toBe(SessionSystemPrompt.render(PROMPT_GPT, Object.keys(event.tools))) - expect(Object.keys(event.tools).sort()).toEqual(["edit", "glob", "grep", "patch", "read", "shell", "write"]) - const claude = context("claude-sonnet-4-6") - yield* hooks.trigger("session", "context", claude) - expect(claude.system.map((part) => part.text)).toEqual([fallback]) - expect(Object.keys(claude.tools).sort()).toEqual(["edit", "patch", "read", "shell", "write"]) - }), - ) - it.effect("uses catalog names in Meta prompts for Muse model IDs", () => Effect.gen(function* () { const catalog = yield* Provider.Service @@ -282,23 +218,6 @@ describe("OptimizePlugin", () => { }), ) - it.effect("still curates tools when agent lookup fails", () => - Effect.gen(function* () { - const agents = yield* Agent.Service - const hooks = yield* PluginHooks.Service - const pluginHost = yield* makeHost - yield* OptimizePlugin.OpenAIPlugin.effect(pluginHost) - yield* OptimizePlugin.OpenAIToolsPlugin.effect(pluginHost) - yield* agents.transform((editor) => editor.remove(Agent.ID.make("build"))) - const event = context("gpt-5") - - yield* hooks.trigger("session", "context", event) - - expect(event.system.map((part) => part.text)).toEqual([fallback]) - expect(Object.keys(event.tools).sort()).toEqual(["edit", "patch", "read", "shell", "write"]) - }), - ) - it.effect("allows one model-lab optimization plugin to be enabled independently", () => Effect.gen(function* () { const hooks = yield* PluginHooks.Service diff --git a/packages/core/test/plugin/plan.test.ts b/packages/core/test/plugin/plan.test.ts index bb1244c4b1a..31a80de8588 100644 --- a/packages/core/test/plugin/plan.test.ts +++ b/packages/core/test/plugin/plan.test.ts @@ -126,6 +126,7 @@ type ToolErrorEvent = Extract ({ tool, + codemode: false, input: {}, sessionID, agent: plan, diff --git a/packages/core/test/plugin/promise-tool.test.ts b/packages/core/test/plugin/promise-tool.test.ts index 94029d92ab6..dc015308247 100644 --- a/packages/core/test/plugin/promise-tool.test.ts +++ b/packages/core/test/plugin/promise-tool.test.ts @@ -7,7 +7,7 @@ import { PluginPromise } from "@opencode/core/plugin/promise" import { Tool } from "@opencode/core/tool" import { Session } from "@opencode/schema/session" import { SessionMessage } from "@opencode/schema/session-message" -import { Cause, Deferred, Effect, Exit, Fiber, Option } from "effect" +import { Cause, Deferred, Effect, Exit, Fiber, Option, Schema } from "effect" import { testEffect } from "../lib/effect" import { PluginTestLayer } from "./fixture" @@ -136,3 +136,92 @@ it.live("Promise tools that rethrow a decline attach it to the tool failure", () expect(Option.getOrUndefined(Exit.findErrorOption(exit))?.error).toBe(declined) }), ) + +it.live("Promise tools infer codemode override schemas and pass info and codemode to hooks", () => + Effect.gen(function* () { + type Equal = (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 ? true : false + + const plugins = yield* Plugin.Service + const tools = yield* Tool.Service + const seen: Array<{ tool: string; codemode: boolean; override: boolean }> = [] + yield* PluginPromise.fromPromise({ + id: "override-promise-tool", + async setup(context) { + await context.tool.hook("execute.before", (event) => { + seen.push({ + tool: event.tool, + codemode: event.codemode, + override: typeof event.info?.options?.codemode === "object", + }) + }) + await context.tool.transform((editor) => { + editor.add({ + name: "shell_like", + description: "Direct shell", + input: Schema.Struct({ command: Schema.String, background: Schema.optionalKey(Schema.Boolean) }), + output: Schema.String, + options: { + codemode: { + description: "Code Mode shell", + input: Schema.Struct({ command: Schema.String }), + output: Schema.Struct({ summary: Schema.String }), + }, + }, + execute: async (input, ctx) => { + const _inputExact: Equal< + typeof input, + { readonly command: string; readonly background?: boolean } | { readonly command: string } + > = true + const background = "background" in input ? input.background : undefined + const _backgroundOptional: Equal = true + void _inputExact + void _backgroundOptional + const text = `${input.command}:${String(background ?? "none")}` + return { output: ctx.codemode ? { summary: text } : text } + }, + }) + editor.add({ + name: "plain_typed", + description: "Unchanged plain tool", + input: Schema.Struct({ count: Schema.Number }), + execute: async (input) => { + const _unchanged: Equal = true + void _unchanged + return { content: String(input.count) } + }, + }) + }) + }, + }).effect(yield* PluginHost.make(plugins, "test")) + + const direct = yield* tools.snapshot(undefined, { tools: { direct: new Set(["shell_like"]) } }) + expect( + (yield* direct.execute({ + sessionID: Session.ID.make("ses_promise_override"), + agent: Agent.ID.make("build"), + messageID: SessionMessage.ID.make("msg_promise_override"), + call: { type: "tool-call", id: "call_direct", name: "shell_like", input: { command: "ls", background: true } }, + })).output, + ).toBe("ls:true") + + const inCodeMode = yield* tools.snapshot() + expect( + (yield* inCodeMode.execute({ + sessionID: Session.ID.make("ses_promise_override"), + agent: Agent.ID.make("build"), + messageID: SessionMessage.ID.make("msg_promise_override"), + call: { + type: "tool-call", + id: "call_cm", + name: "execute", + input: { code: 'return await tools.shell_like({ command: "pwd" })' }, + }, + })).output, + ).toMatchObject({ output: JSON.stringify({ summary: "pwd:none" }) }) + expect(seen).toEqual([ + { tool: "shell_like", codemode: false, override: true }, + { tool: "execute", codemode: false, override: false }, + { tool: "shell_like", codemode: true, override: true }, + ]) + }), +) diff --git a/packages/core/test/plugin/provider-opencode-watches.test.ts b/packages/core/test/plugin/provider-opencode-watches.test.ts index a5329a69e99..e461a00ed3a 100644 --- a/packages/core/test/plugin/provider-opencode-watches.test.ts +++ b/packages/core/test/plugin/provider-opencode-watches.test.ts @@ -912,6 +912,7 @@ describe("OpencodePlugin event watches", () => { const shell = (command: string, output: string) => hooks.trigger("tool", "execute.after", { tool: "shell", + codemode: false, sessionID: session.id, agent: Agent.ID.make("build"), messageID: SessionMessage.ID.create(), @@ -952,6 +953,7 @@ describe("OpencodePlugin event watches", () => { console.state.refuse = refuse yield* hooks.trigger("tool", "execute.after", { tool: "shell", + codemode: false, sessionID: session.id, agent: Agent.ID.make("build"), messageID: SessionMessage.ID.create(), diff --git a/packages/core/test/plugin/tool-input-repair-integration.test.ts b/packages/core/test/plugin/tool-input-repair-integration.test.ts index 38578f105c8..eff2481e469 100644 --- a/packages/core/test/plugin/tool-input-repair-integration.test.ts +++ b/packages/core/test/plugin/tool-input-repair-integration.test.ts @@ -153,3 +153,47 @@ it.effect("repairs namespaced inner tool input called from Code Mode", () => expect(executed).toEqual([{ count: 3 }]) }), ) + +it.effect("repairs nested Code Mode calls against the Code Mode input schema", () => + Effect.gen(function* () { + const plugins = yield* Plugin.Service + const registry = yield* Tool.Service + const executed: unknown[] = [] + yield* plugins.activate([{ ...ToolInputRepairPlugin.Plugin, revision: "1" }]) + yield* registry.transform((draft) => + draft.add({ + name: "inspect", + description: "Inspect", + input: Schema.Struct({ count: Schema.Int }), + options: { + codemode: { + input: Schema.Struct({ count: Schema.Int, detail: Schema.optionalKey(Schema.Boolean) }), + }, + }, + execute: (input) => Effect.sync(() => executed.push(input)).pipe(Effect.as({ content: "ok" })), + }), + ) + + const inCodeMode = yield* registry.snapshot() + yield* inCodeMode.execute({ + ...identity, + call: { + type: "tool-call", + id: "call-codemode-dynamic", + name: "execute", + input: { code: 'return await tools.inspect({ count: "3", detail: "true", extra: true })' }, + }, + }) + const direct = yield* registry.snapshot(undefined, { tools: { direct: new Set(["inspect"]) } }) + yield* direct.execute({ + ...identity, + call: { + type: "tool-call", + id: "call-direct-dynamic", + name: "inspect", + input: { count: "4", detail: true }, + }, + }) + expect(executed).toEqual([{ count: 3, detail: true }, { count: 4 }]) + }), +) diff --git a/packages/core/test/plugin/tool-input-repair.test.ts b/packages/core/test/plugin/tool-input-repair.test.ts index df3cc01413e..c5bfd444eab 100644 --- a/packages/core/test/plugin/tool-input-repair.test.ts +++ b/packages/core/test/plugin/tool-input-repair.test.ts @@ -10,8 +10,17 @@ import { it } from "../lib/effect" import { host } from "./host" function run(input: unknown, inputSchema: JsonSchema.JsonSchema) { + const tool = { + id: "test", + name: "test", + description: "Test repair", + input: inputSchema, + execute: () => Effect.succeed({ content: "unused" }), + } const event: ToolHooks["execute.before"] = { tool: "test", + info: tool, + codemode: false, input, sessionID: Session.ID.make("ses_repair"), agent: Agent.ID.make("build"), @@ -22,13 +31,6 @@ function run(input: unknown, inputSchema: JsonSchema.JsonSchema) { "execute.before": event, "execute.after": { ...event, status: "error", error: new Tool.Error({ message: "unused" }) }, } - const tool = { - id: "test", - name: "test", - description: "Test repair", - input: inputSchema, - execute: () => Effect.succeed({ content: "unused" }), - } const base = host() return ToolInputRepairPlugin.Plugin.effect( host({ diff --git a/packages/core/test/session-generate.test.ts b/packages/core/test/session-generate.test.ts index 072eb772d37..6ce5c0faf70 100644 --- a/packages/core/test/session-generate.test.ts +++ b/packages/core/test/session-generate.test.ts @@ -95,6 +95,7 @@ const client = Layer.mock(LLMClient.Service)({ }), }) const models = Layer.mock(SessionRunnerModel.Service)({ + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed( SessionRunnerModel.resolved(model, { diff --git a/packages/core/test/session-runner-recorded.test.ts b/packages/core/test/session-runner-recorded.test.ts index b0c1fac750a..ad2a0b8ebc6 100644 --- a/packages/core/test/session-runner-recorded.test.ts +++ b/packages/core/test/session-runner-recorded.test.ts @@ -66,6 +66,7 @@ const model = OpenAIChat.route }) .model({ id: "gpt-4o-mini", capabilities: { promptCacheKey: true } }) const models = Layer.mock(SessionRunnerModel.Service)({ + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed( SessionRunnerModel.resolved(model, { diff --git a/packages/core/test/session-runner.test.ts b/packages/core/test/session-runner.test.ts index 498af59f406..2ae6f0ab732 100644 --- a/packages/core/test/session-runner.test.ts +++ b/packages/core/test/session-runner.test.ts @@ -348,6 +348,14 @@ const layer = Layer.unwrap( ) const echoNode = makeLocationNode({ name: "test/session-runner-tools", layer: echo, deps: [Tool.node] }) const models = Layer.mock(SessionRunnerModel.Service)({ + select: (session) => + Effect.sync(() => { + const selected = session.model?.id === "replacement" ? replacementModel : state.currentModel + return { + info: Model.Info.default(Provider.ID.make(selected.provider), Model.ID.make(selected.id)), + variant: session.model?.variant, + } + }), resolve: (session) => state.modelResolveHook.pipe( Effect.map(() => { diff --git a/packages/core/test/shell-restart.test.ts b/packages/core/test/shell-restart.test.ts index 1882acc901c..edc22f48ba2 100644 --- a/packages/core/test/shell-restart.test.ts +++ b/packages/core/test/shell-restart.test.ts @@ -39,6 +39,7 @@ const idleCommand = process.platform === "win32" ? "Start-Sleep -Seconds 60" : " const model = SessionRunnerModel.node.replace( Layer.succeed(SessionRunnerModel.Service, { + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed( SessionRunnerModel.resolved(LanguageModel.make({ id: "restart", provider: "test", route: OpenAIChat.route }), { diff --git a/packages/core/test/subagent-idle-e2e.test.ts b/packages/core/test/subagent-idle-e2e.test.ts index 57462dd498b..f905d9ec6b7 100644 --- a/packages/core/test/subagent-idle-e2e.test.ts +++ b/packages/core/test/subagent-idle-e2e.test.ts @@ -95,6 +95,7 @@ const nodes = LayerNode.group([ const modelLayer = Layer.succeed( SessionRunnerModel.Service, SessionRunnerModel.Service.of({ + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: (_session, _available, request) => Effect.succeed( SessionRunnerModel.resolved( diff --git a/packages/core/test/subagent-lifetime.test.ts b/packages/core/test/subagent-lifetime.test.ts index d24148b8d9b..5a7c9b1c4f6 100644 --- a/packages/core/test/subagent-lifetime.test.ts +++ b/packages/core/test/subagent-lifetime.test.ts @@ -35,6 +35,7 @@ const it = testEffect( LayerNodePlatform.llmClient.replace(llmLayer), SessionRunnerModel.node.replace( Layer.succeed(SessionRunnerModel.Service, { + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed( SessionRunnerModel.resolved( diff --git a/packages/core/test/tool-model-policy.test.ts b/packages/core/test/tool-model-policy.test.ts new file mode 100644 index 00000000000..31505d591ea --- /dev/null +++ b/packages/core/test/tool-model-policy.test.ts @@ -0,0 +1,289 @@ +import { describe, expect, test } from "bun:test" +import { Agent } from "@opencode/core/agent" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { FileMutation } from "@opencode/core/file-mutation" +import { FileWrite } from "@opencode/core/file-write" +import { Flag } from "@opencode/core/flag" +import { Formatter } from "@opencode/core/formatter" +import { InstructionBuiltIns } from "@opencode/core/instructions/builtins" +import { InstructionDiscovery } from "@opencode/core/instruction-discovery" +import { Instructions } from "@opencode/core/instructions/index" +import { Location } from "@opencode/core/location" +import { Mcp } from "@opencode/core/mcp/index" +import { Model } from "@opencode/core/model" +import { Provider } from "@opencode/core/provider" +import { ReferenceInstructions } from "@opencode/core/reference/instructions" +import { AbsolutePath } from "@opencode/core/schema" +import { Session } from "@opencode/core/session" +import { SessionContext } from "@opencode/core/session/context" +import { SessionRunnerModel } from "@opencode/core/session/runner/model" +import { SkillInstructions } from "@opencode/core/skill/instructions" +import { Tool } from "@opencode/core/tool" +import { modelTools } from "@opencode/core/tool/model-policy" +import { EditTool } from "@opencode/core/tool/plugin/edit" +import { PatchTool } from "@opencode/core/tool/plugin/patch" +import { WriteTool } from "@opencode/core/tool/plugin/write" +import { WebSearch } from "@opencode/core/websearch" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { Effect, Layer, Schema } from "effect" +import { testEffect } from "./lib/effect" +import { readInitial } from "./lib/instructions" +import { codeModeListings, registerToolPlugin } from "./lib/tool" +import { PluginTestLayer } from "./plugin/fixture" + +const makeModel = ( + providerID: string, + id: string, + overrides: Partial> = {}, +): Model.Info => ({ + ...Model.Info.default(Provider.ID.make(providerID), Model.ID.make(id)), + ...overrides, + package: Provider.aisdk("@ai-sdk/openai"), +}) + +const policy = (model: Model.Info | undefined, websearch = true, fullCodeMode = true) => { + const result = modelTools({ model, websearch, fullCodeMode }) + return { direct: [...result.direct].sort(), hidden: [...result.hidden].sort() } +} + +describe("modelTools", () => { + test("gives GPT-5+ patch and leaves file tools, shell, and websearch in Code Mode when fullCodeMode is on", () => { + for (const model of [makeModel("openai", "gpt-5"), makeModel("azure", "dep", { modelID: Model.ID.make("gpt-6") })]) + expect(policy(model)).toEqual({ + direct: [], + hidden: ["edit", "glob", "grep", "webfetch", "write"], + }) + }) + + test("keeps edit and write instead of patch for gpt-4 and gpt-oss models", () => { + for (const model of [ + makeModel("openai", "gpt-4.1"), + makeModel("openrouter", "openai/gpt-oss-120b"), + makeModel("azure", "gpt-dep", { modelID: Model.ID.make("gpt-4o") }), + ]) + expect(policy(model)).toEqual({ + direct: [], + hidden: ["glob", "grep", "patch", "webfetch"], + }) + }) + + test("treats Anthropic, Claude, and claude-agent models as strong when fullCodeMode is on", () => { + for (const model of [ + makeModel("anthropic", "custom-sonnet"), + makeModel("claude-agent", "opus"), + makeModel("gateway", "sonnet", { canonical: Provider.ID.make("anthropic") }), + makeModel("gateway", "opus", { canonical: Provider.ID.make("claude-agent") }), + makeModel("amazon-bedrock", "us.anthropic.claude-opus-4-6-v1"), + makeModel("custom", "alias", { modelID: Model.ID.make("claude-sonnet-4-5") }), + makeModel("custom", "sonnet-v4", { family: Model.Family.make("claude-sonnet") }), + ]) + expect(policy(model)).toEqual({ + direct: [], + hidden: ["glob", "grep", "patch", "webfetch"], + }) + }) + + test("needs no demotion when fullCodeMode is off while still applying patch and websearch rules", () => { + expect(policy(makeModel("openai", "gpt-5"), true, false)).toEqual({ direct: [], hidden: ["edit", "write"] }) + expect(policy(makeModel("claude-agent", "opus"), false, false)).toEqual({ + direct: [], + hidden: ["patch", "websearch"], + }) + }) + + test("keeps non-strong and absent models direct when fullCodeMode is on, hiding websearch when unavailable", () => { + expect(policy(makeModel("deepseek", "deepseek-reasoner"))).toEqual({ + direct: ["edit", "read", "shell", "websearch", "write"], + hidden: ["patch"], + }) + expect(policy(undefined, true, true)).toEqual({ + direct: ["edit", "patch", "read", "shell", "websearch", "write"], + hidden: [], + }) + expect(policy(undefined, false, true)).toEqual({ + direct: ["edit", "patch", "read", "shell", "write"], + hidden: ["websearch"], + }) + }) +}) + +const emptyInstructions = () => Effect.succeed(Instructions.empty) +const makeContextLayer = (overrides: string | undefined) => + Layer.mergeAll( + PluginTestLayer, + AppNodeBuilder.build(LayerNode.group([SessionContext.node, FileMutation.node, FileWrite.node, Formatter.node]), [ + Location.node.replace(Location.boundNode({ directory: AbsolutePath.make("/project") })), + Mcp.node.replace( + Layer.mock(Mcp.Service, { + awaitStartup: () => Effect.void, + instructions: () => Effect.succeed([{ server: Mcp.ServerName.make("alpha"), instructions: "Alpha docs" }]), + tools: () => + Effect.succeed([{ server: Mcp.ServerName.make("alpha"), name: "search", inputSchema: { type: "object" } }]), + }), + ), + InstructionBuiltIns.node.replace(Layer.mock(InstructionBuiltIns.Service, { load: emptyInstructions })), + InstructionDiscovery.node.replace( + Layer.mock(InstructionDiscovery.Service, { + project: true, + global: true, + claude: true, + load: emptyInstructions, + }), + ), + SkillInstructions.node.replace(Layer.mock(SkillInstructions.Service, { load: emptyInstructions })), + ReferenceInstructions.node.replace(Layer.mock(ReferenceInstructions.Service, { load: emptyInstructions })), + ]), + ).pipe(Layer.provide(Layer.succeed(Flag.Overrides, overrides))) + +const setupContext = Effect.gen(function* () { + const agents = yield* Agent.Service + const providers = yield* Provider.Service + const models = yield* Model.Service + const registry = yield* Tool.Service + const websearch = yield* WebSearch.Service + const sessions = yield* Session.Service + const context = yield* SessionContext.Service + const flags = yield* Flag.Service + const fullCodeMode = yield* flags.enabled("full_codemode") + + yield* Effect.all([ + registerToolPlugin(EditTool.Plugin), + registerToolPlugin(WriteTool.Plugin), + registerToolPlugin(PatchTool.Plugin), + ]) + yield* agents.transform((editor) => + editor.update(Agent.defaultID, (agent) => { + agent.mode = "primary" + }), + ) + yield* providers.transform((editor) => { + for (const id of ["openai", "anthropic", "deepseek"]) + editor.update(Provider.ID.make(id), (provider) => { + provider.activation = "enabled" + }) + }) + yield* models.transform((editor) => { + for (const [provider, id] of [ + ["openai", "gpt-5"], + ["anthropic", "claude-sonnet-4-5"], + ["deepseek", "deepseek-reasoner"], + ] as const) + editor.update(Provider.ID.make(provider), Model.ID.make(id), (model) => { + model.package = Provider.aisdk("@ai-sdk/openai") + }) + }) + yield* websearch.transform((editor) => + editor.add({ id: WebSearch.ID.make("exa"), name: "Exa", execute: () => Effect.succeed([]) }), + ) + yield* registry.transform((editor) => { + for (const name of ["read", "glob", "grep", "webfetch", "websearch", "shell"]) { + const variant = name === "read" || name === "shell" + editor.add({ + name, + description: `Direct ${name}`, + input: Schema.Struct({}), + output: Schema.String, + options: variant + ? fullCodeMode + ? { codemode: { pinned: true, description: `Code Mode ${name}` } } + : { codemode: false } + : name === "websearch" + ? { codemode: fullCodeMode } + : { codemode: false }, + execute: () => Effect.succeed({ output: name }), + }) + } + editor.add({ + name: "session_move", + description: "Move session", + input: Schema.Struct({}), + output: Schema.String, + options: { namespace: "opencode", codemode: { pinned: true } }, + execute: () => Effect.succeed({ output: "moved" }), + }) + }) + + const select = (providerID: string, id: string, permissions?: Session.Info["permissions"]) => + sessions + .create({ + location: Location.Ref.make({ directory: AbsolutePath.make("/project") }), + model: Model.Ref.make({ providerID: Provider.ID.make(providerID), id: Model.ID.make(id) }), + ...(permissions ? { permissions } : {}), + }) + .pipe(Effect.flatMap((session) => context.select(session.id))) + + return { registry, websearch, context, select } +}) + +const names = (selected: SessionContext.Selection) => selected.tools.definitions.map((tool) => tool.name) +const paths = (selected: SessionContext.Selection) => + codeModeListings(selected.tools.codeModeCatalog!).map((entry) => entry.path) +const defaultIt = testEffect(makeContextLayer(undefined)) +const codeModeIt = testEffect(makeContextLayer("full_codemode")) + +describe("SessionContext.select model tool policy", () => { + defaultIt.effect("keeps strong-model tools direct when full_codemode is off", () => + Effect.gen(function* () { + const { select } = yield* setupContext + expect(names(yield* select("openai", "gpt-5")).join(",")).toBe( + "glob,grep,patch,read,shell,webfetch,websearch,execute", + ) + }), + ) + + codeModeIt.effect( + "places tools per model, propagates Code Mode to MCP instructions, and uses configured ref fallback", + () => + Effect.gen(function* () { + const { registry, websearch, context, select } = yield* setupContext + + const catalog = (yield* registry.snapshot()).codeModeCatalog! + for (const name of ["edit", "write", "patch"]) { + const entry = catalog.tools.find((item) => item.type === "tool" && item.name === name) + expect(entry).toMatchObject({ type: "tool", pinned: true }) + if (entry?.type !== "tool") continue + expect(entry.description).not.toContain("\n") + expect(entry.description.length).toBeLessThan(500) + } + + const gpt = yield* select("openai", "gpt-5") + expect(names(gpt)).toEqual(["execute"]) + const gptListings = codeModeListings(gpt.tools.codeModeCatalog!) + expect(gptListings.map((entry) => entry.path)).toEqual([ + "alpha.search", + "opencode.session_move", + "patch", + "read", + "shell", + "websearch", + ]) + expect(gptListings.find((entry) => entry.path === "patch")?.line).toContain("*** Begin Patch") + expect(gptListings.find((entry) => entry.path === "read")?.line).toContain("Code Mode read") + expect((yield* readInitial(gpt.instructions)).text).toContain( + 'Use tools from this server through `execute` under `tools["alpha"]`.', + ) + + const gptDirect = yield* select("openai", "gpt-5", [{ action: "execute", resource: "*", effect: "deny" }]) + const directInstructions = (yield* readInitial(gptDirect.instructions)).text + expect(directInstructions).toContain("Alpha docs") + expect(directInstructions).not.toContain("through `execute`") + + const claude = yield* select("anthropic", "claude-sonnet-4-5") + expect(names(claude)).toEqual(["execute"]) + expect(paths(claude).join(",")).toBe("alpha.search,edit,opencode.session_move,read,shell,websearch,write") + + const deepseek = yield* select("deepseek", "deepseek-reasoner") + expect(names(deepseek).join(",")).toBe("edit,glob,grep,read,shell,webfetch,websearch,write,execute") + expect(paths(deepseek)).toEqual(["alpha.search", "opencode.session_move"]) + + yield* websearch.select(false) + expect(paths(yield* select("openai", "gpt-5"))).not.toContain("websearch") + + const unavailable = yield* select("openai", "gpt-5-missing") + expect(paths(unavailable)).toContain("patch") + expect(yield* context.load(unavailable).pipe(Effect.flip)).toBeInstanceOf( + SessionRunnerModel.ModelUnavailableError, + ) + }), + ) +}) diff --git a/packages/core/test/tool-opencode.test.ts b/packages/core/test/tool-opencode.test.ts index 869b7b26595..76fa6cabbb9 100644 --- a/packages/core/test/tool-opencode.test.ts +++ b/packages/core/test/tool-opencode.test.ts @@ -5,6 +5,7 @@ import { Database } from "@opencode/core/database/database" import { Location } from "@opencode/core/location" import { Permission } from "@opencode/core/permission" import { Plugin } from "@opencode/core/plugin" +import { PluginHooks } from "@opencode/core/plugin/hooks" import { PluginHost } from "@opencode/core/plugin/host" import { ProjectTable } from "@opencode/core/project/sql" import { Provider } from "@opencode/core/provider" @@ -261,3 +262,32 @@ worktreeIt.live("creates, lists, and removes worktrees for the plugin's project" expect((yield* run("worktree_list", {})).worktrees).not.toContainEqual({ directory, strategy: "git" }) }), ) + +it.effect("adapts the worktree session_move hint to execute, direct tools, or neither", () => + Effect.gen(function* () { + const plugins = yield* Plugin.Service + const hooks = yield* PluginHooks.Service + yield* OpenCodeTools.Plugin.effect(yield* PluginHost.make(plugins, "test")) + const model = Model.Ref.make({ providerID: Provider.ID.make("test"), id: Model.ID.make("alpha") }) + const trigger = (tools: Record }>) => + hooks + .trigger("session", "context", { + sessionID: Session.ID.make("ses_opencode_hint"), + agent: toolIdentity.agent, + model, + system: [], + messages: [], + tools, + options: {}, + }) + .pipe(Effect.map((event) => event.system.map((part) => part.text))) + + expect(yield* trigger({ execute: { description: "execute", input: {} } })).toEqual([ + "When you create a worktree outside the current working directory and intend to use it as your primary working directory, consider using `execute` to call `tools.opencode.session_move` and make the worktree the session's working directory.", + ]) + expect(yield* trigger({ opencode_session_move: { description: "move", input: {} } })).toEqual([ + "When you create a worktree outside the current working directory and intend to use it as your primary working directory, consider calling `opencode_session_move` to make the worktree the session's working directory.", + ]) + expect(yield* trigger({ read: { description: "read", input: {} } })).toEqual([]) + }), +) diff --git a/packages/core/test/tool-patch.test.ts b/packages/core/test/tool-patch.test.ts index 0fbe32a5d01..6faed32db9e 100644 --- a/packages/core/test/tool-patch.test.ts +++ b/packages/core/test/tool-patch.test.ts @@ -11,14 +11,11 @@ import { Formatter } from "@opencode/core/formatter" import { FileMutation } from "@opencode/core/file-mutation" import { Location } from "@opencode/core/location" import { FileAccess } from "@opencode/core/file-access" -import { Model } from "@opencode/core/model" import { Permission } from "@opencode/core/permission" -import { Provider } from "@opencode/core/provider" import { AbsolutePath } from "@opencode/core/schema" import { Session } from "@opencode/core/session" import { Tool } from "@opencode/core/tool" import { PatchTool } from "@opencode/core/tool/plugin/patch" -import type { SessionHooks } from "@opencode/plugin/effect/session" import { transformEnvironmentFiles } from "./fixture/environment" import { location } from "./fixture/location" import { tmpdir, withTempDir } from "./fixture/tmpdir" @@ -27,20 +24,9 @@ import { testEffect } from "./lib/effect" import { permissionLayer } from "./lib/permission" import { toolIdentity, executeTool, registerToolPlugin, toolDefinitions } from "./lib/tool" -const sessionHooks = new Map Effect.Effect>() const patchToolNode = makeLocationNode({ name: "test/patch-tool-plugin", - layer: Layer.effectDiscard( - registerToolPlugin(PatchTool.Plugin, { - session: { - hook: (name, callback) => - Effect.sync(() => { - sessionHooks.set(name, callback as (event: SessionHooks["context"]) => Effect.Effect) - return { dispose: Effect.void } - }), - }, - }), - ), + layer: Layer.effectDiscard(registerToolPlugin(PatchTool.Plugin)), deps: [ Tool.node, FileAccess.node, @@ -168,34 +154,6 @@ const withTempTool = (body: (directory: string, registry: Tool.Interfac }) describe("PatchTool", () => { - it.live("selects the same edit tools for compaction and generate requests as the agent loop", () => - withTempTool(() => - Effect.gen(function* () { - const event = (id: string): SessionHooks["context"] => ({ - sessionID, - agent: toolIdentity.agent, - model: Model.Ref.make({ providerID: Provider.ID.make("test"), id: Model.ID.make(id) }), - system: [], - messages: [], - tools: Object.fromEntries( - ["patch", "edit", "write", "read"].map((name) => [name, { description: name, input: { type: "object" } }]), - ), - options: {}, - }) - for (const name of ["context", "compaction", "generate"]) { - const hook = sessionHooks.get(name) - expect(hook).toBeDefined() - const claude = event("claude-sonnet-4") - yield* hook!(claude) - expect(Object.keys(claude.tools)).toEqual(["edit", "write", "read"]) - const gpt = event("gpt-5") - yield* hook!(gpt) - expect(Object.keys(gpt.tools)).toEqual(["patch", "read"]) - } - }), - ), - ) - it.live("registers and sequentially applies add, update, and delete hunks", () => withTempDir((tmp) => { reset() diff --git a/packages/core/test/tool-read.test.ts b/packages/core/test/tool-read.test.ts index 7bdaa54b4ba..e42ed66c2d3 100644 --- a/packages/core/test/tool-read.test.ts +++ b/packages/core/test/tool-read.test.ts @@ -139,6 +139,7 @@ const readLayer = (imageLayer: Layer.Layer) => imageLayer, ) const it = testEffect(readLayer(imageLayer)) +const codeModeIt = testEffect(readLayer(imageLayer).pipe(Layer.provide(Layer.succeed(Flag.Overrides, "full_codemode")))) // Real-file tests provide their own layer per temp folder. const live = testEffect(Layer.empty) // Reads through the real filesystem with the location at `directory`. @@ -195,7 +196,9 @@ describe("ReadTool", () => { Effect.gen(function* () { const registry = yield* Tool.Service - expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["read", "execute"]) + const direct = yield* toolDefinitions(registry) + expect(direct.map((tool) => tool.name)).toEqual(["read", "execute"]) + expect(direct[0]?.description).toContain("Each text line is prefixed by its 1-based line number") expect( (yield* toolDefinitions(registry, [{ action: "read", resource: "*", effect: "deny" }])).map( (tool) => tool.name, @@ -222,6 +225,25 @@ describe("ReadTool", () => { }), ) + codeModeIt.effect("places read in Code Mode with full_codemode unless demoted to direct", () => + Effect.gen(function* () { + const registry = yield* Tool.Service + const inCodeMode = yield* registry.snapshot() + expect(inCodeMode.definitions.map((tool) => tool.name)).toEqual(["execute"]) + expect(inCodeMode.codeModeCatalog?.tools[0]).toMatchObject({ + type: "tool", + name: "read", + pinned: true, + }) + expect(inCodeMode.codeModeCatalog?.tools[0]?.description).toContain( + "Reading an image or PDF automatically attaches it to the execute result", + ) + const demoted = yield* registry.snapshot(undefined, { tools: { direct: new Set(["read"]) } }) + expect(demoted.definitions.map((tool) => tool.name)).toEqual(["read", "execute"]) + expect(demoted.definitions[0]?.description).toContain("Each text line is prefixed by its 1-based line number") + }), + ) + it.effect("rejects a zero limit before reading", () => Effect.gen(function* () { const registry = yield* Tool.Service diff --git a/packages/core/test/tool-registry.test.ts b/packages/core/test/tool-registry.test.ts index 2d14ed4be58..c2d3ef1ec49 100644 --- a/packages/core/test/tool-registry.test.ts +++ b/packages/core/test/tool-registry.test.ts @@ -43,7 +43,7 @@ const registryLayer = AppNodeBuilder.build(LayerNode.group([Tool.node, PluginHoo ...toolNodeReplacements(), Image.node.replace(imageStore), ]) -const it = testEffect(registryLayer) +const it = testEffect(registryLayer.pipe(Layer.provide(Layer.succeed(Flag.Overrides, undefined)))) const codeModeIt = testEffect(registryLayer.pipe(Layer.provide(Layer.succeed(Flag.Overrides, "full_codemode")))) const identity = { agent: Agent.ID.make("build"), @@ -80,7 +80,7 @@ const transform = (service: Tool.Interface, tools: Readonly describe("Code Mode path and Bun", () => { const types = Effect.gen(function* () { const tools = yield* Tool.Service - const snapshot = yield* tools.snapshot(undefined, codeModeServices("/session/dir")) + const snapshot = yield* tools.snapshot(undefined, { services: codeModeServices("/session/dir") }) const result = yield* snapshot.execute({ ...call("execute"), call: { @@ -753,6 +753,243 @@ describe("Tool", () => { }), ) + it.effect( + "places tools with options.codemode overrides in Code Mode by default, honors direct policy demotion, and resolves pinned", + () => + Effect.gen(function* () { + type Equal = (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 ? true : false + + const service = yield* Tool.Service + const hooks = yield* PluginHooks.Service + const hooked: Array<{ phase: string; tool: string; codemode: boolean; override: boolean }> = [] + yield* hooks.register("tool", "execute.before", (event) => + Effect.sync(() => { + hooked.push({ + phase: "before", + tool: event.tool, + codemode: event.codemode, + override: typeof event.info?.options?.codemode === "object", + }) + }), + ) + yield* hooks.register("tool", "execute.after", (event) => + Effect.sync(() => { + hooked.push({ + phase: "after", + tool: event.tool, + codemode: event.codemode, + override: typeof event.info?.options?.codemode === "object", + }) + }), + ) + const directInput = Schema.Struct({ command: Schema.String, background: Schema.optionalKey(Schema.Boolean) }) + const codemodeInput = Schema.Struct({ command: Schema.String }) + const codemodeOutput = Schema.Struct({ summary: Schema.String }) + yield* service.transform((editor) => { + editor.add({ + name: "shell", + description: "Direct shell", + input: directInput, + output: Schema.String, + options: { + codemode: { + pinned: true, + description: "Code Mode shell", + input: codemodeInput, + output: codemodeOutput, + }, + }, + execute: (input, context) => { + const _inputExact: Equal< + typeof input, + { readonly command: string; readonly background?: boolean } | { readonly command: string } + > = true + const background = "background" in input ? input.background : undefined + const _backgroundOptional: Equal = true + void _inputExact + void _backgroundOptional + const summary = `${input.command}:${"background" in input ? String(input.background) : "omitted"}:${String(Boolean(context.codemode))}` + return Effect.succeed({ output: context.codemode ? { summary } : summary }) + }, + }) + editor.add({ + name: "glob", + description: "Find files", + input: Schema.Struct({ pattern: Schema.String }), + output: Schema.String, + options: { codemode: false }, + execute: (input) => { + const _unchanged: Equal = true + void _unchanged + return Effect.succeed({ output: input.pattern }) + }, + }) + editor.add({ ...make(), name: "mcp_search" }) + editor.add({ ...make(), name: "legacy_pin", options: { pinned: true } }) + editor.add({ ...make(), name: "unpinned_override", options: { codemode: { pinned: false }, pinned: true } }) + }) + + const listed = (yield* service.list()).find((tool) => tool.id === "shell") + expect(listed?.description).toBe("Direct shell") + expect(typeof listed?.options?.codemode).toBe("object") + + // An override object places the tool in Code Mode by default; codemode: false stays direct. + const defaultSnap = yield* service.snapshot() + expect(defaultSnap.definitions.map((tool) => tool.name)).toEqual(["glob", "execute"]) + const listings = codeModeListings(defaultSnap.codeModeCatalog!) + expect(listings.map((tool) => tool.path)).toEqual(["legacy_pin", "mcp_search", "shell", "unpinned_override"]) + const shellListing = listings.find((tool) => tool.path === "shell")! + expect(shellListing.line).toContain("Code Mode shell") + expect(shellListing.line).not.toContain("background") + expect(defaultSnap.codeModeCatalog?.tools.find((tool) => tool.name === "shell")).toMatchObject({ pinned: true }) + expect(defaultSnap.codeModeCatalog?.tools.find((tool) => tool.name === "legacy_pin")).toMatchObject({ + pinned: true, + }) + expect(defaultSnap.codeModeCatalog?.tools.find((tool) => tool.name === "unpinned_override")).toMatchObject({ + pinned: false, + }) + + // Decodes and encodes Code Mode calls with the Code Mode override schemas and passes context.codemode = true. + const executed = yield* defaultSnap.execute({ + ...call("execute"), + call: { + type: "tool-call", + id: "call-cm-shell", + name: "execute", + input: { code: 'return await tools.shell({ command: "ls", background: true })' }, + }, + }) + expect(executed.output).toMatchObject({ output: JSON.stringify({ summary: "ls:omitted:true" }) }) + expect( + yield* service.check({ + code: 'return await tools.shell({ command: "build", background: true })', + tools: ["shell"], + bindings: {}, + permissions: [], + limits: {}, + context: { sessionID, ...identity, progress: () => Effect.void }, + }), + ).toMatchObject({ ok: true, value: { summary: "build:omitted:true" } }) + expect( + yield* service.check({ + code: 'return await tools.glob({ pattern: "*" })', + tools: ["glob"], + bindings: {}, + permissions: [], + limits: {}, + context: { sessionID, ...identity, progress: () => Effect.void }, + }), + ).toMatchObject({ ok: false, error: { kind: "UnknownTool" } }) + + // Policy `direct` keeps a Code Mode tool on the direct list with its direct description and schemas. + const demotePolicy = { hidden: new Set(["glob"]), direct: new Set(["shell"]) } + const demoted = yield* service.snapshot(undefined, { tools: demotePolicy }) + expect(demoted.definitions.map((tool) => tool.name)).toEqual(["shell", "execute"]) + expect(demoted.definitions.find((tool) => tool.name === "shell")?.description).toBe("Direct shell") + expect(demoted.definitions.find((tool) => tool.name === "shell")?.inputSchema.properties).toHaveProperty( + "background", + ) + expect( + (yield* demoted.execute({ + ...call("shell"), + call: { + type: "tool-call", + id: "call-direct-shell", + name: "shell", + input: { command: "ls", background: true }, + }, + })).output, + ).toBe("ls:true:false") + + // When execute is denied, Code Mode tools fall back to their direct form while hidden tools stay hidden. + const denied = yield* service.snapshot([{ action: "execute", resource: "*", effect: "deny" }], { + tools: { hidden: new Set(["glob"]) }, + }) + expect(denied.codeModeCatalog).toBeUndefined() + expect(denied.definitions.map((tool) => tool.name)).toEqual([ + "legacy_pin", + "mcp_search", + "shell", + "unpinned_override", + ]) + expect(denied.definitions.find((tool) => tool.name === "shell")?.description).toBe("Direct shell") + expect(denied.definitions.find((tool) => tool.name === "shell")?.inputSchema.properties).toHaveProperty( + "background", + ) + + // Plugin edits to tool.description only change the direct form; options.codemode stays intact. + yield* service.transform((editor) => { + expect(editor.get("shell")?.description).toBe("Direct shell") + editor.update("shell", (tool) => { + tool.description = "Edited direct shell" + }) + }) + expect( + (yield* service.snapshot(undefined, { tools: demotePolicy })).definitions.find( + (tool) => tool.name === "shell", + )?.description, + ).toBe("Edited direct shell") + expect( + codeModeListings((yield* service.snapshot()).codeModeCatalog!).find((tool) => tool.path === "shell")?.line, + ).toContain("Code Mode shell") + + expect(hooked).toEqual([ + { phase: "before", tool: "execute", codemode: false, override: false }, + { phase: "before", tool: "shell", codemode: true, override: true }, + { phase: "after", tool: "shell", codemode: true, override: true }, + { phase: "after", tool: "execute", codemode: false, override: false }, + { phase: "before", tool: "shell", codemode: true, override: true }, + { phase: "after", tool: "shell", codemode: true, override: true }, + { phase: "before", tool: "shell", codemode: false, override: true }, + { phase: "after", tool: "shell", codemode: false, override: true }, + ]) + }), + ) + + it.effect("caches the 5 most recently used Code Mode catalogs and invalidates on registry changes", () => + Effect.gen(function* () { + const service = yield* Tool.Service + yield* transform(service, { + t1: make(), + t2: make(), + t3: make(), + t4: make(), + t5: make(), + t6: make(), + }) + const deny = (action: string): Permission.Ruleset => [{ action, resource: "*", effect: "deny" }] + + const s1 = yield* service.snapshot(deny("t1")) + const s2 = yield* service.snapshot(deny("t2")) + const s3 = yield* service.snapshot(deny("t3")) + const s4 = yield* service.snapshot(deny("t4")) + const s5 = yield* service.snapshot(deny("t5")) + + // Touch s1 so s2 becomes least recently used, then insert a 6th distinct tool set. + expect((yield* service.snapshot(deny("t1"))).codeModeCatalog).toBe(s1.codeModeCatalog) + const s6 = yield* service.snapshot(deny("t6")) + + expect((yield* service.snapshot(deny("t1"))).codeModeCatalog).toBe(s1.codeModeCatalog) + expect((yield* service.snapshot(deny("t3"))).codeModeCatalog).toBe(s3.codeModeCatalog) + expect((yield* service.snapshot(deny("t4"))).codeModeCatalog).toBe(s4.codeModeCatalog) + expect((yield* service.snapshot(deny("t5"))).codeModeCatalog).toBe(s5.codeModeCatalog) + expect((yield* service.snapshot(deny("t6"))).codeModeCatalog).toBe(s6.codeModeCatalog) + expect((yield* service.snapshot(deny("t2"))).codeModeCatalog).not.toBe(s2.codeModeCatalog) + + // Invalidates inside State.batch before notify runs, as well as on reload. + const beforeBatch = yield* service.snapshot(deny("t1")) + yield* State.batch( + Effect.gen(function* () { + yield* transform(service, { extra: make() }) + expect((yield* service.snapshot(deny("t1"))).codeModeCatalog).not.toBe(beforeBatch.codeModeCatalog) + }), + ) + const afterBatch = yield* service.snapshot(deny("t1")) + yield* service.reload() + expect((yield* service.snapshot(deny("t1"))).codeModeCatalog).not.toBe(afterBatch.codeModeCatalog) + }), + ) + it.effect("exposes Code Mode tools directly when execute is denied", () => Effect.gen(function* () { const service = yield* Tool.Service diff --git a/packages/core/test/tool-subagent.test.ts b/packages/core/test/tool-subagent.test.ts index 15628d66d1e..3843e153890 100644 --- a/packages/core/test/tool-subagent.test.ts +++ b/packages/core/test/tool-subagent.test.ts @@ -165,6 +165,7 @@ const completionIt = testEffect( LayerNodePlatform.llmClient.replace(completionLLM), SessionRunnerModel.node.replace( Layer.succeed(SessionRunnerModel.Service, { + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed( SessionRunnerModel.resolved( diff --git a/packages/core/test/tool-websearch.test.ts b/packages/core/test/tool-websearch.test.ts index c9043eba6ff..d15f0f04a5e 100644 --- a/packages/core/test/tool-websearch.test.ts +++ b/packages/core/test/tool-websearch.test.ts @@ -19,10 +19,7 @@ import { permissionLayer } from "./lib/permission" import { toolIdentity, executeTool, registerToolPlugin, toolDefinitions, toolNodeReplacements } from "./lib/tool" import { webSearchHost } from "./plugin/host" import { TestWebSearch } from "./lib/websearch" -import type { SessionContext } from "@opencode/plugin/effect/session" -// The plugin's `context` hook, which edits the tools offered to the model. -const contextHooks: ((event: SessionContext) => Effect.Effect)[] = [] const webSearchToolNode = makeLocationNode({ name: "test/websearch-tool-plugin", layer: Layer.effectDiscard( @@ -30,13 +27,6 @@ const webSearchToolNode = makeLocationNode({ const websearch = yield* WebSearch.Service yield* registerToolPlugin(WebSearchTool.Plugin, { websearch: webSearchHost(websearch), - session: { - hook: (name, callback) => - Effect.sync(() => { - if (name === "context") contextHooks.push(callback as (event: SessionContext) => Effect.Effect) - return { dispose: Effect.void } - }), - }, }) }), ), @@ -358,23 +348,6 @@ describe("WebSearchTool registration", () => { }), ) - it.effect("offers the tool to the model only while a provider remains", () => - Effect.gen(function* () { - contextHooks.length = 0 - const fixture = yield* setup - const offered = Effect.fnUntraced(function* () { - const event = { tools: { [WebSearchTool.name]: { description: "", input: {} } } } - yield* Effect.forEach(contextHooks, (hook) => hook(event as unknown as SessionContext)) - return WebSearchTool.name in event.tools - }) - expect(yield* offered()).toBe(true) - - // As when policy denies every provider. - yield* fixture.websearch.transform((editor) => editor.list().forEach((provider) => editor.remove(provider.id))) - expect(yield* offered()).toBe(false) - }), - ) - it.effect("persists the choice to disable web search", () => Effect.gen(function* () { const fixture = yield* setup diff --git a/packages/plugin/src/effect/tool.ts b/packages/plugin/src/effect/tool.ts index 04494b2630e..c3eb6d9da50 100644 --- a/packages/plugin/src/effect/tool.ts +++ b/packages/plugin/src/effect/tool.ts @@ -9,8 +9,13 @@ export interface ToolEditor { list(): readonly (Tool.Info & { readonly id: string })[] get(id: string): (Tool.Info & { readonly id: string }) | undefined namespace(namespace: Tool.Namespace): void - add, Output extends Tool.ValueSchema | undefined>( - tool: Tool.Info, + add< + Input extends Tool.ValueSchema, + Output extends Tool.ValueSchema | undefined = undefined, + CMInput extends Tool.ValueSchema = Input, + CMOutput extends Tool.ValueSchema | undefined = Output, + >( + tool: Tool.Info, ): void /** Updates an existing tool; missing IDs are ignored. */ update(id: string, update: (tool: Types.Mutable) => void): void @@ -20,6 +25,8 @@ export interface ToolEditor { export interface ToolHooks { readonly "execute.before": { tool: string + readonly info?: Tool.Info + readonly codemode: boolean readonly sessionID: Session.ID readonly agent: Agent.ID readonly messageID: SessionMessage.ID @@ -28,6 +35,8 @@ export interface ToolHooks { } readonly "execute.after": { readonly tool: string + readonly info?: Tool.Info + readonly codemode: boolean readonly sessionID: Session.ID readonly agent: Agent.ID readonly messageID: SessionMessage.ID diff --git a/packages/plugin/src/promise/adapter.ts b/packages/plugin/src/promise/adapter.ts index ec91156ba46..c070175744a 100644 --- a/packages/plugin/src/promise/adapter.ts +++ b/packages/plugin/src/promise/adapter.ts @@ -6,10 +6,9 @@ import { Effect, Schema, SchemaAST, Stream } from "effect" import type { Scope } from "effect" import { HttpApiEndpoint, HttpApiSchema } from "effect/http-api" import { define } from "../effect/plugin.js" -import type { ToolFailures, ToolHooks } from "../effect/tool.js" import { AssertInput } from "../permission.js" import type { Plugin } from "./plugin.js" -import type { Info } from "./tool.js" +import type { Info, ToolHooks } from "./tool.js" import type { RpcDomain, RpcHandlers } from "./rpc.js" type HostRegistration = { readonly dispose: Effect.Effect } @@ -263,6 +262,40 @@ export function fromPromise(plugin: Plugin) { { signal: context.signal }, ) + // Only execute.before may reject a call; a rejection fails that call alone, like an Effect hook. + const adaptToolHook: { + readonly [Name in keyof ToolHooks]: ( + callback: (event: ToolHooks[Name]) => Promise | void, + ) => Parameters>[1] + } = { + "execute.before": (callback) => (event) => { + const adapted: ToolHooks["execute.before"] = { + ...event, + info: event.info && { ...event.info, execute: promiseExecutor(event.info.execute) }, + } + return Effect.tryPromise({ + try: () => + Promise.resolve(callback(adapted)).then(() => { + event.tool = adapted.tool + event.input = adapted.input + }), + catch: toolError, + }) + }, + "execute.after": (callback) => (event) => { + const adapted: ToolHooks["execute.after"] = { + ...event, + info: event.info && { ...event.info, execute: promiseExecutor(event.info.execute) }, + } + return Effect.promise(() => + Promise.resolve(callback(adapted)).then(() => { + if (event.status === "completed" && adapted.status === "completed") event.result = adapted.result + if (event.status === "error" && adapted.status === "error") event.error = adapted.error + }), + ) + }, + } + const adaptApiMethod = ( endpoint: HttpApiEndpoint.Top, method: (input: never) => Effect.Effect, @@ -551,8 +584,7 @@ export function fromPromise(plugin: Plugin) { }), ), ), - hook: (name, callback) => - register(host.tool.hook(name, (event) => toolHook[name](() => Promise.resolve(callback(event))))), + hook: (name, callback) => register(host.tool.hook(name, adaptToolHook[name](callback))), }, vcs: { get: adaptApiMethod(VcsEndpoints["vcs.get"], host.vcs.get), @@ -690,14 +722,6 @@ const toolError = (error: unknown) => ? error : new Tool.Error({ message: error instanceof Error ? error.message : String(error), error }) -// Only execute.before may reject a call; a rejection fails that call alone, like an Effect hook. -const toolHook: { - readonly [Name in keyof ToolHooks]: (run: () => Promise) => Effect.Effect -} = { - "execute.before": (run) => Effect.tryPromise({ try: run, catch: toolError }), - "execute.after": (run) => Effect.promise(run), -} - const executePromiseTool = (tool: Info, input: any, context: Tool.Context) => Effect.tryPromise({ try: (interrupted) => { diff --git a/packages/plugin/src/promise/tool.ts b/packages/plugin/src/promise/tool.ts index e2a05b47f66..cb9492b1881 100644 --- a/packages/plugin/src/promise/tool.ts +++ b/packages/plugin/src/promise/tool.ts @@ -22,28 +22,37 @@ export interface ToolContext extends Omit { export type Info< Input extends Tool.ValueSchema = Tool.ValueSchema, Output extends Tool.ValueSchema | undefined = Tool.ValueSchema | undefined, -> = Omit, "execute"> & { + CMInput extends Tool.ValueSchema = Input, + CMOutput extends Tool.ValueSchema | undefined = Output, +> = Omit, "execute"> & { readonly execute: ( - input: Parameters["execute"]>[0], + input: Parameters["execute"]>[0], context: ToolContext, - ) => Promise> + ) => Promise> } export interface ToolEditor { list(): readonly (Info & { readonly id: string })[] get(id: string): (Info & { readonly id: string }) | undefined namespace(namespace: Tool.Namespace): void - add, Output extends Tool.ValueSchema | undefined>( - tool: Info, + add< + Input extends Tool.ValueSchema, + Output extends Tool.ValueSchema | undefined = undefined, + CMInput extends Tool.ValueSchema = Input, + CMOutput extends Tool.ValueSchema | undefined = Output, + >( + tool: Info, ): void /** Updates an existing tool; missing IDs are ignored. */ update(id: string, update: (tool: Types.Mutable) => void): void remove(id: string): void } -interface ToolHooks { +export interface ToolHooks { readonly "execute.before": { tool: string + readonly info?: Info + readonly codemode: boolean readonly sessionID: Session.ID readonly agent: Agent.ID readonly messageID: SessionMessage.ID @@ -52,6 +61,8 @@ interface ToolHooks { } readonly "execute.after": { readonly tool: string + readonly info?: Info + readonly codemode: boolean readonly sessionID: Session.ID readonly agent: Agent.ID readonly messageID: SessionMessage.ID diff --git a/packages/schema/src/tool.ts b/packages/schema/src/tool.ts index c2f9f017d29..4fe0184e39a 100644 --- a/packages/schema/src/tool.ts +++ b/packages/schema/src/tool.ts @@ -34,6 +34,8 @@ export interface Context { * has; a tool that does not is interrupted. */ readonly cancel?: Effect.Effect + /** True when the tool is invoked from inside Code Mode (`execute`). */ + readonly codemode?: boolean } export interface Namespace { @@ -41,22 +43,23 @@ export interface Namespace { readonly description: string } -interface BaseOptions { +export interface Options< + CMInput extends ValueSchema = ValueSchema, + CMOutput extends ValueSchema | undefined = ValueSchema | undefined, +> { readonly namespace?: string readonly permission?: string -} - -export type Options = BaseOptions & - ( + readonly codemode?: + | boolean | { - readonly codemode?: true readonly pinned?: boolean + readonly description?: string + readonly input?: CMInput + readonly output?: CMOutput } - | { - readonly codemode: boolean - readonly pinned?: never - } - ) + /** @deprecated Use `codemode.pinned` instead. Removed in the next minor. */ + readonly pinned?: boolean +} export type ValueSchema = Schema.Codec | StandardSchemaV1 | JsonSchema.JsonSchema @@ -67,13 +70,15 @@ type InputValue = 0 extends 1 & S : S extends StandardSchemaV1 ? A : unknown -type OutputValue = S extends undefined - ? never - : S extends Schema.Codec - ? A - : S extends StandardSchemaV1 +type OutputValue = 0 extends 1 & S + ? any + : S extends undefined + ? never + : S extends Schema.Codec ? A - : any + : S extends StandardSchemaV1 + ? A + : any export class Error extends Schema.TaggedError()("Tool.Error", { message: Schema.String, @@ -109,12 +114,17 @@ export interface Result | undefined = ValueSchem export type Info< Input extends ValueSchema = ValueSchema, Output extends ValueSchema | undefined = ValueSchema | undefined, + CMInput extends ValueSchema = Input, + CMOutput extends ValueSchema | undefined = Output, > = { readonly name: string readonly input: Input readonly freeform?: Freeform readonly description: string - readonly execute: (input: InputValue, context: Context) => Effect.Effect, Error> + readonly execute: ( + input: InputValue | InputValue, + context: Context, + ) => Effect.Effect, Error> readonly output?: Output - readonly options?: Options + readonly options?: Options } diff --git a/packages/sdk/test/embedded.test.ts b/packages/sdk/test/embedded.test.ts index 85d270dd087..9c2697ed9fc 100644 --- a/packages/sdk/test/embedded.test.ts +++ b/packages/sdk/test/embedded.test.ts @@ -501,6 +501,7 @@ const workspaceModelScenario = (fixture: Fixture, policy: "eager" | "lazy") => }, }) const models = Layer.mock(SessionRunnerModel.Service, { + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed( SessionRunnerModel.resolved(model, { @@ -602,6 +603,7 @@ it.live( return TestLLM.toolCall("call-shell", "shell", { command: "echo hi" }) }) const models = Layer.mock(SessionRunnerModel.Service, { + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed( SessionRunnerModel.resolved(model, { diff --git a/packages/sdk/test/instances-effect.test.ts b/packages/sdk/test/instances-effect.test.ts index 6bd8c1a1fba..2e04d2fb216 100644 --- a/packages/sdk/test/instances-effect.test.ts +++ b/packages/sdk/test/instances-effect.test.ts @@ -100,7 +100,7 @@ it.live( overrides: [ llmClient.replace(Layer.succeed(LLMClient.Service, llm)), SessionRunnerModel.node.replace( - Layer.succeed(SessionRunnerModel.Service, { resolve: () => Effect.succeed(model) }), + Layer.succeed(SessionRunnerModel.Service, { select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed(model) }), ), ], } @@ -193,7 +193,7 @@ it.live( overrides: [ llmClient.replace(Layer.succeed(LLMClient.Service, llm)), SessionRunnerModel.node.replace( - Layer.succeed(SessionRunnerModel.Service, { resolve: () => Effect.succeed(model) }), + Layer.succeed(SessionRunnerModel.Service, { select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed(model) }), ), ], }, diff --git a/packages/server/test/flag-channel.test.ts b/packages/server/test/flag-channel.test.ts index c9f14b74a00..6efdab3b16f 100644 --- a/packages/server/test/flag-channel.test.ts +++ b/packages/server/test/flag-channel.test.ts @@ -55,7 +55,7 @@ const runChannel = (channel: "dev" | "latest") => Global.node.replace(tempGlobalLayer), llmClient.replace(Layer.succeed(LLMClient.Service, llm)), SessionRunnerModel.node.replace( - Layer.succeed(SessionRunnerModel.Service, { resolve: () => Effect.succeed(model) }), + Layer.succeed(SessionRunnerModel.Service, { select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed(model) }), ), Image.node.replace(imagePassthrough), ], diff --git a/packages/server/test/session-instances.test.ts b/packages/server/test/session-instances.test.ts index f2b32ee6ec4..729f75308aa 100644 --- a/packages/server/test/session-instances.test.ts +++ b/packages/server/test/session-instances.test.ts @@ -61,7 +61,7 @@ it.live( Watcher.node.replace(Watcher.configured({ enabled: false })), llmClient.replace(Layer.succeed(LLMClient.Service, llm)), SessionRunnerModel.node.replace( - Layer.succeed(SessionRunnerModel.Service, { resolve: () => Effect.succeed(model) }), + Layer.succeed(SessionRunnerModel.Service, { select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed(model) }), ), Instance.node.replace( makeGlobalNode({