Skip to content

Commit 007afb1

Browse files
authored
feat(core): choose tools and Code Mode placement from the session's model (anomalyco#64515)
1 parent 6fcf388 commit 007afb1

60 files changed

Lines changed: 1345 additions & 511 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/core/src/automation/code.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type { SessionMessage } from "../session/message.js"
1111
import type { SessionSchema } from "../session/schema.js"
1212
import { Tool } from "../tool.js"
1313
import { McpTool } from "../tool/mcp.js"
14+
import { defaultCodeMode } from "../tool/runtime.js"
1415
import { Wildcard } from "../util/wildcard.js"
1516
import { type Invocation, matchesAuthor } from "./author.js"
1617
import type { AutomationEvent } from "./event.js"
@@ -134,9 +135,7 @@ const resolveTools = Effect.fnUntraced(function* (paths: ReadonlyArray<string>)
134135
const registered = yield* tools.list()
135136
const actions = new Set<string>()
136137
for (const path of paths) {
137-
const found = registered.find(
138-
(item) => item.options?.codemode !== false && CodeModeTool.qualifiedName(item) === path,
139-
)
138+
const found = registered.find((item) => defaultCodeMode(item) && CodeModeTool.qualifiedName(item) === path)
140139
if (!found) return yield* Effect.fail(`Unknown Code Mode tool: ${path}`)
141140
actions.add(found.options?.permission ?? found.id)
142141
}

‎packages/core/src/codemode/instructions.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,8 @@ export const make = (inventory?: CodeModeCatalog.Inventory): Instructions.List =
158158
// Rendered once, against the inventory that produced `current`, and stored with the update.
159159
changed: (previous, current) =>
160160
update(previous, current, inventory === undefined ? () => undefined : CodeModeCatalog.lookup(inventory)),
161-
removed: () => "Code Mode tools are no longer available. Do not use any previously listed Code Mode tools.",
161+
removed: () =>
162+
"The `execute` tool is no longer available. Permitted tools are now available as direct tool calls.",
162163
},
163164
})
164165
}

