opencode-model-router 1.14.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.
@@ -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,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
+ }