opencode-model-router 2.10.0 → 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 +306 -0
- package/README.md +3 -2
- package/package.json +8 -1
- package/src/compat/background.ts +5 -0
- package/src/compat/session-lookup.ts +21 -0
- package/src/compat/v2-hooks.ts +256 -88
- package/src/compat/v2-observations.ts +1 -0
- package/src/compat/v2-vocabulary.ts +14 -0
- package/src/executor/create.ts +3 -0
- package/src/executor/git.ts +110 -26
- package/src/executor/integrate/checks.ts +29 -11
- 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 +1010 -226
- 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 +107 -27
- package/src/router/answer-dedup.ts +198 -0
- package/src/router/common-dir.ts +241 -0
- package/src/router/config.ts +71 -12
- package/src/router/diff-handles.ts +322 -0
- package/src/router/diff-summary.ts +318 -0
- package/src/router/git-metadata-guard.ts +144 -7
- package/src/router/git-tools.ts +930 -73
- package/src/router/role-agents.ts +100 -36
- package/src/router/run-summary.ts +253 -0
- package/src/router/run-tools.ts +145 -23
- package/src/router/sessions.ts +14 -1
- package/src/routing/classify/rules.ts +93 -14
- package/src/routing/wire/hint.ts +9 -2
- package/src/v2.ts +3 -1
- package/src/verify/exec.ts +454 -2
- package/src/verify/plan-task.ts +86 -26
- package/src/verify/runner.ts +14 -6
- package/src/verify/tree.ts +5 -1
- package/src/verify/types.ts +44 -0
- package/src/verify/wiring.ts +87 -10
package/src/index.ts
CHANGED
|
@@ -2,6 +2,7 @@ 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
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,7 @@ 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";
|
|
28
30
|
import { gitMetadataUnknownDirectoryRefusal, gitMetadataWriteRefusal } from "./router/git-metadata-guard";
|
|
29
31
|
import { isReadOnlyTier, legacyReadOnlyTools, mergePermissions, readOnlyPermissions } from "./router/read-only";
|
|
30
32
|
import { buildPluginAgentDefinition, mergeHostAgentEntry, pluginAgentMarker } from "./router/plugin-agents";
|
|
@@ -71,6 +73,7 @@ import {
|
|
|
71
73
|
} from "./router/protocol";
|
|
72
74
|
import { resolveRoles, type RoleSpec } from "./router/roles";
|
|
73
75
|
import { routerRunTool, type RunRecord } from "./router/run-tools";
|
|
76
|
+
import { forgetAnswers, noteToolCall } from "./router/answer-dedup";
|
|
74
77
|
import type { WorkRootAnswer } from "./router/git-tools";
|
|
75
78
|
import { GUARD_CUMULATIVE_MULTIPLIER, roleGuardProfile, type GuardProfile } from "./router/guard-profile";
|
|
76
79
|
import { currentBinding } from "./routing/roles/binding";
|
|
@@ -96,6 +99,7 @@ import { countUnknownBindings } from "./routing/outcomes/stats";
|
|
|
96
99
|
import { roleAgentSteps } from "./router/role-agents";
|
|
97
100
|
import type { HostBudgetObservation } from "./compat/v2-hooks";
|
|
98
101
|
import { ROUTER_TURN_STATE_ATTACH, TURN_STATE_ROOT, type TurnStateRegistry } from "./compat/turn-state";
|
|
102
|
+
import { v2Instructions } from "./compat/v2-vocabulary";
|
|
99
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";
|
|
100
104
|
import type { DispatchDelta } from "./verify/dispatch";
|
|
101
105
|
import { configAsWritten, configuredV2OnlyKeys, setConfigNoticeHost } from "./router/config";
|
|
@@ -133,6 +137,7 @@ import {
|
|
|
133
137
|
DEFAULT_TIER_CAPS,
|
|
134
138
|
READ_ONLY_TOOLS,
|
|
135
139
|
awaitExecutionEnd,
|
|
140
|
+
isHandleExpansion,
|
|
136
141
|
lastStepContext,
|
|
137
142
|
} from "./router/sessions";
|
|
138
143
|
import type { Cap, SubagentState } from "./router/sessions";
|
|
@@ -527,6 +532,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
527
532
|
* The lookup behind resolveIsRootSession: true (no parentID), false (a parentID), or undefined
|
|
528
533
|
* when it is not known (the lookup failed, or failed recently and is throttled). QA-2.4-2 treats
|
|
529
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.
|
|
530
538
|
*/
|
|
531
539
|
const lookupRootSession = async (sessionID: string): Promise<boolean | undefined> => {
|
|
532
540
|
const memo = sessionRootMemo.get(sessionID);
|
|
@@ -540,7 +548,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
540
548
|
return undefined;
|
|
541
549
|
}
|
|
542
550
|
try {
|
|
543
|
-
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;
|
|
544
553
|
if (!res || (res as { error?: unknown }).error || !res.data) {
|
|
545
554
|
throw new Error("session.get returned no session data");
|
|
546
555
|
}
|
|
@@ -688,6 +697,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
688
697
|
/** The role of a session: what its tool hooks named, else what the dispatch registry recorded for it. */
|
|
689
698
|
const roleOfSession = (sessionID: unknown): RoleSpec | undefined => typeof sessionID !== "string" || sessionID === ""
|
|
690
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);
|
|
691
703
|
/**
|
|
692
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
|
|
693
705
|
* adapter's `execute.before` before any tool of the child runs). Not a role session → `{ role: false }` (git keeps today's
|
|
@@ -1191,6 +1203,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1191
1203
|
}
|
|
1192
1204
|
/** Late-bound: the lease guard exists only once the v2 adapter attaches (FinishAttach `leaseGate`); the wiring reads it per use. */
|
|
1193
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;
|
|
1194
1211
|
/** Phase 5.1 D11 (v2 only): the plan-task gates' own holders, exempt from the lease wait in their own slot tree. */
|
|
1195
1212
|
const planTaskLeaseExemptions = createLeaseSelfExemptions((root) => planTreeKey(root));
|
|
1196
1213
|
const {
|
|
@@ -1228,6 +1245,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1228
1245
|
return { waitedMs: wait.waitedMs, holders: wait.holders, fileCount: wait.holders.length === 0 ? 0 : fileCount };
|
|
1229
1246
|
},
|
|
1230
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),
|
|
1231
1250
|
}),
|
|
1232
1251
|
});
|
|
1233
1252
|
// 2.1.5b: sweep reference dirs a crashed instance left behind. Fire-and-forget; never throws.
|
|
@@ -1976,9 +1995,12 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1976
1995
|
: `[router_plan] ${planCallerRefusal}`,
|
|
1977
1996
|
} } : {}),
|
|
1978
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).
|
|
1979
2001
|
...gitTools(rolesAtStart ? {
|
|
1980
2002
|
resolveWorkRoot: resolveWorkRootFor("router_git"), ...(ctx.directory ? { dispatchRepository: ctx.directory } : {}),
|
|
1981
|
-
...(crossRepoAtStart ? { resolveRoot: resolveGitRootFor } : {}),
|
|
2003
|
+
...(crossRepoAtStart ? { resolveRoot: resolveGitRootFor } : {}), summarizeDiffs: true, handles: true, dedupe: true,
|
|
1982
2004
|
} : {}),
|
|
1983
2005
|
// #84 P2.1 (handoffs 11, 13): roles mode only. `router_run` runs in the bound work root; each run feeds the `run` signal.
|
|
1984
2006
|
...(rolesAtStart ? {
|
|
@@ -1986,6 +2008,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1986
2008
|
config: () => resolveRolesRouting(cfg, "v2").run,
|
|
1987
2009
|
resolveWorkRoot: resolveWorkRootFor("router_run"),
|
|
1988
2010
|
recordRun: (run) => pushBounded(roleRuns, run.sessionID, run),
|
|
2011
|
+
dedupe: true,
|
|
1989
2012
|
}),
|
|
1990
2013
|
} : {}),
|
|
1991
2014
|
// #84 P2.1: the authority ladder (P1.6) for dynamic roles (`general`).
|
|
@@ -3014,7 +3037,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3014
3037
|
if (res.block) {
|
|
3015
3038
|
trajectoryStore.recordToolEvent(sid, {
|
|
3016
3039
|
tool: input.tool,
|
|
3017
|
-
readOnly:
|
|
3040
|
+
readOnly: roleReadOnly(sid, input.tool, output?.args),
|
|
3018
3041
|
blocked: true,
|
|
3019
3042
|
selfScript: res.guard === "anti_self_script",
|
|
3020
3043
|
});
|
|
@@ -3031,7 +3054,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3031
3054
|
// treats them as ground truth rather than advisory system noise.
|
|
3032
3055
|
// -----------------------------------------------------------------------
|
|
3033
3056
|
"tool.execute.after": async (input: any, output: any) => {
|
|
3034
|
-
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
|
+
}
|
|
3035
3061
|
if (input?.tool === "grep" && typeof output.output === "string") {
|
|
3036
3062
|
const tier = input.agent ?? pluginAgentSessions.get(input.sessionID) ?? sessionStore.getTier(input.sessionID);
|
|
3037
3063
|
const definition = tier && getActiveTiers(cfg)[tier];
|
|
@@ -3043,7 +3069,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3043
3069
|
noteBypassedRoleCall(input?.sessionID); // QA-P21-1-7
|
|
3044
3070
|
return;
|
|
3045
3071
|
}
|
|
3046
|
-
|
|
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 });
|
|
3047
3074
|
|
|
3048
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
|
|
3049
3076
|
// `task` return feeds the return/run signals, read BEFORE any router note is put in front of the child's text.
|
|
@@ -3104,7 +3131,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3104
3131
|
if (sid && sessionStore.isSubagent(sid) && typeof input?.tool === "string") {
|
|
3105
3132
|
trajectoryStore.recordToolEvent(sid, {
|
|
3106
3133
|
tool: input.tool,
|
|
3107
|
-
readOnly:
|
|
3134
|
+
readOnly: roleReadOnly(sid, input.tool, input?.args),
|
|
3108
3135
|
});
|
|
3109
3136
|
try {
|
|
3110
3137
|
const profile = roleGuardProfileOf(sid, input?.agent); // handoff 27, as in the before-hook
|
|
@@ -3189,6 +3216,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3189
3216
|
lateBuffer?.forget(id);
|
|
3190
3217
|
forgetRoleSession(id); // #84 P2.1 (the binding and authority registries are evicted by the v2 adapter)
|
|
3191
3218
|
forgetWorkingSet(id); // cross-repo P1.4: the orchestrator's bound repository locations
|
|
3219
|
+
forgetAnswers(id); // #108 slice 4: its deduplicated answers
|
|
3192
3220
|
// 2.4.2b: a deleted orchestrator's handles, tombstones and lineage records go with it.
|
|
3193
3221
|
// 2.4.5: so do its background requests and late notices; its run in flight is aborted.
|
|
3194
3222
|
background?.forgetSession(id);
|
|
@@ -3198,6 +3226,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3198
3226
|
// QA-SYNC1-14: its calls' arguments and routed-role copies go too.
|
|
3199
3227
|
forgetSessionTaskArgs(id);
|
|
3200
3228
|
releasePendingClaimOf(id);
|
|
3229
|
+
forgetHandles(id); // #108 slice 3: its router_git_diff handles
|
|
3201
3230
|
}
|
|
3202
3231
|
} catch {
|
|
3203
3232
|
// best-effort: cleanup must never crash a real session
|
|
@@ -3873,6 +3902,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3873
3902
|
extra?: {
|
|
3874
3903
|
delta?: DispatchDelta; dod?: ReturnType<typeof buildDelegationDoD>; graderParentSessionID?: string; workRoot?: string;
|
|
3875
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;
|
|
3876
3910
|
/** QA-SYNC1-3: the journaled dispatch-time head of a restored held entry; the branch check compares it as before. */
|
|
3877
3911
|
restoredHead?: DispatchHeadState;
|
|
3878
3912
|
/**
|
|
@@ -4042,7 +4076,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4042
4076
|
const completedFailures: string[] = [];
|
|
4043
4077
|
// Keep the native grader unparented on the backend; only depth tracking uses its caller. DF-1-3 (v2 finish API only,
|
|
4044
4078
|
// absent on the v1 after-hook): a background completion names the parent whose retained context launches the grader.
|
|
4045
|
-
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);
|
|
4046
4081
|
gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
|
|
4047
4082
|
// #84 QA-G-B-2-1: a carried acceptance never passes on a testsPass/lintClean that ran no process.
|
|
4048
4083
|
if (carriedRole) gateDeps.deterministic.noAffectedUnverifiable = CARRIED_NO_PROCESS_REASON;
|
|
@@ -4391,9 +4426,23 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4391
4426
|
const HELD_HEAD_READ_MS = 2_000;
|
|
4392
4427
|
/** QA-2.1-31: handles whose restored pending entry the adapter settled after posting the verdict itself (no second post). */
|
|
4393
4428
|
const directlySettled = new Set<string>();
|
|
4394
|
-
type
|
|
4429
|
+
type HeldClaimResult = ReturnType<typeof pending.markVerifying>;
|
|
4430
|
+
type HeldClaim = Extract<HeldClaimResult, { kind: "claimed" }>;
|
|
4395
4431
|
type HeldSettlement = Parameters<HeldClaim["settle"]>[0];
|
|
4396
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
|
+
}
|
|
4397
4446
|
/**
|
|
4398
4447
|
* QA-DF1-16: what a held entry settles with: a gate verdict as the gate reached it (method, reasons, caveats, notes), anything
|
|
4399
4448
|
* else as `heldVerification`. QA-DF1-29: its `pass`/`outcome` are those of the posted tag (the gate's decision, `accepted`, which
|
|
@@ -4475,27 +4524,54 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4475
4524
|
} | undefined,
|
|
4476
4525
|
preClaim: HeldClaim | undefined,
|
|
4477
4526
|
): void {
|
|
4478
|
-
|
|
4479
|
-
|
|
4480
|
-
|
|
4481
|
-
const
|
|
4482
|
-
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
const reason = held.reasons[0];
|
|
4486
|
-
if (claim.kind !== "claimed") return postHeldDirect(handle, held.verdict, text, reason);
|
|
4487
|
-
rememberHeldText(handle, fin.parentSessionID, text, { verdict: held.verdict, ...(reason !== undefined ? { reason } : {}) });
|
|
4488
|
-
// QA-DF1-16: a gate verdict settles as the gate reached it (method, outcome, reasons, caveats, notes).
|
|
4489
|
-
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,
|
|
4490
4534
|
parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
|
|
4491
|
-
claim.settle(
|
|
4492
|
-
|
|
4493
|
-
|
|
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
|
+
}
|
|
4494
4567
|
};
|
|
4495
4568
|
// DF-1-3: the held gate's grader launches from the orchestrator's retained context too (C14 launcher A).
|
|
4496
4569
|
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-enqueue", source: "held-gate", handle,
|
|
4497
4570
|
parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
|
|
4498
|
-
|
|
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) => {
|
|
4499
4575
|
logger.warn("[router] held verification failed", { handle, error: describeError(error) });
|
|
4500
4576
|
return settleHeld({ kind: "error", reason: `verification unavailable: ${scrubText(String(error))}` });
|
|
4501
4577
|
}));
|
|
@@ -4520,7 +4596,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4520
4596
|
const verdict = heldVerdictKind(claim.result.verdict.outcome, claim.result.verdict.pass);
|
|
4521
4597
|
const reason = claim.result.verdict.reasons[0];
|
|
4522
4598
|
const line = `[router] ${verdict}${reason === undefined ? "" : ` — ${scrubText(reason)}`}`;
|
|
4523
|
-
trackHeldGate(postHeldDirect(handle, verdict,
|
|
4599
|
+
trackHeldGate(postHeldDirect(handle, verdict, heldResultText(fin, scratch, line), reason));
|
|
4524
4600
|
return heldResult;
|
|
4525
4601
|
}
|
|
4526
4602
|
if (claim.kind === "joined") {
|
|
@@ -4535,7 +4611,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4535
4611
|
const description = typeof args.description === "string" ? args.description : undefined;
|
|
4536
4612
|
const dod = entry.dod ?? (prompt === undefined ? undefined : buildDelegationDoD({ prompt, description }));
|
|
4537
4613
|
const settleLost = (reason: string): FinishResult => {
|
|
4538
|
-
const text =
|
|
4614
|
+
const text = heldResultText(fin, scratch, `[router] UNVERIFIABLE — ${reason}`);
|
|
4539
4615
|
rememberHeldText(handle, fin.parentSessionID, text);
|
|
4540
4616
|
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-settle", source: "held-lost", handle,
|
|
4541
4617
|
parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
|
|
@@ -4795,6 +4871,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4795
4871
|
const outcome = await finishDispatch(callInput, scratch, undefined, {
|
|
4796
4872
|
...(delta === undefined ? {} : { delta }), graderParentSessionID: fin.parentSessionID,
|
|
4797
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 } : {}),
|
|
4798
4877
|
});
|
|
4799
4878
|
const suffix = suffixOf();
|
|
4800
4879
|
const verification: FinishResult["verification"] =
|
|
@@ -4805,9 +4884,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4805
4884
|
return { outputText: fin.outputText + suffix, suffix, verification, metadata: {} };
|
|
4806
4885
|
},
|
|
4807
4886
|
};
|
|
4808
|
-
const attachFinish: FinishAttach = ({ held, leaseGate }) => {
|
|
4887
|
+
const attachFinish: FinishAttach = ({ held, leaseGate, leaseGateScope }) => {
|
|
4809
4888
|
heldSink = held;
|
|
4810
4889
|
leaseGateRef = leaseGate;
|
|
4890
|
+
leaseGateHeldOnly = leaseGateScope === "held";
|
|
4811
4891
|
return finishApi;
|
|
4812
4892
|
};
|
|
4813
4893
|
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #108 slice 4 (OpenCode v2 roles mode, role sessions only): an identical repeated answer is replaced by a short stub.
|
|
3
|
+
*
|
|
4
|
+
* `router_git_diff`, `router_git_status`, `router_git_show`, `router_git_log` and `router_run` remember, per call key, the
|
|
5
|
+
* SHA-256 and byte length of the last answer they gave in full. When the same key gets the same answer again, the tool returns
|
|
6
|
+
* a stub naming the earlier call instead; `force: true` returns the full answer (byte-identical) and stores it again.
|
|
7
|
+
*
|
|
8
|
+
* - Key: the session, the tool, how the repository was reached (`via`), the resolved root's real path and the call's canonical
|
|
9
|
+
* arguments ({@link canonicalArgs}: without `force`, defaults filled in). Stored as the SHA-256 of that text.
|
|
10
|
+
* - Only a successful answer above {@link DEDUP_MIN_BYTES} bytes is stored or stubbed. Any other answer for the key (an error,
|
|
11
|
+
* one at most that long, or one given while the call was aborted) forgets the key, so a stub always names the answer the
|
|
12
|
+
* previous identical call returned. A refusal before the key is known forgets the session's entries of that tool.
|
|
13
|
+
* - Window: a stub is given only while fewer than {@link ANSWER_WINDOW_CALLS} tool calls of the session have completed since the
|
|
14
|
+
* full answer was given ({@link noteToolCall}); later the answer is given in full again (the host may have pruned the old one).
|
|
15
|
+
* A stub does not renew the window. Entries also go on compaction (the v2 compaction hook and `session.compaction.ended`), on
|
|
16
|
+
* a revert ({@link ANSWER_FORGET_EVENTS}) and on `session.deleted`; a resume keeps them. Banners the router appends after the
|
|
17
|
+
* tool ran (cap banner, lease run note) are never part of the comparison.
|
|
18
|
+
* - Off for the whole process once {@link disableAnswerDedup} ran (the compaction hook could not be registered).
|
|
19
|
+
*
|
|
20
|
+
* MODULE (process) scope, like the dispatch-facts registry (sessions.ts): the host may deliver a session's events to the
|
|
21
|
+
* plugin instance of every live location, so every instance must see the same entries. Bounded: the least recently used key
|
|
22
|
+
* goes first, at most {@link MAX_ANSWERS_PER_SESSION} per session and {@link MAX_ANSWERS} overall.
|
|
23
|
+
*/
|
|
24
|
+
import { createHash } from "node:crypto";
|
|
25
|
+
|
|
26
|
+
/** Answers of at most this many bytes are always given in full (a stub would save little). */
|
|
27
|
+
export const DEDUP_MIN_BYTES = 512;
|
|
28
|
+
export const MAX_ANSWERS_PER_SESSION = 128;
|
|
29
|
+
export const MAX_ANSWERS = 4096;
|
|
30
|
+
/** A stored answer may be stubbed while fewer than this many tool calls of its session have completed since it was given. */
|
|
31
|
+
export const ANSWER_WINDOW_CALLS = 20;
|
|
32
|
+
/** OpenCode v2 events after which a session's answers are forgotten: a revert removes them, a compaction summarizes them. */
|
|
33
|
+
export const ANSWER_FORGET_EVENTS: ReadonlySet<string> = new Set([
|
|
34
|
+
"session.revert.staged", "session.revert.committed", "session.revert.cleared", "session.compaction.ended",
|
|
35
|
+
]);
|
|
36
|
+
/** The `force` argument's description (the tools' own descriptions do not change). */
|
|
37
|
+
export const FORCE_ARG_DESCRIPTION = "Return the full answer even when it is identical to your previous identical call";
|
|
38
|
+
/** The stub of a `router_run` whose output is unchanged; it follows the run's own status line. */
|
|
39
|
+
export const RUN_UNCHANGED_NOTE = "[router_run] unchanged: the output is exactly that of your previous identical run in this session. Pass force: true to see it again.";
|
|
40
|
+
|
|
41
|
+
/** One call's identity. `via` and `args` must be JSON-serialisable; build `args` with {@link canonicalArgs}. */
|
|
42
|
+
export interface AnswerKey {
|
|
43
|
+
readonly sessionID: string;
|
|
44
|
+
readonly tool: string;
|
|
45
|
+
readonly via: unknown;
|
|
46
|
+
/** The real path of the directory the call inspected or ran in. */
|
|
47
|
+
readonly root: string;
|
|
48
|
+
readonly args: unknown;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface Stored {
|
|
52
|
+
readonly digest: string;
|
|
53
|
+
readonly bytes: number;
|
|
54
|
+
readonly tool: string;
|
|
55
|
+
/** The session's completed-call count when the answer was given in full. */
|
|
56
|
+
readonly at: number;
|
|
57
|
+
}
|
|
58
|
+
interface SessionAnswers {
|
|
59
|
+
/** Tool calls of the session completed while it had entries. */
|
|
60
|
+
calls: number;
|
|
61
|
+
/** Its entries by key digest, least recently used first. */
|
|
62
|
+
readonly entries: Map<string, Stored>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Every entry's key digest, least recently used first (Map insertion order); the value is the entry's session. */
|
|
66
|
+
const order = new Map<string, string>();
|
|
67
|
+
const bySession = new Map<string, SessionAnswers>();
|
|
68
|
+
let disabled = false;
|
|
69
|
+
|
|
70
|
+
const ERROR_ANSWER = /^\[[a-z_]+\] error:/;
|
|
71
|
+
|
|
72
|
+
const sha256 = (text: string): string => createHash("sha256").update(text, "utf8").digest("hex");
|
|
73
|
+
|
|
74
|
+
function keyId(key: AnswerKey): string {
|
|
75
|
+
return sha256(JSON.stringify([key.sessionID, key.tool, key.via, key.root, key.args]));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function drop(id: string): void {
|
|
79
|
+
const session = order.get(id);
|
|
80
|
+
if (session === undefined) return;
|
|
81
|
+
order.delete(id);
|
|
82
|
+
const answers = bySession.get(session);
|
|
83
|
+
answers?.entries.delete(id);
|
|
84
|
+
if (answers !== undefined && answers.entries.size === 0) bySession.delete(session);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function store(sessionID: string, id: string, value: Omit<Stored, "at">, at?: number): void {
|
|
88
|
+
let answers = bySession.get(sessionID);
|
|
89
|
+
if (answers === undefined) bySession.set(sessionID, answers = { calls: 0, entries: new Map() });
|
|
90
|
+
// Re-inserted as the most recently used; the session (and its call count) stays, even when this was its only entry.
|
|
91
|
+
answers.entries.delete(id);
|
|
92
|
+
order.delete(id);
|
|
93
|
+
answers.entries.set(id, { ...value, at: at ?? answers.calls });
|
|
94
|
+
order.set(id, sessionID);
|
|
95
|
+
while (answers.entries.size > MAX_ANSWERS_PER_SESSION) drop(answers.entries.keys().next().value as string);
|
|
96
|
+
while (order.size > MAX_ANSWERS) drop(order.keys().next().value as string);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A key's canonical form of nested values: object keys sorted at every depth, undefined members dropped, arrays in order. */
|
|
100
|
+
function sortedValue(value: unknown): unknown {
|
|
101
|
+
if (Array.isArray(value)) return value.map(sortedValue);
|
|
102
|
+
if (value === null || typeof value !== "object") return value;
|
|
103
|
+
return Object.fromEntries(Object.entries(value).filter(([, member]) => member !== undefined)
|
|
104
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([name, member]) => [name, sortedValue(member)]));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* A call's arguments for its key: the parsed arguments without `force` (and the names in `omit`), undefined values dropped,
|
|
109
|
+
* `defaults` filled in for absent ones, keys sorted at every depth. A new argument is part of the key without listing it here.
|
|
110
|
+
*/
|
|
111
|
+
export function canonicalArgs(args: object, defaults: Readonly<Record<string, unknown>> = {}, omit: readonly string[] = []): Record<string, unknown> {
|
|
112
|
+
const merged: Record<string, unknown> = { ...defaults };
|
|
113
|
+
for (const [name, value] of Object.entries(args)) if (value !== undefined && name !== "force" && !omit.includes(name)) merged[name] = value;
|
|
114
|
+
return sortedValue(merged) as Record<string, unknown>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The answer to give for `key`: `stub(bytes)` when `compared` (default `answer`) equals the last answer given in full for the key,
|
|
119
|
+
* within the window, and `force` is not set; else `answer`, stored when it qualifies (successful, more than
|
|
120
|
+
* {@link DEDUP_MIN_BYTES} bytes, the call not `aborted`) and otherwise forgetting the key. `bytes` is the UTF-8 length of `compared`.
|
|
121
|
+
*/
|
|
122
|
+
export function dedupeAnswer(key: AnswerKey, answer: string,
|
|
123
|
+
options: { force: boolean; stub: (bytes: number) => string; compared?: string; aborted?: boolean }): string {
|
|
124
|
+
if (disabled) return answer;
|
|
125
|
+
const compared = options.compared ?? answer;
|
|
126
|
+
const id = keyId(key);
|
|
127
|
+
const bytes = Buffer.byteLength(compared);
|
|
128
|
+
if (options.aborted === true || ERROR_ANSWER.test(answer) || bytes <= DEDUP_MIN_BYTES) {
|
|
129
|
+
drop(id);
|
|
130
|
+
return answer;
|
|
131
|
+
}
|
|
132
|
+
const digest = sha256(compared);
|
|
133
|
+
const answers = bySession.get(key.sessionID);
|
|
134
|
+
const previous = answers?.entries.get(id);
|
|
135
|
+
const named = answers !== undefined && previous !== undefined && !options.force && previous.digest === digest && previous.bytes === bytes
|
|
136
|
+
&& answers.calls - previous.at < ANSWER_WINDOW_CALLS ? previous : undefined;
|
|
137
|
+
// A stub keeps the window of the full answer it names; a full answer starts a new one.
|
|
138
|
+
store(key.sessionID, id, { digest, bytes, tool: key.tool }, named?.at);
|
|
139
|
+
return named === undefined ? answer : options.stub(bytes);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Forget one key (its call failed, or was aborted, before an answer could be compared). */
|
|
143
|
+
export function forgetAnswer(key: AnswerKey): void {
|
|
144
|
+
drop(keyId(key));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Forget a session's entries of one tool (a refusal before the call's key was known; at most 128 entries are looked at). */
|
|
148
|
+
export function forgetToolAnswers(sessionID: string, tool: string): void {
|
|
149
|
+
const answers = bySession.get(sessionID);
|
|
150
|
+
if (answers === undefined) return;
|
|
151
|
+
for (const [id, stored] of [...answers.entries]) if (stored.tool === tool) drop(id);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Forget every answer of a session (compaction, revert, `session.deleted`). */
|
|
155
|
+
export function forgetAnswers(sessionID: string): void {
|
|
156
|
+
const answers = bySession.get(sessionID);
|
|
157
|
+
if (answers === undefined) return;
|
|
158
|
+
for (const id of [...answers.entries.keys()]) drop(id);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** One completed tool call of `sessionID` (any tool): moves the window of its stored answers. A no-op for a session without any. */
|
|
162
|
+
export function noteToolCall(sessionID: string): void {
|
|
163
|
+
const answers = bySession.get(sessionID);
|
|
164
|
+
if (answers !== undefined) answers.calls += 1;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Turn dedup off for the process and drop every entry. True the first time only (log once). */
|
|
168
|
+
export function disableAnswerDedup(): boolean {
|
|
169
|
+
const first = !disabled;
|
|
170
|
+
disabled = true;
|
|
171
|
+
order.clear();
|
|
172
|
+
bySession.clear();
|
|
173
|
+
return first;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Tests: dedup on again, no entries. */
|
|
177
|
+
export function resetAnswerDedupForTests(): void {
|
|
178
|
+
disabled = false;
|
|
179
|
+
order.clear();
|
|
180
|
+
bySession.clear();
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** How many answers are stored: for one session, or overall (tests, diagnostics). */
|
|
184
|
+
export function storedAnswerCount(sessionID?: string): number {
|
|
185
|
+
return sessionID === undefined ? order.size : bySession.get(sessionID)?.entries.size ?? 0;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** The stub of a `router_git_*` call whose answer is unchanged. */
|
|
189
|
+
export function gitUnchangedStub(tool: string, bytes: number): string {
|
|
190
|
+
return `[router_git] unchanged: this ${tool} call returns exactly the answer of your previous identical call in this session (${bytes} bytes). Pass force: true to get it again.`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** A `router_run` answer as compared: its first line (the status line) without `; duration <x>`. */
|
|
194
|
+
export function withoutRunDuration(answer: string): string {
|
|
195
|
+
const end = answer.indexOf("\n");
|
|
196
|
+
const first = end === -1 ? answer : answer.slice(0, end);
|
|
197
|
+
return `${first.replace(/; duration [^;\n]*$/, "")}${end === -1 ? "" : answer.slice(end)}`;
|
|
198
|
+
}
|