opencode-model-router 1.11.0 → 1.12.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 +145 -0
- package/README.md +10 -8
- package/package.json +1 -1
- package/src/escalate/ladder.ts +6 -0
- package/src/guard/fingerprint.ts +11 -2
- package/src/guard/guards.ts +9 -0
- package/src/index.ts +309 -38
- package/src/router/config.ts +61 -1
- package/src/router/dispatch-header.ts +36 -0
- package/src/router/false-refusal.ts +43 -0
- package/src/router/instructions.ts +65 -0
- package/src/router/prompts.ts +23 -6
- package/src/router/protocol.ts +2 -1
- package/src/router/sessions.ts +27 -2
- package/src/telemetry/trajectory.ts +10 -0
- package/src/verify/baseline.ts +78 -0
- package/src/verify/checker.ts +6 -0
- package/src/verify/deterministic.ts +45 -5
- package/src/verify/dispatch.ts +159 -8
- package/src/verify/gate.ts +31 -9
- package/src/verify/timeout.ts +8 -0
- package/src/verify/tree.ts +52 -0
- package/src/verify/types.ts +10 -0
- package/src/verify/wiring.ts +52 -15
- package/tiers.json +26 -25
package/src/index.ts
CHANGED
|
@@ -12,7 +12,10 @@ import {
|
|
|
12
12
|
} from "./router/config";
|
|
13
13
|
import type { RouterConfig, TierConfig, Preset, ModeConfig } from "./router/config";
|
|
14
14
|
import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
|
|
15
|
-
import { selectTierPrompt } from "./router/prompts";
|
|
15
|
+
import { selectTierPrompt, TOOL_AUTHORITY_CLAUSE } from "./router/prompts";
|
|
16
|
+
import { stripDelegateInstructions } from "./router/instructions";
|
|
17
|
+
import { buildDispatchHeader } from "./router/dispatch-header";
|
|
18
|
+
import { detectFalseRefusal, parseTaskResult as parseRefusalTaskResult } from "./router/false-refusal";
|
|
16
19
|
import {
|
|
17
20
|
buildTiersOutput,
|
|
18
21
|
buildPresetList,
|
|
@@ -72,7 +75,7 @@ import { exec as nodeExec } from "node:child_process";
|
|
|
72
75
|
import { access, readFile as fsReadFile } from "node:fs/promises";
|
|
73
76
|
import { tool } from "@opencode-ai/plugin";
|
|
74
77
|
import { scrubText } from "./guard/scrub";
|
|
75
|
-
import { accept } from "./verify/gate";
|
|
78
|
+
import { accept, unverifiableGateResult } from "./verify/gate";
|
|
76
79
|
import { createVerificationWiring, extractAssistantText } from "./verify/wiring";
|
|
77
80
|
import {
|
|
78
81
|
DEFAULT_DELEGATE_PROMPT_TIMEOUT_MS,
|
|
@@ -208,12 +211,105 @@ function buildPresetOutput(cfg: RouterConfig, args: string): string {
|
|
|
208
211
|
return buildUnknownPreset(cfg, requestedPreset);
|
|
209
212
|
}
|
|
210
213
|
|
|
214
|
+
// Fail-closed skips in system.transform are silent by design, but a transform
|
|
215
|
+
// that never carries a sessionID would silently disable routing for the whole
|
|
216
|
+
// session. Surface it once rather than never.
|
|
217
|
+
let warnedMissingTransformSession = false;
|
|
218
|
+
function warnMissingTransformSessionOnce(): void {
|
|
219
|
+
if (warnedMissingTransformSession) return;
|
|
220
|
+
warnedMissingTransformSession = true;
|
|
221
|
+
console.warn(
|
|
222
|
+
"[model-router] chat.system.transform received no sessionID; skipping delegation-protocol injection (fail-closed)",
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
let warnedSessionLookupFailed = false;
|
|
227
|
+
function warnSessionLookupFailedOnce(): void {
|
|
228
|
+
if (warnedSessionLookupFailed) return;
|
|
229
|
+
warnedSessionLookupFailed = true;
|
|
230
|
+
console.warn(
|
|
231
|
+
"[model-router] session lookup failed while classifying a chat.system.transform session; assuming top-level orchestrator",
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const SESSION_ROOT_MEMO_MAX = 500;
|
|
236
|
+
const SESSION_LOOKUP_RETRY_MS = 30_000;
|
|
237
|
+
|
|
211
238
|
const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
212
239
|
let cfg = loadConfig();
|
|
213
240
|
const activeTiers = getActiveTiers(cfg);
|
|
214
241
|
|
|
215
242
|
// Per-plugin-instance session store: owns subagentSessionIDs and subagentCapState.
|
|
216
243
|
const sessionStore = createSessionStore();
|
|
244
|
+
let systemDebugLogged = false;
|
|
245
|
+
let dispatchDebugLogged = false;
|
|
246
|
+
|
|
247
|
+
// Authoritative orchestrator-vs-child classification memo, keyed by sessionID.
|
|
248
|
+
// true = proven top-level (no parentID) -> inject the delegation protocol
|
|
249
|
+
// false = proven child -> never inject
|
|
250
|
+
// absent = not yet resolved
|
|
251
|
+
//
|
|
252
|
+
// Exists because session.created is an EVENT: nothing guarantees the plugin
|
|
253
|
+
// has processed it before the child's first system.transform runs. Tier-named
|
|
254
|
+
// agents are also marked synchronously from chat.message, but `general`,
|
|
255
|
+
// `explore`, markdown-defined agents and everything mapped through
|
|
256
|
+
// `subagentTiers` (which can never be tier-named by construction) have no
|
|
257
|
+
// synchronous path at all. One session.get per session closes that race
|
|
258
|
+
// without depending on event ordering.
|
|
259
|
+
const sessionRootMemo = new Map<string, boolean>();
|
|
260
|
+
/** Recent lookup failures throttle retries without permanently memoising root. */
|
|
261
|
+
const sessionLookupFailedAt = new Map<string, number>();
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Resolve whether a session is the top-level orchestrator, authoritatively.
|
|
265
|
+
*
|
|
266
|
+
* Returns true only when the backend confirms the session has no parentID.
|
|
267
|
+
* Returns false when it confirms a parentID (and marks the session as a child
|
|
268
|
+
* so the synchronous path catches it next time).
|
|
269
|
+
*
|
|
270
|
+
* On lookup failure it returns true — deliberately NOT fail-closed. A transient
|
|
271
|
+
* backend error must not silently strip the orchestrator of its routing rules
|
|
272
|
+
* for the rest of the session; the event path and the chat.message path both
|
|
273
|
+
* still cover the common cases, so the exposure is a rare, transient re-run of
|
|
274
|
+
* the old behaviour rather than a permanent loss of function.
|
|
275
|
+
*/
|
|
276
|
+
const resolveIsRootSession = async (sessionID: string): Promise<boolean> => {
|
|
277
|
+
const memo = sessionRootMemo.get(sessionID);
|
|
278
|
+
if (memo !== undefined) {
|
|
279
|
+
if (!memo) sessionStore.markChildSession(sessionID);
|
|
280
|
+
return memo;
|
|
281
|
+
}
|
|
282
|
+
const failedAt = sessionLookupFailedAt.get(sessionID);
|
|
283
|
+
if (failedAt !== undefined && Date.now() - failedAt < SESSION_LOOKUP_RETRY_MS) {
|
|
284
|
+
return true;
|
|
285
|
+
}
|
|
286
|
+
try {
|
|
287
|
+
const res = await ctx.client.session.get({ path: { id: sessionID } });
|
|
288
|
+
if (!res || (res as { error?: unknown }).error || !res.data) {
|
|
289
|
+
throw new Error("session.get returned no session data");
|
|
290
|
+
}
|
|
291
|
+
sessionLookupFailedAt.delete(sessionID);
|
|
292
|
+
const parentID = res?.data?.parentID;
|
|
293
|
+
const isRoot = !(typeof parentID === "string" && parentID !== "");
|
|
294
|
+
sessionRootMemo.set(sessionID, isRoot);
|
|
295
|
+
while (sessionRootMemo.size > SESSION_ROOT_MEMO_MAX) {
|
|
296
|
+
const oldest = sessionRootMemo.keys().next().value;
|
|
297
|
+
if (oldest === undefined) break;
|
|
298
|
+
sessionRootMemo.delete(oldest);
|
|
299
|
+
}
|
|
300
|
+
if (!isRoot) sessionStore.markChildSession(sessionID);
|
|
301
|
+
return isRoot;
|
|
302
|
+
} catch {
|
|
303
|
+
sessionLookupFailedAt.set(sessionID, Date.now());
|
|
304
|
+
while (sessionLookupFailedAt.size > SESSION_ROOT_MEMO_MAX) {
|
|
305
|
+
const oldest = sessionLookupFailedAt.keys().next().value;
|
|
306
|
+
if (oldest === undefined) break;
|
|
307
|
+
sessionLookupFailedAt.delete(oldest);
|
|
308
|
+
}
|
|
309
|
+
warnSessionLookupFailedOnce();
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
312
|
+
};
|
|
217
313
|
|
|
218
314
|
// Per-plugin-instance trajectory store (Phase 0.3 scaffolding — RECORD-ONLY).
|
|
219
315
|
// Observes subagent tool activity to build a per-session scorecard. It emits
|
|
@@ -242,7 +338,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
242
338
|
// Layer-2's impure corner: exec, fs, and the opencode client, built once and
|
|
243
339
|
// read back through getConfig so a reloaded cfg (from /preset, /budget or
|
|
244
340
|
// /router enforce) applies to graded work too.
|
|
245
|
-
const { graderSessions, dispatchGrader, buildGateDeps, disposeChildSession } =
|
|
341
|
+
const { graderSessions, dispatchGrader, buildGateDeps, disposeChildSession, beginVerification, prepareVerification } =
|
|
246
342
|
createVerificationWiring({
|
|
247
343
|
client: ctx.client,
|
|
248
344
|
directory: ctx.directory,
|
|
@@ -371,6 +467,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
371
467
|
// here (not inside the try) so the finally below can dispose any that an
|
|
372
468
|
// early return or a throw skipped — otherwise each retry leaks another.
|
|
373
469
|
const producerSessions: string[] = [];
|
|
470
|
+
let baselineID: string | undefined;
|
|
374
471
|
try {
|
|
375
472
|
let activeCfg = cfg;
|
|
376
473
|
try {
|
|
@@ -432,6 +529,12 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
432
529
|
const producerSid: string | undefined = created?.data?.id;
|
|
433
530
|
if (!producerSid) return null;
|
|
434
531
|
producerSessions.push(producerSid);
|
|
532
|
+
// Keep the ORIGINAL dispatch reference across retries/escalations:
|
|
533
|
+
// recapturing after a failed attempt would excuse its regression.
|
|
534
|
+
if (!baselineID) {
|
|
535
|
+
baselineID = producerSid;
|
|
536
|
+
beginVerification(changedFileStore, baselineID, args.cwd, dod);
|
|
537
|
+
}
|
|
435
538
|
// Compose with Layer 1: guard the plugin-created producer session.
|
|
436
539
|
try {
|
|
437
540
|
sessionStore.registerProducerSession(producerSid, tier, activeCfg);
|
|
@@ -477,8 +580,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
477
580
|
producerText = "";
|
|
478
581
|
}
|
|
479
582
|
|
|
583
|
+
const verification = await prepareVerification(changedFileStore, baselineID, producerSid, args.cwd);
|
|
480
584
|
const artefact = {
|
|
481
|
-
changedFiles:
|
|
585
|
+
changedFiles: verification.changedFiles,
|
|
586
|
+
changeBaseline: verification.changeBaseline,
|
|
482
587
|
finalReturnText: producerText,
|
|
483
588
|
declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
|
|
484
589
|
producerSessionID: producerSid,
|
|
@@ -491,6 +596,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
491
596
|
);
|
|
492
597
|
// Grader sessions opened by THIS accept() call, and only those.
|
|
493
598
|
const gateGraderSessions = new Set<string>();
|
|
599
|
+
const completedFailures: string[] = [];
|
|
600
|
+
const gateDeps = buildGateDeps(toolCtx?.sessionID, gateGraderSessions);
|
|
601
|
+
gateDeps.deterministic.testBaseline = verification.testBaseline;
|
|
602
|
+
gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
|
|
494
603
|
let gateRes;
|
|
495
604
|
try {
|
|
496
605
|
gateRes = producerError
|
|
@@ -512,15 +621,14 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
512
621
|
...(args.cwd ? { cwd: args.cwd } : {}),
|
|
513
622
|
},
|
|
514
623
|
artefact,
|
|
515
|
-
|
|
624
|
+
gateDeps,
|
|
516
625
|
),
|
|
517
626
|
gateBudgetMs,
|
|
518
627
|
"verification gate",
|
|
519
628
|
);
|
|
520
629
|
} catch (error) {
|
|
521
|
-
//
|
|
522
|
-
//
|
|
523
|
-
// pass. Abort any grader still in flight so the ceiling is a
|
|
630
|
+
// Budget exhaustion is unavailable verification, not producer
|
|
631
|
+
// failure. Abort any grader still in flight so the ceiling is a
|
|
524
632
|
// real cancellation and not just a stopped wait.
|
|
525
633
|
//
|
|
526
634
|
// Scoped to THIS gate invocation's graders. The wiring-global
|
|
@@ -538,25 +646,21 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
538
646
|
}
|
|
539
647
|
}
|
|
540
648
|
}
|
|
541
|
-
gateRes =
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
: "verification failed (fail-closed)",
|
|
550
|
-
],
|
|
551
|
-
},
|
|
552
|
-
dodSource: dod.source,
|
|
553
|
-
};
|
|
649
|
+
gateRes = unverifiableGateResult(
|
|
650
|
+
error instanceof RouterTimeoutError
|
|
651
|
+
? `verification gate timed out after ${gateBudgetMs}ms`
|
|
652
|
+
: `verification unavailable: ${scrubText(String(error))}`,
|
|
653
|
+
dod.source,
|
|
654
|
+
activeCfg.enforcement?.verify?.strictUnverifiable,
|
|
655
|
+
completedFailures,
|
|
656
|
+
);
|
|
554
657
|
}
|
|
555
658
|
|
|
556
659
|
// Per-attempt cleanup (drop producer session tracking + state).
|
|
557
|
-
changedFileStore.clear(producerSid);
|
|
660
|
+
if (producerSid !== baselineID) changedFileStore.clear(producerSid);
|
|
558
661
|
try {
|
|
559
662
|
sessionStore.unregister(producerSid);
|
|
663
|
+
sessionRootMemo.delete(producerSid);
|
|
560
664
|
} catch {
|
|
561
665
|
// non-fatal
|
|
562
666
|
}
|
|
@@ -596,7 +700,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
596
700
|
|
|
597
701
|
const action = nextAction(
|
|
598
702
|
state,
|
|
599
|
-
{ pass: gateRes.accepted, reasons: gateRes.verdict.reasons },
|
|
703
|
+
{ pass: gateRes.accepted, outcome: gateRes.verdict.outcome, reasons: gateRes.verdict.reasons },
|
|
600
704
|
policy,
|
|
601
705
|
);
|
|
602
706
|
|
|
@@ -607,7 +711,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
607
711
|
true,
|
|
608
712
|
gateRes.verdict.method,
|
|
609
713
|
);
|
|
610
|
-
return producerText + buildAcceptedSuffix(gateRes.verdict.method);
|
|
714
|
+
return producerText + buildAcceptedSuffix(gateRes.verdict.method, gateRes.verdict.caveats, gateRes.verdict.notes);
|
|
611
715
|
}
|
|
612
716
|
if (action.action === "give_up") {
|
|
613
717
|
dumpDelegateScorecard(
|
|
@@ -636,6 +740,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
636
740
|
// disposeChildSession is fail-soft, so re-disposing an already
|
|
637
741
|
// disposed session is harmless.
|
|
638
742
|
for (const sid of producerSessions) {
|
|
743
|
+
changedFileStore.clear(sid);
|
|
639
744
|
await disposeChildSession(sid);
|
|
640
745
|
}
|
|
641
746
|
}
|
|
@@ -779,6 +884,59 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
779
884
|
// -----------------------------------------------------------------------
|
|
780
885
|
"tool.execute.before": async (input: any, output: any) => {
|
|
781
886
|
if (bypassed) return;
|
|
887
|
+
// Observe before execution too: an in-flight edit must contaminate a
|
|
888
|
+
// capture even if the test finishes before the edit's after-hook fires.
|
|
889
|
+
if (typeof input?.tool === "string") changedFileStore.observeEdit(input.tool,
|
|
890
|
+
typeof output?.args?.cwd === "string" ? output.args.cwd : undefined);
|
|
891
|
+
if (input?.tool === "task" && typeof input.callID === "string" && typeof input.sessionID === "string") {
|
|
892
|
+
const mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
|
|
893
|
+
if (shouldVerifyTask("task", mode, cfg.enforcement?.verify?.require)) {
|
|
894
|
+
beginVerification(changedFileStore, `task:${input.sessionID}:${input.callID}`,
|
|
895
|
+
typeof output?.args?.cwd === "string" ? output.args.cwd : undefined,
|
|
896
|
+
buildDelegationDoD({
|
|
897
|
+
prompt: typeof output?.args?.prompt === "string" ? output.args.prompt : undefined,
|
|
898
|
+
description: typeof output?.args?.description === "string" ? output.args.description : undefined,
|
|
899
|
+
}));
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
// Dispatch hygiene is independent of subagent guard enforcement below.
|
|
903
|
+
// The plugin API declares generic args, not a task-specific argument shape.
|
|
904
|
+
try {
|
|
905
|
+
if (input?.tool === "task" && cfg.dispatchHeader !== false) {
|
|
906
|
+
const rawArgs: unknown = output?.args;
|
|
907
|
+
if (rawArgs && typeof rawArgs === "object" && !Array.isArray(rawArgs)) {
|
|
908
|
+
const args = rawArgs as Record<string, unknown>;
|
|
909
|
+
const tier = typeof args.subagent_type === "string"
|
|
910
|
+
? args.subagent_type : args.subagentType;
|
|
911
|
+
if (
|
|
912
|
+
typeof tier === "string" &&
|
|
913
|
+
Object.prototype.hasOwnProperty.call(getActiveTiers(cfg), tier) &&
|
|
914
|
+
typeof args.prompt === "string" &&
|
|
915
|
+
!args.prompt.startsWith("[router] You are @")
|
|
916
|
+
) {
|
|
917
|
+
// Resolve from the original dispatch, using the registration rules.
|
|
918
|
+
const parsed = parseCapDirective(args.prompt);
|
|
919
|
+
const override =
|
|
920
|
+
parsed === "none" && !/\breason:/i.test(args.prompt) ? null : parsed;
|
|
921
|
+
const baseline = cfg.tierCaps?.[tier] ?? DEFAULT_TIER_CAPS[tier] ?? 5;
|
|
922
|
+
const cap = override ?? baseline;
|
|
923
|
+
const prompt = buildDispatchHeader({ tier, cap, projectDirectory: ctx.directory }) +
|
|
924
|
+
"\n\n---\n\n" + args.prompt;
|
|
925
|
+
args.prompt = prompt;
|
|
926
|
+
if (process.env.MODEL_ROUTER_DISPATCH_DEBUG === "1" && !dispatchDebugLogged) {
|
|
927
|
+
dispatchDebugLogged = true;
|
|
928
|
+
const dir = join(tmpdir(), "opencode-model-router-trajectory");
|
|
929
|
+
mkdirSync(dir, { recursive: true });
|
|
930
|
+
writeFileSync(join(dir, "dispatch.log"), JSON.stringify({
|
|
931
|
+
headerApplied: true, tier, promptLength: prompt.length,
|
|
932
|
+
}) + "\n", { flag: "a" });
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
} catch {
|
|
938
|
+
// Best-effort: malformed args or debug I/O must never break a dispatch.
|
|
939
|
+
}
|
|
782
940
|
const sid = input?.sessionID;
|
|
783
941
|
if (!sid || !sessionStore.isSubagent(sid) || typeof input?.tool !== "string") {
|
|
784
942
|
return;
|
|
@@ -823,6 +981,23 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
823
981
|
if (bypassed) return;
|
|
824
982
|
sessionStore.recordToolCall(input, output);
|
|
825
983
|
|
|
984
|
+
// Best-effort false-refusal observation alongside the existing guard path.
|
|
985
|
+
// Keep scorecards unchanged; counts live in the TTL-managed trajectory.
|
|
986
|
+
try {
|
|
987
|
+
if (input?.tool === "task" && cfg.falseRefusalDetection !== false) {
|
|
988
|
+
const { childSessionID, text } = parseRefusalTaskResult(output);
|
|
989
|
+
if (childSessionID) {
|
|
990
|
+
const calls = trajectoryStore.toolCallCount(childSessionID);
|
|
991
|
+
if (detectFalseRefusal({ toolCalls: calls, resultText: text }).suspected) {
|
|
992
|
+
output.output = `[router] FALSE-REFUSAL SUSPECT — this delegate returned a hand-back after 0 tool calls. No tool call was observed for this child, so the capability claim in its answer is untested rather than demonstrated. Re-dispatch the same work with task_id="${childSessionID}" and an instruction to attempt it, or do it yourself; do not escalate a tier on this result.\n\n${output.output}`;
|
|
993
|
+
trajectoryStore.recordFalseRefusal(childSessionID);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
} catch {
|
|
998
|
+
// Best-effort: malformed/frozen results must never break a dispatch.
|
|
999
|
+
}
|
|
1000
|
+
|
|
826
1001
|
// Record-only trajectory observation (mutates internal maps only; never
|
|
827
1002
|
// touches output, so emitted banners/observations stay byte-identical).
|
|
828
1003
|
const sid = input?.sessionID;
|
|
@@ -874,10 +1049,11 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
874
1049
|
prompt: input?.args?.prompt,
|
|
875
1050
|
description: input?.args?.description,
|
|
876
1051
|
});
|
|
1052
|
+
const dispatchID = `task:${input.sessionID}:${input.callID}`;
|
|
1053
|
+
const verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", input?.args?.cwd);
|
|
877
1054
|
const artefact = {
|
|
878
|
-
changedFiles:
|
|
879
|
-
|
|
880
|
-
: [],
|
|
1055
|
+
changedFiles: verification.changedFiles,
|
|
1056
|
+
changeBaseline: verification.changeBaseline,
|
|
881
1057
|
finalReturnText,
|
|
882
1058
|
declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
|
|
883
1059
|
producerSessionID: childSessionID ?? "",
|
|
@@ -900,9 +1076,12 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
900
1076
|
artefact.changedFiles.length === 0
|
|
901
1077
|
) {
|
|
902
1078
|
if (childSessionID) changedFileStore.clear(childSessionID);
|
|
1079
|
+
changedFileStore.clear(dispatchID);
|
|
903
1080
|
return;
|
|
904
1081
|
}
|
|
905
1082
|
|
|
1083
|
+
const gateDeps = buildGateDeps();
|
|
1084
|
+
gateDeps.deterministic.testBaseline = verification.testBaseline;
|
|
906
1085
|
const res = await accept(
|
|
907
1086
|
{
|
|
908
1087
|
dod,
|
|
@@ -916,19 +1095,23 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
916
1095
|
: {}),
|
|
917
1096
|
},
|
|
918
1097
|
artefact,
|
|
919
|
-
|
|
1098
|
+
gateDeps,
|
|
920
1099
|
);
|
|
921
1100
|
if (!res.accepted && !res.verdict.skipped) {
|
|
922
1101
|
const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
|
|
923
1102
|
const li = ladder.indexOf(producerTier);
|
|
924
|
-
const nextTier = li >= 0 && li < ladder.length - 1 ? ladder[li + 1] : null;
|
|
1103
|
+
const nextTier = res.verdict.outcome !== "unverifiable" && li >= 0 && li < ladder.length - 1 ? ladder[li + 1] : null;
|
|
925
1104
|
const note = scrubText(buildForcingNote(res.verdict.reasons, { producerTier, nextTier }));
|
|
926
1105
|
output.output =
|
|
927
1106
|
typeof output.output === "string"
|
|
928
1107
|
? output.output + "\n\n" + note
|
|
929
1108
|
: note;
|
|
930
1109
|
}
|
|
1110
|
+
if (res.accepted && (res.verdict.caveats?.length || res.verdict.notes?.length)) {
|
|
1111
|
+
output.output += buildAcceptedSuffix(res.verdict.method, res.verdict.caveats, res.verdict.notes);
|
|
1112
|
+
}
|
|
931
1113
|
if (childSessionID) changedFileStore.clear(childSessionID);
|
|
1114
|
+
changedFileStore.clear(dispatchID);
|
|
932
1115
|
} catch {
|
|
933
1116
|
// fail-closed: a verification error must NEVER throw out of the after-hook
|
|
934
1117
|
}
|
|
@@ -960,13 +1143,51 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
960
1143
|
},
|
|
961
1144
|
|
|
962
1145
|
// -----------------------------------------------------------------------
|
|
963
|
-
//
|
|
964
|
-
//
|
|
965
|
-
//
|
|
966
|
-
// for manual inspection. Best-effort;
|
|
967
|
-
//
|
|
1146
|
+
// Session lifecycle: classify children on session.created, then write
|
|
1147
|
+
// enforcement scorecards on session.idle. Full trajectory debug dumps
|
|
1148
|
+
// remain opt-in behind MODEL_ROUTER_TRAJECTORY_DEBUG=1 (Phase 0.3, T0.3.3).
|
|
1149
|
+
// Dumps go under the OS temp dir for manual inspection. Best-effort;
|
|
1150
|
+
// never throws into the session or emits model-visible debug output.
|
|
968
1151
|
// -----------------------------------------------------------------------
|
|
969
1152
|
event: async ({ event }: any) => {
|
|
1153
|
+
if (event?.type === "session.deleted") {
|
|
1154
|
+
try {
|
|
1155
|
+
const id = event?.properties?.info?.id;
|
|
1156
|
+
if (typeof id === "string") {
|
|
1157
|
+
sessionRootMemo.delete(id);
|
|
1158
|
+
sessionLookupFailedAt.delete(id);
|
|
1159
|
+
sessionStore.unregister(id);
|
|
1160
|
+
}
|
|
1161
|
+
} catch {
|
|
1162
|
+
// best-effort: cleanup must never crash a real session
|
|
1163
|
+
}
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
// Child-session classification. opencode reports every child session with
|
|
1167
|
+
// a parentID, which is the only agent-name-INDEPENDENT signal available:
|
|
1168
|
+
// registerFromChatMessage recognises a session only when its agent name is
|
|
1169
|
+
// literally an active tier, so `general`, `explore`, markdown agents,
|
|
1170
|
+
// every agent mapped through `subagentTiers` (which by construction can
|
|
1171
|
+
// never be tier-named — see resolveSubagentOverrides) and the plugin's own
|
|
1172
|
+
// grader sessions all went unmarked. Unmarked meant system.transform
|
|
1173
|
+
// injected "You are the orchestrator, delegate with Task(...)" into a
|
|
1174
|
+
// subagent that has no task tool, and the subagent refused the work.
|
|
1175
|
+
if (event?.type === "session.created") {
|
|
1176
|
+
const info = event?.properties?.info;
|
|
1177
|
+
if (
|
|
1178
|
+
typeof info?.id === "string" &&
|
|
1179
|
+
typeof info?.parentID === "string" &&
|
|
1180
|
+
info.parentID !== ""
|
|
1181
|
+
) {
|
|
1182
|
+
try {
|
|
1183
|
+
sessionStore.markChildSession(info.id);
|
|
1184
|
+
} catch {
|
|
1185
|
+
// best-effort: classification must never crash a real session
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
|
|
970
1191
|
if (event?.type !== "session.idle") return;
|
|
971
1192
|
const sid = event?.properties?.sessionID;
|
|
972
1193
|
if (typeof sid !== "string") return;
|
|
@@ -1017,16 +1238,29 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1017
1238
|
? `${CLAUDE_TIER_PREFIX[name]}\n\n${CLAUDE_ANTI_NARRATION}`
|
|
1018
1239
|
: CLAUDE_TIER_PREFIX[name]
|
|
1019
1240
|
: undefined;
|
|
1020
|
-
const
|
|
1241
|
+
const styledPrompt =
|
|
1021
1242
|
claudePrefix && resolvedPrompt
|
|
1022
1243
|
? `${claudePrefix}\n\n---\n\n${resolvedPrompt}`
|
|
1023
1244
|
: resolvedPrompt;
|
|
1024
1245
|
|
|
1246
|
+
// The tool-authority clause is appended HERE rather than inside each
|
|
1247
|
+
// tier prompt, for three reasons: one copy instead of six; the
|
|
1248
|
+
// style-comparison contracts in test/unit/prompt-style.test.ts compare
|
|
1249
|
+
// goal-oriented against prescriptive length, and adding the same
|
|
1250
|
+
// constant to both sides erodes a ratio it is meant to protect; and a
|
|
1251
|
+
// user-supplied `tier.prompt` bypasses the shipped defaults entirely,
|
|
1252
|
+
// so a clause living in the defaults would not protect the tiers most
|
|
1253
|
+
// likely to be hand-written.
|
|
1254
|
+
const finalPrompt = styledPrompt
|
|
1255
|
+
? `${styledPrompt}\n\n${TOOL_AUTHORITY_CLAUSE}`
|
|
1256
|
+
: TOOL_AUTHORITY_CLAUSE;
|
|
1257
|
+
|
|
1025
1258
|
const agentDef: Record<string, unknown> = {
|
|
1026
1259
|
model: tier.model,
|
|
1027
1260
|
mode: "subagent",
|
|
1028
1261
|
description: tier.description ?? `@${name} tier (${tier.model})`,
|
|
1029
1262
|
maxSteps: tier.steps,
|
|
1263
|
+
steps: tier.steps,
|
|
1030
1264
|
prompt: finalPrompt,
|
|
1031
1265
|
color: tier.color,
|
|
1032
1266
|
};
|
|
@@ -1146,10 +1380,47 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1146
1380
|
// Use last known config if file read fails
|
|
1147
1381
|
}
|
|
1148
1382
|
|
|
1149
|
-
//
|
|
1150
|
-
//
|
|
1383
|
+
// Inject ONLY when this is provably the top-level orchestrator session.
|
|
1384
|
+
//
|
|
1385
|
+
// Fail CLOSED. The old guard was `sessionID && isSubagent(sessionID)`,
|
|
1386
|
+
// which injected whenever the session could not be proven to be a child.
|
|
1387
|
+
// Both failure directions are not equal: a missed injection costs the
|
|
1388
|
+
// orchestrator its routing rules, while a spurious injection tells a
|
|
1389
|
+
// subagent it is an orchestrator that MUST delegate with a `task` tool it
|
|
1390
|
+
// does not have — and a literal-minded model then refuses the dispatch
|
|
1391
|
+
// outright instead of doing the work.
|
|
1151
1392
|
const sessionID = _input?.sessionID;
|
|
1152
|
-
if (sessionID
|
|
1393
|
+
if (typeof sessionID !== "string" || sessionID === "") {
|
|
1394
|
+
warnMissingTransformSessionOnce();
|
|
1395
|
+
return;
|
|
1396
|
+
}
|
|
1397
|
+
// graderSessions is checked separately from isSubagent because it is
|
|
1398
|
+
// populated synchronously the instant client.session.create resolves,
|
|
1399
|
+
// whereas the session.created event that feeds markChildSession may not
|
|
1400
|
+
// have arrived yet. A grader told to orchestrate stalls until its budget
|
|
1401
|
+
// expires.
|
|
1402
|
+
const isChild =
|
|
1403
|
+
graderSessions.has(sessionID) ||
|
|
1404
|
+
sessionStore.isSubagent(sessionID) ||
|
|
1405
|
+
!(await resolveIsRootSession(sessionID));
|
|
1406
|
+
|
|
1407
|
+
if (isChild) {
|
|
1408
|
+
if (process.env.MODEL_ROUTER_SYSTEM_DEBUG === "1" && !systemDebugLogged) {
|
|
1409
|
+
systemDebugLogged = true;
|
|
1410
|
+
try {
|
|
1411
|
+
const dir = join(tmpdir(), "opencode-model-router-trajectory");
|
|
1412
|
+
mkdirSync(dir, { recursive: true });
|
|
1413
|
+
writeFileSync(join(dir, "system.log"), JSON.stringify({
|
|
1414
|
+
length: output.system.length,
|
|
1415
|
+
entries: output.system.map((entry: string) => entry.slice(0, 60)),
|
|
1416
|
+
}) + "\n", { flag: "a" });
|
|
1417
|
+
} catch {
|
|
1418
|
+
// Best-effort opt-in diagnostics must never break a real session.
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
stripDelegateInstructions(output, cfg, ctx.directory);
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1153
1424
|
|
|
1154
1425
|
// For Claude-backed orchestrators, prepend an adversarial opener that
|
|
1155
1426
|
// revokes the cached "Claude Code explorer" priming for the routing
|
package/src/router/config.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { homedir } from "node:os";
|
|
|
10
10
|
import { dirname, join } from "node:path";
|
|
11
11
|
import { fileURLToPath } from "node:url";
|
|
12
12
|
import { parseJsonc } from "./jsonc";
|
|
13
|
+
import type { DelegateInstructionsPolicy } from "./instructions";
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
16
|
* Filename of the optional user overrides file (global and project copies share
|
|
@@ -125,7 +126,13 @@ export interface EnforcementConfig {
|
|
|
125
126
|
verify?: { require?: "never" | "whenDoDPresent" | "always"; requireExplicitDoD?: boolean; preferDeterministic?: boolean; graderPolicy?: "atLeastProducerTier"; graderTemperature?: number; minGraderTier?: string | null;
|
|
126
127
|
/** Ceiling for one producer `session.prompt` turn, in ms. Default 600000. */
|
|
127
128
|
delegateTimeoutMs?: number;
|
|
128
|
-
/**
|
|
129
|
+
/** Reject unavailable verification. Default false; never escalates it. */
|
|
130
|
+
strictUnverifiable?: boolean;
|
|
131
|
+
/** Capture/cache conservative dispatch-time test baselines. Default true. */
|
|
132
|
+
testBaseline?: boolean;
|
|
133
|
+
/** Independent capture ceiling, including fingerprinting. Default 60000 ms. */
|
|
134
|
+
baselineTimeoutMs?: number;
|
|
135
|
+
/** Override tier ceilings: fast 60000 / medium 180000 / heavy 600000 ms. */
|
|
129
136
|
graderTimeoutMs?: number;
|
|
130
137
|
/** Ceiling for the whole acceptance gate, in ms. Default 90000. */
|
|
131
138
|
gateBudgetMs?: number };
|
|
@@ -134,6 +141,28 @@ export interface EnforcementConfig {
|
|
|
134
141
|
}
|
|
135
142
|
|
|
136
143
|
export interface RouterConfig {
|
|
144
|
+
/**
|
|
145
|
+
* Detect a delegate that hands a dispatch back having made zero tool calls
|
|
146
|
+
* while complaining about tool availability, and annotate the result so the
|
|
147
|
+
* orchestrator retries instead of escalating a tier on a refusal that was
|
|
148
|
+
* never tested. Defaults to true.
|
|
149
|
+
*/
|
|
150
|
+
falseRefusalDetection?: boolean;
|
|
151
|
+
/**
|
|
152
|
+
* Prepend a short mechanical header to every task dispatch: tier identity,
|
|
153
|
+
* working directory, tool-schema authority, empty-results-are-results, the
|
|
154
|
+
* read-only budget, and the false-refusal notice. Defaults to true. Set false
|
|
155
|
+
* to restore the pre-feature behaviour where this guidance existed only if the
|
|
156
|
+
* orchestrator remembered to write it.
|
|
157
|
+
*/
|
|
158
|
+
dispatchHeader?: boolean;
|
|
159
|
+
/**
|
|
160
|
+
* DELEGATE sessions only, never the orchestrator. `strip-global` (default)
|
|
161
|
+
* removes instruction files outside the project, where orchestrator personas
|
|
162
|
+
* normally live, and keeps project-local files. `strip-all` removes every
|
|
163
|
+
* instruction file; `keep` restores pre-feature behaviour.
|
|
164
|
+
*/
|
|
165
|
+
delegateInstructions?: DelegateInstructionsPolicy;
|
|
137
166
|
activePreset: string;
|
|
138
167
|
activeMode?: string;
|
|
139
168
|
presets: Record<string, Preset>;
|
|
@@ -477,6 +506,27 @@ function validateCoreKeys(obj: Record<string, unknown>): void {
|
|
|
477
506
|
}
|
|
478
507
|
}
|
|
479
508
|
|
|
509
|
+
function validateDispatchHeader(obj: Record<string, unknown>): void {
|
|
510
|
+
if (obj.dispatchHeader !== undefined && typeof obj.dispatchHeader !== "boolean") {
|
|
511
|
+
throw new Error("tiers.json: 'dispatchHeader' must be a boolean");
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function validateFalseRefusalDetection(obj: Record<string, unknown>): void {
|
|
516
|
+
if (obj.falseRefusalDetection !== undefined && typeof obj.falseRefusalDetection !== "boolean") {
|
|
517
|
+
throw new Error("tiers.json: 'falseRefusalDetection' must be a boolean");
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function validateDelegateInstructions(obj: Record<string, unknown>): void {
|
|
522
|
+
if (obj.delegateInstructions === undefined) return;
|
|
523
|
+
if (!["strip-global", "strip-all", "keep"].some((policy) => policy === obj.delegateInstructions)) {
|
|
524
|
+
throw new Error(
|
|
525
|
+
"tiers.json: 'delegateInstructions' must be one of strip-global|strip-all|keep",
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
480
530
|
function validateModes(obj: Record<string, unknown>): void {
|
|
481
531
|
// Validate modes if present
|
|
482
532
|
if (obj.modes !== undefined) {
|
|
@@ -636,6 +686,12 @@ function validateEnforcement(obj: Record<string, unknown>): void {
|
|
|
636
686
|
enforcement.verify !== null
|
|
637
687
|
) {
|
|
638
688
|
const verify = enforcement.verify as Record<string, unknown>;
|
|
689
|
+
if (verify.testBaseline !== undefined && typeof verify.testBaseline !== "boolean") {
|
|
690
|
+
throw new Error("tiers.json: enforcement.verify.testBaseline must be a boolean");
|
|
691
|
+
}
|
|
692
|
+
if (verify.strictUnverifiable !== undefined && typeof verify.strictUnverifiable !== "boolean") {
|
|
693
|
+
throw new Error("tiers.json: enforcement.verify.strictUnverifiable must be a boolean");
|
|
694
|
+
}
|
|
639
695
|
if (
|
|
640
696
|
verify.graderPolicy !== undefined &&
|
|
641
697
|
verify.graderPolicy !== "atLeastProducerTier"
|
|
@@ -673,6 +729,7 @@ function validateEnforcement(obj: Record<string, unknown>): void {
|
|
|
673
729
|
"delegateTimeoutMs",
|
|
674
730
|
"graderTimeoutMs",
|
|
675
731
|
"gateBudgetMs",
|
|
732
|
+
"baselineTimeoutMs",
|
|
676
733
|
] as const) {
|
|
677
734
|
const value = verify[key];
|
|
678
735
|
if (value !== undefined) {
|
|
@@ -864,6 +921,9 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
864
921
|
validateTaskPatterns(obj);
|
|
865
922
|
validateSubagentTiers(obj);
|
|
866
923
|
validateEnforcement(obj);
|
|
924
|
+
validateDelegateInstructions(obj);
|
|
925
|
+
validateDispatchHeader(obj);
|
|
926
|
+
validateFalseRefusalDetection(obj);
|
|
867
927
|
|
|
868
928
|
return raw as RouterConfig;
|
|
869
929
|
}
|