opencode-model-router 2.9.1 → 2.11.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 +482 -0
- package/README.md +4 -2
- package/package.json +12 -5
- package/src/compat/background.ts +56 -19
- package/src/compat/child-history.ts +134 -0
- package/src/compat/child-report.ts +185 -0
- package/src/compat/child-session.ts +10 -0
- package/src/compat/session-lookup.ts +21 -0
- package/src/compat/v2-client.ts +124 -6
- package/src/compat/v2-hooks.ts +525 -203
- package/src/compat/v2-observations.ts +1 -0
- package/src/compat/v2-vocabulary.ts +14 -0
- package/src/executor/create.ts +47 -28
- package/src/executor/git.ts +226 -30
- package/src/executor/integrate/checks.ts +29 -11
- package/src/executor/integrate/land.ts +32 -2
- package/src/executor/integrate/queue.ts +95 -13
- package/src/executor/ledger.ts +16 -12
- package/src/executor/lfs-restore.ts +492 -0
- package/src/executor/paths.ts +7 -2
- package/src/executor/recovery.ts +2 -1
- package/src/executor/runtime.ts +1062 -243
- package/src/executor/slots/pool.ts +120 -19
- package/src/executor/slots/provision.ts +111 -23
- package/src/executor/slots/root.ts +81 -0
- package/src/executor/types.ts +28 -2
- package/src/executor/unattended.ts +6 -1
- package/src/executor/verify-trees.ts +507 -0
- package/src/guard/enforce.ts +2 -1
- package/src/guard/fingerprint.ts +9 -0
- package/src/guard/guards.ts +7 -1
- package/src/index.ts +191 -31
- package/src/router/answer-dedup.ts +198 -0
- package/src/router/common-dir.ts +241 -0
- package/src/router/config.ts +228 -40
- package/src/router/diff-handles.ts +322 -0
- package/src/router/diff-summary.ts +318 -0
- package/src/router/git-metadata-guard.ts +317 -0
- package/src/router/git-tools.ts +1136 -49
- package/src/router/read-only.ts +37 -13
- package/src/router/role-agents.ts +100 -36
- package/src/router/run-summary.ts +253 -0
- package/src/router/run-tools.ts +177 -25
- package/src/router/sessions.ts +23 -1
- package/src/router/tool-paths.ts +62 -4
- package/src/routing/classify/rules.ts +93 -14
- package/src/routing/roles/read-set.ts +10 -1
- package/src/routing/roles/work-root.ts +20 -3
- package/src/routing/wire/hint.ts +9 -2
- package/src/v2.ts +3 -1
- package/src/verify/exec.ts +454 -2
- package/src/verify/head.ts +6 -1
- package/src/verify/pending.ts +14 -1
- package/src/verify/plan-task.ts +86 -26
- package/src/verify/reference.ts +60 -7
- package/src/verify/runner.ts +14 -6
- package/src/verify/tree.ts +34 -10
- package/src/verify/types.ts +44 -0
- package/src/verify/wiring.ts +134 -22
package/src/index.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode-ai/plugin";
|
|
2
2
|
import { completionIdentity, observeV2 } from "./compat/v2-observations";
|
|
3
3
|
import type { RouterPluginInput } from "./compat/child-session";
|
|
4
|
-
import { DEPTH_BANNER, ResumeRejectedError, TASK_VERIFICATION } from "./compat/child-session";
|
|
4
|
+
import { DEPTH_BANNER, ResumeRejectedError, SESSION_DIRECTORY, TASK_VERIFICATION } from "./compat/child-session";
|
|
5
|
+
import { SESSION_INFO_LOOKUP_MS, sessionLookupWithin } from "./compat/session-lookup";
|
|
5
6
|
|
|
6
7
|
// Imports for internal use within this module
|
|
7
8
|
import {
|
|
@@ -25,6 +26,8 @@ import {
|
|
|
25
26
|
import type { RouterConfig, TierConfig, Preset, ModeConfig, EffortLevel } from "./router/config";
|
|
26
27
|
import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
|
|
27
28
|
import { gitTools, nearestCheckout, type GitRootResolver } from "./router/git-tools";
|
|
29
|
+
import { forgetHandles } from "./router/diff-handles";
|
|
30
|
+
import { gitMetadataUnknownDirectoryRefusal, gitMetadataWriteRefusal } from "./router/git-metadata-guard";
|
|
28
31
|
import { isReadOnlyTier, legacyReadOnlyTools, mergePermissions, readOnlyPermissions } from "./router/read-only";
|
|
29
32
|
import { buildPluginAgentDefinition, mergeHostAgentEntry, pluginAgentMarker } from "./router/plugin-agents";
|
|
30
33
|
import { filterSensitiveGrep } from "./router/sensitive-paths";
|
|
@@ -70,6 +73,7 @@ import {
|
|
|
70
73
|
} from "./router/protocol";
|
|
71
74
|
import { resolveRoles, type RoleSpec } from "./router/roles";
|
|
72
75
|
import { routerRunTool, type RunRecord } from "./router/run-tools";
|
|
76
|
+
import { forgetAnswers, noteToolCall } from "./router/answer-dedup";
|
|
73
77
|
import type { WorkRootAnswer } from "./router/git-tools";
|
|
74
78
|
import { GUARD_CUMULATIVE_MULTIPLIER, roleGuardProfile, type GuardProfile } from "./router/guard-profile";
|
|
75
79
|
import { currentBinding } from "./routing/roles/binding";
|
|
@@ -95,6 +99,7 @@ import { countUnknownBindings } from "./routing/outcomes/stats";
|
|
|
95
99
|
import { roleAgentSteps } from "./router/role-agents";
|
|
96
100
|
import type { HostBudgetObservation } from "./compat/v2-hooks";
|
|
97
101
|
import { ROUTER_TURN_STATE_ATTACH, TURN_STATE_ROOT, type TurnStateRegistry } from "./compat/turn-state";
|
|
102
|
+
import { v2Instructions } from "./compat/v2-vocabulary";
|
|
98
103
|
import { ADOPTION_REFUSED, ROUTER_FINISH_ATTACH, type AdoptedRecords, type AdoptionRefused, type FinishApi, type FinishAttach, type FinishInput, type FinishResult, type HeldSink, type InflightJournal, type LeaseGuard, type PersistedRecord, type RestoredDispatch, type RoutedRoleSnapshot } from "./compat/background";
|
|
99
104
|
import type { DispatchDelta } from "./verify/dispatch";
|
|
100
105
|
import { configAsWritten, configuredV2OnlyKeys, setConfigNoticeHost } from "./router/config";
|
|
@@ -132,6 +137,7 @@ import {
|
|
|
132
137
|
DEFAULT_TIER_CAPS,
|
|
133
138
|
READ_ONLY_TOOLS,
|
|
134
139
|
awaitExecutionEnd,
|
|
140
|
+
isHandleExpansion,
|
|
135
141
|
lastStepContext,
|
|
136
142
|
} from "./router/sessions";
|
|
137
143
|
import type { Cap, SubagentState } from "./router/sessions";
|
|
@@ -526,6 +532,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
526
532
|
* The lookup behind resolveIsRootSession: true (no parentID), false (a parentID), or undefined
|
|
527
533
|
* when it is not known (the lookup failed, or failed recently and is throttled). QA-2.4-2 treats
|
|
528
534
|
* undefined as NOT root (isProvenRootCaller), where the protocol injection treats it as root.
|
|
535
|
+
* #161: on the OpenCode v2 host a lookup the host has not answered within SESSION_INFO_LOOKUP_MS
|
|
536
|
+
* is a failed one (the guard's refusals wait for it, as for the v2 session record); on v1 it is
|
|
537
|
+
* not bounded.
|
|
529
538
|
*/
|
|
530
539
|
const lookupRootSession = async (sessionID: string): Promise<boolean | undefined> => {
|
|
531
540
|
const memo = sessionRootMemo.get(sessionID);
|
|
@@ -539,7 +548,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
539
548
|
return undefined;
|
|
540
549
|
}
|
|
541
550
|
try {
|
|
542
|
-
const
|
|
551
|
+
const lookup = ctx.client.session.get({ path: { id: sessionID } });
|
|
552
|
+
const res = ctx.routerHost === "v2" ? await sessionLookupWithin(lookup, SESSION_INFO_LOOKUP_MS) : await lookup;
|
|
543
553
|
if (!res || (res as { error?: unknown }).error || !res.data) {
|
|
544
554
|
throw new Error("session.get returned no session data");
|
|
545
555
|
}
|
|
@@ -687,6 +697,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
687
697
|
/** The role of a session: what its tool hooks named, else what the dispatch registry recorded for it. */
|
|
688
698
|
const roleOfSession = (sessionID: unknown): RoleSpec | undefined => typeof sessionID !== "string" || sessionID === ""
|
|
689
699
|
? undefined : roleSpecOf(roleSessions.get(sessionID) ?? lookupDispatch(sessionID)?.agent);
|
|
700
|
+
/** A read-only call for the trajectory: a read-only tool, or (#108 slice 5) a role session's handle expansion. */
|
|
701
|
+
const roleReadOnly = (sessionID: unknown, tool: string, args: unknown): boolean =>
|
|
702
|
+
READ_ONLY_TOOLS.has(tool) || (isHandleExpansion(tool, args) && roleOfSession(sessionID) !== undefined);
|
|
690
703
|
/**
|
|
691
704
|
* Handoff 11 (P-10, P-18): the ONE work-root resolver of `router_run` and `router_git_*`, from the child's binding (bound by the
|
|
692
705
|
* adapter's `execute.before` before any tool of the child runs). Not a role session → `{ role: false }` (git keeps today's
|
|
@@ -1190,6 +1203,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1190
1203
|
}
|
|
1191
1204
|
/** Late-bound: the lease guard exists only once the v2 adapter attaches (FinishAttach `leaseGate`); the wiring reads it per use. */
|
|
1192
1205
|
let leaseGateRef: Pick<LeaseGuard, "waitTreeFree"> | undefined;
|
|
1206
|
+
/**
|
|
1207
|
+
* #191 (v2 only, FinishAttach `leaseGateScope: "held"`): only the gate of a background finish waits for `leaseGateRef`
|
|
1208
|
+
* (`finishDispatch` `backgroundFinish`, read by the wiring through `leaseGateScope`).
|
|
1209
|
+
*/
|
|
1210
|
+
let leaseGateHeldOnly = false;
|
|
1193
1211
|
/** Phase 5.1 D11 (v2 only): the plan-task gates' own holders, exempt from the lease wait in their own slot tree. */
|
|
1194
1212
|
const planTaskLeaseExemptions = createLeaseSelfExemptions((root) => planTreeKey(root));
|
|
1195
1213
|
const {
|
|
@@ -1227,6 +1245,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1227
1245
|
return { waitedMs: wait.waitedMs, holders: wait.holders, fileCount: wait.holders.length === 0 ? 0 : fileCount };
|
|
1228
1246
|
},
|
|
1229
1247
|
},
|
|
1248
|
+
// #191: under `routing.background.mode: "off"` only a background finish waits for the lease gate (a foreground check, as before).
|
|
1249
|
+
leaseGateScope: () => (leaseGateHeldOnly ? "held" : undefined),
|
|
1230
1250
|
}),
|
|
1231
1251
|
});
|
|
1232
1252
|
// 2.1.5b: sweep reference dirs a crashed instance left behind. Fire-and-forget; never throws.
|
|
@@ -1975,9 +1995,12 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1975
1995
|
: `[router_plan] ${planCallerRefusal}`,
|
|
1976
1996
|
} } : {}),
|
|
1977
1997
|
// QA-G-A2-2: a role session's work root must belong to the repository its dispatch listed the worktrees in (this directory's).
|
|
1998
|
+
// #108: roles mode at start implies OpenCode v2 (`startedInRoles`); a role session's router_git_diff is then stat-first,
|
|
1999
|
+
// its summary lines carry gd_ handles and router_git_show expands them (slice 3), and its identical repeated answer of
|
|
2000
|
+
// diff/status/show/log (an expansion too) becomes a stub unless `force` is passed (slice 4).
|
|
1978
2001
|
...gitTools(rolesAtStart ? {
|
|
1979
2002
|
resolveWorkRoot: resolveWorkRootFor("router_git"), ...(ctx.directory ? { dispatchRepository: ctx.directory } : {}),
|
|
1980
|
-
...(crossRepoAtStart ? { resolveRoot: resolveGitRootFor } : {}),
|
|
2003
|
+
...(crossRepoAtStart ? { resolveRoot: resolveGitRootFor } : {}), summarizeDiffs: true, handles: true, dedupe: true,
|
|
1981
2004
|
} : {}),
|
|
1982
2005
|
// #84 P2.1 (handoffs 11, 13): roles mode only. `router_run` runs in the bound work root; each run feeds the `run` signal.
|
|
1983
2006
|
...(rolesAtStart ? {
|
|
@@ -1985,6 +2008,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1985
2008
|
config: () => resolveRolesRouting(cfg, "v2").run,
|
|
1986
2009
|
resolveWorkRoot: resolveWorkRootFor("router_run"),
|
|
1987
2010
|
recordRun: (run) => pushBounded(roleRuns, run.sessionID, run),
|
|
2011
|
+
dedupe: true,
|
|
1988
2012
|
}),
|
|
1989
2013
|
} : {}),
|
|
1990
2014
|
// #84 P2.1: the authority ladder (P1.6) for dynamic roles (`general`).
|
|
@@ -2614,7 +2638,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2614
2638
|
try {
|
|
2615
2639
|
const target = parseRouterVerifyArgs(args);
|
|
2616
2640
|
if ("error" in target) return target.error;
|
|
2617
|
-
// R6: handles are scoped by the calling session; without one,
|
|
2641
|
+
// R6: handles are scoped by the calling session; without one, the call is answered "no session".
|
|
2618
2642
|
const sessionID = typeof toolCtx?.sessionID === "string" ? toolCtx.sessionID : "";
|
|
2619
2643
|
const report = await verifyHandles(sessionID, target, toolCtx?.abort !== undefined ? { signal: toolCtx.abort } : {});
|
|
2620
2644
|
// Phase 1.2 (v2 only): the late notices this report answers stop being retained for the turn-state tail.
|
|
@@ -2814,6 +2838,38 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2814
2838
|
sessionStore.markChildSession(input.sessionID);
|
|
2815
2839
|
applyPendingRoleCap(input.sessionID); // QA-P21-2-3
|
|
2816
2840
|
}
|
|
2841
|
+
// Security: a delegated agent never writes git metadata (router/git-metadata-guard.ts); on v2 a role agent was already refused
|
|
2842
|
+
// by its authority check. Always on: neither `/bypass` nor the enforcement mode turns it off. Only a session the router has
|
|
2843
|
+
// not proven to be the root is checked (`isProvenRootCaller`: a tracked child, a grader, a session with a parentID, an unknown
|
|
2844
|
+
// or unresolvable one): the orchestrator is the user's own agent, acting under the host's permissions. The paths are checked
|
|
2845
|
+
// first, so a call that writes no git metadata never costs a session lookup. Relative paths and the session's repository are
|
|
2846
|
+
// resolved against the session's own location on v2 (the bridge's SESSION_DIRECTORY), else the instance directory (v1, which
|
|
2847
|
+
// never sets it). #161: a `null` SESSION_DIRECTORY (v2: the session's directory is unknown) refuses every write-class call
|
|
2848
|
+
// (fail closed), with the path refusal's own text when the paths alone already refuse it; the root exemption below still
|
|
2849
|
+
// applies, so in that state every write-class call costs the root check (no host call for a session already proven root).
|
|
2850
|
+
if (typeof input?.tool === "string") {
|
|
2851
|
+
let gitRefusal: string | undefined;
|
|
2852
|
+
try {
|
|
2853
|
+
const sessionDirectory: unknown = input?.[SESSION_DIRECTORY];
|
|
2854
|
+
const base = typeof sessionDirectory === "string" && isAbsolute(sessionDirectory) ? sessionDirectory : projectDir ?? process.cwd();
|
|
2855
|
+
gitRefusal = sessionDirectory === null
|
|
2856
|
+
? gitMetadataUnknownDirectoryRefusal(input.tool, output?.args, base)
|
|
2857
|
+
: gitMetadataWriteRefusal(input.tool, output?.args, base);
|
|
2858
|
+
} catch {
|
|
2859
|
+
// Unreachable (the guard never throws); a delegated session is still refused (fail closed).
|
|
2860
|
+
gitRefusal = "[router] Refused: the router could not check this write for git metadata, which delegated agents may not write (fail closed).";
|
|
2861
|
+
}
|
|
2862
|
+
if (gitRefusal !== undefined && !(await isProvenRootCaller(input?.sessionID))) {
|
|
2863
|
+
try {
|
|
2864
|
+
if (typeof input.sessionID === "string") {
|
|
2865
|
+
trajectoryStore.recordToolEvent(input.sessionID, { tool: input.tool, readOnly: false, blocked: true });
|
|
2866
|
+
}
|
|
2867
|
+
} catch (error) {
|
|
2868
|
+
logger.warn("[router] git metadata guard: refusal not recorded", { error: describeError(error) });
|
|
2869
|
+
}
|
|
2870
|
+
throw new Error(gitRefusal);
|
|
2871
|
+
}
|
|
2872
|
+
}
|
|
2817
2873
|
if (bypassed) {
|
|
2818
2874
|
noteBypassedRoleCall(input?.sessionID); // QA-P21-1-7
|
|
2819
2875
|
return;
|
|
@@ -2981,7 +3037,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2981
3037
|
if (res.block) {
|
|
2982
3038
|
trajectoryStore.recordToolEvent(sid, {
|
|
2983
3039
|
tool: input.tool,
|
|
2984
|
-
readOnly:
|
|
3040
|
+
readOnly: roleReadOnly(sid, input.tool, output?.args),
|
|
2985
3041
|
blocked: true,
|
|
2986
3042
|
selfScript: res.guard === "anti_self_script",
|
|
2987
3043
|
});
|
|
@@ -2998,7 +3054,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2998
3054
|
// treats them as ground truth rather than advisory system noise.
|
|
2999
3055
|
// -----------------------------------------------------------------------
|
|
3000
3056
|
"tool.execute.after": async (input: any, output: any) => {
|
|
3001
|
-
if (typeof input?.sessionID === "string")
|
|
3057
|
+
if (typeof input?.sessionID === "string") {
|
|
3058
|
+
consumeExecutorChildRound(input.sessionID);
|
|
3059
|
+
noteToolCall(input.sessionID); // #108 slice 4: the window of the session's deduplicated answers (a no-op without any)
|
|
3060
|
+
}
|
|
3002
3061
|
if (input?.tool === "grep" && typeof output.output === "string") {
|
|
3003
3062
|
const tier = input.agent ?? pluginAgentSessions.get(input.sessionID) ?? sessionStore.getTier(input.sessionID);
|
|
3004
3063
|
const definition = tier && getActiveTiers(cfg)[tier];
|
|
@@ -3010,7 +3069,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3010
3069
|
noteBypassedRoleCall(input?.sessionID); // QA-P21-1-7
|
|
3011
3070
|
return;
|
|
3012
3071
|
}
|
|
3013
|
-
|
|
3072
|
+
// #108 slice 5: a role session's handle expansion is a read (cap banner); every other session is unchanged.
|
|
3073
|
+
sessionStore.recordToolCall(input, output, { roleExpansionReads: roleOfSession(input?.sessionID) !== undefined });
|
|
3014
3074
|
|
|
3015
3075
|
// #84 P2.1 (handoffs 13, 15-17, 23): role children only (roles mode on v2). Edit times feed the `run` signal; the parent's
|
|
3016
3076
|
// `task` return feeds the return/run signals, read BEFORE any router note is put in front of the child's text.
|
|
@@ -3071,7 +3131,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3071
3131
|
if (sid && sessionStore.isSubagent(sid) && typeof input?.tool === "string") {
|
|
3072
3132
|
trajectoryStore.recordToolEvent(sid, {
|
|
3073
3133
|
tool: input.tool,
|
|
3074
|
-
readOnly:
|
|
3134
|
+
readOnly: roleReadOnly(sid, input.tool, input?.args),
|
|
3075
3135
|
});
|
|
3076
3136
|
try {
|
|
3077
3137
|
const profile = roleGuardProfileOf(sid, input?.agent); // handoff 27, as in the before-hook
|
|
@@ -3156,6 +3216,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3156
3216
|
lateBuffer?.forget(id);
|
|
3157
3217
|
forgetRoleSession(id); // #84 P2.1 (the binding and authority registries are evicted by the v2 adapter)
|
|
3158
3218
|
forgetWorkingSet(id); // cross-repo P1.4: the orchestrator's bound repository locations
|
|
3219
|
+
forgetAnswers(id); // #108 slice 4: its deduplicated answers
|
|
3159
3220
|
// 2.4.2b: a deleted orchestrator's handles, tombstones and lineage records go with it.
|
|
3160
3221
|
// 2.4.5: so do its background requests and late notices; its run in flight is aborted.
|
|
3161
3222
|
background?.forgetSession(id);
|
|
@@ -3165,6 +3226,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3165
3226
|
// QA-SYNC1-14: its calls' arguments and routed-role copies go too.
|
|
3166
3227
|
forgetSessionTaskArgs(id);
|
|
3167
3228
|
releasePendingClaimOf(id);
|
|
3229
|
+
forgetHandles(id); // #108 slice 3: its router_git_diff handles
|
|
3168
3230
|
}
|
|
3169
3231
|
} catch {
|
|
3170
3232
|
// best-effort: cleanup must never crash a real session
|
|
@@ -3840,6 +3902,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3840
3902
|
extra?: {
|
|
3841
3903
|
delta?: DispatchDelta; dod?: ReturnType<typeof buildDelegationDoD>; graderParentSessionID?: string; workRoot?: string;
|
|
3842
3904
|
unattributedWriters?: readonly string[];
|
|
3905
|
+
/**
|
|
3906
|
+
* #191: the finish of a background completion (`FinishInput.mode` background, held or not). Under a lease gate scoped to held
|
|
3907
|
+
* results (`routing.background.mode: "off"`) only such a gate waits for file leases (`buildGateDeps` `backgroundFinish`).
|
|
3908
|
+
*/
|
|
3909
|
+
backgroundFinish?: true;
|
|
3843
3910
|
/** QA-SYNC1-3: the journaled dispatch-time head of a restored held entry; the branch check compares it as before. */
|
|
3844
3911
|
restoredHead?: DispatchHeadState;
|
|
3845
3912
|
/**
|
|
@@ -4009,7 +4076,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4009
4076
|
const completedFailures: string[] = [];
|
|
4010
4077
|
// Keep the native grader unparented on the backend; only depth tracking uses its caller. DF-1-3 (v2 finish API only,
|
|
4011
4078
|
// absent on the v1 after-hook): a background completion names the parent whose retained context launches the grader.
|
|
4012
|
-
const gateDeps = buildGateDeps(extra?.graderParentSessionID, gateGraderSessions, verification, gateDeadline, false, orchestratorSessionID || null
|
|
4079
|
+
const gateDeps = buildGateDeps(extra?.graderParentSessionID, gateGraderSessions, verification, gateDeadline, false, orchestratorSessionID || null,
|
|
4080
|
+
undefined, extra?.backgroundFinish === true);
|
|
4013
4081
|
gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
|
|
4014
4082
|
// #84 QA-G-B-2-1: a carried acceptance never passes on a testsPass/lintClean that ran no process.
|
|
4015
4083
|
if (carriedRole) gateDeps.deterministic.noAffectedUnverifiable = CARRIED_NO_PROCESS_REASON;
|
|
@@ -4231,6 +4299,16 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4231
4299
|
const heldTexts = new Map<string, { readonly sessionID: string; readonly text: string; readonly post?: HeldPost }>();
|
|
4232
4300
|
/** = MAX_HOLDS_GLOBAL (background.ts): there are never more live holds than this. */
|
|
4233
4301
|
const MAX_HELD_TEXTS = 10_000;
|
|
4302
|
+
// Live registrations only, never journal-restored entries. Keep bounded tombstones after pending-entry eviction so a late
|
|
4303
|
+
// duplicate cannot gate or post again merely because its entry was forgotten. Oldest handles leave at the same global bound.
|
|
4304
|
+
const registeredLiveHolds = new Set<string>();
|
|
4305
|
+
function rememberLiveHold(handle: string): void {
|
|
4306
|
+
registeredLiveHolds.add(handle);
|
|
4307
|
+
if (registeredLiveHolds.size > MAX_HELD_TEXTS) {
|
|
4308
|
+
const oldest = registeredLiveHolds.values().next();
|
|
4309
|
+
if (!oldest.done) registeredLiveHolds.delete(oldest.value);
|
|
4310
|
+
}
|
|
4311
|
+
}
|
|
4234
4312
|
function rememberHeldText(handle: string, sessionID: string, text: string, post?: HeldPost): void {
|
|
4235
4313
|
heldTexts.delete(handle);
|
|
4236
4314
|
heldTexts.set(handle, { sessionID, text, ...(post === undefined ? {} : { post }) });
|
|
@@ -4348,9 +4426,23 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4348
4426
|
const HELD_HEAD_READ_MS = 2_000;
|
|
4349
4427
|
/** QA-2.1-31: handles whose restored pending entry the adapter settled after posting the verdict itself (no second post). */
|
|
4350
4428
|
const directlySettled = new Set<string>();
|
|
4351
|
-
type
|
|
4429
|
+
type HeldClaimResult = ReturnType<typeof pending.markVerifying>;
|
|
4430
|
+
type HeldClaim = Extract<HeldClaimResult, { kind: "claimed" }>;
|
|
4352
4431
|
type HeldSettlement = Parameters<HeldClaim["settle"]>[0];
|
|
4353
4432
|
type HeldScratch = { output: string; title: string; metadata: Record<string, unknown> };
|
|
4433
|
+
/**
|
|
4434
|
+
* #191: the result text a held verdict carries (the finish API is v2-only): the child's own final text, verbatim, then the
|
|
4435
|
+
* lines the router added after the `task` frame the gate read (`taskOutputText`) and `line`, in v2 vocabulary
|
|
4436
|
+
* (`v2Instructions`, as the adapter translates a foreground result). Neither the frame (`task_id:`, `<task_result>`) nor a v1
|
|
4437
|
+
* tool name (`Task(subagent_type=…)`) reaches the parent.
|
|
4438
|
+
*/
|
|
4439
|
+
function heldResultText(fin: FinishInput, scratch: HeldScratch, line?: string): string {
|
|
4440
|
+
const withLine = (text: string): string => (line === undefined ? text : `${text.trimEnd()}\n\n${line}`);
|
|
4441
|
+
const frame = taskOutputText(fin.childSessionID, fin.outputText);
|
|
4442
|
+
// finishDispatch only appends to the frame; should that ever change, every router line is kept (translated), none dropped.
|
|
4443
|
+
if (!scratch.output.startsWith(frame)) return v2Instructions(withLine(scratch.output));
|
|
4444
|
+
return fin.outputText + v2Instructions(withLine(scratch.output.slice(frame.length)));
|
|
4445
|
+
}
|
|
4354
4446
|
/**
|
|
4355
4447
|
* QA-DF1-16: what a held entry settles with: a gate verdict as the gate reached it (method, reasons, caveats, notes), anything
|
|
4356
4448
|
* else as `heldVerification`. QA-DF1-29: its `pass`/`outcome` are those of the posted tag (the gate's decision, `accepted`, which
|
|
@@ -4432,27 +4524,54 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4432
4524
|
} | undefined,
|
|
4433
4525
|
preClaim: HeldClaim | undefined,
|
|
4434
4526
|
): void {
|
|
4435
|
-
|
|
4436
|
-
|
|
4437
|
-
|
|
4438
|
-
const
|
|
4439
|
-
|
|
4440
|
-
|
|
4441
|
-
|
|
4442
|
-
const reason = held.reasons[0];
|
|
4443
|
-
if (claim.kind !== "claimed") return postHeldDirect(handle, held.verdict, text, reason);
|
|
4444
|
-
rememberHeldText(handle, fin.parentSessionID, text, { verdict: held.verdict, ...(reason !== undefined ? { reason } : {}) });
|
|
4445
|
-
// QA-DF1-16: a gate verdict settles as the gate reached it (method, outcome, reasons, caveats, notes).
|
|
4446
|
-
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-settle", source: "held-gate", handle,
|
|
4527
|
+
/** #193 (2.1-r3-c): the settlement of `settleHeld` could not be built; the claim settles UNVERIFIABLE with the scrubbed error. */
|
|
4528
|
+
const settleHeldUnavailable = (claim: HeldClaimResult | undefined, error: unknown): Promise<void> | undefined => {
|
|
4529
|
+
const reason = `verification unavailable: ${describeError(error)}`;
|
|
4530
|
+
const text = heldResultText(fin, scratch, `[router] UNVERIFIABLE — ${reason}`);
|
|
4531
|
+
if (claim?.kind !== "claimed") return postHeldDirect(handle, "UNVERIFIABLE", text, reason);
|
|
4532
|
+
rememberHeldText(handle, fin.parentSessionID, text, { verdict: "UNVERIFIABLE", reason });
|
|
4533
|
+
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-settle", source: "held-error", handle,
|
|
4447
4534
|
parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
|
|
4448
|
-
claim.settle(
|
|
4449
|
-
|
|
4450
|
-
|
|
4535
|
+
claim.settle(heldVerification("UNVERIFIABLE", [reason]));
|
|
4536
|
+
return claim.entry.hold === undefined ? postHeldDirect(handle, "UNVERIFIABLE", text, reason) : undefined;
|
|
4537
|
+
};
|
|
4538
|
+
const settleHeld = (outcome: FinishOutcome): Promise<void> | undefined => {
|
|
4539
|
+
// #193 (2.1-r3-c): a claim settles exactly once. A step before its settle that throws settles it UNVERIFIABLE instead
|
|
4540
|
+
// of leaving it `verifying` (router_verify would join that run until its deadline); a settle that threw is not repeated.
|
|
4541
|
+
let claim: HeldClaimResult | undefined = preClaim;
|
|
4542
|
+
let settleCalled = false;
|
|
4543
|
+
try {
|
|
4544
|
+
// QA-SYNC1-14: the held finish settled; its call's arguments and routed-role copy are no longer needed.
|
|
4545
|
+
forgetTaskArgs(fin.callID);
|
|
4546
|
+
claim ??= pending.markVerifying(fin.parentSessionID, handle);
|
|
4547
|
+
// QA-2.1-1: only a gate verdict is a verdict; none/deferred/skipped/error post UNVERIFIABLE with their reason.
|
|
4548
|
+
const held = heldOutcomeOf(outcome);
|
|
4549
|
+
const text = heldResultText(fin, scratch, held.line);
|
|
4550
|
+
const reason = held.reasons[0];
|
|
4551
|
+
if (claim.kind !== "claimed") return postHeldDirect(handle, held.verdict, text, reason);
|
|
4552
|
+
rememberHeldText(handle, fin.parentSessionID, text, { verdict: held.verdict, ...(reason !== undefined ? { reason } : {}) });
|
|
4553
|
+
// QA-DF1-16: a gate verdict settles as the gate reached it (method, outcome, reasons, caveats, notes).
|
|
4554
|
+
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-settle", source: "held-gate", handle,
|
|
4555
|
+
parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
|
|
4556
|
+
const settlement = heldSettlementOf(outcome, held);
|
|
4557
|
+
settleCalled = true;
|
|
4558
|
+
claim.settle(settlement);
|
|
4559
|
+
// onVerdict posts only for an entry that carries its hold.
|
|
4560
|
+
return claim.entry.hold === undefined ? postHeldDirect(handle, held.verdict, text, reason) : undefined;
|
|
4561
|
+
} catch (error) {
|
|
4562
|
+
// The settle itself (or what followed it) threw: never a second settle; trackHeldGate logs the error.
|
|
4563
|
+
if (settleCalled) throw error;
|
|
4564
|
+
logger.warn("[router] held verification could not be settled; settling UNVERIFIABLE", { handle, error: describeError(error) });
|
|
4565
|
+
return settleHeldUnavailable(claim, error);
|
|
4566
|
+
}
|
|
4451
4567
|
};
|
|
4452
4568
|
// DF-1-3: the held gate's grader launches from the orchestrator's retained context too (C14 launcher A).
|
|
4453
4569
|
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-enqueue", source: "held-gate", handle,
|
|
4454
4570
|
parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
|
|
4455
|
-
|
|
4571
|
+
// #191: a background finish, so a lease gate scoped to held results (`leaseGateScope: "held"`) applies to its gate.
|
|
4572
|
+
trackHeldGate(finishDispatch(callInput, scratch, undefined, {
|
|
4573
|
+
...extra, graderParentSessionID: fin.parentSessionID, ...(fin.mode === "background" ? { backgroundFinish: true as const } : {}),
|
|
4574
|
+
}).then(settleHeld, (error: unknown) => {
|
|
4456
4575
|
logger.warn("[router] held verification failed", { handle, error: describeError(error) });
|
|
4457
4576
|
return settleHeld({ kind: "error", reason: `verification unavailable: ${scrubText(String(error))}` });
|
|
4458
4577
|
}));
|
|
@@ -4477,7 +4596,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4477
4596
|
const verdict = heldVerdictKind(claim.result.verdict.outcome, claim.result.verdict.pass);
|
|
4478
4597
|
const reason = claim.result.verdict.reasons[0];
|
|
4479
4598
|
const line = `[router] ${verdict}${reason === undefined ? "" : ` — ${scrubText(reason)}`}`;
|
|
4480
|
-
trackHeldGate(postHeldDirect(handle, verdict,
|
|
4599
|
+
trackHeldGate(postHeldDirect(handle, verdict, heldResultText(fin, scratch, line), reason));
|
|
4481
4600
|
return heldResult;
|
|
4482
4601
|
}
|
|
4483
4602
|
if (claim.kind === "joined") {
|
|
@@ -4492,7 +4611,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4492
4611
|
const description = typeof args.description === "string" ? args.description : undefined;
|
|
4493
4612
|
const dod = entry.dod ?? (prompt === undefined ? undefined : buildDelegationDoD({ prompt, description }));
|
|
4494
4613
|
const settleLost = (reason: string): FinishResult => {
|
|
4495
|
-
const text =
|
|
4614
|
+
const text = heldResultText(fin, scratch, `[router] UNVERIFIABLE — ${reason}`);
|
|
4496
4615
|
rememberHeldText(handle, fin.parentSessionID, text);
|
|
4497
4616
|
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-settle", source: "held-lost", handle,
|
|
4498
4617
|
parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
|
|
@@ -4656,10 +4775,39 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4656
4775
|
forgetTaskArgs(fin.callID);
|
|
4657
4776
|
return { outputText: fin.outputText, suffix: "", verification: { kind: "none" }, metadata: {} };
|
|
4658
4777
|
}
|
|
4659
|
-
|
|
4778
|
+
const priorHold = fin.heldHandle === undefined ? undefined : pending.get(fin.parentSessionID, fin.heldHandle);
|
|
4779
|
+
// A journal-restored held entry can lack its optional dispatch. It is not a live registration of this instance and
|
|
4780
|
+
// must settle through recovery, rather than silently joining a gate that this process never started.
|
|
4781
|
+
const restoredWithoutDispatch = fin.heldHandle !== undefined && !registeredLiveHolds.has(fin.heldHandle)
|
|
4782
|
+
&& !taskArgsByCall.has(fin.callID) && priorHold?.kind === "found"
|
|
4783
|
+
&& priorHold.entry.dispatchID === fin.callID && priorHold.entry.producerSessionID === fin.childSessionID
|
|
4784
|
+
&& priorHold.entry.hold?.callID === fin.callID && priorHold.entry.hold.childSessionID === fin.childSessionID;
|
|
4785
|
+
if (fin.restored !== undefined || restoredWithoutDispatch) {
|
|
4660
4786
|
const restored = finishRestored(fin, args, scratch);
|
|
4661
4787
|
if (restored !== undefined) return restored;
|
|
4662
4788
|
}
|
|
4789
|
+
// A repeated live completion must not re-gate an already registered hold: its first gate owns the verdict, even while
|
|
4790
|
+
// running. In particular, that gate may already have consumed the call's arguments and change-set records.
|
|
4791
|
+
const existingLiveHold = (): FinishResult | undefined => {
|
|
4792
|
+
if (fin.restored !== undefined || fin.heldHandle === undefined || !registeredLiveHolds.has(fin.heldHandle)) return undefined;
|
|
4793
|
+
return { outputText: fin.outputText, suffix: "", verification: { kind: "held", handle: fin.heldHandle }, metadata: {} };
|
|
4794
|
+
};
|
|
4795
|
+
const existing = existingLiveHold();
|
|
4796
|
+
if (existing !== undefined) return existing;
|
|
4797
|
+
// No dispatch inputs is not evidence of a read-only delegation. Never infer acceptance (or a pass) from the empty
|
|
4798
|
+
// fallback above when a live call's inputs were consumed or evicted. Restored calls retain their own fail-closed path.
|
|
4799
|
+
if (fin.restored === undefined && !taskArgsByCall.has(fin.callID) && verificationModeOfArgs(args) !== "none") {
|
|
4800
|
+
changedFileStore.clear(`task:${fin.parentSessionID}:${fin.callID}`);
|
|
4801
|
+
changedFileStore.clear(fin.childSessionID);
|
|
4802
|
+
const reason = "dispatch inputs were lost; acceptance and changes could not be evaluated";
|
|
4803
|
+
const suffix = `\n\n[router] UNVERIFIABLE — ${reason}`;
|
|
4804
|
+
if (fin.heldHandle !== undefined) {
|
|
4805
|
+
trackHeldGate(postHeldDirect(fin.heldHandle, "UNVERIFIABLE", fin.outputText + suffix, reason));
|
|
4806
|
+
pending.releaseHandle(fin.heldHandle);
|
|
4807
|
+
return { outputText: fin.outputText, suffix: "", verification: { kind: "held", handle: fin.heldHandle }, metadata: {} };
|
|
4808
|
+
}
|
|
4809
|
+
return { outputText: fin.outputText + suffix, suffix, verification: { kind: "required", verdict: "UNVERIFIABLE" }, metadata: {} };
|
|
4810
|
+
}
|
|
4663
4811
|
if (fin.heldHandle !== undefined) {
|
|
4664
4812
|
const handle = fin.heldHandle;
|
|
4665
4813
|
const dod = buildDelegationDoD({
|
|
@@ -4673,6 +4821,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4673
4821
|
const headRead = changedFileStore.baselineHead(dispatchKey);
|
|
4674
4822
|
const startHead = headRead === undefined ? undefined
|
|
4675
4823
|
: await withTimeout(headRead, HELD_HEAD_READ_MS, "dispatch head").catch(() => undefined);
|
|
4824
|
+
// Another finish may have registered this hold while the head read yielded. Registration and gate launch below are
|
|
4825
|
+
// synchronous, so only the first finish after this check owns them.
|
|
4826
|
+
const registered = existingLiveHold();
|
|
4827
|
+
if (registered !== undefined) return registered;
|
|
4676
4828
|
// The head the gate compares the tree with (as prepareVerification: the head read, else the dispatch snapshot's head and
|
|
4677
4829
|
// branch) is journaled as plain data, so the gate re-run after a restart runs the same branch check. A head reader whose
|
|
4678
4830
|
// read gave nothing (the gate fails closed on it too) is journaled as the fact alone (`hadHead`, restored as headLost).
|
|
@@ -4705,7 +4857,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4705
4857
|
...(heldHead ? { heldHead: true as const } : {}),
|
|
4706
4858
|
...(dispatchHead !== undefined ? { dispatchHead } : {}),
|
|
4707
4859
|
});
|
|
4708
|
-
if (!reg.ok)
|
|
4860
|
+
if (!reg.ok) {
|
|
4861
|
+
logger.warn("[router] held dispatch not registered", { code: reg.code, detail: reg.detail });
|
|
4862
|
+
// The gate below posts the verdict directly; a reservation left behind would make router_verify answer `held` for hours.
|
|
4863
|
+
pending.releaseHandle(handle);
|
|
4864
|
+
} else rememberLiveHold(handle);
|
|
4709
4865
|
runHeldGate(fin, handle, callInput, scratch, delta === undefined ? undefined : { delta }, undefined);
|
|
4710
4866
|
return { outputText: fin.outputText, suffix: "", verification: { kind: "held", handle }, metadata: {} };
|
|
4711
4867
|
}
|
|
@@ -4715,6 +4871,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4715
4871
|
const outcome = await finishDispatch(callInput, scratch, undefined, {
|
|
4716
4872
|
...(delta === undefined ? {} : { delta }), graderParentSessionID: fin.parentSessionID,
|
|
4717
4873
|
...(restoredWorkRoot === undefined ? {} : { workRoot: restoredWorkRoot }),
|
|
4874
|
+
// #191: a background finish that is not held (holding unavailable, a failed journal or hold write, the hold limit) still
|
|
4875
|
+
// waits for file leases under a lease gate scoped to held results.
|
|
4876
|
+
...(fin.mode === "background" ? { backgroundFinish: true as const } : {}),
|
|
4718
4877
|
});
|
|
4719
4878
|
const suffix = suffixOf();
|
|
4720
4879
|
const verification: FinishResult["verification"] =
|
|
@@ -4725,9 +4884,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4725
4884
|
return { outputText: fin.outputText + suffix, suffix, verification, metadata: {} };
|
|
4726
4885
|
},
|
|
4727
4886
|
};
|
|
4728
|
-
const attachFinish: FinishAttach = ({ held, leaseGate }) => {
|
|
4887
|
+
const attachFinish: FinishAttach = ({ held, leaseGate, leaseGateScope }) => {
|
|
4729
4888
|
heldSink = held;
|
|
4730
4889
|
leaseGateRef = leaseGate;
|
|
4890
|
+
leaseGateHeldOnly = leaseGateScope === "held";
|
|
4731
4891
|
return finishApi;
|
|
4732
4892
|
};
|
|
4733
4893
|
|