‎packages/core/src/codemode/tool.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ export const create = (
163163
const executed = yield* executeTool(name, tool, input, {
164164
...context,
165165
id,
166+
codemode: true,
166167
// Progress replaces the execute call's own, so an inner tool's updates would hide the call rows.
167168
progress: () => Effect.void,
168169
// 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<ExecuteCall>) => Array<Exe
258259
} satisfies CodeMode.Hooks
259260
}
260261

262+
const isPinned = (registration: Info) => {
263+
const codemode = registration.options?.codemode
264+
const pinned = typeof codemode === "object" && codemode !== null ? codemode.pinned : undefined
265+
return (pinned ?? registration.options?.pinned) === true
266+
}
267+
261268
export const catalog = (inventory: Inventory) => {
262-
const pinned = new Set(
263-
Array.from(inventory.tools.values())
264-
.filter((registration) => registration.options?.pinned === true)
265-
.map(qualifiedName),
266-
)
269+
const pinned = new Set(Array.from(inventory.tools.values()).filter(isPinned).map(qualifiedName))
267270
const root: CatalogNode = { children: new Map() }
268271
for (const namespace of inventory.namespaces?.values() ?? []) getNode(root, namespace.name).namespace = namespace
269272
for (const tool of runtime(inventory).catalog)
@@ -353,7 +356,7 @@ function inventoryTools(inventory: Inventory) {
353356
const root: ToolNode = { children: new Map() }
354357
for (const namespace of inventory.namespaces?.values() ?? []) getNode(root, namespace.name).namespace = namespace
355358
for (const [name, registration] of inventory.tools) {
356-
const child = definition(registration)
359+
const child = definition(registration, true)
357360
getNode(root, qualifiedName(registration)).tool = Tool.make({
358361
description: child.description,
359362
input: child.inputSchema,

‎packages/core/src/mcp/instructions.ts‎

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ export * as McpInstructions from "./instructions.js"
22

33
import { makeLocationNode } from "@opencode/util/effect/app-node"
44
import { Context, Effect, Layer, Schema } from "effect"
5-
import { Permission } from "../permission.js"
5+
import type { CodeModeCatalog } from "../codemode/catalog.js"
6+
import type { Tool } from "../tool.js"
67
import { McpTool } from "../tool/mcp.js"
8+
import { normalizedName } from "../tool/runtime.js"
79
import { Mcp } from "./index.js"
810
import { Instructions } from "../instructions/index.js"
911

@@ -42,9 +44,19 @@ const update = Instructions.listUpdate<Summary>({
4244
},
4345
})
4446

47+
function catalogPaths(
48+
items: ReadonlyArray<CodeModeCatalog.Tool | CodeModeCatalog.Namespace>,
49+
prefix = "",
50+
): ReadonlyArray<string> {
51+
return items.flatMap((item) => {
52+
const path = prefix ? `${prefix}.${item.name}` : item.name
53+
return item.type === "tool" ? [path] : catalogPaths(item.tools, path)
54+
})
55+
}
56+
4557
export interface Interface {
46-
/** Lists server instructions reachable under the given ruleset; callers pass the merged agent and Session permissions. */
47-
readonly load: (permissions: Permission.Ruleset) => Effect.Effect<Instructions.List>
58+
/** Lists instructions for MCP servers that have at least one tool in the Session's tool snapshot. */
59+
readonly load: (tools: Pick<Tool.Snapshot, "definitions" | "codeModeCatalog">) => Effect.Effect<Instructions.List>
4860
}
4961

5062
export class Service extends Context.Service<Service, Interface>()("@opencode/McpInstructions") {}
@@ -55,7 +67,7 @@ export const layer = Layer.effect(
5567
const mcp = yield* Mcp.Service
5668

5769
return Service.of({
58-
load: Effect.fn("McpInstructions.load")(function* (permissions) {
70+
load: Effect.fn("McpInstructions.load")(function* (snapshot) {
5971
const source = (value: ReadonlyArray<Summary> | Instructions.Removed) =>
6072
Instructions.make<ReadonlyArray<Summary>>({
6173
key: Instructions.Key.make("core/mcp-guidance"),
@@ -70,22 +82,18 @@ export const layer = Layer.effect(
7082
const [instructions, tools] = yield* Effect.all([mcp.instructions(), mcp.tools()], {
7183
concurrency: "unbounded",
7284
})
73-
const canExecute = Permission.evaluate("execute", "*", permissions).effect !== "deny"
85+
const direct = new Set(snapshot.definitions.map((tool) => tool.name))
86+
const codemode = new Set(snapshot.codeModeCatalog ? catalogPaths(snapshot.codeModeCatalog.tools) : [])
7487
// Instructions are useful only when this Session can reach at least one server tool.
7588
const visible = instructions
7689
.flatMap((item) => {
90+
const namespace = McpTool.namespace(item.server)
7791
const owned = tools.filter((tool) => tool.server === item.server)
78-
// Without execute, Code Mode server tools are exposed directly.
79-
const codemode = canExecute && owned[0]?.codemode !== false
80-
if (
81-
!owned.some(
82-
(tool) =>
83-
Permission.evaluate(McpTool.name(tool.server, tool.name), "*", permissions).effect !== "deny",
84-
)
85-
)
86-
return []
92+
const inCodeMode = owned.some((tool) => codemode.has(`${namespace}.${normalizedName({ name: tool.name })}`))
93+
const inDirect = owned.some((tool) => direct.has(McpTool.name(item.server, tool.name)))
94+
if (!inCodeMode && !inDirect) return []
8795
return [
88-
codemode
96+
inCodeMode
8997
? { server: item.server, instructions: item.instructions }
9098
: { server: item.server, instructions: item.instructions, codemode: false as const },
9199
]

‎packages/core/src/plugin/internal.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,6 @@ const pre = [
262262
...ProviderPlugins,
263263
...WebSearchPlugins,
264264
PatchTool.Plugin,
265-
// Render model prompts after the patch plugin selects the available editing tools.
266265
...OptimizePlugin.Plugins,
267266
VerbosityPlugin.Plugin,
268267
IdentityPlugin.Plugin,

‎packages/core/src/plugin/optimize.ts‎

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -29,25 +29,6 @@ export const AnthropicPlugin = make(
2929
"append",
3030
)
3131

32-
// Both OpenAIToolsPlugin and AnthropicToolsPlugin are disabled intentionally until we can figure out a good ux for displaying
33-
// heavy grep/glob usage done via shell or other mechanisms
34-
35-
export const OpenAIToolsPlugin = make("opencode.optimize.openai.tools", (model, tools) => {
36-
const ids = [model.id, model.modelID, model.family].join(" ").toLowerCase()
37-
if (!ids.includes("gpt")) return undefined
38-
delete tools.grep
39-
delete tools.glob
40-
return undefined
41-
})
42-
43-
export const AnthropicToolsPlugin = make("opencode.optimize.anthropic.tools", (model, tools) => {
44-
const ids = [model.id, model.modelID, model.family].join(" ").toLowerCase()
45-
if (!ids.includes("claude")) return undefined
46-
delete tools.grep
47-
delete tools.glob
48-
return undefined
49-
})
50-
5132
export const KimiPlugin = make("opencode.prompt.kimi", (model) =>
5233
model.id.toLowerCase().includes("kimi") ? PROMPT_KIMI : undefined,
5334
)
@@ -77,7 +58,7 @@ export const resolveModel = (ctx: Context, event: SessionHooks["context"]) =>
7758

7859
function make(
7960
id: string,
80-
optimize: (model: Model.Info, tools: SessionHooks["context"]["tools"]) => string | undefined,
61+
optimize: (model: Model.Info) => string | undefined,
8162
mode: "override" | "append" = "override",
8263
) {
8364
return define({
@@ -86,8 +67,7 @@ function make(
8667
const hook = (event: SessionHooks["context"]) =>
8768
Effect.gen(function* () {
8869
const model = yield* resolveModel(ctx, event)
89-
// Curate tools before rendering their guidance, including for agents with a custom system prompt.
90-
const template = optimize(model, event.tools)
70+
const template = optimize(model)
9171
if (!template) return
9272
if ((yield* ctx.agent.get({ agentID: event.agent })).data.system) return
9373
const system = event.system[0]

‎packages/core/src/plugin/provider/opencode-watches.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ export const make = Effect.fnUntraced(function* (ctx: Context, http: HttpClient.
282282
),
283283
}),
284284
output: Watch,
285-
options: { namespace, codemode: true, pinned: true },
285+
options: { namespace, codemode: { pinned: true } },
286286
execute: (input, context) =>
287287
Effect.gen(function* () {
288288
// A link or shorthand, or one event type of a server with its arguments; never both.

‎packages/core/src/plugin/tool-input-repair.ts‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,20 +30,19 @@ export const Plugin = define({
3030
const aliased = new Map<string, string>()
3131
yield* ctx.tool.hook("execute.before", (event) =>
3232
Effect.gen(function* () {
33-
// The outer Code Mode tool is built per snapshot rather than registered, so it cannot be
34-
// looked up here. Its `{ code }` input is trivial; the tools it calls are repaired normally.
33+
// The outer Code Mode tool is built per snapshot rather than registered; its `{ code }`
34+
// input is trivial, and the tools it calls are repaired normally.
3535
if (event.tool === "execute") return
36-
const tools = yield* ctx.tool.list()
37-
const alias = aliases.get(event.tool)
38-
const tool =
39-
tools.find((tool) => tool.id === event.tool) ??
40-
(alias === undefined ? undefined : tools.find((tool) => tool.id === alias))
36+
const alias = event.info ? undefined : aliases.get(event.tool)
37+
const aliasedTool =
38+
alias === undefined ? undefined : (yield* ctx.tool.list()).find((tool) => tool.id === alias)
39+
const tool = event.info ?? aliasedTool
4140
if (!tool) return
42-
if (tool.id !== event.tool) {
41+
if (aliasedTool) {
4342
aliased.set(event.id, event.tool)
44-
event.tool = tool.id
43+
event.tool = aliasedTool.id
4544
}
46-
const schema = definition(tool).inputSchema
45+
const schema = definition(tool, event.codemode).inputSchema
4746
if (schema.type !== "object") return
4847
event.input = repair(event.input, schema, schema, 0)
4948
}),

‎packages/core/src/session/context.ts‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { Environment } from "../environment/index.js"
1212
import { FileAccess } from "../file-access.js"
1313
import { FileMutation } from "../file-mutation.js"
1414
import { FileWrite } from "../file-write.js"
15+
import { Flag } from "../flag.js"
1516
import { makeLocationNode } from "@opencode/util/effect/app-node"
1617
import { InstructionDiscovery } from "../instruction-discovery.js"
1718
import { Instructions } from "../instructions/index.js"
@@ -22,6 +23,8 @@ import { McpTool } from "../tool/mcp.js"
2223
import { ReferenceInstructions } from "../reference/instructions.js"
2324
import { SkillInstructions } from "../skill/instructions.js"
2425
import { Tool } from "../tool.js"
26+
import { modelTools } from "../tool/model-policy.js"
27+
import { WebSearch } from "../websearch.js"
2528
import { AgentNotFoundError } from "./error.js"
2629
import { SessionHistory } from "./history.js"
2730
import { InstructionEntry } from "./instruction-entry.js"
@@ -86,6 +89,7 @@ const layer = Layer.effect(
8689
const db = (yield* Database.Service).db
8790
const discovery = yield* InstructionDiscovery.Service
8891
const entries = yield* InstructionEntry.Service
92+
const flags = yield* Flag.Service
8993
const location = yield* Location.Service
9094
const mcpInstructions = yield* McpInstructions.Service
9195
const mcpTools = yield* McpTool.Service
@@ -95,7 +99,8 @@ const layer = Layer.effect(
9599
const skillInstructions = yield* SkillInstructions.Service
96100
const store = yield* SessionStore.Service
97101
const registry = yield* Tool.Service
98-
const codeMode = yield* CodeModeTool.services
102+
const services = yield* CodeModeTool.services
103+
const websearch = yield* WebSearch.Service
99104

100105
const resolveModel = (
101106
session: SessionSchema.Info,
@@ -150,14 +155,27 @@ const layer = Layer.effect(
150155
if (!agent.info) return yield* new AgentNotFoundError({ sessionID: session.id, agent: session.agent ?? agent.id })
151156
// Session permissions narrow discovery the same way they narrow the tool snapshot.
152157
const permissions = Permission.merge(agent.info.permissions, session.permissions ?? [])
158+
const [selected, hasWebSearch, fullCodeMode] = yield* Effect.all(
159+
[
160+
models.select(session, model.available).pipe(Effect.orElseSucceed(() => undefined)),
161+
websearch.available(),
162+
flags.enabled("full_codemode"),
163+
],
164+
{ concurrency: "unbounded" },
165+
)
166+
const fallbackRef = session.model ?? agent.info.model
167+
const policyModel = selected?.info ?? (fallbackRef && Model.Info.default(fallbackRef.providerID, fallbackRef.id))
168+
const tools = yield* registry.snapshot(permissions, {
169+
services,
170+
tools: modelTools({ model: policyModel, websearch: hasWebSearch, fullCodeMode }),
171+
})
153172
const loaded = yield* Effect.all(
154173
{
155-
tools: registry.snapshot(permissions, codeMode),
156174
builtins: builtins.load(),
157175
discovery: discovery.load(),
158176
skills: skillInstructions.load(permissions),
159177
references: referenceInstructions.load(),
160-
mcp: mcpInstructions.load(permissions),
178+
mcp: mcpInstructions.load(tools),
161179
entries: entries.load(sessionID),
162180
},
163181
{ concurrency: "unbounded" },
@@ -169,15 +187,15 @@ const layer = Layer.effect(
169187
// prompt-cache prefix: user-level catalog and guidance, then project instructions, then
170188
// the date and environment, which vary by day and directory.
171189
instructions: Instructions.combine([
172-
CodeModeInstructions.make(loaded.tools.codeModeCatalog),
190+
CodeModeInstructions.make(tools.codeModeCatalog),
173191
loaded.mcp,
174192
loaded.references,
175193
loaded.skills,
176194
loaded.discovery,
177195
loaded.builtins,
178196
loaded.entries,
179197
]),
180-
tools: loaded.tools,
198+
tools,
181199
}
182200
})
183201

@@ -229,6 +247,7 @@ export const node = makeLocationNode({
229247
FileAccess.node,
230248
FileMutation.node,
231249
FileWrite.node,
250+
Flag.node,
232251
InstructionBuiltIns.node,
233252
InstructionDiscovery.node,
234253
InstructionEntry.node,
@@ -241,5 +260,6 @@ export const node = makeLocationNode({
241260
SessionStore.node,
242261
SkillInstructions.node,
243262
Tool.node,
263+
WebSearch.node,
244264
],
245265
})

‎packages/core/src/session/runner/model.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,13 @@ export type Error = ModelNotSelectedError | ModelUnavailableError | ModelResolve
3636
export type Resolved = ModelResolver.Resolved
3737

3838
export interface Interface {
39+
readonly select: (
40+
session: SessionSchema.Info,
41+
available: () => Effect.Effect<ReadonlyArray<Model.Info>>,
42+
) => Effect.Effect<
43+
{ readonly info: Model.Info; readonly variant: Model.VariantID | undefined },
44+
ModelNotSelectedError | ModelUnavailableError
45+
>
3946
/** Availability is sampled lazily for each explicitly selected model resolution. */
4047
readonly resolve: (
4148
session: SessionSchema.Info,
@@ -99,6 +106,7 @@ const layer = Layer.effect(
99106
return yield* new ModelNotSelectedError({ sessionID: session.id })
100107
})
101108
return Service.of({
109+
select,
102110
resolve: Effect.fn("SessionRunnerModel.resolve")(function* (session, available, request) {
103111
const selected = yield* select(session, available)
104112
const ref = Model.Ref.make({

0 commit comments

Comments
 (0)