From 3da74420981e8a5ae1ca256395635243b6be75c8 Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 17 Nov 2026 20:42:03 +0000 Subject: [PATCH 1/2] feat(core): choose tools and Code Mode placement from the session's model User decisions: - GPT models use patch; other models use edit and write - Hide websearch when it is turned off or no provider is available - GPT and Anthropic models get file tools and shell in Code Mode, with glob, grep and webfetch hidden - Other models keep file tools and shell as top-level tools - Hard-code this in one function decided in the select phase, no layout or hook - Apply regardless of the full_codemode flag --- packages/core/src/codemode/instructions.ts | 3 +- packages/core/src/mcp/instructions.ts | 10 +- packages/core/src/session/context.ts | 28 +- packages/core/src/session/runner/model.ts | 9 + packages/core/src/tool.ts | 171 +++++++---- packages/core/src/tool/model-policy.ts | 45 +++ packages/core/src/tool/plugin/edit.ts | 11 +- packages/core/src/tool/plugin/glob.ts | 14 +- packages/core/src/tool/plugin/grep.ts | 14 +- packages/core/src/tool/plugin/opencode.ts | 12 +- packages/core/src/tool/plugin/patch.ts | 27 +- packages/core/src/tool/plugin/read.ts | 37 +-- packages/core/src/tool/plugin/shell.ts | 39 ++- packages/core/src/tool/plugin/webfetch.ts | 15 +- packages/core/src/tool/plugin/websearch.ts | 22 +- packages/core/src/tool/plugin/write.ts | 11 +- packages/core/test/boot-work.test.ts | 1 + .../core/test/codemode/instructions.test.ts | 2 +- .../core/test/config/command-subagent.test.ts | 1 + packages/core/test/lib/tool.ts | 3 +- packages/core/test/mcp-instructions.test.ts | 24 ++ packages/core/test/plugin/goal.test.ts | 1 + packages/core/test/session-generate.test.ts | 1 + .../core/test/session-runner-recorded.test.ts | 1 + packages/core/test/session-runner.test.ts | 8 + packages/core/test/shell-restart.test.ts | 1 + packages/core/test/subagent-idle-e2e.test.ts | 1 + packages/core/test/subagent-lifetime.test.ts | 1 + packages/core/test/tool-model-policy.test.ts | 286 ++++++++++++++++++ packages/core/test/tool-opencode.test.ts | 30 ++ packages/core/test/tool-patch.test.ts | 44 +-- packages/core/test/tool-read.test.ts | 9 +- packages/core/test/tool-registry.test.ts | 115 ++++++- packages/core/test/tool-shell.test.ts | 28 +- packages/core/test/tool-subagent.test.ts | 1 + packages/core/test/tool-websearch.test.ts | 27 -- packages/schema/src/tool.ts | 8 + packages/sdk/test/embedded.test.ts | 2 + packages/sdk/test/instances-effect.test.ts | 4 +- packages/server/test/flag-channel.test.ts | 2 +- .../server/test/session-instances.test.ts | 2 +- 41 files changed, 776 insertions(+), 295 deletions(-) create mode 100644 packages/core/src/tool/model-policy.ts create mode 100644 packages/core/test/tool-model-policy.test.ts diff --git a/packages/core/src/codemode/instructions.ts b/packages/core/src/codemode/instructions.ts index d368e12ac51a..ec2c3c507415 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/mcp/instructions.ts b/packages/core/src/mcp/instructions.ts index d8d0871f4b4a..344b6e133299 100644 --- a/packages/core/src/mcp/instructions.ts +++ b/packages/core/src/mcp/instructions.ts @@ -44,7 +44,10 @@ const update = Instructions.listUpdate({ 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 + readonly load: ( + permissions: Permission.Ruleset, + options?: { readonly codemode?: boolean }, + ) => Effect.Effect } export class Service extends Context.Service()("@opencode/McpInstructions") {} @@ -55,7 +58,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* (permissions, options) { const source = (value: ReadonlyArray | Instructions.Removed) => Instructions.make>({ key: Instructions.Key.make("core/mcp-guidance"), @@ -70,7 +73,8 @@ 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 canExecute = + options?.codemode !== false && Permission.evaluate("execute", "*", permissions).effect !== "deny" // Instructions are useful only when this Session can reach at least one server tool. const visible = instructions .flatMap((item) => { diff --git a/packages/core/src/session/context.ts b/packages/core/src/session/context.ts index ca15f25d42e4..370f8210d371 100644 --- a/packages/core/src/session/context.ts +++ b/packages/core/src/session/context.ts @@ -17,6 +17,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" @@ -90,6 +92,7 @@ const layer = Layer.effect( const skillInstructions = yield* SkillInstructions.Service const store = yield* SessionStore.Service const registry = yield* Tool.Service + const websearch = yield* WebSearch.Service const resolveModel = ( session: SessionSchema.Info, @@ -144,14 +147,30 @@ 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] = yield* Effect.all( + [ + models.select(session, model.available).pipe(Effect.orElseSucceed(() => undefined)), + Effect.all({ + disabled: websearch.default().pipe( + Effect.as(false), + Effect.catchTag("WebSearch.Disabled", () => Effect.succeed(true)), + ), + providers: websearch.providers(), + }).pipe(Effect.map((result) => !result.disabled && result.providers.length > 0)), + ], + { concurrency: "unbounded" }, + ) + const tools = yield* registry.snapshot(permissions, { + location, + tools: modelTools({ model: selected?.info, websearch: hasWebSearch }), + }) const loaded = yield* Effect.all( { - tools: registry.snapshot(permissions, location), builtins: builtins.load(), discovery: discovery.load(), skills: skillInstructions.load(permissions), references: referenceInstructions.load(), - mcp: mcpInstructions.load(permissions), + mcp: mcpInstructions.load(permissions, { codemode: tools.codeModeCatalog !== undefined }), entries: entries.load(sessionID), }, { concurrency: "unbounded" }, @@ -163,7 +182,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, @@ -171,7 +190,7 @@ const layer = Layer.effect( loaded.builtins, loaded.entries, ]), - tools: loaded.tools, + tools, } }) @@ -231,5 +250,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 918b20680bcc..b1311361a674 100644 --- a/packages/core/src/session/runner/model.ts +++ b/packages/core/src/session/runner/model.ts @@ -34,8 +34,16 @@ export class ModelUnavailableError extends Schema.TaggedError Effect.Effect>, + ) => Effect.Effect /** Availability is sampled lazily for each explicitly selected model resolution. */ readonly resolve: ( session: SessionSchema.Info, @@ -99,6 +107,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 04de7d8752b0..314c660c4f15 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -1,6 +1,6 @@ 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 { CodeMode, Context, Metadata, Namespace, Options, Result } from "@opencode/schema/tool" import { ToolDefinition, type ToolCall } from "@opencode/ai/effect" import type { CodeMode } from "@opencode/codemode" @@ -44,10 +44,20 @@ type Data = { errors: { kind: "tool" | "namespace"; name: string; namespace?: string; error: RegistrationError }[] } +export interface Policy { + readonly hidden?: ReadonlySet + readonly codemode?: ReadonlySet +} + +export interface SnapshotOptions { + /** With `full_codemode`, Code Mode gets the experimental `path` global, resolving against `location`'s directory. */ + readonly location?: Location.Interface + readonly tools?: Policy +} + export interface Interface extends State.Transformable { readonly list: () => Effect.Effect> - /** With `full_codemode`, Code Mode gets the experimental `path` global, resolving against `location`'s directory. */ - readonly snapshot: (permissions?: Permission.Ruleset, location?: Location.Interface) => 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`. @@ -200,16 +210,13 @@ const layer = Layer.effect( return yield* executeTool(selected, event.tool, event.input, context) }) - let catalog: - | { - data: Data - names: string - path: 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: () => ({ @@ -231,12 +238,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, + options: tool.options && { ...tool.options }, + codemode: tool.codemode && { ...tool.codemode }, + }) }, update: (id, update) => { const current = editor.tools.get(id) if (!current) return - const tool = { ...current, options: current.options && { ...current.options } } + const tool = { + ...current, + options: current.options && { ...current.options }, + codemode: current.codemode && { ...current.codemode }, + } update(tool) tool.name = current.name tool.id = id @@ -250,7 +266,8 @@ const layer = Layer.effect( }, }), notify: (value) => { - catalog = undefined + catalogData = undefined + catalogs.clear() return Effect.forEach( value.errors, ({ kind, name, namespace, error }) => @@ -268,57 +285,75 @@ 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, location) => + snapshot: Effect.fn("Tool.snapshot")((permissions, options) => Effect.map(flags.enabled("full_codemode"), (enabled) => { - const path = enabled && location !== undefined const data = state.get() + if (catalogData !== data) { + catalogData = data + catalogs.clear() + } const active = new Map() const rules = permissions ?? [] + const hidden = options?.tools?.hidden + const promoted = options?.tools?.codemode for (const [name, tool] of data.tools) { + if (hidden?.has(name)) continue if (whollyDisabled(tool.options?.permission ?? name, rules)) continue active.set(name, tool) } const codeModeEnabled = !whollyDisabled("execute", rules) + const inCodeMode = (name: string, tool: Tool.Info) => + tool.options?.codemode !== false || Boolean(promoted?.has(name)) // 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)) + ? new Map(Array.from(active).filter(([name, tool]) => !inCodeMode(name, tool))) : 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.path === path ? 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, - path ? location : undefined, - ) - : undefined - const codeModeCatalog = !codeModeEnabled + const codeMode = !codeModeEnabled ? undefined - : (cached?.value ?? CodeModeTool.catalog(codeModeInventory)) - const codeModeDefinition = codeModeTool && (cached?.definition ?? definition(codeModeTool)) - if (codeModeCatalog && codeModeDefinition) - catalog = { - data, - names, - path, - inventory: codeModeInventory, - value: codeModeCatalog, - definition: codeModeDefinition, - } + : (() => { + const path = enabled && options?.location !== undefined + const codeModeTools = new Map( + Array.from(active) + .filter(([name, tool]) => inCodeMode(name, tool)) + .map(([name, tool]) => [name, toCodeModeTool(tool)]), + ) + const key = `${path ? "1" : "0"}\0${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 = catalogs.get(key) + if (cached) { + catalogs.delete(key) + catalogs.set(key, cached) + } + const inventory = cached?.inventory ?? { tools: codeModeTools, namespaces: data.namespaces } + const tool = CodeModeTool.create( + inventory, + (name, item, input, context) => run(inventory.tools, item, name, input, context), + permission, + path ? options.location : 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 = { @@ -332,11 +367,11 @@ const layer = Layer.effect( const event = yield* beforeExecute(input.call.name, input.call.input, context) const requested = input.definitions?.get(event.tool) // Preserve session context removal and alias resolution, now after the repair hook. - if (!requested && input.definitions && (direct.has(event.tool) || codeModeTool?.name === event.tool)) + 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) } @@ -411,6 +446,22 @@ const whollyDisabled = (action: string, rules: Permission.Ruleset) => { return rule?.resource === "*" && rule.effect === "deny" } +const CATALOG_CACHE_LIMIT = 5 + +function toCodeModeTool(tool: Tool.Info): Tool.Info { + if (!tool.codemode) return tool + return { + ...tool, + ...(tool.codemode.description === undefined ? {} : { description: tool.codemode.description }), + ...(tool.codemode.input === undefined ? {} : { input: tool.codemode.input }), + options: { + ...tool.options, + codemode: true, + ...(tool.codemode.pinned === undefined ? {} : { pinned: tool.codemode.pinned }), + }, + } +} + const formatSchemaIssue = SchemaIssue.makeFormatterDefault() function schemaMakeError(error: unknown) { @@ -435,6 +486,22 @@ function register(tool: Tool.Info): Result.Result ToolDefinition.make(definition(toCodeModeTool(tool))), + catch: (error) => + new RegistrationError({ name: id, message: `Invalid tool definition ${id}: ${schemaMakeError(error)}` }), + }) + if (Result.isFailure(variant)) return variant + } return Result.try({ try: () => ToolDefinition.make(definition(tool)), catch: (error) => diff --git a/packages/core/src/tool/model-policy.ts b/packages/core/src/tool/model-policy.ts new file mode 100644 index 000000000000..e6766a342d74 --- /dev/null +++ b/packages/core/src/tool/model-policy.ts @@ -0,0 +1,45 @@ +import type { Model } from "@opencode/schema/model" + +export interface ModelTools { + readonly hidden: Set + readonly codemode: Set +} + +export function modelTools(input: { readonly model?: Model.Info; readonly websearch: boolean }): ModelTools { + const hidden = new Set() + const codemode = new Set() + if (!input.websearch) hidden.add("websearch") + if (!input.model) return { hidden, codemode } + + const id = input.model.id.toLowerCase() + const usePatch = id.includes("gpt-") && !id.includes("oss") && !id.includes("gpt-4") + if (usePatch) { + hidden.add("edit") + hidden.add("write") + } + if (!usePatch) hidden.add("patch") + + if (isStrongModel(input.model)) { + hidden.add("glob") + hidden.add("grep") + hidden.add("webfetch") + for (const name of ["read", "write", "edit", "patch", "shell"]) { + if (!hidden.has(name)) codemode.add(name) + } + } + return { hidden, codemode } +} + +function isStrongModel(model: Model.Info) { + const id = model.id.toLowerCase() + const modelID = model.modelID.toLowerCase() + const family = model.family?.toLowerCase() + if (id.includes("gpt") || modelID.includes("gpt")) return true + return ( + model.providerID === "anthropic" || + model.canonical === "anthropic" || + id.includes("claude") || + modelID.includes("claude") || + Boolean(family?.includes("claude")) + ) +} diff --git a/packages/core/src/tool/plugin/edit.ts b/packages/core/src/tool/plugin/edit.ts index 949fc767bef5..2c8d8a1d95b7 100644 --- a/packages/core/src/tool/plugin/edit.ts +++ b/packages/core/src/tool/plugin/edit.ts @@ -9,9 +9,6 @@ export * as EditTool from "./edit.js" import type { Context } from "@opencode/plugin/effect/plugin" import { ToolFailure } from "@opencode/ai/effect" import { Effect, Schema } from "effect" -import { Config } from "../../config.js" -import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js" -import { Flag } from "../../flag.js" import { toolFailure } from "../runtime.js" import { Environment } from "../../environment/index.js" import { FileMutation } from "../../file-mutation.js" @@ -264,17 +261,13 @@ export const Plugin = { const environment = yield* Environment.Service const location = yield* Location.Service const permission = yield* Permission.Service - const config = yield* Config.Service - const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload()) - const flags = yield* Flag.Service yield* ctx.tool .transform((editor) => editor.add({ name, - options: flags.resolve(loaded.entries).full_codemode.enabled - ? { codemode: true, pinned: true, permission: "edit" } - : { codemode: false, permission: "edit" }, + options: { codemode: false, permission: "edit" }, + codemode: { pinned: true }, 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.", input: Input, diff --git a/packages/core/src/tool/plugin/glob.ts b/packages/core/src/tool/plugin/glob.ts index e27d2e63ab49..ff3e20c4c999 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 314685594195..6caebdc01c05 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 bfd091e1cdb8..f6315d6390c6 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) diff --git a/packages/core/src/tool/plugin/patch.ts b/packages/core/src/tool/plugin/patch.ts index 8b58eaa3bb58..00c514723e75 100644 --- a/packages/core/src/tool/plugin/patch.ts +++ b/packages/core/src/tool/plugin/patch.ts @@ -1,14 +1,10 @@ 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" import { Bom } from "@opencode/util/bom" -import { Config } from "../../config.js" -import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js" -import { Flag } from "../../flag.js" import { toolFailure } from "../runtime.js" import { Environment } from "../../environment/index.js" import { Formatter } from "../../formatter.js" @@ -60,17 +56,13 @@ export const Plugin = { const formatter = yield* Formatter.Service const location = yield* Location.Service const permission = yield* Permission.Service - const config = yield* Config.Service - const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload()) - const flags = yield* Flag.Service yield* ctx.tool .transform((editor) => editor.add({ name, - options: flags.resolve(loaded.entries).full_codemode.enabled - ? { codemode: true, pinned: true, permission: "edit" } - : { codemode: false, permission: "edit" }, + options: { codemode: false, permission: "edit" }, + codemode: { pinned: true }, description: DESCRIPTION, input: Input, freeform: { type: "lark", grammar: GRAMMAR }, @@ -296,21 +288,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 d9e1bdce34ee..3df378f86eec 100644 --- a/packages/core/src/tool/plugin/read.ts +++ b/packages/core/src/tool/plugin/read.ts @@ -5,9 +5,6 @@ import { basename, dirname, extname, isAbsolute, join, relative } from "path" import { ToolFailure } from "@opencode/ai/effect" import { Effect, Schema } from "effect" import { FSUtil } from "@opencode/util/fs-util" -import { Config } from "../../config.js" -import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js" -import { Flag } from "../../flag.js" import { Location } from "../../location.js" import { FileAccess } from "../../file-access.js" import { InstructionDiscovery } from "../../instruction-discovery.js" @@ -32,6 +29,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) { @@ -43,28 +49,15 @@ export const Plugin = { const fs = yield* FSUtil.Service const location = yield* Location.Service const environment = yield* Environment.Service - const config = yield* Config.Service - const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload()) - const flags = yield* Flag.Service 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: { codemode: false }, + description: description(false), + codemode: { pinned: true, description: description(true) }, input: Input, output: ReadToolFileSystem.Output, execute: (input, context) => { @@ -198,8 +191,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 72b51319b594..0e7d4b4f87c1 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -7,10 +7,8 @@ import type { ShellCreateBefore } from "@opencode/plugin/effect/shell" import type { Shell as ShellSchema } from "@opencode/schema/shell" import type { Tool } from "@opencode/schema/tool" import { Clock, Deferred, Effect, Fiber, Option, Schema, Struct } from "effect" -import { Config } from "../../config.js" -import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js" +import { CodeModeExecution } from "../../codemode/execution.js" import { Environment } from "../../environment/index.js" -import { Flag } from "../../flag.js" import { Job } from "../../job.js" import { FileAccess } from "../../file-access.js" import { Permission } from "../../permission.js" @@ -306,10 +304,6 @@ export const Plugin = { const shellSelect = yield* ShellSelect.Service const compatibleShell = shellSelect.resolve({ priority: "compat" }) 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 const prepare = Effect.fn("ShellTool.prepare")(function* (invocation: ShellCreateBefore, context: Tool.Context) { const target = yield* access.resolve({ path: invocation.cwd, kind: "directory" }) @@ -373,26 +367,31 @@ 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, + options: { codemode: false }, + description: description(undefined, false), + input: Input, + // When placed in Code Mode, shell is pinned so the catalog always lists it, however many other tools there are. + codemode: { + pinned: true, + description: description(undefined, true), + input: CodeModeInput, + }, 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 timeout = background ? (input.timeout ?? 0) : foreground - let finalTimeout = timeout + let finalTimeout = 0 // Uninterruptible from spawning to blocking, so an interrupt cannot orphan a started command. return Effect.uninterruptibleMask((restore) => Effect.gen(function* () { + const codeMode = Option.isSome(yield* Effect.serviceOption(CodeModeExecution.Service)) + // 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 timeout = background ? (input.timeout ?? 0) : foreground + finalTimeout = timeout // Listens for the user's stop for the whole call, starting before the command does, so a stop always // reaches this tool through `cancel` instead of interrupting it, even while the command starts. const stopped = yield* Deferred.make() @@ -514,8 +513,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 644651ec2d1d..56407820fd21 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" @@ -133,15 +130,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 }, @@ -203,8 +194,8 @@ export const Plugin = { } return { output: result, content: result.output, metadata: { contentType: result.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 5c28858d1cf9..70e830c39f20 100644 --- a/packages/core/src/tool/plugin/websearch.ts +++ b/packages/core/src/tool/plugin/websearch.ts @@ -1,13 +1,9 @@ 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" -import { Config } from "../../config.js" -import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js" -import { Flag } from "../../flag.js" import { Form } from "../../form.js" import { Permission } from "../../permission.js" import { WebSearch } from "../../websearch.js" @@ -42,15 +38,12 @@ export const Plugin = { const permission = yield* Permission.Service const forms = yield* Form.Service const websearch = yield* WebSearch.Service - const config = yield* Config.Service - const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload()) - const flags = yield* Flag.Service yield* ctx.tool .transform((editor) => editor.add({ name, - options: { codemode: flags.resolve(loaded.entries).full_codemode.enabled }, + options: { codemode: false }, description, input: Input, output: Output, @@ -190,18 +183,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 882ef22d69a3..7ab730b69031 100644 --- a/packages/core/src/tool/plugin/write.ts +++ b/packages/core/src/tool/plugin/write.ts @@ -9,10 +9,7 @@ export * as WriteTool from "./write.js" import type { Context } from "@opencode/plugin/effect/plugin" import { ToolFailure } from "@opencode/ai/effect" import { Effect, Schema } from "effect" -import { Config } from "../../config.js" -import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js" import { FileWrite } from "../../file-write.js" -import { Flag } from "../../flag.js" export const name = "write" @@ -36,17 +33,13 @@ export const Plugin = { id: "opencode.tool.write", effect: Effect.fn("WriteTool.Plugin")(function* (ctx: Context) { const fileWrite = yield* FileWrite.Service - const config = yield* Config.Service - const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload()) - const flags = yield* Flag.Service yield* ctx.tool .transform((editor) => editor.add({ name, - options: flags.resolve(loaded.entries).full_codemode.enabled - ? { codemode: true, pinned: true, permission: "edit" } - : { codemode: false, permission: "edit" }, + options: { codemode: false, permission: "edit" }, + codemode: { pinned: true }, 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.", input: Input, diff --git a/packages/core/test/boot-work.test.ts b/packages/core/test/boot-work.test.ts index 1f2636c8fa08..209954c4e22a 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/instructions.test.ts b/packages/core/test/codemode/instructions.test.ts index 58c62af60541..aa5553d38c72 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 318b63cbf275..19a53ac1e24b 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/lib/tool.ts b/packages/core/test/lib/tool.ts index ad95a5c6221c..7813a1a9be2d 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 dda4467ff73c..21e9ee9bd6bc 100644 --- a/packages/core/test/mcp-instructions.test.ts +++ b/packages/core/test/mcp-instructions.test.ts @@ -65,6 +65,30 @@ describe("McpInstructions", () => { ), ) + it.effect("omits the execute instruction when Code Mode is off", () => + Effect.gen(function* () { + const service = yield* McpInstructions.Service + const generation = yield* service.load([], { codemode: false }).pipe(Effect.flatMap(readInitial)) + + expect(generation.text).toBe( + [ + "", + ' ', + " Alpha instructions", + " ", + "", + ].join("\n"), + ) + }).pipe( + Effect.provide( + layer( + () => [instructions("alpha", "Alpha instructions")], + () => [tool("alpha")], + ), + ), + ), + ) + it.effect("lists Code Mode servers as direct tools when the agent cannot use execute", () => Effect.gen(function* () { const service = yield* McpInstructions.Service diff --git a/packages/core/test/plugin/goal.test.ts b/packages/core/test/plugin/goal.test.ts index 73bdb518e3ba..fe927eeedc8f 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/session-generate.test.ts b/packages/core/test/session-generate.test.ts index 4a901bc4e6c5..ac97f4d9c7ed 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 e35f07efb32b..2d94a1a74d94 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 ebddaab97d59..bf503153da52 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 1882acc901ca..edc22f48ba23 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 57462dd498b8..f905d9ec6b7c 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 d24148b8d9b8..5a7c9b1c4f66 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 000000000000..34b218e00c75 --- /dev/null +++ b/packages/core/test/tool-model-policy.test.ts @@ -0,0 +1,286 @@ +import { describe, expect, test } from "bun:test" +import { Agent } from "@opencode/core/agent" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +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 { McpInstructions } from "@opencode/core/mcp/instructions" +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 { 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 { codeModeListings } 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.modelID === undefined ? {} : { modelID: overrides.modelID }), + ...(overrides.family === undefined ? {} : { family: overrides.family }), + ...(overrides.canonical === undefined ? {} : { canonical: overrides.canonical }), + package: overrides.package ?? Provider.aisdk("@ai-sdk/openai"), +}) + +describe("modelTools", () => { + test("gives GPT-5+ models patch and places file tools and shell in Code Mode with glob, grep, and webfetch hidden", () => { + for (const model of [ + makeModel("openai", "gpt-5"), + makeModel("openai", "gpt-5.4-codex"), + makeModel("azure", "gpt-6"), + ]) { + const result = modelTools({ model, websearch: true }) + expect([...result.codemode].sort()).toEqual(["patch", "read", "shell"]) + expect([...result.hidden].sort()).toEqual(["edit", "glob", "grep", "webfetch", "write"]) + } + }) + + test("keeps edit and write instead of patch for gpt-4 and gpt-oss models while still placing file tools and shell in Code Mode", () => { + for (const model of [ + makeModel("openai", "gpt-4o"), + makeModel("openai", "gpt-4.1"), + makeModel("openrouter", "openai/gpt-oss-120b"), + ]) { + const result = modelTools({ model, websearch: true }) + expect([...result.codemode].sort()).toEqual(["edit", "read", "shell", "write"]) + expect([...result.hidden].sort()).toEqual(["glob", "grep", "patch", "webfetch"]) + } + }) + + test("gives Claude and Anthropic models edit, write, read, and shell in Code Mode with patch, glob, grep, and webfetch hidden", () => { + for (const model of [ + makeModel("anthropic", "claude-sonnet-4-5"), + makeModel("anthropic", "custom-sonnet"), + makeModel("amazon-bedrock", "us.anthropic.claude-opus-4-6-v1"), + makeModel("openrouter", "anthropic/claude-sonnet-4"), + makeModel("custom", "sonnet-v4", { family: Model.Family.make("claude-sonnet") }), + makeModel("gateway", "sonnet", { canonical: Provider.ID.make("anthropic") }), + ]) { + const result = modelTools({ model, websearch: true }) + expect([...result.codemode].sort()).toEqual(["edit", "read", "shell", "write"]) + expect([...result.hidden].sort()).toEqual(["glob", "grep", "patch", "webfetch"]) + } + }) + + test("keeps file tools, shell, glob, grep, and webfetch as direct tools for non-strong models", () => { + for (const model of [makeModel("deepseek", "deepseek-reasoner"), makeModel("opencode", "gemini-4-carbon")]) { + const result = modelTools({ model, websearch: true }) + expect([...result.codemode]).toEqual([]) + expect([...result.hidden]).toEqual(["patch"]) + } + }) + + test("hides websearch when disabled or no provider is available, and applies no model rules when model is absent", () => { + expect([...modelTools({ model: makeModel("openai", "gpt-5"), websearch: false }).hidden].sort()).toEqual([ + "edit", + "glob", + "grep", + "webfetch", + "websearch", + "write", + ]) + expect([...modelTools({ model: makeModel("deepseek", "deepseek-chat"), websearch: false }).hidden].sort()).toEqual([ + "patch", + "websearch", + ]) + expect(modelTools({ model: undefined, websearch: true })).toEqual({ + hidden: new Set(), + codemode: new Set(), + }) + expect(modelTools({ model: undefined, websearch: false })).toEqual({ + hidden: new Set(["websearch"]), + codemode: new Set(), + }) + }) +}) + +const contextLayer = Layer.mergeAll( + PluginTestLayer, + AppNodeBuilder.build(LayerNode.group([SessionContext.node]), [ + Location.node.replace(Location.boundNode({ directory: AbsolutePath.make("/project") })), + InstructionBuiltIns.node.replace( + Layer.mock(InstructionBuiltIns.Service, { load: () => Effect.succeed(Instructions.empty) }), + ), + InstructionDiscovery.node.replace( + Layer.mock(InstructionDiscovery.Service, { + project: true, + global: true, + claude: true, + claudeGlobal: true, + load: () => Effect.succeed(Instructions.empty), + }), + ), + SkillInstructions.node.replace( + Layer.mock(SkillInstructions.Service, { load: () => Effect.succeed(Instructions.empty) }), + ), + ReferenceInstructions.node.replace( + Layer.mock(ReferenceInstructions.Service, { load: () => Effect.succeed(Instructions.empty) }), + ), + McpInstructions.node.replace( + Layer.mock(McpInstructions.Service, { load: () => Effect.succeed(Instructions.empty) }), + ), + ]), +) + +const it = testEffect(contextLayer) + +describe("SessionContext.select model tool policy", () => { + it.effect("places tools per selected model and websearch availability, falling back cleanly when unavailable", () => + 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 + + 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) => { + editor.update(Provider.ID.make("openai"), Model.ID.make("gpt-5"), (model) => { + model.package = Provider.aisdk("@ai-sdk/openai") + }) + editor.update(Provider.ID.make("anthropic"), Model.ID.make("claude-sonnet-4-5"), (model) => { + model.package = Provider.aisdk("@ai-sdk/anthropic") + }) + editor.update(Provider.ID.make("deepseek"), Model.ID.make("deepseek-reasoner"), (model) => { + model.package = Provider.aisdk("@ai-sdk/openai-compatible") + }) + }) + 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"]) { + editor.add({ + name, + description: `Direct ${name}`, + ...(name === "read" || name === "shell" + ? { codemode: { description: `Code Mode ${name}`, ...(name === "shell" ? { pinned: true } : {}) } } + : {}), + input: Schema.Struct({}), + output: Schema.String, + options: { codemode: false }, + execute: () => Effect.succeed({ output: name }), + }) + } + for (const name of ["edit", "write", "patch"]) { + editor.add({ + name, + description: name, + input: Schema.Struct({}), + output: Schema.String, + options: { codemode: false, permission: "edit" }, + execute: () => Effect.succeed({ output: name }), + }) + } + editor.add({ + name: "session_move", + description: "Move session", + input: Schema.Struct({}), + output: Schema.String, + options: { namespace: "opencode", codemode: true, pinned: true }, + execute: () => Effect.succeed({ output: "moved" }), + }) + }) + + const selectFor = (providerID: string, id: string) => + Effect.gen(function* () { + const session = yield* sessions.create({ + location: Location.Ref.make({ directory: AbsolutePath.make("/project") }), + model: Model.Ref.make({ providerID: Provider.ID.make(providerID), id: Model.ID.make(id) }), + }) + return yield* context.select(session.id) + }) + + const gpt = yield* selectFor("openai", "gpt-5") + expect(gpt.tools.definitions.map((tool) => tool.name)).toEqual(["websearch", "execute"]) + expect(codeModeListings(gpt.tools.codeModeCatalog!).map((entry) => entry.path)).toEqual([ + "opencode.session_move", + "patch", + "read", + "shell", + ]) + expect(codeModeListings(gpt.tools.codeModeCatalog!).find((entry) => entry.path === "read")?.line).toContain( + "Code Mode read", + ) + + const claude = yield* selectFor("anthropic", "claude-sonnet-4-5") + expect(claude.tools.definitions.map((tool) => tool.name)).toEqual(["websearch", "execute"]) + expect(codeModeListings(claude.tools.codeModeCatalog!).map((entry) => entry.path)).toEqual([ + "edit", + "opencode.session_move", + "read", + "shell", + "write", + ]) + + const deepseek = yield* selectFor("deepseek", "deepseek-reasoner") + expect(deepseek.tools.definitions.map((tool) => tool.name)).toEqual([ + "edit", + "glob", + "grep", + "read", + "shell", + "webfetch", + "websearch", + "write", + "execute", + ]) + expect(deepseek.tools.definitions.find((tool) => tool.name === "read")?.description).toBe("Direct read") + expect(codeModeListings(deepseek.tools.codeModeCatalog!).map((entry) => entry.path)).toEqual([ + "opencode.session_move", + ]) + + // Removing all providers or turning off websearch hides the websearch tool. + yield* websearch.transform((editor) => editor.remove(WebSearch.ID.make("exa"))) + expect((yield* selectFor("openai", "gpt-5")).tools.definitions.map((tool) => tool.name)).toEqual(["execute"]) + yield* websearch.transform((editor) => + editor.add({ + id: WebSearch.ID.make("exa"), + name: "Exa", + execute: () => Effect.succeed([]), + }), + ) + yield* websearch.select(false) + const withoutWebSearch = yield* selectFor("openai", "gpt-5") + expect(withoutWebSearch.tools.definitions.map((tool) => tool.name)).toEqual(["execute"]) + + // An unavailable model applies no model rules in select and surfaces ModelUnavailableError in load. + const unavailable = yield* selectFor("openai", "missing-model") + expect(unavailable.tools.definitions.map((tool) => tool.name)).toContain("patch") + expect(unavailable.tools.definitions.map((tool) => tool.name)).toContain("edit") + 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 869b7b265950..76fa6cabbb96 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 0fbe32a5d01d..6faed32db9ea 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 7bdaa54b4bac..a44c5670a924 100644 --- a/packages/core/test/tool-read.test.ts +++ b/packages/core/test/tool-read.test.ts @@ -195,7 +195,14 @@ 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") + const promoted = yield* registry.snapshot(undefined, { tools: { codemode: new Set(["read"]) } }) + expect(promoted.definitions.map((tool) => tool.name)).toEqual(["execute"]) + expect(promoted.codeModeCatalog?.tools[0]?.description).toContain( + "Reading an image or PDF automatically attaches it to the execute result", + ) expect( (yield* toolDefinitions(registry, [{ action: "read", resource: "*", effect: "deny" }])).map( (tool) => tool.name, diff --git a/packages/core/test/tool-registry.test.ts b/packages/core/test/tool-registry.test.ts index 110afd5f1fa9..12694dca44fb 100644 --- a/packages/core/test/tool-registry.test.ts +++ b/packages/core/test/tool-registry.test.ts @@ -82,7 +82,7 @@ describe("Code Mode path", () => { const session = location({ directory: AbsolutePath.make("/session/dir") }) const typeOfPath = Effect.gen(function* () { const tools = yield* Tool.Service - const snapshot = yield* tools.snapshot(undefined, session) + const snapshot = yield* tools.snapshot(undefined, { location: session }) const result = yield* snapshot.execute({ ...call("execute"), call: { type: "tool-call", id: "call-path", name: "execute", input: { code: `return [typeof path]` } }, @@ -750,6 +750,119 @@ describe("Tool", () => { }), ) + it.effect( + "applies model tool policy and Code Mode variants, falling back to direct variants when execute is denied", + () => + Effect.gen(function* () { + const service = yield* Tool.Service + yield* service.transform((editor) => { + editor.add({ + name: "shell", + description: "Direct shell", + input: Schema.Struct({ command: Schema.String, background: Schema.optionalKey(Schema.Boolean) }), + codemode: { + pinned: true, + description: "Code Mode shell", + input: Schema.Struct({ command: Schema.String }), + }, + output: Schema.String, + options: { codemode: false }, + execute: (input) => + Effect.succeed({ + output: `${input.command}:${"background" in input ? String(input.background) : "omitted"}`, + }), + }) + editor.add({ ...make(), name: "glob", options: { codemode: false } }) + editor.add({ ...make(), name: "mcp_search" }) + }) + + const direct = yield* service.snapshot() + expect(direct.definitions.map((tool) => tool.name)).toEqual(["glob", "shell", "execute"]) + expect(direct.definitions.find((tool) => tool.name === "shell")?.description).toBe("Direct shell") + expect(direct.definitions.find((tool) => tool.name === "shell")?.inputSchema.properties).toHaveProperty( + "background", + ) + expect(codeModeListings(direct.codeModeCatalog!).map((tool) => tool.path)).toEqual(["mcp_search"]) + + const policy = { hidden: new Set(["glob"]), codemode: new Set(["shell"]) } + const promoted = yield* service.snapshot(undefined, { tools: policy }) + expect(promoted.definitions.map((tool) => tool.name)).toEqual(["execute"]) + const listings = codeModeListings(promoted.codeModeCatalog!) + expect(listings.map((tool) => tool.path)).toEqual(["mcp_search", "shell"]) + const shellListing = listings.find((tool) => tool.path === "shell")! + expect(shellListing.line).toContain("Code Mode shell") + expect(shellListing.line).not.toContain("background") + expect(promoted.codeModeCatalog?.tools.find((tool) => tool.name === "shell")).toMatchObject({ pinned: true }) + + // Decodes Code Mode calls with the Code Mode input schema, stripping direct-only fields. + const executed = yield* promoted.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: "ls:omitted" }) + + // When execute is denied, promoted tools fall back to their direct form while hidden tools stay hidden. + const denied = yield* service.snapshot([{ action: "execute", resource: "*", effect: "deny" }], { + tools: policy, + }) + expect(denied.codeModeCatalog).toBeUndefined() + expect(denied.definitions.map((tool) => tool.name)).toEqual(["mcp_search", "shell"]) + expect(denied.definitions.find((tool) => tool.name === "shell")?.description).toBe("Direct shell") + expect(denied.definitions.find((tool) => tool.name === "shell")?.inputSchema.properties).toHaveProperty( + "background", + ) + }), + ) + + 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-shell.test.ts b/packages/core/test/tool-shell.test.ts index 97ff4f573dd2..ded53d2e42c5 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -180,7 +180,6 @@ const replacements = [ const productionIt = testEffect(AppNodeBuilder.build(nodes, replacements)) const shellLayer = AppNodeBuilder.build(nodes, [...replacements, PluginSupervisor.node.replace(shellPluginSupervisor)]) const it = testEffect(shellLayer) -const codeModeIt = testEffect(shellLayer.pipe(Layer.provide(Layer.succeed(Flag.Overrides, "full_codemode")))) // On the real process daemon (when its binary is compatible; otherwise this falls back to spawning). const daemonIt = testEffect( AppNodeBuilder.build(nodes, [...daemonReplacements, PluginSupervisor.node.replace(shellPluginSupervisor)]), @@ -891,12 +890,13 @@ describe("ShellTool", () => { }), ) - codeModeIt.live("runs parallel Code Mode shells with the long default and notifies after a shorter timeout", () => + it.live("runs parallel Code Mode shells with the long default and notifies after a shorter timeout", () => withTempDir((tmp) => { reset() + const policy = { tools: { codemode: new Set(["shell"]) } } return withSession(tmp.path, (registry) => Effect.gen(function* () { - const snapshot = yield* registry.snapshot() + const snapshot = yield* registry.snapshot(undefined, policy) // Pinned: listed even when the catalog has no room for other tools, with the result contract in the field // annotations. const pinned = CodeModeCatalog.summarize(snapshot.codeModeCatalog!, { budget: 0 }).namespaces.flatMap( @@ -925,16 +925,20 @@ describe("ShellTool", () => { ) const quick = JSON.stringify({ command: bodyExitCommand }) const long = JSON.stringify({ command: progressOverflowCommand(6, "release"), timeout: 10 }) - const result = yield* executeTool(registry, { - sessionID, - ...toolIdentity, - call: { - type: "tool-call", - id: "call-parallel-shells", - name: "execute", - input: { code: `return await Promise.all([tools.shell(${quick}), tools.shell(${long})])` }, + const result = yield* executeTool( + registry, + { + sessionID, + ...toolIdentity, + call: { + type: "tool-call", + id: "call-parallel-shells", + name: "execute", + input: { code: `return await Promise.all([tools.shell(${quick}), tools.shell(${long})])` }, + }, }, - }).pipe(Effect.timeout("3 seconds")) + policy, + ).pipe(Effect.timeout("3 seconds")) expect(result.status).toBe("completed") const [completed, running] = JSON.parse(result.output.output) expect(completed).toEqual({ diff --git a/packages/core/test/tool-subagent.test.ts b/packages/core/test/tool-subagent.test.ts index 15628d66d1e9..3843e1538906 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 c9043eba6ffb..d15f0f04a5ee 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/schema/src/tool.ts b/packages/schema/src/tool.ts index c2f9f017d29e..48d4c39659f1 100644 --- a/packages/schema/src/tool.ts +++ b/packages/schema/src/tool.ts @@ -106,6 +106,12 @@ export interface Result | undefined = ValueSchem readonly metadata?: Metadata } +export interface CodeMode { + readonly description?: string + readonly input?: ValueSchema + readonly pinned?: boolean +} + export type Info< Input extends ValueSchema = ValueSchema, Output extends ValueSchema | undefined = ValueSchema | undefined, @@ -117,4 +123,6 @@ export type Info< readonly execute: (input: InputValue, context: Context) => Effect.Effect, Error> readonly output?: Output readonly options?: Options + /** Overrides applied when the tool is exposed through Code Mode instead of directly. */ + readonly codemode?: CodeMode } diff --git a/packages/sdk/test/embedded.test.ts b/packages/sdk/test/embedded.test.ts index 85d270dd087e..9c2697ed9fc1 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 6bd8c1a1fba2..2e04d2fb2160 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 c9f14b74a004..6efdab3b16fc 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 f2b32ee6ec42..729f75308aa4 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({ From 92d0c68fbbc2662bce935198f73e9d6f8309d2e3 Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 17 Nov 2026 23:26:00 +0000 Subject: [PATCH 2/2] refactor(core): let McpInstructions follow the tool snapshot's Code Mode decision User decisions: - Decide in one place whether MCP servers are reached through execute --- packages/core/src/mcp/instructions.ts | 16 +++---- packages/core/src/session/context.ts | 2 +- packages/core/test/mcp-instructions.test.ts | 53 +++++++-------------- 3 files changed, 24 insertions(+), 47 deletions(-) diff --git a/packages/core/src/mcp/instructions.ts b/packages/core/src/mcp/instructions.ts index 344b6e133299..bf2af9621109 100644 --- a/packages/core/src/mcp/instructions.ts +++ b/packages/core/src/mcp/instructions.ts @@ -43,11 +43,11 @@ const update = Instructions.listUpdate({ }) export interface Interface { - /** Lists server instructions reachable under the given ruleset; callers pass the merged agent and Session permissions. */ - readonly load: ( - permissions: Permission.Ruleset, - options?: { readonly codemode?: boolean }, - ) => Effect.Effect + /** + * Lists server instructions reachable under the given ruleset; callers pass the merged agent and Session permissions. + * `codeMode` says whether the Session's tool snapshot has Code Mode, which decides whether servers are reached through `execute`. + */ + readonly load: (permissions: Permission.Ruleset, codeMode: boolean) => Effect.Effect } export class Service extends Context.Service()("@opencode/McpInstructions") {} @@ -58,7 +58,7 @@ export const layer = Layer.effect( const mcp = yield* Mcp.Service return Service.of({ - load: Effect.fn("McpInstructions.load")(function* (permissions, options) { + load: Effect.fn("McpInstructions.load")(function* (permissions, codeMode) { const source = (value: ReadonlyArray | Instructions.Removed) => Instructions.make>({ key: Instructions.Key.make("core/mcp-guidance"), @@ -73,14 +73,12 @@ export const layer = Layer.effect( const [instructions, tools] = yield* Effect.all([mcp.instructions(), mcp.tools()], { concurrency: "unbounded", }) - const canExecute = - options?.codemode !== false && Permission.evaluate("execute", "*", permissions).effect !== "deny" // Instructions are useful only when this Session can reach at least one server tool. const visible = instructions .flatMap((item) => { 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 + const codemode = codeMode && owned[0]?.codemode !== false if ( !owned.some( (tool) => diff --git a/packages/core/src/session/context.ts b/packages/core/src/session/context.ts index 370f8210d371..49f90dec897a 100644 --- a/packages/core/src/session/context.ts +++ b/packages/core/src/session/context.ts @@ -170,7 +170,7 @@ const layer = Layer.effect( discovery: discovery.load(), skills: skillInstructions.load(permissions), references: referenceInstructions.load(), - mcp: mcpInstructions.load(permissions, { codemode: tools.codeModeCatalog !== undefined }), + mcp: mcpInstructions.load(permissions, tools.codeModeCatalog !== undefined), entries: entries.load(sessionID), }, { concurrency: "unbounded" }, diff --git a/packages/core/test/mcp-instructions.test.ts b/packages/core/test/mcp-instructions.test.ts index 21e9ee9bd6bc..59f5adc00507 100644 --- a/packages/core/test/mcp-instructions.test.ts +++ b/packages/core/test/mcp-instructions.test.ts @@ -29,10 +29,13 @@ describe("McpInstructions", () => { 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" }, - ]) + .load( + [ + { action: McpTool.name("alpha", "restricted"), resource: "*", effect: "deny" }, + { action: McpTool.name("hidden", "search"), resource: "*", effect: "deny" }, + ], + true, + ) .pipe(Effect.flatMap(readInitial)) expect(generation.text).toBe( @@ -65,35 +68,11 @@ describe("McpInstructions", () => { ), ) - it.effect("omits the execute instruction when Code Mode is off", () => - Effect.gen(function* () { - const service = yield* McpInstructions.Service - const generation = yield* service.load([], { codemode: false }).pipe(Effect.flatMap(readInitial)) - - expect(generation.text).toBe( - [ - "", - ' ', - " Alpha instructions", - " ", - "", - ].join("\n"), - ) - }).pipe( - Effect.provide( - layer( - () => [instructions("alpha", "Alpha instructions")], - () => [tool("alpha")], - ), - ), - ), - ) - it.effect("lists Code Mode servers as direct tools when the agent cannot use execute", () => Effect.gen(function* () { const service = yield* McpInstructions.Service const generation = yield* service - .load([{ action: "execute", resource: "*", effect: "deny" }]) + .load([{ action: "execute", resource: "*", effect: "deny" }], false) .pipe(Effect.flatMap(readInitial)) expect(generation.text).toBe( @@ -119,7 +98,7 @@ describe("McpInstructions", () => { Effect.gen(function* () { const service = yield* McpInstructions.Service const generation = yield* service - .load([{ action: "execute", resource: "*", effect: "deny" }]) + .load([{ action: "execute", resource: "*", effect: "deny" }], false) .pipe(Effect.flatMap(readInitial)) expect(generation.text).toBe( @@ -152,10 +131,10 @@ describe("McpInstructions", () => { 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* service.load([], true).pipe(Effect.flatMap(readInitial)) tools = [{ ...tool("alpha"), codemode: false }] - const changed = yield* readUpdate(yield* service.load([]), initialized) + const changed = yield* readUpdate(yield* service.load([], true), initialized) expect(changed.text).toBe( [ "The following MCP server instructions have changed. Each entry replaces the previously listed server with the same name:", @@ -179,10 +158,10 @@ describe("McpInstructions", () => { 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* service.load([], true).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* service.load([], true), initialized) expect(added.text).toBe( [ "New MCP server instructions are available in addition to those previously listed:", @@ -194,7 +173,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* service.load([], true), added) expect(changed.text).toBe( [ "The following MCP server instructions have changed. Each entry replaces the previously listed server with the same name:", @@ -206,11 +185,11 @@ describe("McpInstructions", () => { ) catalog = [instructions("beta", "Beta instructions")] - const removed = yield* readUpdate(yield* service.load([]), changed) + const removed = yield* readUpdate(yield* service.load([], true), 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( + expect((yield* readUpdate(yield* service.load([], true), removed)).text).toBe( "MCP server instructions are no longer available.", ) }).pipe(