opencode-model-router 1.15.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +126 -0
- package/README.md +148 -30
- package/package.json +8 -4
- package/server.ts +3 -0
- package/src/compat/child-session.ts +32 -0
- package/src/compat/v2-client.ts +183 -0
- package/src/compat/v2-hooks.ts +409 -0
- package/src/escalate/effort-override.ts +165 -0
- package/src/escalate/ladder.ts +57 -7
- package/src/index.ts +243 -54
- package/src/router/agent-options.ts +43 -12
- package/src/router/config.ts +145 -23
- package/src/router/depth-guard.ts +152 -0
- package/src/router/depth.ts +826 -0
- package/src/router/protocol.ts +1 -0
- package/src/v2.ts +25 -0
- package/src/verify/checker.ts +1 -1
- package/src/verify/dispatch.ts +1 -1
- package/src/verify/dod.ts +8 -1
- package/src/verify/gate.ts +16 -1
- package/src/verify/paths.ts +9 -1
- package/src/verify/wiring.ts +95 -4
- package/tiers.json +20 -17
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import type { Plugin } from "@opencode/plugin";
|
|
3
|
+
import type { ToolContext } from "@opencode/plugin/promise/tool";
|
|
4
|
+
import type { SessionContext } from "@opencode/plugin/promise/session";
|
|
5
|
+
import type { ChildSessionRunner } from "./child-session";
|
|
6
|
+
|
|
7
|
+
export const V2_GRADER_AGENT = "model-router-grader";
|
|
8
|
+
const RETAINED_CONTEXT_LIMIT = 500;
|
|
9
|
+
|
|
10
|
+
/** The small v1 client surface still used by the shared hooks. */
|
|
11
|
+
export function createV2Runtime(ctx: Plugin.Context) {
|
|
12
|
+
type ToolScope = { context: ToolContext; active: boolean };
|
|
13
|
+
const currentTool = new AsyncLocalStorage<ToolScope>();
|
|
14
|
+
const retainedContexts = new Map<string, ToolScope>();
|
|
15
|
+
const lifetime = new AbortController();
|
|
16
|
+
const childSystems = new Map<string, string>();
|
|
17
|
+
const activeChildren = new Map<string, AbortController>();
|
|
18
|
+
|
|
19
|
+
const interrupt = async (sessionID: string, signal?: AbortSignal) => {
|
|
20
|
+
activeChildren.get(sessionID)?.abort();
|
|
21
|
+
return ctx.session.interrupt({ sessionID }, signal ? { signal } : undefined);
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const client = {
|
|
25
|
+
session: {
|
|
26
|
+
async get(input: { path: { id: string }; signal?: AbortSignal }) {
|
|
27
|
+
return { data: await ctx.session.get({ sessionID: input.path.id }, input.signal ? { signal: input.signal } : undefined) };
|
|
28
|
+
},
|
|
29
|
+
async abort(input: { path: { id: string }; signal?: AbortSignal }) {
|
|
30
|
+
return { data: await interrupt(input.path.id, input.signal) };
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
config: {
|
|
34
|
+
async providers() {
|
|
35
|
+
const location = { directory: ctx.location.directory };
|
|
36
|
+
const [providers, models, defaultModel] = await Promise.all([
|
|
37
|
+
ctx.provider.list({ location }),
|
|
38
|
+
ctx.model.list({ location }),
|
|
39
|
+
ctx.model.default({ location }),
|
|
40
|
+
]);
|
|
41
|
+
return {
|
|
42
|
+
data: {
|
|
43
|
+
providers: providers.data.map(provider => ({
|
|
44
|
+
id: provider.id,
|
|
45
|
+
name: provider.name,
|
|
46
|
+
models: Object.fromEntries(models.data
|
|
47
|
+
.filter(model => model.providerID === provider.id && model.enabled)
|
|
48
|
+
.map(model => [model.id, { id: model.id, status: model.status }])),
|
|
49
|
+
})),
|
|
50
|
+
default: defaultModel.data
|
|
51
|
+
? { [defaultModel.data.providerID]: defaultModel.data.id }
|
|
52
|
+
: {},
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
// v2 has no app.log endpoint. createPluginLogger uses its console fallback.
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const childRunner: ChildSessionRunner = {
|
|
61
|
+
async run(request) {
|
|
62
|
+
lifetime.signal.throwIfAborted();
|
|
63
|
+
const current = currentTool.getStore();
|
|
64
|
+
// A shared background worker can run in a different caller's async
|
|
65
|
+
// scope. Only a real context previously observed for the requested
|
|
66
|
+
// parent may authorize that dispatch; never manufacture call/message IDs.
|
|
67
|
+
const scope = request.parentSessionID && request.parentSessionID !== current?.context.sessionID
|
|
68
|
+
? retainedContexts.get(request.parentSessionID)
|
|
69
|
+
: current;
|
|
70
|
+
if (!scope) throw new Error("[model-router] v2 child dispatch requires an active tool context or a retained context matching its parent");
|
|
71
|
+
const toolContext = scope.context;
|
|
72
|
+
// Retained-scope permission prompts remain attributed to the originating
|
|
73
|
+
// real call IDs, never fabricated replacements.
|
|
74
|
+
const native = (await ctx.tool.list()).find(tool => tool.id === "subagent");
|
|
75
|
+
if (!native) throw new Error("[model-router] OpenCode v2's native subagent tool is unavailable");
|
|
76
|
+
const controller = new AbortController();
|
|
77
|
+
// Deferred verification outlives its originating tool call. Its own
|
|
78
|
+
// deadline and plugin lifetime govern cancellation once that call ends.
|
|
79
|
+
const signal = AbortSignal.any([
|
|
80
|
+
lifetime.signal, controller.signal,
|
|
81
|
+
...(scope.active ? [toolContext.signal] : []),
|
|
82
|
+
...(request.signal ? [request.signal] : []),
|
|
83
|
+
]);
|
|
84
|
+
signal.throwIfAborted();
|
|
85
|
+
let childID: string | undefined;
|
|
86
|
+
const model = request.model;
|
|
87
|
+
try {
|
|
88
|
+
const result = await native.execute({
|
|
89
|
+
agent: request.agent ?? V2_GRADER_AGENT,
|
|
90
|
+
description: request.agent ? `Router ${request.agent} delegation` : "Router result verification",
|
|
91
|
+
prompt: request.prompt,
|
|
92
|
+
...(model ? { model: `${model.providerID}/${model.modelID}${model.variant ? `#${model.variant}` : ""}` } : {}),
|
|
93
|
+
background: false,
|
|
94
|
+
}, {
|
|
95
|
+
...toolContext,
|
|
96
|
+
signal,
|
|
97
|
+
async progress(metadata) {
|
|
98
|
+
const sessionID = metadata.sessionID;
|
|
99
|
+
if (typeof sessionID === "string" && sessionID !== childID) {
|
|
100
|
+
if (childID) throw new Error("[model-router] native subagent changed its child session ID");
|
|
101
|
+
childID = sessionID;
|
|
102
|
+
activeChildren.set(sessionID, controller);
|
|
103
|
+
if (request.system) childSystems.set(sessionID, request.system);
|
|
104
|
+
// The native subagent awaits progress after creating its child and
|
|
105
|
+
// before prompting it. Register guards and scope graders here.
|
|
106
|
+
await request.onCreated(sessionID);
|
|
107
|
+
if (request.cwd) await ctx.session.move({ sessionID, directory: request.cwd }, { signal });
|
|
108
|
+
signal.throwIfAborted();
|
|
109
|
+
}
|
|
110
|
+
// V2 rejects progress outside a running call. Deferred/queued graders
|
|
111
|
+
// retain settled parent contexts; also tolerate settlement during progress.
|
|
112
|
+
if (scope.active) {
|
|
113
|
+
try { await toolContext.progress(metadata); }
|
|
114
|
+
catch (error) { if (scope.active) throw error; }
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
signal.throwIfAborted();
|
|
119
|
+
const output = result.output as { sessionID?: unknown; status?: unknown; output?: unknown } | undefined;
|
|
120
|
+
if (!childID || output?.sessionID !== childID || output.status !== "completed" || typeof output.output !== "string") {
|
|
121
|
+
throw new Error("[model-router] native subagent did not return a completed child result; verification cannot use a pending result");
|
|
122
|
+
}
|
|
123
|
+
return { sessionID: childID, text: output.output };
|
|
124
|
+
} catch (error) {
|
|
125
|
+
controller.abort();
|
|
126
|
+
if (childID) {
|
|
127
|
+
try { await ctx.session.interrupt({ sessionID: childID }); } catch { /* keep the original dispatch failure */ }
|
|
128
|
+
}
|
|
129
|
+
throw error;
|
|
130
|
+
} finally {
|
|
131
|
+
if (childID) {
|
|
132
|
+
childSystems.delete(childID);
|
|
133
|
+
activeChildren.delete(childID);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
async dispose(sessionID) {
|
|
138
|
+
childSystems.delete(sessionID);
|
|
139
|
+
await interrupt(sessionID);
|
|
140
|
+
// Removal was added in 2.0.21; older hosts retain child history.
|
|
141
|
+
// disposeChildSession catches cleanup failures without masking the result.
|
|
142
|
+
if (typeof ctx.session.remove === "function") await ctx.session.remove({ sessionID });
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
client,
|
|
148
|
+
childRunner,
|
|
149
|
+
async withToolContext<T>(context: ToolContext, operation: () => Promise<T>): Promise<T> {
|
|
150
|
+
lifetime.signal.throwIfAborted();
|
|
151
|
+
const scope = { context, active: true };
|
|
152
|
+
retainedContexts.delete(context.sessionID);
|
|
153
|
+
retainedContexts.set(context.sessionID, scope);
|
|
154
|
+
while (retainedContexts.size > RETAINED_CONTEXT_LIMIT) {
|
|
155
|
+
retainedContexts.delete(retainedContexts.keys().next().value!);
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
return await currentTool.run(scope, operation);
|
|
159
|
+
} finally {
|
|
160
|
+
scope.active = false;
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
applyChildSystem(sessionID: string, system: SessionContext["system"]): void {
|
|
164
|
+
const text = childSystems.get(sessionID);
|
|
165
|
+
if (text && !system.some(part => part.text === text)) system.push({ type: "text", text });
|
|
166
|
+
},
|
|
167
|
+
forgetSession(sessionID: string): void {
|
|
168
|
+
retainedContexts.delete(sessionID);
|
|
169
|
+
childSystems.delete(sessionID);
|
|
170
|
+
activeChildren.get(sessionID)?.abort();
|
|
171
|
+
},
|
|
172
|
+
async dispose(): Promise<void> {
|
|
173
|
+
lifetime.abort();
|
|
174
|
+
const sessions = [...activeChildren.keys()];
|
|
175
|
+
retainedContexts.clear();
|
|
176
|
+
childSystems.clear();
|
|
177
|
+
await Promise.allSettled(sessions.map(sessionID => interrupt(sessionID)));
|
|
178
|
+
activeChildren.clear();
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export type V2Runtime = ReturnType<typeof createV2Runtime>;
|
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
import type { Hooks } from "@opencode-ai/plugin";
|
|
2
|
+
import { tool } from "@opencode-ai/plugin";
|
|
3
|
+
import type { Context } from "@opencode/plugin/promise/plugin";
|
|
4
|
+
import type { ToolContext } from "@opencode/plugin/promise/tool";
|
|
5
|
+
import type { SystemPart } from "@opencode/ai";
|
|
6
|
+
import type { V2Runtime } from "./v2-client";
|
|
7
|
+
import { V2_GRADER_AGENT } from "./v2-client";
|
|
8
|
+
import { DEPTH_BANNER, TASK_VERIFICATION } from "./child-session";
|
|
9
|
+
import { isAbsolute, resolve } from "node:path";
|
|
10
|
+
import { loadConfig } from "../router/config";
|
|
11
|
+
import { getActiveTiers } from "../router/protocol";
|
|
12
|
+
import { resolveSubagentOverrides } from "../router/subagents";
|
|
13
|
+
import { stripDelegateInstructions } from "../router/instructions";
|
|
14
|
+
import { GRADER_SYSTEM } from "../verify/checker";
|
|
15
|
+
|
|
16
|
+
/** Translate the router's own v1 tool vocabulary at the v2 boundary. */
|
|
17
|
+
export function v2Instructions(text: string): string {
|
|
18
|
+
return text
|
|
19
|
+
.replace(/\bTask(?=\s*\()/g, "subagent")
|
|
20
|
+
.replace(/\bTask (calls?|tool)\b/g, "subagent $1")
|
|
21
|
+
.replace(/\btask tool\b/g, "subagent tool")
|
|
22
|
+
.replace(/`task`/g, "`subagent`")
|
|
23
|
+
.replace(/\bsubagent_type\b/g, "agent")
|
|
24
|
+
.replace(/\btask_id\b/g, "sessionID");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type LegacyAgent = Record<string, any>;
|
|
28
|
+
type LegacyConfig = { agent: Record<string, LegacyAgent>; command: Record<string, any> };
|
|
29
|
+
type LegacyHook = (input: any, output: any) => Promise<void>;
|
|
30
|
+
|
|
31
|
+
function modelRef(value: string, variant?: string): any {
|
|
32
|
+
const slash = value.indexOf("/");
|
|
33
|
+
if (slash < 1) throw new Error(`[model-router] Invalid model reference: ${value}`);
|
|
34
|
+
return { providerID: value.slice(0, slash), id: value.slice(slash + 1), ...(variant ? { variant } : {}) };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function taskArgs(toolName: string, input: unknown): any {
|
|
38
|
+
if (!input || typeof input !== "object") return input;
|
|
39
|
+
const args = input as Record<string, unknown>;
|
|
40
|
+
if (toolName === "subagent") return { ...args, subagent_type: args.agent, task_id: args.sessionID };
|
|
41
|
+
if (toolName === "shell") return { ...args, cwd: args.workdir };
|
|
42
|
+
if (["read", "write", "edit"].includes(toolName)) return { ...args, filePath: args.path };
|
|
43
|
+
return input;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function nativeArgs(toolName: string, args: any, original: any, verifying: boolean): any {
|
|
47
|
+
if (!args || typeof args !== "object") return args;
|
|
48
|
+
if (toolName === "subagent") {
|
|
49
|
+
const { subagent_type, task_id, ...rest } = args;
|
|
50
|
+
return { ...rest, agent: subagent_type, ...(task_id === undefined ? {} : { sessionID: task_id }), ...(verifying ? { background: false } : {}) };
|
|
51
|
+
}
|
|
52
|
+
if (toolName === "shell") { const { cwd, ...rest } = args; return { ...rest, ...(cwd === undefined ? {} : { workdir: cwd }) }; }
|
|
53
|
+
if (["read", "write", "edit"].includes(toolName)) {
|
|
54
|
+
const { filePath, ...rest } = args;
|
|
55
|
+
return { ...rest, path: filePath === original?.filePath ? rest.path : filePath };
|
|
56
|
+
}
|
|
57
|
+
return args;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function legacyToolName(name: string): string { return name === "subagent" ? "task" : name === "shell" ? "bash" : name; }
|
|
61
|
+
|
|
62
|
+
function contentText(content: unknown): string {
|
|
63
|
+
if (typeof content === "string") return content;
|
|
64
|
+
if (!Array.isArray(content)) return "";
|
|
65
|
+
return content.filter((item) => item?.type === "text").map((item) => item.text).join("\n");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Rewrite new router prose without changing retained source code or user text. */
|
|
69
|
+
function translateAdded(before: string, after: string): string {
|
|
70
|
+
let prefix = 0;
|
|
71
|
+
while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix]) prefix++;
|
|
72
|
+
let suffix = 0;
|
|
73
|
+
while (suffix < before.length - prefix && suffix < after.length - prefix
|
|
74
|
+
&& before[before.length - suffix - 1] === after[after.length - suffix - 1]) suffix++;
|
|
75
|
+
return after.slice(0, prefix) + v2Instructions(after.slice(prefix, after.length - suffix)) + after.slice(after.length - suffix);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Register the existing router engine on the public OpenCode 2 domain APIs. */
|
|
79
|
+
export async function registerV2Hooks(
|
|
80
|
+
ctx: Context,
|
|
81
|
+
hooks: Hooks,
|
|
82
|
+
runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession">>,
|
|
83
|
+
): Promise<() => Promise<void>> {
|
|
84
|
+
// The old plugin surface uses separate mutable input/output bags. Keep those
|
|
85
|
+
// casts confined to this adapter, rather than weakening the v2 event types.
|
|
86
|
+
const legacy = hooks as unknown as Record<string, LegacyHook | undefined>;
|
|
87
|
+
const registrations: Array<{ dispose(): Promise<void> }> = [];
|
|
88
|
+
const abort = new AbortController();
|
|
89
|
+
const verifyingCalls = new Set<string>();
|
|
90
|
+
const depthBanners = new Map<string, string>();
|
|
91
|
+
let eventTask: Promise<void> | undefined;
|
|
92
|
+
let disposed = false;
|
|
93
|
+
const within = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
|
|
94
|
+
runtime ? runtime.withToolContext(context, operation) : operation();
|
|
95
|
+
const scopedArgs = async (event: { tool: string; input: unknown; sessionID: any }): Promise<any> => {
|
|
96
|
+
const args = taskArgs(event.tool, event.input);
|
|
97
|
+
if (["read", "write", "edit"].includes(event.tool) && typeof args?.filePath === "string" && !isAbsolute(args.filePath)) {
|
|
98
|
+
const session = await ctx.session.get({ sessionID: event.sessionID });
|
|
99
|
+
args.filePath = resolve(session.location?.directory ?? ctx.location.directory, args.filePath);
|
|
100
|
+
}
|
|
101
|
+
return args;
|
|
102
|
+
};
|
|
103
|
+
const hookContext = (event: { sessionID: any; agent: any; messageID: any; id: any }): ToolContext => ({
|
|
104
|
+
...event, signal: abort.signal, progress: async () => {},
|
|
105
|
+
});
|
|
106
|
+
const cleanup = async () => {
|
|
107
|
+
if (disposed) return;
|
|
108
|
+
disposed = true;
|
|
109
|
+
abort.abort();
|
|
110
|
+
await runtime?.dispose?.();
|
|
111
|
+
await eventTask;
|
|
112
|
+
await Promise.allSettled(registrations.map((registration) => registration.dispose()));
|
|
113
|
+
await hooks.dispose?.();
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
try {
|
|
117
|
+
const agents = await ctx.agent.list();
|
|
118
|
+
const config: LegacyConfig = { agent: {}, command: {} };
|
|
119
|
+
for (const agent of agents.data) config.agent[agent.id] = {
|
|
120
|
+
mode: agent.mode,
|
|
121
|
+
model: agent.model && `${agent.model.providerID}/${agent.model.id}`,
|
|
122
|
+
variant: agent.model?.variant,
|
|
123
|
+
};
|
|
124
|
+
const originals = new Map(Object.entries(config.agent).map(([id, agent]) => [id, JSON.stringify(agent)]));
|
|
125
|
+
await hooks.config?.(config);
|
|
126
|
+
const agentOptions = new Map<string, Record<string, unknown>>();
|
|
127
|
+
for (const [name, definition] of Object.entries(config.agent)) {
|
|
128
|
+
if (originals.get(name) === JSON.stringify(definition) || !definition.options) continue;
|
|
129
|
+
const { reasoning_effort, reasoning_summary, budget_tokens, ...options } = definition.options;
|
|
130
|
+
const normalized = { ...options };
|
|
131
|
+
if (reasoning_effort !== undefined && normalized.reasoningEffort === undefined) normalized.reasoningEffort = reasoning_effort;
|
|
132
|
+
if (reasoning_summary !== undefined && normalized.reasoningSummary === undefined) normalized.reasoningSummary = reasoning_summary;
|
|
133
|
+
if (budget_tokens !== undefined && normalized.thinking === undefined) normalized.thinking = { type: "enabled", budgetTokens: budget_tokens };
|
|
134
|
+
agentOptions.set(name, normalized);
|
|
135
|
+
}
|
|
136
|
+
registrations.push(await ctx.agent.transform((editor) => {
|
|
137
|
+
if (runtime) editor.update(V2_GRADER_AGENT, (agent) => {
|
|
138
|
+
agent.mode = "subagent";
|
|
139
|
+
agent.hidden = true;
|
|
140
|
+
agent.description = "Model router verification grader";
|
|
141
|
+
agent.system = GRADER_SYSTEM;
|
|
142
|
+
});
|
|
143
|
+
for (const [name, definition] of Object.entries(config.agent)) {
|
|
144
|
+
if (originals.get(name) === JSON.stringify(definition)) continue;
|
|
145
|
+
editor.update(name, (agent) => {
|
|
146
|
+
if (definition.model) agent.model = modelRef(definition.model, definition.variant);
|
|
147
|
+
if (definition.mode) agent.mode = definition.mode;
|
|
148
|
+
if (definition.description !== undefined) agent.description = definition.description;
|
|
149
|
+
if (definition.prompt !== undefined) agent.system = v2Instructions(definition.prompt);
|
|
150
|
+
if (definition.color !== undefined) agent.color = definition.color;
|
|
151
|
+
if (definition.steps !== undefined) agent.steps = definition.steps;
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
}));
|
|
155
|
+
|
|
156
|
+
registrations.push(await ctx.command.transform((editor) => {
|
|
157
|
+
for (const [name, definition] of Object.entries(config.command)) editor.add({
|
|
158
|
+
name,
|
|
159
|
+
description: definition.description,
|
|
160
|
+
execute: async (invocation) => {
|
|
161
|
+
const text = String(definition.template ?? "").replaceAll("$ARGUMENTS", () => invocation.prompt.text);
|
|
162
|
+
const output = { parts: text ? [{ type: "text", text }] : [] };
|
|
163
|
+
await legacy["command.execute.before"]?.({
|
|
164
|
+
command: name, arguments: invocation.prompt.text, sessionID: invocation.sessionID,
|
|
165
|
+
}, output);
|
|
166
|
+
await ctx.session.prompt({
|
|
167
|
+
...invocation.prompt,
|
|
168
|
+
sessionID: invocation.sessionID,
|
|
169
|
+
delivery: invocation.delivery,
|
|
170
|
+
text: output.parts.map((part) => v2Instructions(part.text)).join("\n\n"),
|
|
171
|
+
});
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
}));
|
|
175
|
+
|
|
176
|
+
registrations.push(await ctx.tool.transform((editor) => {
|
|
177
|
+
for (const [name, definition] of Object.entries(hooks.tool ?? {})) editor.add({
|
|
178
|
+
name,
|
|
179
|
+
description: v2Instructions(definition.description),
|
|
180
|
+
input: tool.schema.object(definition.args),
|
|
181
|
+
// Router tools must remain directly callable, matching v1 tool exposure.
|
|
182
|
+
options: { codemode: false },
|
|
183
|
+
execute: async (args, context) => within(context, async () => {
|
|
184
|
+
const result = await definition.execute(args, {
|
|
185
|
+
sessionID: context.sessionID, messageID: context.messageID, agent: context.agent,
|
|
186
|
+
directory: ctx.location.directory, worktree: ctx.location.project.directory,
|
|
187
|
+
abort: context.signal,
|
|
188
|
+
metadata: (metadata) => { void context.progress(metadata); },
|
|
189
|
+
ask: async () => { throw new Error("[model-router] This tool cannot request v1 permissions on OpenCode 2"); },
|
|
190
|
+
});
|
|
191
|
+
if (typeof result === "string") return { content: result };
|
|
192
|
+
return {
|
|
193
|
+
content: [
|
|
194
|
+
{ type: "text" as const, text: result.output },
|
|
195
|
+
...(result.attachments ?? []).map((file) => ({
|
|
196
|
+
type: "file" as const, uri: file.url, mime: file.mime, ...(file.filename ? { name: file.filename } : {}),
|
|
197
|
+
})),
|
|
198
|
+
],
|
|
199
|
+
metadata: { ...result.metadata, ...(result.title ? { title: result.title } : {}) },
|
|
200
|
+
};
|
|
201
|
+
}),
|
|
202
|
+
});
|
|
203
|
+
}));
|
|
204
|
+
|
|
205
|
+
registrations.push(await ctx.session.hook("prompt", async (event) => {
|
|
206
|
+
const session = await ctx.session.get({ sessionID: event.sessionID });
|
|
207
|
+
const output = { message: { agent: session.agent }, parts: [{ type: "text", text: event.prompt.text }] };
|
|
208
|
+
await legacy["chat.message"]?.({ sessionID: event.sessionID, agent: session.agent }, output);
|
|
209
|
+
event.prompt.text = output.parts.map((part) => part.text).join("\n\n");
|
|
210
|
+
}));
|
|
211
|
+
registrations.push(await ctx.session.hook("context", async (event) => {
|
|
212
|
+
const input = { sessionID: event.sessionID, agent: event.agent, model: { ...event.model, modelID: event.model.id } };
|
|
213
|
+
// V2 consumes per-turn options, not Agent.Info.request.settings.
|
|
214
|
+
for (const [key, value] of Object.entries(agentOptions.get(event.agent) ?? {})) {
|
|
215
|
+
if (!(key in event.options)) event.options[key] = value;
|
|
216
|
+
}
|
|
217
|
+
await legacy["chat.params"]?.(input, event.options);
|
|
218
|
+
const verify = loadConfig().enforcement?.verify;
|
|
219
|
+
if (event.agent === V2_GRADER_AGENT
|
|
220
|
+
&& (verify?.graderTemperature === null
|
|
221
|
+
|| !(verify?.graderTemperatureModels ?? []).includes(`${event.model.providerID}/${event.model.id}`))) {
|
|
222
|
+
delete event.options.temperature;
|
|
223
|
+
}
|
|
224
|
+
const original = new Map<string, SystemPart[]>();
|
|
225
|
+
for (const part of event.system) {
|
|
226
|
+
const copies = original.get(part.text) ?? [];
|
|
227
|
+
copies.push(part);
|
|
228
|
+
original.set(part.text, copies);
|
|
229
|
+
}
|
|
230
|
+
const output = { system: event.system.map((part) => part.text) };
|
|
231
|
+
// The router pushes its own instructions, but may splice edited user text.
|
|
232
|
+
// Only pushed text belongs to the router and may have its vocabulary translated.
|
|
233
|
+
const added = new Set<string>();
|
|
234
|
+
Object.defineProperty(output.system, "push", { value: (...texts: string[]) => {
|
|
235
|
+
for (const text of texts) added.add(text);
|
|
236
|
+
return Array.prototype.push.apply(output.system, texts);
|
|
237
|
+
} });
|
|
238
|
+
await legacy["experimental.chat.system.transform"]?.(input, output);
|
|
239
|
+
event.system = output.system.map((text): SystemPart =>
|
|
240
|
+
original.get(text)?.shift() ?? { type: "text", text: added.has(text) ? v2Instructions(text) : text });
|
|
241
|
+
runtime?.applyChildSystem(event.sessionID, event.system);
|
|
242
|
+
// Native reads load nested AGENTS.md as synthetic user-role messages.
|
|
243
|
+
// Correlate their IDs with durable attribution before removing anything;
|
|
244
|
+
// a user prompt containing identical text must remain untouched.
|
|
245
|
+
const candidates = event.messages?.filter((message) => message.role === "user"
|
|
246
|
+
&& message.content.some((part) => part.type === "text" && /^Instructions from:/m.test(part.text)));
|
|
247
|
+
if (candidates?.length) {
|
|
248
|
+
const session = await ctx.session.get({ sessionID: event.sessionID });
|
|
249
|
+
if (session.parentID) {
|
|
250
|
+
const history = await ctx.session.context({ sessionID: event.sessionID });
|
|
251
|
+
const attributed = new Map(history.filter((message) => message.type === "synthetic"
|
|
252
|
+
&& message.metadata?.instruction && typeof message.metadata.instruction === "object"
|
|
253
|
+
&& "paths" in message.metadata.instruction && Array.isArray(message.metadata.instruction.paths))
|
|
254
|
+
.map((message) => [message.id, message]));
|
|
255
|
+
for (const message of candidates) {
|
|
256
|
+
const source = message.id ? attributed.get(message.id) : undefined;
|
|
257
|
+
if (!source || source.type !== "synthetic") continue;
|
|
258
|
+
const filtered = { system: [source.text] };
|
|
259
|
+
stripDelegateInstructions(filtered, loadConfig(), session.location?.directory ?? ctx.location.directory);
|
|
260
|
+
const retained = filtered.system.join("");
|
|
261
|
+
if (retained === source.text) continue;
|
|
262
|
+
const index = event.messages.indexOf(message);
|
|
263
|
+
const content = message.content.flatMap((part) => part.type === "text" && part.text === source.text
|
|
264
|
+
? retained ? [{ ...part, text: retained }] : [] : [part]);
|
|
265
|
+
if (content.length) event.messages[index] = Object.assign(Object.create(Object.getPrototypeOf(message)), message, { content });
|
|
266
|
+
else event.messages.splice(index, 1);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}));
|
|
271
|
+
|
|
272
|
+
registrations.push(await ctx.tool.hook("execute.before", async (event) => {
|
|
273
|
+
const args = await scopedArgs(event);
|
|
274
|
+
const original = args && typeof args === "object" ? { ...args } : args;
|
|
275
|
+
const output = { args };
|
|
276
|
+
if (event.tool === "subagent" && args && typeof args.agent === "string" && args.model === undefined) {
|
|
277
|
+
const cfg = loadConfig();
|
|
278
|
+
if (cfg.subagentTiers?.[args.agent]) {
|
|
279
|
+
const actual = await ctx.agent.list();
|
|
280
|
+
const overrides = actual.data.some((agent) => agent.id === args.agent) ? resolveSubagentOverrides({
|
|
281
|
+
subagentTiers: cfg.subagentTiers, tiers: getActiveTiers(cfg),
|
|
282
|
+
existingAgents: Object.fromEntries(actual.data.map((agent) => [agent.id, { mode: agent.mode }])),
|
|
283
|
+
}) : {};
|
|
284
|
+
const override = overrides[args.agent];
|
|
285
|
+
if (override) args.model = `${override.model}${override.variant ? `#${override.variant}` : ""}`;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
await within(hookContext(event), async () => {
|
|
289
|
+
await legacy["tool.execute.before"]?.({ ...event, tool: legacyToolName(event.tool), callID: event.id }, output);
|
|
290
|
+
});
|
|
291
|
+
const verifying = (output as Record<PropertyKey, unknown>)[TASK_VERIFICATION] === true;
|
|
292
|
+
const banner = (output as Record<PropertyKey, unknown>)[DEPTH_BANNER];
|
|
293
|
+
if (typeof banner === "string") {
|
|
294
|
+
depthBanners.delete(event.id);
|
|
295
|
+
depthBanners.set(event.id, banner);
|
|
296
|
+
while (depthBanners.size > 1000) depthBanners.delete(depthBanners.keys().next().value!);
|
|
297
|
+
}
|
|
298
|
+
if (verifying) {
|
|
299
|
+
verifyingCalls.add(event.id);
|
|
300
|
+
while (verifyingCalls.size > 1000) verifyingCalls.delete(verifyingCalls.values().next().value!);
|
|
301
|
+
}
|
|
302
|
+
if (event.tool === "subagent" && typeof output.args?.prompt === "string") {
|
|
303
|
+
const prompt = typeof original?.prompt === "string" ? original.prompt : typeof original?.description === "string" ? original.description : "";
|
|
304
|
+
output.args.prompt = translateAdded(prompt, output.args.prompt);
|
|
305
|
+
}
|
|
306
|
+
event.input = nativeArgs(event.tool, output.args, original, verifying);
|
|
307
|
+
}));
|
|
308
|
+
registrations.push(await ctx.tool.hook("execute.after", async (event) => {
|
|
309
|
+
const banner = depthBanners.get(event.id);
|
|
310
|
+
depthBanners.delete(event.id);
|
|
311
|
+
const verifying = verifyingCalls.delete(event.id);
|
|
312
|
+
if (event.status !== "completed") return;
|
|
313
|
+
const structured = event.result.output;
|
|
314
|
+
// A user can background a foreground subagent while it is running. That
|
|
315
|
+
// acknowledgement is not a final result and must never enter acceptance.
|
|
316
|
+
if (event.tool === "subagent" && structured?.status === "running") {
|
|
317
|
+
const notices = [
|
|
318
|
+
...(verifying ? ["[router] This subagent is still running. Its result has not been verified; automatic acceptance requires a completed foreground return."] : []),
|
|
319
|
+
...(banner === undefined ? [] : [banner]),
|
|
320
|
+
];
|
|
321
|
+
if (!notices.length) return;
|
|
322
|
+
const notice = notices.join("\n\n");
|
|
323
|
+
const content = Array.isArray(event.result.content) ? [...event.result.content]
|
|
324
|
+
: typeof event.result.content === "string" ? [{ type: "text" as const, text: event.result.content }] : [];
|
|
325
|
+
event.result = {
|
|
326
|
+
...event.result,
|
|
327
|
+
content: [...content, { type: "text", text: notice }],
|
|
328
|
+
output: { ...structured, output: `${typeof structured.output === "string" ? structured.output + "\n\n" : ""}${notice}` },
|
|
329
|
+
};
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
const text = event.tool === "subagent" && structured && typeof structured === "object" && typeof structured.output === "string"
|
|
333
|
+
? structured.output : contentText(event.result.content);
|
|
334
|
+
const output = { title: "", output: text, metadata: { ...event.result.metadata } };
|
|
335
|
+
await within(hookContext(event), async () => {
|
|
336
|
+
await legacy["tool.execute.after"]?.({
|
|
337
|
+
...event, tool: legacyToolName(event.tool),
|
|
338
|
+
callID: event.id, args: await scopedArgs(event),
|
|
339
|
+
}, output);
|
|
340
|
+
});
|
|
341
|
+
const changed = output.output !== text;
|
|
342
|
+
if (!changed && banner === undefined) return;
|
|
343
|
+
const routed = changed ? translateAdded(text, output.output) : text;
|
|
344
|
+
const final = banner === undefined ? routed : [routed.trimEnd(), banner].filter(Boolean).join("\n\n");
|
|
345
|
+
const content = Array.isArray(event.result.content) ? [...event.result.content]
|
|
346
|
+
: typeof event.result.content === "string" ? [{ type: "text" as const, text: event.result.content }] : [];
|
|
347
|
+
const childText = text.trimEnd();
|
|
348
|
+
const routedText = routed.trimEnd();
|
|
349
|
+
let visible;
|
|
350
|
+
if (event.tool === "subagent" && structured && typeof structured === "object" && typeof structured.output === "string"
|
|
351
|
+
&& content.some((part) => part.type === "text") && routedText.startsWith(childText)) {
|
|
352
|
+
// The host's visible text owns the session envelope (and resume handle).
|
|
353
|
+
// Footer helpers trim the bare output. Compare trimmed tails before taking
|
|
354
|
+
// only the router's suffix; other rewrites must replace, not repeat, it.
|
|
355
|
+
const suffix = changed ? routedText.slice(childText.length) : "";
|
|
356
|
+
const notices = [suffix, banner].filter((part) => part !== undefined && part !== "").join("\n\n");
|
|
357
|
+
visible = [
|
|
358
|
+
...content,
|
|
359
|
+
...(notices ? [{ type: "text" as const, text: notices }] : []),
|
|
360
|
+
];
|
|
361
|
+
} else {
|
|
362
|
+
visible = [{ type: "text" as const, text: final }, ...content.filter((part) => part.type !== "text")];
|
|
363
|
+
}
|
|
364
|
+
event.result = {
|
|
365
|
+
...event.result,
|
|
366
|
+
content: visible,
|
|
367
|
+
metadata: output.metadata,
|
|
368
|
+
...(typeof structured === "string" ? { output: final }
|
|
369
|
+
: structured && typeof structured === "object" && typeof structured.output === "string"
|
|
370
|
+
? { output: { ...structured, output: final } } : {}),
|
|
371
|
+
};
|
|
372
|
+
}));
|
|
373
|
+
|
|
374
|
+
// V2 events are immutable facts. A completed-text warning is a synthetic
|
|
375
|
+
// transcript entry, instead of mutating an already-persisted text part.
|
|
376
|
+
eventTask = (async () => {
|
|
377
|
+
for await (const event of ctx.event.subscribe({ signal: abort.signal })) {
|
|
378
|
+
if (abort.signal.aborted) break;
|
|
379
|
+
try {
|
|
380
|
+
const data = event.data as Record<string, any>;
|
|
381
|
+
if (event.type === "session.deleted") runtime?.forgetSession?.(data.sessionID);
|
|
382
|
+
if (event.type === "session.text.ended") {
|
|
383
|
+
const output = { text: data.text };
|
|
384
|
+
await legacy["experimental.text.complete"]?.({ sessionID: data.sessionID, messageID: data.assistantMessageID }, output);
|
|
385
|
+
if (typeof data.text === "string" && output.text.startsWith(data.text) && output.text !== data.text && !abort.signal.aborted) {
|
|
386
|
+
await ctx.session.synthetic({ sessionID: data.sessionID, text: output.text.slice(data.text.length).trim(), description: "Model router narration warning", resume: false });
|
|
387
|
+
}
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
const translated = event.type === "session.created"
|
|
391
|
+
? { type: event.type, properties: { info: { ...data, id: data.sessionID } } }
|
|
392
|
+
: event.type === "session.deleted"
|
|
393
|
+
? { type: event.type, properties: { info: { id: data.sessionID } } }
|
|
394
|
+
: ["session.execution.succeeded", "session.execution.failed", "session.execution.interrupted"].includes(event.type)
|
|
395
|
+
? { type: "session.idle", properties: { sessionID: data.sessionID } } : undefined;
|
|
396
|
+
if (translated) await legacy.event?.({ event: translated }, undefined);
|
|
397
|
+
} catch (error) {
|
|
398
|
+
if (!abort.signal.aborted) console.warn("[model-router] OpenCode 2 event handling failed", error);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
})().catch((error: unknown) => {
|
|
402
|
+
if (!abort.signal.aborted) console.warn("[model-router] OpenCode 2 event subscription failed", error);
|
|
403
|
+
});
|
|
404
|
+
return cleanup;
|
|
405
|
+
} catch (error) {
|
|
406
|
+
await cleanup();
|
|
407
|
+
throw error;
|
|
408
|
+
}
|
|
409
|
+
}
|