opencode-model-router 1.15.0 → 2.0.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 +58 -0
- package/README.md +79 -27
- package/package.json +7 -3
- package/server.ts +3 -0
- package/src/compat/child-session.ts +27 -0
- package/src/compat/v2-client.ts +183 -0
- package/src/compat/v2-hooks.ts +376 -0
- package/src/index.ts +64 -41
- package/src/router/config.ts +14 -3
- package/src/router/protocol.ts +1 -0
- package/src/v2.ts +24 -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 +79 -2
- package/tiers.json +20 -17
|
@@ -0,0 +1,376 @@
|
|
|
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 { 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
|
+
let eventTask: Promise<void> | undefined;
|
|
91
|
+
let disposed = false;
|
|
92
|
+
const within = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
|
|
93
|
+
runtime ? runtime.withToolContext(context, operation) : operation();
|
|
94
|
+
const scopedArgs = async (event: { tool: string; input: unknown; sessionID: any }): Promise<any> => {
|
|
95
|
+
const args = taskArgs(event.tool, event.input);
|
|
96
|
+
if (["read", "write", "edit"].includes(event.tool) && typeof args?.filePath === "string" && !isAbsolute(args.filePath)) {
|
|
97
|
+
const session = await ctx.session.get({ sessionID: event.sessionID });
|
|
98
|
+
args.filePath = resolve(session.location?.directory ?? ctx.location.directory, args.filePath);
|
|
99
|
+
}
|
|
100
|
+
return args;
|
|
101
|
+
};
|
|
102
|
+
const hookContext = (event: { sessionID: any; agent: any; messageID: any; id: any }): ToolContext => ({
|
|
103
|
+
...event, signal: abort.signal, progress: async () => {},
|
|
104
|
+
});
|
|
105
|
+
const cleanup = async () => {
|
|
106
|
+
if (disposed) return;
|
|
107
|
+
disposed = true;
|
|
108
|
+
abort.abort();
|
|
109
|
+
await runtime?.dispose?.();
|
|
110
|
+
await eventTask;
|
|
111
|
+
await Promise.allSettled(registrations.map((registration) => registration.dispose()));
|
|
112
|
+
await hooks.dispose?.();
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
try {
|
|
116
|
+
const agents = await ctx.agent.list();
|
|
117
|
+
const config: LegacyConfig = { agent: {}, command: {} };
|
|
118
|
+
for (const agent of agents.data) config.agent[agent.id] = {
|
|
119
|
+
mode: agent.mode,
|
|
120
|
+
model: agent.model && `${agent.model.providerID}/${agent.model.id}`,
|
|
121
|
+
variant: agent.model?.variant,
|
|
122
|
+
};
|
|
123
|
+
const originals = new Map(Object.entries(config.agent).map(([id, agent]) => [id, JSON.stringify(agent)]));
|
|
124
|
+
await hooks.config?.(config);
|
|
125
|
+
const agentOptions = new Map<string, Record<string, unknown>>();
|
|
126
|
+
for (const [name, definition] of Object.entries(config.agent)) {
|
|
127
|
+
if (originals.get(name) === JSON.stringify(definition) || !definition.options) continue;
|
|
128
|
+
const { reasoning_effort, reasoning_summary, budget_tokens, ...options } = definition.options;
|
|
129
|
+
agentOptions.set(name, {
|
|
130
|
+
...options,
|
|
131
|
+
...(reasoning_effort === undefined ? {} : { reasoningEffort: reasoning_effort }),
|
|
132
|
+
...(reasoning_summary === undefined ? {} : { reasoningSummary: reasoning_summary }),
|
|
133
|
+
...(budget_tokens === undefined ? {} : { thinking: { type: "enabled", budgetTokens: budget_tokens } }),
|
|
134
|
+
});
|
|
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
|
+
if (verifying) {
|
|
293
|
+
verifyingCalls.add(event.id);
|
|
294
|
+
while (verifyingCalls.size > 1000) verifyingCalls.delete(verifyingCalls.values().next().value!);
|
|
295
|
+
}
|
|
296
|
+
if (event.tool === "subagent" && typeof output.args?.prompt === "string") {
|
|
297
|
+
const prompt = typeof original?.prompt === "string" ? original.prompt : typeof original?.description === "string" ? original.description : "";
|
|
298
|
+
output.args.prompt = translateAdded(prompt, output.args.prompt);
|
|
299
|
+
}
|
|
300
|
+
event.input = nativeArgs(event.tool, output.args, original, verifying);
|
|
301
|
+
}));
|
|
302
|
+
registrations.push(await ctx.tool.hook("execute.after", async (event) => {
|
|
303
|
+
const verifying = verifyingCalls.delete(event.id);
|
|
304
|
+
if (event.status !== "completed") return;
|
|
305
|
+
const structured = event.result.output;
|
|
306
|
+
// A user can background a foreground subagent while it is running. That
|
|
307
|
+
// acknowledgement is not a final result and must never enter acceptance.
|
|
308
|
+
if (event.tool === "subagent" && structured?.status === "running") {
|
|
309
|
+
if (!verifying) return;
|
|
310
|
+
const notice = "[router] This subagent is still running. Its result has not been verified; automatic acceptance requires a completed foreground return.";
|
|
311
|
+
const content = Array.isArray(event.result.content) ? [...event.result.content]
|
|
312
|
+
: typeof event.result.content === "string" ? [{ type: "text" as const, text: event.result.content }] : [];
|
|
313
|
+
event.result = {
|
|
314
|
+
...event.result,
|
|
315
|
+
content: [...content, { type: "text", text: notice }],
|
|
316
|
+
output: { ...structured, output: `${typeof structured.output === "string" ? structured.output + "\n\n" : ""}${notice}` },
|
|
317
|
+
};
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
const text = event.tool === "subagent" && structured && typeof structured === "object" && typeof structured.output === "string"
|
|
321
|
+
? structured.output : contentText(event.result.content);
|
|
322
|
+
const output = { title: "", output: text, metadata: { ...event.result.metadata } };
|
|
323
|
+
await within(hookContext(event), async () => {
|
|
324
|
+
await legacy["tool.execute.after"]?.({
|
|
325
|
+
...event, tool: legacyToolName(event.tool),
|
|
326
|
+
callID: event.id, args: await scopedArgs(event),
|
|
327
|
+
}, output);
|
|
328
|
+
});
|
|
329
|
+
if (output.output === text) return;
|
|
330
|
+
const content = Array.isArray(event.result.content) ? event.result.content.filter((part) => part.type !== "text") : [];
|
|
331
|
+
event.result = {
|
|
332
|
+
...event.result,
|
|
333
|
+
content: [{ type: "text", text: translateAdded(text, output.output) }, ...content],
|
|
334
|
+
metadata: output.metadata,
|
|
335
|
+
...(typeof structured === "string" ? { output: translateAdded(text, output.output) }
|
|
336
|
+
: structured && typeof structured === "object" && typeof structured.output === "string"
|
|
337
|
+
? { output: { ...structured, output: translateAdded(text, output.output) } } : {}),
|
|
338
|
+
};
|
|
339
|
+
}));
|
|
340
|
+
|
|
341
|
+
// V2 events are immutable facts. A completed-text warning is a synthetic
|
|
342
|
+
// transcript entry, instead of mutating an already-persisted text part.
|
|
343
|
+
eventTask = (async () => {
|
|
344
|
+
for await (const event of ctx.event.subscribe({ signal: abort.signal })) {
|
|
345
|
+
if (abort.signal.aborted) break;
|
|
346
|
+
try {
|
|
347
|
+
const data = event.data as Record<string, any>;
|
|
348
|
+
if (event.type === "session.deleted") runtime?.forgetSession?.(data.sessionID);
|
|
349
|
+
if (event.type === "session.text.ended") {
|
|
350
|
+
const output = { text: data.text };
|
|
351
|
+
await legacy["experimental.text.complete"]?.({ sessionID: data.sessionID, messageID: data.assistantMessageID }, output);
|
|
352
|
+
if (typeof data.text === "string" && output.text.startsWith(data.text) && output.text !== data.text && !abort.signal.aborted) {
|
|
353
|
+
await ctx.session.synthetic({ sessionID: data.sessionID, text: output.text.slice(data.text.length).trim(), description: "Model router narration warning", resume: false });
|
|
354
|
+
}
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
const translated = event.type === "session.created"
|
|
358
|
+
? { type: event.type, properties: { info: { ...data, id: data.sessionID } } }
|
|
359
|
+
: event.type === "session.deleted"
|
|
360
|
+
? { type: event.type, properties: { info: { id: data.sessionID } } }
|
|
361
|
+
: ["session.execution.succeeded", "session.execution.failed", "session.execution.interrupted"].includes(event.type)
|
|
362
|
+
? { type: "session.idle", properties: { sessionID: data.sessionID } } : undefined;
|
|
363
|
+
if (translated) await legacy.event?.({ event: translated }, undefined);
|
|
364
|
+
} catch (error) {
|
|
365
|
+
if (!abort.signal.aborted) console.warn("[model-router] OpenCode 2 event handling failed", error);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
})().catch((error: unknown) => {
|
|
369
|
+
if (!abort.signal.aborted) console.warn("[model-router] OpenCode 2 event subscription failed", error);
|
|
370
|
+
});
|
|
371
|
+
return cleanup;
|
|
372
|
+
} catch (error) {
|
|
373
|
+
await cleanup();
|
|
374
|
+
throw error;
|
|
375
|
+
}
|
|
376
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import type { Plugin
|
|
1
|
+
import type { Plugin } from "@opencode-ai/plugin";
|
|
2
|
+
import type { RouterPluginInput } from "./compat/child-session";
|
|
3
|
+
import { TASK_VERIFICATION } from "./compat/child-session";
|
|
2
4
|
|
|
3
5
|
// Imports for internal use within this module
|
|
4
6
|
import {
|
|
@@ -238,7 +240,7 @@ function warnSessionLookupFailedOnce(): void {
|
|
|
238
240
|
const SESSION_ROOT_MEMO_MAX = 500;
|
|
239
241
|
const SESSION_LOOKUP_RETRY_MS = 30_000;
|
|
240
242
|
|
|
241
|
-
const ModelRouterPlugin: Plugin = async (ctx:
|
|
243
|
+
const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
242
244
|
let cfg = loadConfig();
|
|
243
245
|
const activeTiers = getActiveTiers(cfg);
|
|
244
246
|
|
|
@@ -369,6 +371,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
369
371
|
background,
|
|
370
372
|
} = createVerificationWiring({
|
|
371
373
|
client: ctx.client,
|
|
374
|
+
childRunner: ctx.routerChildRunner,
|
|
372
375
|
directory: ctx.directory,
|
|
373
376
|
getConfig: () => cfg,
|
|
374
377
|
logger,
|
|
@@ -558,6 +561,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
558
561
|
prompt: args.task,
|
|
559
562
|
acceptance: args.acceptance,
|
|
560
563
|
});
|
|
564
|
+
const effectiveCwd = typeof args.cwd === "string" && args.cwd.trim() ? args.cwd : dod.cwd;
|
|
561
565
|
|
|
562
566
|
const policy = buildEscalatePolicy(activeCfg);
|
|
563
567
|
let state = newLadderState(initialTier, policy);
|
|
@@ -601,27 +605,33 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
601
605
|
? `${scrubText(forcingNote)}\n\n${args.task}`
|
|
602
606
|
: args.task;
|
|
603
607
|
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
608
|
+
let producerSid: string | undefined;
|
|
609
|
+
const registerProducer = async (sid: string) => {
|
|
610
|
+
producerSid = sid;
|
|
611
|
+
producerSessions.push(sid);
|
|
612
|
+
// Keep the ORIGINAL dispatch reference across retries/escalations:
|
|
613
|
+
// recapturing after a failed attempt would excuse its regression.
|
|
614
|
+
if (!baselineID) {
|
|
615
|
+
baselineID = sid;
|
|
616
|
+
// Capture before the child gets its first prompt, on either API.
|
|
617
|
+
dispatchStart = await startDispatch(changedFileStore, baselineID, effectiveCwd, dod, args.task, false);
|
|
618
|
+
}
|
|
619
|
+
// Compose with Layer 1: guard the plugin-created producer session.
|
|
620
|
+
try {
|
|
621
|
+
sessionStore.registerProducerSession(sid, tier, activeCfg);
|
|
622
|
+
} catch {
|
|
623
|
+
// non-fatal
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
if (!ctx.routerChildRunner) {
|
|
627
|
+
const created: any = await ctx.client.session.create({
|
|
628
|
+
body: {
|
|
629
|
+
...(toolCtx?.sessionID ? { parentID: toolCtx.sessionID } : {}),
|
|
630
|
+
},
|
|
631
|
+
});
|
|
632
|
+
const sid: string | undefined = created?.data?.id;
|
|
633
|
+
if (!sid) return null;
|
|
634
|
+
await registerProducer(sid);
|
|
625
635
|
}
|
|
626
636
|
|
|
627
637
|
const model = tierModel(activeCfg, tier) ?? undefined;
|
|
@@ -639,10 +649,18 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
639
649
|
// the same failed-attempt path as any other producer error — it
|
|
640
650
|
// is never an empty artefact that a lenient DoD could pass.
|
|
641
651
|
let producerError: string | null = null;
|
|
652
|
+
const childAbort = ctx.routerChildRunner ? new AbortController() : undefined;
|
|
642
653
|
try {
|
|
643
|
-
const res: any = await withTimeout(
|
|
644
|
-
ctx.
|
|
645
|
-
|
|
654
|
+
const res: any = await withTimeout<unknown>(
|
|
655
|
+
ctx.routerChildRunner ? ctx.routerChildRunner.run({
|
|
656
|
+
parentSessionID: toolCtx?.sessionID,
|
|
657
|
+
agent: tier,
|
|
658
|
+
model: model ? { ...model, variant: getActiveTiers(activeCfg)[tier]?.variant } : undefined,
|
|
659
|
+
prompt: taskText,
|
|
660
|
+
signal: childAbort!.signal,
|
|
661
|
+
onCreated: registerProducer,
|
|
662
|
+
}) : ctx.client.session.prompt({
|
|
663
|
+
path: { id: producerSid! },
|
|
646
664
|
body: {
|
|
647
665
|
...(model ? { model } : {}),
|
|
648
666
|
...(tier ? { agent: tier } : {}),
|
|
@@ -655,12 +673,15 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
655
673
|
),
|
|
656
674
|
"delegate producer prompt",
|
|
657
675
|
);
|
|
658
|
-
producerText = extractAssistantText(res);
|
|
676
|
+
producerText = ctx.routerChildRunner ? res.text : extractAssistantText(res);
|
|
659
677
|
} catch (error) {
|
|
660
678
|
producerError =
|
|
661
679
|
error instanceof Error ? error.message : String(error);
|
|
662
680
|
producerText = "";
|
|
681
|
+
} finally {
|
|
682
|
+
childAbort?.abort();
|
|
663
683
|
}
|
|
684
|
+
if (!producerSid || !baselineID) return null;
|
|
664
685
|
// pending.ts R11: the producer's changes landed by now.
|
|
665
686
|
const returnedAt = Date.now();
|
|
666
687
|
|
|
@@ -675,7 +696,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
675
696
|
producerSessionID: producerSid,
|
|
676
697
|
producerTier: tier,
|
|
677
698
|
description: args.task,
|
|
678
|
-
cwd:
|
|
699
|
+
cwd: effectiveCwd,
|
|
679
700
|
dod,
|
|
680
701
|
dispatchedAt: dispatchStart.dispatchedAt,
|
|
681
702
|
})
|
|
@@ -714,7 +735,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
714
735
|
const gateDeadline = createDeadline(gateBudgetMs);
|
|
715
736
|
let verification;
|
|
716
737
|
try {
|
|
717
|
-
verification = await prepareVerification(changedFileStore, baselineID, producerSid,
|
|
738
|
+
verification = await prepareVerification(changedFileStore, baselineID, producerSid, effectiveCwd, gateDeadline);
|
|
718
739
|
} catch (error) {
|
|
719
740
|
gateDeadline.dispose();
|
|
720
741
|
throw error;
|
|
@@ -751,7 +772,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
751
772
|
dod,
|
|
752
773
|
trivial: false,
|
|
753
774
|
mode: "modeA",
|
|
754
|
-
...(
|
|
775
|
+
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
|
755
776
|
},
|
|
756
777
|
artefact,
|
|
757
778
|
gateDeps,
|
|
@@ -960,7 +981,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
960
981
|
try {
|
|
961
982
|
if (input?.sessionID && graderSessions.has(input.sessionID)) {
|
|
962
983
|
const graderTemperature = cfg.enforcement?.verify?.graderTemperature;
|
|
963
|
-
if (graderTemperature
|
|
984
|
+
if (graderTemperature === null) {
|
|
985
|
+
delete output.temperature;
|
|
986
|
+
} else if (graderTemperature !== undefined && input?.model?.capabilities?.temperature !== false) {
|
|
964
987
|
output.temperature = graderTemperature;
|
|
965
988
|
}
|
|
966
989
|
}
|
|
@@ -1082,14 +1105,17 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1082
1105
|
if (input?.tool === "task" && typeof input.callID === "string" && typeof input.sessionID === "string") {
|
|
1083
1106
|
const mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
|
|
1084
1107
|
if (shouldVerifyTask("task", mode, cfg.enforcement?.verify?.require)) {
|
|
1108
|
+
if (output && typeof output === "object") output[TASK_VERIFICATION] = true;
|
|
1085
1109
|
const prompt = typeof output?.args?.prompt === "string" ? output.args.prompt : undefined;
|
|
1086
1110
|
const description = typeof output?.args?.description === "string" ? output.args.description : undefined;
|
|
1111
|
+
const dod = buildDelegationDoD({ prompt, description });
|
|
1112
|
+
const effectiveCwd = typeof output?.args?.cwd === "string" && output.args.cwd.trim() ? output.args.cwd : dod.cwd;
|
|
1087
1113
|
// 2.4.2b: the directives come from the orchestrator's own prompt, read here before the
|
|
1088
1114
|
// dispatch header or any repair touches it, and are kept for the after hook. The capture
|
|
1089
1115
|
// is awaited for at most VERIFY_WAIT (section 1.5-14) and continues in the background.
|
|
1090
1116
|
await startDispatch(changedFileStore, `task:${input.sessionID}:${input.callID}`,
|
|
1091
|
-
|
|
1092
|
-
|
|
1117
|
+
effectiveCwd,
|
|
1118
|
+
dod,
|
|
1093
1119
|
dispatchDirectiveText(prompt, description),
|
|
1094
1120
|
true);
|
|
1095
1121
|
}
|
|
@@ -1277,6 +1303,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1277
1303
|
prompt: input?.args?.prompt,
|
|
1278
1304
|
description: input?.args?.description,
|
|
1279
1305
|
});
|
|
1306
|
+
const effectiveCwd = typeof input?.args?.cwd === "string" && input.args.cwd.trim() ? input.args.cwd : dod.cwd;
|
|
1280
1307
|
const dispatchID = `task:${input.sessionID}:${input.callID}`;
|
|
1281
1308
|
const orchestratorSessionID = typeof input.sessionID === "string" ? input.sessionID : "";
|
|
1282
1309
|
const taskPrompt = typeof input?.args?.prompt === "string" ? input.args.prompt : undefined;
|
|
@@ -1297,7 +1324,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1297
1324
|
producerSessionID: childSessionID ?? "",
|
|
1298
1325
|
producerTier,
|
|
1299
1326
|
description: taskDescription?.trim() ? taskDescription : (taskPrompt ?? ""),
|
|
1300
|
-
cwd:
|
|
1327
|
+
cwd: effectiveCwd,
|
|
1301
1328
|
dod,
|
|
1302
1329
|
dispatchedAt: start.dispatchedAt,
|
|
1303
1330
|
});
|
|
@@ -1318,7 +1345,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1318
1345
|
const gateDeadline = createDeadline(gateBudgetMs);
|
|
1319
1346
|
let verification;
|
|
1320
1347
|
try {
|
|
1321
|
-
verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "",
|
|
1348
|
+
verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", effectiveCwd, gateDeadline);
|
|
1322
1349
|
} catch (error) {
|
|
1323
1350
|
gateDeadline.dispose();
|
|
1324
1351
|
throw error;
|
|
@@ -1362,12 +1389,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1362
1389
|
dod,
|
|
1363
1390
|
trivial,
|
|
1364
1391
|
mode: "modeA",
|
|
1365
|
-
//
|
|
1366
|
-
|
|
1367
|
-
// delegate tool's does.
|
|
1368
|
-
...(typeof input?.args?.cwd === "string" && input.args.cwd
|
|
1369
|
-
? { cwd: input.args.cwd }
|
|
1370
|
-
: {}),
|
|
1392
|
+
// Native task has no cwd argument; the acceptance block can supply it.
|
|
1393
|
+
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
|
1371
1394
|
},
|
|
1372
1395
|
artefact,
|
|
1373
1396
|
gateDeps,
|
package/src/router/config.ts
CHANGED
|
@@ -124,7 +124,7 @@ export interface EnforcementConfig {
|
|
|
124
124
|
envGate?: string;
|
|
125
125
|
perTier?: Record<string, "off" | "advisory" | "enforced">;
|
|
126
126
|
guard?: { readDraftCap?: number; sameOpRetryCap?: number; blockSelfScript?: boolean; deliverableFirst?: boolean; budget?: number; blockScriptWrites?: boolean };
|
|
127
|
-
verify?: { require?: "never" | "whenDoDPresent" | "always"; requireExplicitDoD?: boolean; preferDeterministic?: boolean; graderPolicy?: "atLeastProducerTier"; graderTemperature?: number; minGraderTier?: string | null;
|
|
127
|
+
verify?: { require?: "never" | "whenDoDPresent" | "always"; requireExplicitDoD?: boolean; preferDeterministic?: boolean; graderPolicy?: "atLeastProducerTier"; graderTemperature?: number | null; graderTemperatureModels?: string[]; minGraderTier?: string | null;
|
|
128
128
|
/** Ceiling for one producer `session.prompt` turn, in ms. Default 600000. */
|
|
129
129
|
delegateTimeoutMs?: number;
|
|
130
130
|
/** Reject unavailable verification. Default false; never escalates it. */
|
|
@@ -769,17 +769,28 @@ function validateEnforcement(obj: Record<string, unknown>): void {
|
|
|
769
769
|
"tiers.json: enforcement.verify.minGraderTier must be a string or null",
|
|
770
770
|
);
|
|
771
771
|
}
|
|
772
|
-
if (verify.graderTemperature !== undefined) {
|
|
772
|
+
if (verify.graderTemperature !== undefined && verify.graderTemperature !== null) {
|
|
773
773
|
if (
|
|
774
774
|
typeof verify.graderTemperature !== "number" ||
|
|
775
775
|
!Number.isFinite(verify.graderTemperature) ||
|
|
776
776
|
verify.graderTemperature < 0
|
|
777
777
|
) {
|
|
778
778
|
throw new Error(
|
|
779
|
-
"tiers.json: enforcement.verify.graderTemperature must be a number >= 0",
|
|
779
|
+
"tiers.json: enforcement.verify.graderTemperature must be a number >= 0 or null",
|
|
780
780
|
);
|
|
781
781
|
}
|
|
782
782
|
}
|
|
783
|
+
if (verify.graderTemperatureModels !== undefined) {
|
|
784
|
+
if (!Array.isArray(verify.graderTemperatureModels)) {
|
|
785
|
+
throw new Error("tiers.json: enforcement.verify.graderTemperatureModels must be an array");
|
|
786
|
+
}
|
|
787
|
+
for (const entry of verify.graderTemperatureModels) {
|
|
788
|
+
const slash = typeof entry === "string" ? entry.indexOf("/") : -1;
|
|
789
|
+
if (typeof entry !== "string" || slash < 1 || !entry.slice(0, slash).trim() || !entry.slice(slash + 1).trim()) {
|
|
790
|
+
throw new Error("tiers.json: enforcement.verify.graderTemperatureModels entries must be non-empty provider/model strings");
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
783
794
|
// Time-box ceilings. `>= 1` and not `>= 0`: a 0 or negative budget is
|
|
784
795
|
// almost always meant as "no timeout", and silently reading it as an
|
|
785
796
|
// immediately-expiring one would make every delegation fail. Reject it
|
package/src/router/protocol.ts
CHANGED
|
@@ -294,6 +294,7 @@ export function buildDoDProtocolSection(cfg: RouterConfig): string {
|
|
|
294
294
|
"[/acceptance]",
|
|
295
295
|
"",
|
|
296
296
|
"- check kinds: testsPass | buildPasses | lintClean | fileExists path=\u2026 | schemaMatch path=\u2026 schema=\u2026 | run command=\"\u2026\" expect=\u2026",
|
|
297
|
+
"- cwd: <dir> in the block when the producer works outside this directory (e.g. a git worktree); checks, tests and the grader run there.",
|
|
297
298
|
"- testsPass runs only the tests affected by the producer's changes (the full suite is CI's job); prefer it over a hand-written full-suite run command. A failure that also fails at the dispatch-time reference is excused as pre-existing.",
|
|
298
299
|
"- Per dispatch you may add `VERIFY:<mode>` as one token, <mode> being `required` or `deferred` (default deferred: returns at once with a handle and a risk level) and `VERIFY_WAIT:<n>s`. Pick required when later work depends on this delegation, or call router_verify before building on a medium/high-risk deferred result; unverified delegations stay listed in the prompt until verified or expired (1 h, or a restart); absent from the list does not mean verified.",
|
|
299
300
|
"- Command allowlist (first-token basename): npm, npx, pnpm, yarn, bun, node, tsc, tsx, vitest, jest, eslint, prettier, pytest (plus exactly `uv run pytest`). No shell chaining, redirection, substitution or newlines; interpreter inline-eval/print flags are forbidden. buildPasses probes a build script, then root tsconfig.json (npx tsc --noEmit). Unavailable checks produce acceptance caveats, not producer escalation; strictUnverifiable restores rejection.",
|