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/compat/v2-hooks.ts
CHANGED
|
@@ -6,7 +6,8 @@ import type { SessionContext } from "@opencode/plugin/promise/session";
|
|
|
6
6
|
import type { SystemPart } from "@opencode/ai";
|
|
7
7
|
import type { V2Runtime } from "./v2-client";
|
|
8
8
|
import { V2_GRADER_AGENT } from "./v2-client";
|
|
9
|
-
import {
|
|
9
|
+
import { assistantStepCompleted, lastAssistantReply, messageText } from "./child-history";
|
|
10
|
+
import { DEPTH_BANNER, SESSION_DIRECTORY, TASK_VERIFICATION, type SessionDirectory } from "./child-session";
|
|
10
11
|
import { realpathSync, statSync } from "node:fs";
|
|
11
12
|
import { basename, isAbsolute, join, posix, resolve, win32 } from "node:path";
|
|
12
13
|
import { loadConfig, resolveRolesRouting } from "../router/config";
|
|
@@ -38,7 +39,7 @@ import { recordRoleOrphan, takeRoleBindingLookupNotice } from "../routing/roles/
|
|
|
38
39
|
import type { DispatchGrant } from "../routing/roles/policy";
|
|
39
40
|
import { forgetWorkingSet, workingSetOf } from "../routing/wire/working-set";
|
|
40
41
|
import {
|
|
41
|
-
createRepoProbe, displaySafe,
|
|
42
|
+
createRepoProbe, displaySafe, namesGitMetadata, readSetEligible, readSetPredicate, type InReadSet,
|
|
42
43
|
} from "../routing/roles/read-set";
|
|
43
44
|
import {
|
|
44
45
|
AUTHORITY_TEXT, AUTHORITY_TOOL_NAME, consumeAuthority, discardAuthority, evictAuthority, markAnnotated, previewAuthority, quoteChildText,
|
|
@@ -47,8 +48,9 @@ import {
|
|
|
47
48
|
import { budgetExhausted, type BudgetSnapshot } from "../guard/enforce";
|
|
48
49
|
import { ROUTER_BUDGET_NOTE_PREFIX } from "../router/prompts";
|
|
49
50
|
import { parseReturnPrefix } from "../routing/outcomes/signals";
|
|
50
|
-
import { lookupDispatch } from "../router/sessions";
|
|
51
|
+
import { isRunnerDescription, lookupDispatch } from "../router/sessions";
|
|
51
52
|
import { createSystemAugmenter } from "../routing/wire/hint";
|
|
53
|
+
import { leadingChildReport, rewriteChildReportBodies, type ChildReport } from "./child-report";
|
|
52
54
|
import { createTurnStateRegistry, placeTurnState, ROUTER_TURN_STATE_ATTACH, TURN_STATE_ROOT, type TurnStateRegistry } from "./turn-state";
|
|
53
55
|
// 3.1.7 W6: the `plan` provider after the background ones (completed 30, held 40, in-flight 50), before the route hint (90).
|
|
54
56
|
import { PLAN_PROVIDER_NAME, PLAN_PROVIDER_ORDER } from "./turn-state";
|
|
@@ -59,7 +61,7 @@ import { canonicalAuthorityPath, insideWorkRoot } from "../routing/roles/work-ro
|
|
|
59
61
|
import { appliedEffort, appliedThinkingBudget, createEffortStore, registerEffortChannel } from "../tui/effort-channel";
|
|
60
62
|
import {
|
|
61
63
|
acquireLeaseRegistry, ADOPTION_RETRY_MS, attemptLabel, COMPLETION_SETTLE_MS, createCompletionProcessor, createHeldResults, createInFlightRegistry,
|
|
62
|
-
isExecutorOwned,
|
|
64
|
+
isExecutorOwned, indexMessageIDs, precedesDispatch,
|
|
63
65
|
createLeaseGuard, decideBackground, isAdoptionRefused, PENDING_GUARANTEES_TEXT, PROVIDER_ORDER, renderCompleted, renderHeld, renderInFlight,
|
|
64
66
|
restoredDispatchOf, ROUTER_FINISH_ATTACH,
|
|
65
67
|
} from "./background";
|
|
@@ -68,6 +70,8 @@ import type { TimingRecorderHolder } from "../routing/outcomes/timings";
|
|
|
68
70
|
import { createSideLogs, durationSeamsFor, nodePersistDeps, resolveOutcomesDir } from "../routing/outcomes/persist";
|
|
69
71
|
import { homedir, tmpdir } from "node:os";
|
|
70
72
|
import { installGitSearchFilter, nearestRepository, repositoryIdentity } from "../router/git-tools";
|
|
73
|
+
import { ANSWER_FORGET_EVENTS, disableAnswerDedup, forgetAnswers } from "../router/answer-dedup";
|
|
74
|
+
import { SESSION_INFO_LOOKUP_MS, sessionLookupWithin } from "./session-lookup";
|
|
71
75
|
import { readFileSync } from "node:fs";
|
|
72
76
|
import { fileURLToPath } from "node:url";
|
|
73
77
|
import { resolveRouting } from "../router/config";
|
|
@@ -81,6 +85,7 @@ import type {
|
|
|
81
85
|
RestoredDispatch, RestoredHold, RestoredHolds,
|
|
82
86
|
} from "./background";
|
|
83
87
|
import { PENDING_JOURNAL_VANISHED, pendingRecordIdentity } from "../verify/pending";
|
|
88
|
+
import { v2Instructions } from "./v2-vocabulary";
|
|
84
89
|
import type { ExecutorRuntimeHandle, LeaseRegistryPort, PlanTaskVerifier } from "../executor/runtime";
|
|
85
90
|
import type { LeaseRegistry } from "../router/leases";
|
|
86
91
|
import type {
|
|
@@ -209,16 +214,8 @@ export function executorHostContext(history: unknown): HostSessionContext {
|
|
|
209
214
|
return { messages, toolInFlight: historyToolInFlight(entries) };
|
|
210
215
|
}
|
|
211
216
|
|
|
212
|
-
/** Translate the router's own v1 tool vocabulary at the v2 boundary. */
|
|
213
|
-
export
|
|
214
|
-
return text
|
|
215
|
-
.replace(/\bTask(?=\s*\()/g, "subagent")
|
|
216
|
-
.replace(/\bTask (calls?|tool)\b/g, "subagent $1")
|
|
217
|
-
.replace(/\btask tool\b/g, "subagent tool")
|
|
218
|
-
.replace(/`task`/g, "`subagent`")
|
|
219
|
-
.replace(/\bsubagent_type\b/g, "agent")
|
|
220
|
-
.replace(/\btask_id\b/g, "sessionID");
|
|
221
|
-
}
|
|
217
|
+
/** Translate the router's own v1 tool vocabulary at the v2 boundary (src/compat/v2-vocabulary.ts, shared with the finish API). */
|
|
218
|
+
export { v2Instructions };
|
|
222
219
|
|
|
223
220
|
type LegacyAgent = Record<string, any>;
|
|
224
221
|
type LegacyConfig = { agent: Record<string, LegacyAgent>; command: Record<string, any>; mcp?: Parameters<NonNullable<Hooks["config"]>>[0]["mcp"] };
|
|
@@ -281,19 +278,6 @@ function translateAdded(before: string, after: string): string {
|
|
|
281
278
|
// #84 P2.1 (T2.1.3, T2.1.4): role-dispatch helpers of the adapter. Roles mode on v2 only; tiers mode never reaches them.
|
|
282
279
|
// ---------------------------------------------------------------------------
|
|
283
280
|
|
|
284
|
-
/** The text of one session-context message: its `text`, else its text parts (`content` or `parts`) joined. */
|
|
285
|
-
function messageText(message: unknown): string | undefined {
|
|
286
|
-
if (!message || typeof message !== "object") return undefined;
|
|
287
|
-
const m = message as Record<string, unknown>;
|
|
288
|
-
if (typeof m.text === "string") return m.text;
|
|
289
|
-
if (typeof m.content === "string") return m.content;
|
|
290
|
-
const parts = Array.isArray(m.content) ? m.content : Array.isArray(m.parts) ? m.parts : undefined;
|
|
291
|
-
if (parts === undefined) return undefined;
|
|
292
|
-
const texts = parts.flatMap((part) => part && typeof part === "object" && (part as Record<string, unknown>).type === "text"
|
|
293
|
-
&& typeof (part as Record<string, unknown>).text === "string" ? [(part as Record<string, unknown>).text as string] : []);
|
|
294
|
-
return texts.length > 0 ? texts.join("\n") : undefined;
|
|
295
|
-
}
|
|
296
|
-
|
|
297
281
|
/**
|
|
298
282
|
* Handoff 32: `SessionLookup.firstText` — the text parts of the session's first user message, joined (the binding reads the
|
|
299
283
|
* nonce from its last line). A context without a user message falls back to its first message with text.
|
|
@@ -642,7 +626,7 @@ export function toolCallPaths(tool: string, args: unknown): string[] | undefined
|
|
|
642
626
|
export function editsGitMetadata(path: string, target: string, root: string): boolean {
|
|
643
627
|
const base = root.replace(/[\\/]+$/, "");
|
|
644
628
|
const below = target.length > base.length ? target.slice(base.length) : "";
|
|
645
|
-
return
|
|
629
|
+
return namesGitMetadata(path, below);
|
|
646
630
|
}
|
|
647
631
|
|
|
648
632
|
/**
|
|
@@ -943,10 +927,12 @@ export function normalizeAgentOptions(options: Readonly<Record<string, unknown>>
|
|
|
943
927
|
}
|
|
944
928
|
|
|
945
929
|
/** Register the existing router engine on the public OpenCode 2 domain APIs. */
|
|
946
|
-
/**
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
930
|
+
/**
|
|
931
|
+
* One host completion element in a message text (memo §4.4, C2): `<subagent sessionID="X" state="S">body</subagent>` (2.0.x)
|
|
932
|
+
* or `<background-result kind="subagent" sessionID="X" state="S" …>body</background-result>` (2.3+, #174). Both are matched
|
|
933
|
+
* by child-report.ts only; further attributes (the host may add some) are tolerated and kept.
|
|
934
|
+
*/
|
|
935
|
+
export interface CompletionElement { child: string; state: "completed" | "error" | "cancelled"; body: string; description: string | undefined }
|
|
950
936
|
|
|
951
937
|
/** QA-2.1-8: the refusal of a resume while the pending journal is not reloaded (the session may be held). */
|
|
952
938
|
export function reloadFailedResumeText(child: string): string {
|
|
@@ -988,37 +974,25 @@ type ChildEndState =
|
|
|
988
974
|
| { outcome: "succeeded" | "failed" | "interrupted"; text?: string }
|
|
989
975
|
| { outcome: "lost"; text?: undefined; incomplete?: boolean };
|
|
990
976
|
|
|
991
|
-
/**
|
|
992
|
-
* QA-2.1-18: whether an assistant entry of a child's history ended its step (top level or under `info`): a finish reason other
|
|
993
|
-
* than a tool-call continuation, or a completed time; and no tool part still `pending` or `running`. A step cut mid-stream has
|
|
994
|
-
* none of these, and a `tool-calls` finish means the child meant to go on: neither is an end, whatever text it already has.
|
|
995
|
-
*/
|
|
996
|
-
function assistantStepCompleted(message: unknown): boolean {
|
|
997
|
-
if (message === null || typeof message !== "object") return false;
|
|
998
|
-
const m = message as Record<string, unknown>;
|
|
999
|
-
const info = m.info !== null && typeof m.info === "object" ? m.info as Record<string, unknown> : undefined;
|
|
1000
|
-
const parts: readonly unknown[] = Array.isArray(m.content) ? m.content : Array.isArray(m.parts) ? m.parts : [];
|
|
1001
|
-
const toolOpen = parts.some((part) => {
|
|
1002
|
-
if (part === null || typeof part !== "object" || (part as Record<string, unknown>).type !== "tool") return false;
|
|
1003
|
-
const state = (part as Record<string, unknown>).state;
|
|
1004
|
-
const status = state !== null && typeof state === "object" ? (state as Record<string, unknown>).status : state ?? (part as Record<string, unknown>).status;
|
|
1005
|
-
// The v2 tool state is `streaming` | `running` | `completed` | `error` (`pending` is the v1 name of the first).
|
|
1006
|
-
return status === "streaming" || status === "pending" || status === "running";
|
|
1007
|
-
});
|
|
1008
|
-
if (toolOpen) return false;
|
|
1009
|
-
const finish = m.finish ?? info?.finish;
|
|
1010
|
-
if (typeof finish === "string" && finish !== "") return finish !== "tool-calls" && finish !== "unknown";
|
|
1011
|
-
const time = m.time ?? info?.time;
|
|
1012
|
-
// `time.completed` is set once the step ended: epoch millis on the wire, a DateTime once decoded; either counts.
|
|
1013
|
-
const completed = time !== null && typeof time === "object" ? (time as Record<string, unknown>).completed : undefined;
|
|
1014
|
-
return completed !== undefined && completed !== null && completed !== "" && completed !== false;
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
977
|
/**
|
|
1018
978
|
* QA-2.1-11: a failed session-directory lookup is not repeated for this long (the lease guard calls it per tool call).
|
|
1019
979
|
* QA-2.1-25: a failed directory means no lease check and no lease for that call, like a failed kind, so the window is as short.
|
|
1020
980
|
*/
|
|
1021
981
|
export const SESSION_DIR_NEGATIVE_TTL_MS = 2_000;
|
|
982
|
+
/** #161: SESSION_INFO_LOOKUP_MS and `sessionLookupWithin` live in a leaf module, so index.ts bounds its v2 lookups without this one. */
|
|
983
|
+
export { SESSION_INFO_LOOKUP_MS };
|
|
984
|
+
/**
|
|
985
|
+
* #161: how long a tool call waits for the session's current location (its one fresh `session.get`, shared by `scopedArgs` and
|
|
986
|
+
* the git metadata guard). Short: a miss falls back to the session record's directory.
|
|
987
|
+
*/
|
|
988
|
+
export const CALL_DIRECTORY_LOOKUP_MS = 2_000;
|
|
989
|
+
/**
|
|
990
|
+
* #161: how long `execute.after` may still take the directory its call's `execute.before` used. Long: a write can wait on a
|
|
991
|
+
* permission prompt that long; past it (or once the store's bound drops the entry) the after-hook looks the directory up itself.
|
|
992
|
+
*/
|
|
993
|
+
export const CALL_DIRECTORY_STORE_TTL_MS = 60 * 60_000;
|
|
994
|
+
/** #161: calls whose before-hook directory is kept for their `execute.after` (oldest first out). */
|
|
995
|
+
const MAX_CALL_DIRECTORIES = 1000;
|
|
1022
996
|
/**
|
|
1023
997
|
* QA-2.1-25: a failed session-kind lookup is not repeated for this long. Short on purpose: the failure answers `unknown` (root
|
|
1024
998
|
* semantics, no lease), so a write in that window is unguarded; the window only spares a burst of tool calls a failing host call each.
|
|
@@ -1045,11 +1019,34 @@ const MAX_SESSION_DIRS = 1000;
|
|
|
1045
1019
|
const MAX_ADOPTED_SESSIONS = 5000;
|
|
1046
1020
|
/** DF-1-4: the children whose completion elements are remembered, and the elements kept per child. */
|
|
1047
1021
|
const MAX_SEEN_COMPLETION_CHILDREN = 1000;
|
|
1022
|
+
/** #174: dispatched children remembered against the runner-description fallback; unknown children warned about once each. */
|
|
1023
|
+
const MAX_DISPATCHED_CHILDREN = 5000;
|
|
1024
|
+
const MAX_WARNED_COMPLETION_CHILDREN = 1000;
|
|
1048
1025
|
const MAX_SEEN_COMPLETION_ELEMENTS = 64;
|
|
1049
1026
|
/** QA-2.1-8: a failed pending-journal reload is tried again at most this often (fail closed meanwhile). */
|
|
1050
1027
|
export const PENDING_RELOAD_RETRY_MS = 30_000;
|
|
1051
1028
|
/** QA-2.1-8: `dispose` waits at most this long for the background work in flight (verdict posts, recoveries). */
|
|
1052
1029
|
const BACKGROUND_DRAIN_MS = 5_000;
|
|
1030
|
+
/** Host-facing executor wait: allow the runtime's 10 s per-plan queue bound plus runtime/pool teardown headroom. */
|
|
1031
|
+
const EXECUTOR_DISPOSE_MS = 30_000;
|
|
1032
|
+
/**
|
|
1033
|
+
* #190 (QA-5.1-29): the `/plan` description each live router copy of this process registered, keyed by copy. A hot reload
|
|
1034
|
+
* starts the new copy while the old one still has its `/plan` registered; that `/plan` is the router's own, never a user
|
|
1035
|
+
* command. Process-wide (every module copy shares it) under a versioned registry key; a copy's entry goes at its cleanup.
|
|
1036
|
+
*/
|
|
1037
|
+
const ROUTER_PLAN_COMMANDS_KEY = Symbol.for("opencode-model-router.v2.router-plan-commands@1");
|
|
1038
|
+
function routerPlanCommands(): Map<object, string> {
|
|
1039
|
+
const existing: unknown = Reflect.get(globalThis, ROUTER_PLAN_COMMANDS_KEY);
|
|
1040
|
+
if (existing instanceof Map) return existing;
|
|
1041
|
+
const created = new Map<object, string>();
|
|
1042
|
+
Reflect.set(globalThis, ROUTER_PLAN_COMMANDS_KEY, created);
|
|
1043
|
+
return created;
|
|
1044
|
+
}
|
|
1045
|
+
/** QA-5.1-29: whether a listed host command is a `/plan` some live router copy of this process registered. */
|
|
1046
|
+
function isRouterPlanCommand(command: unknown): boolean {
|
|
1047
|
+
const description: unknown = typeof command === "object" && command !== null ? Reflect.get(command, "description") : undefined;
|
|
1048
|
+
return typeof description === "string" && [...routerPlanCommands().values()].includes(description);
|
|
1049
|
+
}
|
|
1053
1050
|
/**
|
|
1054
1051
|
* Non-enumerable slot on the cleanup function `registerV2Hooks` returns: `() => Promise<void>` that resolves once no background
|
|
1055
1052
|
* work is in flight (verdict posts, recoveries, reloads, including work they start). Lets integration tests await what an
|
|
@@ -1058,16 +1055,16 @@ const BACKGROUND_DRAIN_MS = 5_000;
|
|
|
1058
1055
|
export const V2_BACKGROUND_SETTLED: unique symbol = Symbol("opencode-model-router.v2.background-settled");
|
|
1059
1056
|
// QA-2.1-26: a module-private `Symbol()` (not the global registry `Symbol.for`): only code importing this module reaches the seam.
|
|
1060
1057
|
|
|
1061
|
-
/**
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
return
|
|
1058
|
+
/**
|
|
1059
|
+
* The completion element of a text part that STARTS with one (the host writes a completion as a whole message, C2): that one
|
|
1060
|
+
* element only, its body running to the last closing tag of its envelope (#174: a closing tag or a further report forged in the
|
|
1061
|
+
* child's text neither cuts it nor adds an element). Exported for tests.
|
|
1062
|
+
*/
|
|
1063
|
+
export function completionElementsOf(text: string): CompletionElement[] {
|
|
1064
|
+
const report = leadingChildReport(text);
|
|
1065
|
+
const state = report?.state;
|
|
1066
|
+
if (report === undefined || (state !== "completed" && state !== "error" && state !== "cancelled")) return [];
|
|
1067
|
+
return [{ child: report.child, state, body: report.body, description: report.description }];
|
|
1071
1068
|
}
|
|
1072
1069
|
|
|
1073
1070
|
/**
|
|
@@ -1080,27 +1077,32 @@ function completionMessageKey(message: object, index: number): string {
|
|
|
1080
1077
|
return `at:${index}`;
|
|
1081
1078
|
}
|
|
1082
1079
|
|
|
1083
|
-
/** Applies `defang` to the body of every
|
|
1080
|
+
/** Applies `defang` to the body of every completion element of a text, in either envelope (a pure rewrite; the element tags stay). */
|
|
1084
1081
|
function defangSubagentBodies(text: string, defang: (body: string) => string): string {
|
|
1085
|
-
|
|
1086
|
-
return text.replace(COMPLETION_ELEMENT, (whole: string, _child: string, _state: string, body: string) => {
|
|
1087
|
-
const next = defang(body);
|
|
1088
|
-
if (next === body) return whole;
|
|
1089
|
-
const closed = whole.endsWith("</subagent>");
|
|
1090
|
-
const open = whole.slice(0, whole.length - body.length - (closed ? "</subagent>".length : 0));
|
|
1091
|
-
return `${open}${next}${closed ? "</subagent>" : ""}`;
|
|
1092
|
-
});
|
|
1082
|
+
return rewriteChildReportBodies(text, (report) => defang(report.body));
|
|
1093
1083
|
}
|
|
1094
1084
|
|
|
1095
1085
|
/** Memo §12 (fail closed): replaces the body of every completion element whose child `isProcessed` rejects. Pure; the element tags stay. */
|
|
1096
1086
|
function redactUnprocessedElements(text: string, isProcessed: (child: string) => boolean): string {
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1087
|
+
return rewriteChildReportBodies(text, (report) => isProcessed(report.child) ? undefined
|
|
1088
|
+
: `[router] The result of session ${report.child} is withheld: the router could not restore its verification state.`);
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
/** #174: the body the orchestrator reads, in place of the child's text, in the host's report about one of the router's own children. */
|
|
1092
|
+
export const RUNNER_CHILD_REPORT_TEXT = "[router] internal child finished; its result is handled by the router.";
|
|
1093
|
+
|
|
1094
|
+
/**
|
|
1095
|
+
* #174: `text` with the body of every completion element whose child `isRunnerReport` accepts replaced by
|
|
1096
|
+
* {@link RUNNER_CHILD_REPORT_TEXT} (the body's leading and trailing blanks kept). Pure; the element tags stay.
|
|
1097
|
+
*/
|
|
1098
|
+
export function rewriteRunnerChildReports(text: string, isRunnerReport: (report: ChildReport) => boolean): string {
|
|
1099
|
+
return rewriteChildReportBodies(text, (report) => {
|
|
1100
|
+
if (!isRunnerReport(report)) return undefined;
|
|
1101
|
+
const trimmed = report.body.trim();
|
|
1102
|
+
if (trimmed === "") return RUNNER_CHILD_REPORT_TEXT;
|
|
1103
|
+
const lead = report.body.slice(0, report.body.length - report.body.trimStart().length);
|
|
1104
|
+
const trail = report.body.slice(report.body.trimEnd().length);
|
|
1105
|
+
return `${lead}${RUNNER_CHILD_REPORT_TEXT}${trail}`;
|
|
1104
1106
|
});
|
|
1105
1107
|
}
|
|
1106
1108
|
|
|
@@ -1149,7 +1151,8 @@ export interface V2ExecutorHost {
|
|
|
1149
1151
|
/**
|
|
1150
1152
|
* QA-5.1-26: hands the adapter an executor assembled after the factory returned (a claim handover). The adapter adopts it
|
|
1151
1153
|
* through the path it adopts the factory's executor by (its providers and hooks, `start()`, the W7 dispose) and answers
|
|
1152
|
-
* true. False: not adopted (the adapter is disposing,
|
|
1154
|
+
* true. False: not adopted (the adapter is disposing, it already holds another executor, or the wiring failed and was
|
|
1155
|
+
* undone, QA-5.1-32); the caller disposes it.
|
|
1153
1156
|
*/
|
|
1154
1157
|
onExecutor(built: V2Executor): boolean;
|
|
1155
1158
|
}
|
|
@@ -1166,7 +1169,7 @@ export type V2ExecutorFactory = (host: V2ExecutorHost) => V2Executor | null;
|
|
|
1166
1169
|
export async function registerV2Hooks(
|
|
1167
1170
|
ctx: Context,
|
|
1168
1171
|
hooks: Hooks,
|
|
1169
|
-
runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession" | "childRunner">>,
|
|
1172
|
+
runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession" | "childRunner" | "isRunnerChild">>,
|
|
1170
1173
|
/**
|
|
1171
1174
|
* `ingest`: the plugin instance's telemetry ingest (M6, QA-2.1-7); without one the adapter ingests nothing.
|
|
1172
1175
|
* `isBypassed`: the plugin's `/bypass` state (#84 P2.1: the role path's router-gate condition, S10/P-9).
|
|
@@ -1439,11 +1442,14 @@ export async function registerV2Hooks(
|
|
|
1439
1442
|
if (sessionID !== "" && sessionKinds.get(sessionID) !== "root") {
|
|
1440
1443
|
let check = planChildChecks.get(sessionID);
|
|
1441
1444
|
if (check === undefined) {
|
|
1442
|
-
/**
|
|
1445
|
+
/**
|
|
1446
|
+
* True when a verdict was reached; false when the first message could not be read. #161: a host that has not answered
|
|
1447
|
+
* within SESSION_INFO_LOOKUP_MS (the bound of the other session reads a tool call waits for) has not been read either.
|
|
1448
|
+
*/
|
|
1443
1449
|
const verdict = (async (): Promise<boolean> => {
|
|
1444
1450
|
let firstText: string | undefined;
|
|
1445
1451
|
try {
|
|
1446
|
-
firstText = firstMessageText(await ctx.session.context({ sessionID } as Parameters<typeof ctx.session.context>[0]));
|
|
1452
|
+
firstText = firstMessageText(await sessionLookupWithin(ctx.session.context({ sessionID } as Parameters<typeof ctx.session.context>[0]), SESSION_INFO_LOOKUP_MS));
|
|
1447
1453
|
} catch {
|
|
1448
1454
|
firstText = undefined;
|
|
1449
1455
|
}
|
|
@@ -1559,18 +1565,22 @@ export async function registerV2Hooks(
|
|
|
1559
1565
|
if (takeRoleBindingLookupNotice()) ingestLogger.warn(message, extra);
|
|
1560
1566
|
else console.debug(message, extra);
|
|
1561
1567
|
};
|
|
1562
|
-
/**
|
|
1568
|
+
/**
|
|
1569
|
+
* Handoff 32: what the binding reads of a child session (parent, agent, title, first message text). #161: each host call gives up
|
|
1570
|
+
* after SESSION_INFO_LOOKUP_MS, as the session record does (a miss refuses a role agent's call, so a slow but healthy host must
|
|
1571
|
+
* not cause one), and then counts as failed: the session's as lookupFailed, the first message's as no text.
|
|
1572
|
+
*/
|
|
1563
1573
|
const bindingLookup: SessionLookup = async (id) => {
|
|
1564
1574
|
let session: Record<string, unknown>;
|
|
1565
1575
|
try {
|
|
1566
|
-
session = await ctx.session.get({ sessionID: id } as Parameters<typeof ctx.session.get>[0]) as unknown as Record<string, unknown>;
|
|
1576
|
+
session = await sessionLookupWithin(ctx.session.get({ sessionID: id } as Parameters<typeof ctx.session.get>[0]), SESSION_INFO_LOOKUP_MS) as unknown as Record<string, unknown>;
|
|
1567
1577
|
} catch (error) {
|
|
1568
1578
|
warnBindingLookup("[router] roles: a binding session could not be read", id, error);
|
|
1569
1579
|
throw error; // bind treats this as lookupFailed, without caching it
|
|
1570
1580
|
}
|
|
1571
1581
|
let firstText: string | undefined;
|
|
1572
1582
|
try {
|
|
1573
|
-
firstText = firstMessageText(await ctx.session.context({ sessionID: id } as Parameters<typeof ctx.session.context>[0]));
|
|
1583
|
+
firstText = firstMessageText(await sessionLookupWithin(ctx.session.context({ sessionID: id } as Parameters<typeof ctx.session.context>[0]), SESSION_INFO_LOOKUP_MS));
|
|
1574
1584
|
} catch (error) {
|
|
1575
1585
|
warnBindingLookup("[router] roles: a child's first message could not be read", id, error);
|
|
1576
1586
|
firstText = undefined; // the title marker still binds
|
|
@@ -1662,9 +1672,12 @@ export async function registerV2Hooks(
|
|
|
1662
1672
|
};
|
|
1663
1673
|
/**
|
|
1664
1674
|
* The directory the host resolves a session's relative paths against (its location), else the plugin's; and the session's
|
|
1665
|
-
* parent (cross-repo P1.5: the orchestrator whose working set widens R). QA-2.1-11: cached per session
|
|
1666
|
-
*
|
|
1667
|
-
*
|
|
1675
|
+
* parent (cross-repo P1.5: the orchestrator whose working set widens R). QA-2.1-11: cached per session — the first answer, which
|
|
1676
|
+
* the role checks, the file leases and the stale-resume check keep; the host's session move can change the location later, so
|
|
1677
|
+
* `scopedArgs` and the git metadata guard look it up afresh per call ({@link callDirectoryOf}) and fall back to this record.
|
|
1678
|
+
* Concurrent lookups share one host call, and a failed lookup is remembered for SESSION_DIR_NEGATIVE_TTL_MS so a tool hook does
|
|
1679
|
+
* not pay a failing `ctx.session.get` per call. #161: a host call that does not answer within SESSION_INFO_LOOKUP_MS is a failed
|
|
1680
|
+
* lookup, so a hung one is never cached for good. Bounded; forgotten with the session.
|
|
1668
1681
|
*/
|
|
1669
1682
|
type SessionInfo = { directory: string; parentID: string | undefined; agent?: string };
|
|
1670
1683
|
const sessionDirs = new Map<string, { at: number; info: Promise<SessionInfo>; failed: boolean }>();
|
|
@@ -1675,15 +1688,17 @@ export async function registerV2Hooks(
|
|
|
1675
1688
|
at: Date.now(), failed: false, info: Promise.resolve<SessionInfo>({ directory: ctx.location.directory, parentID: undefined }),
|
|
1676
1689
|
};
|
|
1677
1690
|
entry.info = (async () => {
|
|
1678
|
-
const
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
const
|
|
1691
|
+
const lookup = ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]);
|
|
1692
|
+
const answer: unknown = await sessionLookupWithin(lookup, SESSION_INFO_LOOKUP_MS);
|
|
1693
|
+
// #161: an answer that is no session record is a failed lookup, never a session located in the plugin's directory.
|
|
1694
|
+
if (answer === null || typeof answer !== "object") throw new Error("the host returned no session");
|
|
1695
|
+
const session = answer as { location?: { directory?: unknown }; parentID?: unknown; agent?: unknown };
|
|
1696
|
+
const directory = session.location?.directory;
|
|
1697
|
+
const parentID = session.parentID;
|
|
1683
1698
|
return {
|
|
1684
1699
|
directory: typeof directory === "string" && directory !== "" ? directory : ctx.location.directory,
|
|
1685
1700
|
parentID: typeof parentID === "string" && parentID !== "" ? parentID : undefined,
|
|
1686
|
-
agent: typeof session
|
|
1701
|
+
agent: typeof session.agent === "string" && session.agent !== "" ? session.agent : undefined,
|
|
1687
1702
|
};
|
|
1688
1703
|
})();
|
|
1689
1704
|
entry.info.catch(() => {
|
|
@@ -1698,6 +1713,62 @@ export async function registerV2Hooks(
|
|
|
1698
1713
|
};
|
|
1699
1714
|
/** The directory half of {@link sessionInfoOf} (the work-lease wiring's `sessionDir`). */
|
|
1700
1715
|
const sessionDirectoryOf = (sessionID: string): Promise<string> => sessionInfoOf(sessionID).then((info) => info.directory);
|
|
1716
|
+
/** #161: a session's directory as one tool call sees it; `known: false` when its lookup failed and no directory is known. */
|
|
1717
|
+
type CallDirectory = { readonly known: true; readonly directory: string } | { readonly known: false; readonly error: unknown };
|
|
1718
|
+
/** #161: per session, the directory of its last successful {@link callDirectoryOf} lookup. Bounded; forgotten with the session. */
|
|
1719
|
+
const lastCallDirs = new Map<string, string>();
|
|
1720
|
+
/**
|
|
1721
|
+
* #161: the session's directory for one tool call: its current location, looked up afresh within CALL_DIRECTORY_LOOKUP_MS (the
|
|
1722
|
+
* host's session move changes it; a session that answers without one is in the plugin's directory, as in {@link sessionInfoOf};
|
|
1723
|
+
* an answer that is no session record is a failed lookup). When that lookup fails or gives up, the last known directory: the
|
|
1724
|
+
* last successful lookup's, else the session record's (no host call once it is settled; else its shared lookup, bounded by
|
|
1725
|
+
* SESSION_INFO_LOOKUP_MS) — right unless the session moved since. Unknown only when none is known. Never throws.
|
|
1726
|
+
*/
|
|
1727
|
+
const callDirectoryOf = async (sessionID: string): Promise<CallDirectory> => {
|
|
1728
|
+
let failure: unknown;
|
|
1729
|
+
try {
|
|
1730
|
+
const session: unknown = await sessionLookupWithin(ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]), CALL_DIRECTORY_LOOKUP_MS);
|
|
1731
|
+
if (session === null || typeof session !== "object") throw new Error("the host returned no session");
|
|
1732
|
+
const named = (session as { location?: { directory?: unknown } }).location?.directory;
|
|
1733
|
+
const directory = typeof named === "string" && named !== "" ? named : ctx.location.directory;
|
|
1734
|
+
lastCallDirs.delete(sessionID);
|
|
1735
|
+
lastCallDirs.set(sessionID, directory);
|
|
1736
|
+
while (lastCallDirs.size > MAX_SESSION_DIRS) lastCallDirs.delete(lastCallDirs.keys().next().value!);
|
|
1737
|
+
return { known: true, directory };
|
|
1738
|
+
} catch (error) {
|
|
1739
|
+
failure = error;
|
|
1740
|
+
}
|
|
1741
|
+
const last = lastCallDirs.get(sessionID);
|
|
1742
|
+
if (last !== undefined) return { known: true, directory: last };
|
|
1743
|
+
try {
|
|
1744
|
+
return { known: true, directory: await sessionDirectoryOf(sessionID) };
|
|
1745
|
+
} catch {
|
|
1746
|
+
return { known: false, error: failure };
|
|
1747
|
+
}
|
|
1748
|
+
};
|
|
1749
|
+
/**
|
|
1750
|
+
* #161: per tool call (its id), the known directory its `execute.before` used ({@link callDirectoryOf}), so its `execute.after`
|
|
1751
|
+
* resolves the call's paths (the changed-file record, the trajectory, the guard's after-call) against that same answer instead
|
|
1752
|
+
* of a lookup of its own, which can fail and skip that bookkeeping, or see a session moved since. Taken once; bounded
|
|
1753
|
+
* (MAX_CALL_DIRECTORIES, oldest first out), ignored past CALL_DIRECTORY_STORE_TTL_MS, and forgotten with the session.
|
|
1754
|
+
*/
|
|
1755
|
+
const callDirectories = new Map<string, { readonly at: number; readonly sessionID: string; readonly found: CallDirectory }>();
|
|
1756
|
+
const rememberCallDirectory = (callID: string, sessionID: string, found: CallDirectory): void => {
|
|
1757
|
+
if (!found.known || callID === "") return; // an unknown directory: the after-hook tries its own lookup, as before
|
|
1758
|
+
callDirectories.delete(callID);
|
|
1759
|
+
callDirectories.set(callID, { at: Date.now(), sessionID, found });
|
|
1760
|
+
while (callDirectories.size > MAX_CALL_DIRECTORIES) callDirectories.delete(callDirectories.keys().next().value!);
|
|
1761
|
+
};
|
|
1762
|
+
/** Takes (and drops) the entry of `callID`; undefined when there is none, it expired, or another session stored it. */
|
|
1763
|
+
const takeCallDirectory = (callID: string, sessionID: string): CallDirectory | undefined => {
|
|
1764
|
+
const stored = callDirectories.get(callID);
|
|
1765
|
+
callDirectories.delete(callID);
|
|
1766
|
+
if (stored === undefined || stored.sessionID !== sessionID) return undefined;
|
|
1767
|
+
return Date.now() - stored.at >= CALL_DIRECTORY_STORE_TTL_MS ? undefined : stored.found;
|
|
1768
|
+
};
|
|
1769
|
+
const forgetCallDirectories = (sessionID: string): void => {
|
|
1770
|
+
for (const [callID, stored] of callDirectories) if (stored.sessionID === sessionID) callDirectories.delete(callID);
|
|
1771
|
+
};
|
|
1701
1772
|
/**
|
|
1702
1773
|
* Cross-repo P1.5: the read set R of a role session beyond its work root (`routing/roles/read-set.ts`) — the worktrees of its
|
|
1703
1774
|
* orchestrator's working set (the session that dispatched it: its dispatch record, else the session's parent) and the
|
|
@@ -1865,16 +1936,29 @@ export async function registerV2Hooks(
|
|
|
1865
1936
|
});
|
|
1866
1937
|
let eventTask: Promise<void> | undefined;
|
|
1867
1938
|
let disposed = false;
|
|
1939
|
+
/** QA-5.1-29: this copy's key in the process-wide `/plan` registry (`routerPlanCommands`). */
|
|
1940
|
+
const routerPlanOwner = {};
|
|
1941
|
+
/** QA-5.1-29: set once cleanup removed this copy's command registration and its registry entry. */
|
|
1942
|
+
let routerPlanReleased = false;
|
|
1868
1943
|
const within = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
|
|
1869
1944
|
runtime ? runtime.withToolContext(context, operation) : operation();
|
|
1870
1945
|
/** QA-PDF12-7: a context rebuilt from journaled data runs its operation but never becomes the parent's retained context. */
|
|
1871
1946
|
const withinRebuilt = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
|
|
1872
1947
|
runtime ? runtime.withToolContext(context, operation, { retain: false }) : operation();
|
|
1873
|
-
|
|
1948
|
+
/** `directoryOf`: the call's session directory (execute.before passes its per-call answer; default: a lookup of its own). */
|
|
1949
|
+
const scopedArgs = async (
|
|
1950
|
+
event: { tool: string; input: unknown; sessionID: any },
|
|
1951
|
+
directoryOf: () => Promise<CallDirectory> = () => callDirectoryOf(String(event.sessionID)),
|
|
1952
|
+
): Promise<any> => {
|
|
1874
1953
|
const args = taskArgs(event.tool, event.input);
|
|
1875
1954
|
if (["read", "write", "edit"].includes(event.tool) && typeof args?.filePath === "string" && !isAbsolute(args.filePath)) {
|
|
1876
|
-
|
|
1877
|
-
|
|
1955
|
+
// #161: the host resolves the path against the session's location; when it is unknown (the lookup failed or gave up, and no
|
|
1956
|
+
// directory is known) the call fails, as a failed lookup always did, instead of resolving against the plugin's directory.
|
|
1957
|
+
const found = await directoryOf();
|
|
1958
|
+
if (!found.known) {
|
|
1959
|
+
throw new Error(`[router] Refused: the session's location could not be read (${String(found.error)}), so a relative path cannot be resolved (fail closed).`);
|
|
1960
|
+
}
|
|
1961
|
+
args.filePath = resolve(found.directory, args.filePath);
|
|
1878
1962
|
}
|
|
1879
1963
|
return args;
|
|
1880
1964
|
};
|
|
@@ -1974,7 +2058,8 @@ export async function registerV2Hooks(
|
|
|
1974
2058
|
};
|
|
1975
2059
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
1976
2060
|
// Phase 2.1 startup (memo §4.1). Everything below is v2-only (this module is loaded by server.ts alone) and inert under
|
|
1977
|
-
// `routing.background.mode: "off"` + `routing.leases.mode: "off"` except the timing rows (telemetry, not visible to the user)
|
|
2061
|
+
// `routing.background.mode: "off"` + `routing.leases.mode: "off"` except the timing rows (telemetry, not visible to the user)
|
|
2062
|
+
// and, #191, the hold and verification of a verifying call the host runs in the background anyway (OpenCode 2.3+).
|
|
1978
2063
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
1979
2064
|
const startRouting = resolveRouting(loadConfig(ctx.location.directory), "v2", ingestLogger);
|
|
1980
2065
|
const outcomesDir = resolveOutcomesDir(startRouting.outcomes.path, { tmpdir: tmpdir(), homedir: homedir() });
|
|
@@ -2057,9 +2142,10 @@ export async function registerV2Hooks(
|
|
|
2057
2142
|
/**
|
|
2058
2143
|
* The kind of a session WITHOUT a host call (`session.created` and the `prompt` hook record it): an unknown session is a root,
|
|
2059
2144
|
* as in the lease guard (memo §14.1). The dispatch path adds no host call of its own (a static session stays silent, §1.2),
|
|
2060
|
-
* with one exception: DF-1-9 / QA-DF1-23, never for the background decision —
|
|
2061
|
-
* (`bgActive()`), an unrecorded parent is resolved once with
|
|
2062
|
-
* SESSION_KIND_DISPATCH_TIMEOUT_MS, cached once answered; `unknown`
|
|
2145
|
+
* with one exception: DF-1-9 / QA-DF1-23, never for the background decision — for a call the background path tracks
|
|
2146
|
+
* (`bgActive()`; under `off` only a verifying call, #191), an unrecorded parent is resolved once with
|
|
2147
|
+
* `dispatchSessionKindOf` (one `session.get`, bounded by SESSION_KIND_DISPATCH_TIMEOUT_MS, cached once answered; `unknown`
|
|
2148
|
+
* is no root).
|
|
2063
2149
|
*/
|
|
2064
2150
|
const knownKindOf = (sessionID: string): "root" | "child" => sessionKinds.get(sessionID) ?? "root";
|
|
2065
2151
|
/** The in-flight registry and held results exist whatever the mode; they hold nothing until a background dispatch is acknowledged. */
|
|
@@ -2183,52 +2269,104 @@ export async function registerV2Hooks(
|
|
|
2183
2269
|
};
|
|
2184
2270
|
const syntheticRaw: unknown = Reflect.get(ctx.session, "synthetic");
|
|
2185
2271
|
const syntheticOk = typeof syntheticRaw === "function";
|
|
2272
|
+
/**
|
|
2273
|
+
* #174: whether a completion element reports one of the router's own children (an LLM grader, a `router_delegate` producer, a
|
|
2274
|
+
* plan-executor task: every child the native child runner started). The runner's registry is the signal: it still knows the
|
|
2275
|
+
* child after the run ended and the child was removed. The runner's fixed `description` is a fallback only (a registry that
|
|
2276
|
+
* does not know the child: another runtime, or past its bound), and only for a child neither the in-flight registry nor the
|
|
2277
|
+
* record of dispatched children knows: an orchestrator may title its own dispatch alike, and its report must reach it unchanged.
|
|
2278
|
+
*/
|
|
2279
|
+
const isRunnerReport = (report: Pick<ChildReport, "child" | "description">): boolean => {
|
|
2280
|
+
if (runtime?.isRunnerChild?.(report.child) === true) return true;
|
|
2281
|
+
return report.description !== undefined && isRunnerDescription(report.description)
|
|
2282
|
+
&& !dispatchedChildren.has(report.child) && inflight.byChild(report.child) === undefined;
|
|
2283
|
+
};
|
|
2284
|
+
/**
|
|
2285
|
+
* #174: the children of the `subagent` calls this adapter's tool hooks saw (orchestrator and role dispatches, in every mode).
|
|
2286
|
+
* The runner's own native calls reach no tool hook, so a child in here is never given the runner-description fallback above.
|
|
2287
|
+
* Child -> the session whose call dispatched it (#191, the latest). Bounded, oldest first out.
|
|
2288
|
+
*/
|
|
2289
|
+
const dispatchedChildren = new Map<string, string>();
|
|
2290
|
+
const noteDispatchedChild = (parent: string, child: string): void => {
|
|
2291
|
+
dispatchedChildren.delete(child);
|
|
2292
|
+
dispatchedChildren.set(child, parent);
|
|
2293
|
+
for (const old of dispatchedChildren.keys()) {
|
|
2294
|
+
if (dispatchedChildren.size <= MAX_DISPATCHED_CHILDREN) break;
|
|
2295
|
+
dispatchedChildren.delete(old);
|
|
2296
|
+
}
|
|
2297
|
+
};
|
|
2298
|
+
/**
|
|
2299
|
+
* #191: under `off` a child this process dispatched from `session` without tracking it (no verification and no role, so never
|
|
2300
|
+
* held) can never be a held result of that session. The fail-closed state of a journal that is not reloaded (memo §12) neither
|
|
2301
|
+
* withholds its report from that session nor refuses that session's resume of it; a child another session dispatched, or one
|
|
2302
|
+
* this process never dispatched (a previous process's), is still withheld and refused.
|
|
2303
|
+
*/
|
|
2304
|
+
const untrackedUnderOff = (session: string, child: string): boolean =>
|
|
2305
|
+
bgMode === "off" && dispatchedChildren.get(child) === session && inflight.byChild(child) === undefined;
|
|
2186
2306
|
/** The held store, for the compaction hook registered before it exists. */
|
|
2187
2307
|
let heldRef: HeldResults | undefined;
|
|
2188
|
-
/**
|
|
2308
|
+
/**
|
|
2309
|
+
* Memo §4.4 step 5: the compaction hook runs the same matcher over the messages being summarised (C15).
|
|
2310
|
+
* #174: it is registered in every mode, for the runner-child rewrite the context hook also makes in every mode.
|
|
2311
|
+
* #191: the matcher runs in every mode too: under `off` a verifying call the host backgrounds anyway is held.
|
|
2312
|
+
*/
|
|
2189
2313
|
let compactionRegistered = false;
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2314
|
+
try {
|
|
2315
|
+
registrations.push(await ctx.session.hook("compaction", async (event) => {
|
|
2316
|
+
// #108 slice 4: the summary drops the answers a stub would point back to, so the session's deduplicated answers go too.
|
|
2317
|
+
forgetAnswers(String(event.sessionID));
|
|
2318
|
+
const messages = event.messages;
|
|
2319
|
+
if (!Array.isArray(messages)) return;
|
|
2320
|
+
/** `rewrite` over the text parts of the messages being summarised; a changed message is replaced by a copy. */
|
|
2321
|
+
const rewriteTexts = (rewrite: (text: string) => string): void => {
|
|
2322
|
+
messages.forEach((source, index) => {
|
|
2323
|
+
const content: unknown = (source as { content?: unknown }).content;
|
|
2324
|
+
if (!Array.isArray(content)) return;
|
|
2325
|
+
let touched = false;
|
|
2326
|
+
const next = content.map((part: unknown) => {
|
|
2327
|
+
const text: unknown = part !== null && typeof part === "object" ? Reflect.get(part, "text") : undefined;
|
|
2328
|
+
const type: unknown = part !== null && typeof part === "object" ? Reflect.get(part, "type") : undefined;
|
|
2329
|
+
if (typeof text !== "string" || (type !== undefined && type !== "text")) return part;
|
|
2330
|
+
const rewritten = rewrite(text);
|
|
2331
|
+
if (rewritten === text) return part;
|
|
2332
|
+
touched = true;
|
|
2333
|
+
return { ...(part as object), text: rewritten };
|
|
2334
|
+
});
|
|
2335
|
+
if (touched) messages[index] = Object.assign(Object.create(Object.getPrototypeOf(source)), source, { content: next });
|
|
2336
|
+
});
|
|
2337
|
+
};
|
|
2338
|
+
// #191: in every mode (without the finish API the adoption, the redaction and the matcher have nothing to act on).
|
|
2339
|
+
if (heldRef !== undefined) {
|
|
2195
2340
|
adoptSession(String(event.sessionID));
|
|
2196
2341
|
if (finishApi !== undefined && reloadFailed) {
|
|
2197
2342
|
// QA-2.1-8: fail closed exactly like the context hook (memo §12): a summary must not carry a completion this process
|
|
2198
|
-
// cannot prove processed while the journal is not reloaded.
|
|
2343
|
+
// cannot prove processed while the journal is not reloaded. #191: an untracked child under `off` is never held.
|
|
2344
|
+
const summarised = String(event.sessionID);
|
|
2199
2345
|
const isProcessed = (child: string): boolean => {
|
|
2346
|
+
if (untrackedUnderOff(summarised, child)) return true;
|
|
2200
2347
|
const attempt = inflight.byChild(child);
|
|
2201
2348
|
return attempt !== undefined && journal.hasProcessed(attempt.key);
|
|
2202
2349
|
};
|
|
2203
|
-
|
|
2204
|
-
const content: unknown = (source as { content?: unknown }).content;
|
|
2205
|
-
if (!Array.isArray(content)) return;
|
|
2206
|
-
let touched = false;
|
|
2207
|
-
const next = content.map((part: unknown) => {
|
|
2208
|
-
const text: unknown = part !== null && typeof part === "object" ? Reflect.get(part, "text") : undefined;
|
|
2209
|
-
const type: unknown = part !== null && typeof part === "object" ? Reflect.get(part, "type") : undefined;
|
|
2210
|
-
if (typeof text !== "string" || (type !== undefined && type !== "text")) return part;
|
|
2211
|
-
const redacted = redactUnprocessedElements(text, isProcessed);
|
|
2212
|
-
if (redacted === text) return part;
|
|
2213
|
-
touched = true;
|
|
2214
|
-
return { ...(part as object), text: redacted };
|
|
2215
|
-
});
|
|
2216
|
-
if (touched) messages[index] = Object.assign(Object.create(Object.getPrototypeOf(source)), source, { content: next });
|
|
2217
|
-
});
|
|
2350
|
+
rewriteTexts((text) => redactUnprocessedElements(text, isProcessed));
|
|
2218
2351
|
}
|
|
2219
|
-
const shaped = messages.map((source) => ({ source, parts: (source as { content?: unknown }).content }));
|
|
2352
|
+
const shaped = messages.map((source) => ({ source, id: (source as { id?: unknown }).id, parts: (source as { content?: unknown }).content }));
|
|
2220
2353
|
const result = heldRef.apply(String(event.sessionID), shaped);
|
|
2221
|
-
|
|
2222
|
-
result.forEach((entry, index) => {
|
|
2354
|
+
result?.forEach((entry, index) => {
|
|
2223
2355
|
if (entry.parts !== (entry.source as { content?: unknown }).content) {
|
|
2224
2356
|
messages[index] = Object.assign(Object.create(Object.getPrototypeOf(entry.source)), entry.source, { content: entry.parts });
|
|
2225
2357
|
}
|
|
2226
2358
|
});
|
|
2227
|
-
}
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2359
|
+
}
|
|
2360
|
+
// #174: a summary never carries the raw text of one of the router's own children (the same lookup and line as the context hook).
|
|
2361
|
+
rewriteTexts((text) => rewriteRunnerChildReports(text, isRunnerReport));
|
|
2362
|
+
}));
|
|
2363
|
+
compactionRegistered = true;
|
|
2364
|
+
} catch (error) {
|
|
2365
|
+
// #108 slice 4: without the hook a compaction would not clear the deduplicated answers, so a stub could name an answer the
|
|
2366
|
+
// summary dropped: dedup is off for this process (logged once, in every mode).
|
|
2367
|
+
if (disableAnswerDedup()) ingestLogger.warn("[router] answer dedup is off: the compaction hook could not be registered; every answer is given in full", { error: String(error) });
|
|
2368
|
+
// #191: held results depend on it in every mode (under `off`, for a verifying call the host backgrounds anyway).
|
|
2369
|
+
ingestLogger.warn("[router] background: the compaction hook could not be registered; held results are unavailable", { error: String(error) });
|
|
2232
2370
|
}
|
|
2233
2371
|
const held: HeldResults = createHeldResults({
|
|
2234
2372
|
observations: options.observations,
|
|
@@ -2236,7 +2374,7 @@ export async function registerV2Hooks(
|
|
|
2236
2374
|
journal, available: syntheticOk && compactionRegistered, logger: ingestLogger,
|
|
2237
2375
|
});
|
|
2238
2376
|
heldRef = held;
|
|
2239
|
-
/** The legacy plugin's finish API (2.1.4)
|
|
2377
|
+
/** The legacy plugin's finish API (2.1.4), attached in every mode (#191). Absent: no background processing at all. */
|
|
2240
2378
|
let finishApi: FinishApi | undefined;
|
|
2241
2379
|
/**
|
|
2242
2380
|
* Memo §12: the journal reload failed or timed out, or the journal vanished under this process (QA-2.1-8). Holding is off,
|
|
@@ -2397,8 +2535,14 @@ export async function registerV2Hooks(
|
|
|
2397
2535
|
const restoredDispatches = new Map<string, RestoredDispatch>();
|
|
2398
2536
|
/** QA-2.1-29: restored holds of sessions adopted before the processor existed, waiting for the start-up recovery. */
|
|
2399
2537
|
const deferredRestores = new Map<string, RestoredHolds>();
|
|
2400
|
-
/**
|
|
2401
|
-
|
|
2538
|
+
/**
|
|
2539
|
+
* Background guarantees apply: the finish API attached. Otherwise no call is tracked and nothing is held or processed.
|
|
2540
|
+
* #191: in every mode, because OpenCode 2.3+ runs every native child in the background whatever `background` says. Under
|
|
2541
|
+
* `off` the router never asks for the background and tracks only verifying and role-routed calls (`execute.before`), so a
|
|
2542
|
+
* verifying call the host backgrounds anyway is held and verified like one `auto` did not select, and a role call keeps its
|
|
2543
|
+
* binding and notices; every other call stays untracked (`untrackedUnderOff`).
|
|
2544
|
+
*/
|
|
2545
|
+
const bgActive = (): boolean => finishApi !== undefined;
|
|
2402
2546
|
/** `router_run` contamination notes from `execute.before`, appended in `execute.after` (bounded). */
|
|
2403
2547
|
const runNotes = new Map<string, string>();
|
|
2404
2548
|
/** 1.3: the process-wide lease registry and the guard over it (every v2 child; roots take none). */
|
|
@@ -2472,7 +2616,9 @@ export async function registerV2Hooks(
|
|
|
2472
2616
|
}
|
|
2473
2617
|
// Memo §4.1 steps 3-4: the finish API is attached once (with the lease gate when leases are enforced), then the pending journal
|
|
2474
2618
|
// is reloaded, AWAITED with a 5 s bound before the context hook registers. A failure falls back to fail-closed redaction (§12).
|
|
2475
|
-
|
|
2619
|
+
// #191: attached in every mode, so a verifying call the host backgrounds under `off` is still verified. Under `off` only a
|
|
2620
|
+
// held gate waits for the lease gate (`leaseGateScope: "held"`): a foreground check (OpenCode 2.0.x) keeps its timing and result.
|
|
2621
|
+
{
|
|
2476
2622
|
const attachFinish = (hooks as unknown as Record<PropertyKey, unknown>)[ROUTER_FINISH_ATTACH];
|
|
2477
2623
|
if (typeof attachFinish === "function") {
|
|
2478
2624
|
try {
|
|
@@ -2485,7 +2631,10 @@ export async function registerV2Hooks(
|
|
|
2485
2631
|
return posting;
|
|
2486
2632
|
},
|
|
2487
2633
|
};
|
|
2488
|
-
finishApi = (attachFinish as FinishAttach)({
|
|
2634
|
+
finishApi = (attachFinish as FinishAttach)({
|
|
2635
|
+
host: "v2", held: trackedHeld,
|
|
2636
|
+
...(leaseGuard === undefined ? {} : { leaseGate: leaseGuard, ...(bgMode === "off" ? { leaseGateScope: "held" as const } : {}) }),
|
|
2637
|
+
});
|
|
2489
2638
|
// QA-2.1-33: a recreation of the shared journal by another plugin instance of this process writes these records too.
|
|
2490
2639
|
finishApi?.setAdapterSnapshot?.(adapterRecords);
|
|
2491
2640
|
} catch (error) {
|
|
@@ -2693,7 +2842,25 @@ export async function registerV2Hooks(
|
|
|
2693
2842
|
const ownedExecutor = executor;
|
|
2694
2843
|
executor = null;
|
|
2695
2844
|
hostEventListeners.clear();
|
|
2696
|
-
if (ownedExecutor !== null)
|
|
2845
|
+
if (ownedExecutor !== null) {
|
|
2846
|
+
let executorTimer: ReturnType<typeof setTimeout> | undefined;
|
|
2847
|
+
const finished = await Promise.race([
|
|
2848
|
+
// Keep observing the original disposal: it logs late errors and alone owns release of the repository claim.
|
|
2849
|
+
disposeExecutor(ownedExecutor).then(() => true),
|
|
2850
|
+
new Promise<false>((resolve) => { executorTimer = setTimeout(() => resolve(false), EXECUTOR_DISPOSE_MS); }),
|
|
2851
|
+
]);
|
|
2852
|
+
if (executorTimer !== undefined) clearTimeout(executorTimer);
|
|
2853
|
+
if (!finished) {
|
|
2854
|
+
ingestLogger.warn(`[router] executor: disposal did not finish in ${EXECUTOR_DISPOSE_MS} ms; continuing cleanup; the repository claim stays held until disposal completes (restart clears a stuck claim)`);
|
|
2855
|
+
// W7: runtime disposal was attempted first. Still abort launcher-owned controllers before their runner goes away.
|
|
2856
|
+
// This is idempotent, has no internal waits, and may be called again when the original disposal eventually ends.
|
|
2857
|
+
try {
|
|
2858
|
+
await ownedExecutor.launcher.dispose();
|
|
2859
|
+
} catch (error) {
|
|
2860
|
+
ingestLogger.warn("[router] executor: the launcher could not be disposed", { error: String(error) });
|
|
2861
|
+
}
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2697
2864
|
executorLifetime.abort();
|
|
2698
2865
|
for (const dispose of bgDisposers.reverse()) {
|
|
2699
2866
|
try {
|
|
@@ -2709,6 +2876,10 @@ export async function registerV2Hooks(
|
|
|
2709
2876
|
await engine.dispose();
|
|
2710
2877
|
await eventTask;
|
|
2711
2878
|
await Promise.allSettled(registrations.map((registration) => registration.dispose()));
|
|
2879
|
+
// QA-5.1-29: only now is this copy's `/plan` gone from the host; a copy starting while this one disposes still sees it
|
|
2880
|
+
// as the router's. `routerPlanReleased`: a late call of the disposed transform never records it again.
|
|
2881
|
+
routerPlanReleased = true;
|
|
2882
|
+
routerPlanCommands().delete(routerPlanOwner);
|
|
2712
2883
|
await hooks.dispose?.();
|
|
2713
2884
|
};
|
|
2714
2885
|
|
|
@@ -2717,7 +2888,9 @@ export async function registerV2Hooks(
|
|
|
2717
2888
|
// router-modified agents, which would defeat the originals diff on refresh.
|
|
2718
2889
|
const agents = await ctx.agent.list();
|
|
2719
2890
|
// The legacy config bridge has no host commands. Capture the real registry before our transform owns /plan.
|
|
2720
|
-
|
|
2891
|
+
// QA-5.1-29: a `/plan` a live router copy registered (the old copy of a hot reload) is not a user command.
|
|
2892
|
+
const userPlanCommandDefined = (await ctx.command.list?.())?.data
|
|
2893
|
+
.some((command) => command.name === "plan" && !isRouterPlanCommand(command)) ?? false;
|
|
2721
2894
|
let warnedPlanCommand = false;
|
|
2722
2895
|
const baseSeed: Record<string, LegacyAgent> = {};
|
|
2723
2896
|
for (const agent of agents.data) baseSeed[agent.id] = {
|
|
@@ -2968,6 +3141,12 @@ export async function registerV2Hooks(
|
|
|
2968
3141
|
}
|
|
2969
3142
|
return false;
|
|
2970
3143
|
});
|
|
3144
|
+
// QA-5.1-29: this copy's `/plan`, so a hot-reload copy that lists the commands meanwhile does not take it for a user's.
|
|
3145
|
+
const planDescription = commands.find(([name]) => name === "plan")?.[1].description;
|
|
3146
|
+
if (!routerPlanReleased && typeof planDescription === "string" && planDescription !== "") {
|
|
3147
|
+
routerPlanCommands().set(routerPlanOwner, planDescription);
|
|
3148
|
+
}
|
|
3149
|
+
else routerPlanCommands().delete(routerPlanOwner);
|
|
2971
3150
|
for (const [name, definition] of commands) editor.add({
|
|
2972
3151
|
name,
|
|
2973
3152
|
description: definition.description,
|
|
@@ -3084,20 +3263,20 @@ export async function registerV2Hooks(
|
|
|
3084
3263
|
Object.assign(Object.create(Object.getPrototypeOf(source)), source, { content });
|
|
3085
3264
|
/** The held-result matcher over context messages (copies; `undefined` = unchanged). */
|
|
3086
3265
|
const applyHeldTo = (sid: string, messages: readonly ContextMessage[]): ContextMessage[] | undefined => {
|
|
3087
|
-
const shaped = messages.map((source) => ({ source, parts: source.content }));
|
|
3266
|
+
const shaped = messages.map((source) => ({ source, id: Reflect.get(source, "id"), parts: source.content }));
|
|
3088
3267
|
const result = held.apply(sid, shaped);
|
|
3089
3268
|
if (result === undefined) return undefined;
|
|
3090
3269
|
return result.map((entry) => (entry.parts === entry.source.content ? entry.source : withContent(entry.source, entry.parts)));
|
|
3091
3270
|
};
|
|
3092
|
-
/**
|
|
3093
|
-
const
|
|
3271
|
+
/** `rewrite` over every text part of the messages (copies of the changed messages and parts only; `undefined` = unchanged). */
|
|
3272
|
+
const rewriteTextParts = (messages: readonly ContextMessage[], rewrite: (text: string) => string): ContextMessage[] | undefined => {
|
|
3094
3273
|
let changed = false;
|
|
3095
3274
|
const next = messages.map((message) => {
|
|
3096
3275
|
if (!Array.isArray(message.content)) return message;
|
|
3097
3276
|
let touched = false;
|
|
3098
3277
|
const content = message.content.map((part) => {
|
|
3099
3278
|
if (part.type !== "text") return part;
|
|
3100
|
-
const text =
|
|
3279
|
+
const text = rewrite(part.text);
|
|
3101
3280
|
if (text === part.text) return part;
|
|
3102
3281
|
touched = true;
|
|
3103
3282
|
return { ...part, text };
|
|
@@ -3108,12 +3287,31 @@ export async function registerV2Hooks(
|
|
|
3108
3287
|
});
|
|
3109
3288
|
return changed ? next : undefined;
|
|
3110
3289
|
};
|
|
3290
|
+
/** Auto/model: `[router` line starts in every completion element body (either envelope) are defanged (parity with `defangChildResult`). */
|
|
3291
|
+
const defangMessages = (messages: readonly ContextMessage[]): ContextMessage[] | undefined =>
|
|
3292
|
+
rewriteTextParts(messages, (text) => defangSubagentBodies(text, defangRouterLines));
|
|
3293
|
+
/**
|
|
3294
|
+
* #191, `off`: only the completion element bodies of role children (their tracked attempt names a role) are defanged, as the
|
|
3295
|
+
* foreground path defangs a role child's result (`defangChildResult`); every other report stays as the host sent it.
|
|
3296
|
+
*/
|
|
3297
|
+
const defangRoleMessages = (messages: readonly ContextMessage[]): ContextMessage[] | undefined =>
|
|
3298
|
+
rewriteTextParts(messages, (text) => rewriteChildReportBodies(text, (report) =>
|
|
3299
|
+
inflight.byChild(report.child)?.role === undefined ? undefined : defangRouterLines(report.body)));
|
|
3300
|
+
/**
|
|
3301
|
+
* #174: since OpenCode 2.3.0 the host reports every finished child to its parent, the router's own children too: their raw
|
|
3302
|
+
* text (a grader's JSON, a producer's answer) is not for the orchestrator. Their element bodies become one neutral line in
|
|
3303
|
+
* this request snapshot only (the stored history keeps them); the envelope stays.
|
|
3304
|
+
*/
|
|
3305
|
+
const rewriteRunnerReports = (messages: readonly ContextMessage[]): ContextMessage[] | undefined =>
|
|
3306
|
+
rewriteTextParts(messages, (text) => rewriteRunnerChildReports(text, isRunnerReport));
|
|
3111
3307
|
/**
|
|
3112
3308
|
* DF-1-4: per child, the completion elements already seen in its parent's context, by the message that holds them (QA-DF1-20:
|
|
3113
3309
|
* message id, part and element index; never their content); bounded. Per adapter copy and lost on restart: a `child-ended`
|
|
3114
3310
|
* attempt is read again on its parent's next request, so a skipped element never leaves it waiting for the sweep.
|
|
3115
3311
|
*/
|
|
3116
3312
|
const seenCompletionElements = new Map<string, Set<string>>();
|
|
3313
|
+
/** #174: the children of a completion element with no attempt of its parent that were warned about (once each); bounded. */
|
|
3314
|
+
const warnedCompletionChildren = new Set<string>();
|
|
3117
3315
|
/** Records a completion element of `child`; true only the first time it is seen. */
|
|
3118
3316
|
const noteCompletionElement = (child: string, signature: string): boolean => {
|
|
3119
3317
|
let seen = seenCompletionElements.get(child);
|
|
@@ -3151,6 +3349,7 @@ export async function registerV2Hooks(
|
|
|
3151
3349
|
*/
|
|
3152
3350
|
const scanCompletions = async (sid: string, messages: readonly ContextMessage[]): Promise<void> => {
|
|
3153
3351
|
if (processor === undefined) return;
|
|
3352
|
+
const messageIndices = indexMessageIDs(messages);
|
|
3154
3353
|
const waits: string[] = [];
|
|
3155
3354
|
const scanned: Array<{ child: string; signature: string }> = [];
|
|
3156
3355
|
/** The children an element of this request started processing for. */
|
|
@@ -3163,9 +3362,19 @@ export async function registerV2Hooks(
|
|
|
3163
3362
|
for (const [elementIndex, element] of completionElementsOf(part.text).entries()) {
|
|
3164
3363
|
const attempt = inflight.byChild(element.child);
|
|
3165
3364
|
if (attempt === undefined || attempt.parentSessionID !== sid) {
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
3365
|
+
// #174: the host reports the router's own children too (nothing to process, nothing to say); any other child is
|
|
3366
|
+
// warned about once, not on every request whose history still holds its element. #191: under `off` only verifying
|
|
3367
|
+
// calls are tracked, so a report of any other dispatch is expected and never warned about.
|
|
3368
|
+
if (bgMode !== "off" && !isRunnerReport(element) && !warnedCompletionChildren.has(element.child)) {
|
|
3369
|
+
warnedCompletionChildren.add(element.child);
|
|
3370
|
+
for (const old of warnedCompletionChildren) {
|
|
3371
|
+
if (warnedCompletionChildren.size <= MAX_WARNED_COMPLETION_CHILDREN) break;
|
|
3372
|
+
warnedCompletionChildren.delete(old);
|
|
3373
|
+
}
|
|
3374
|
+
ingestLogger.warn("[router] background: a completion element names a child with no attempt of this parent", {
|
|
3375
|
+
parent: sid, child: element.child, state: element.state, attempt: attempt === undefined ? "none" : attempt.parentSessionID,
|
|
3376
|
+
});
|
|
3377
|
+
}
|
|
3169
3378
|
continue;
|
|
3170
3379
|
}
|
|
3171
3380
|
// DF-1-4: the parent's history keeps the completion element of every earlier turn of a resumed child. An element is
|
|
@@ -3176,6 +3385,11 @@ export async function registerV2Hooks(
|
|
|
3176
3385
|
// state and body: a resumed turn's byte-identical answer is a new element.
|
|
3177
3386
|
const signature = `${messageKey}\0${partIndex}\0${elementIndex}`;
|
|
3178
3387
|
scanned.push({ child: element.child, signature });
|
|
3388
|
+
// A first scan can happen only after resume: seen-element caches alone cannot establish attempt ownership.
|
|
3389
|
+
if (precedesDispatch(messageIndices, messageIndex, attempt.callerMessageID)) {
|
|
3390
|
+
noteCompletionElement(element.child, signature);
|
|
3391
|
+
continue;
|
|
3392
|
+
}
|
|
3179
3393
|
const open = attempt.state === "acknowledged" || attempt.state === "child-ended";
|
|
3180
3394
|
if (open && !noteCompletionElement(element.child, signature)) continue;
|
|
3181
3395
|
if (!open && attempt.state !== "processing") noteCompletionElement(element.child, signature);
|
|
@@ -3212,14 +3426,17 @@ export async function registerV2Hooks(
|
|
|
3212
3426
|
/** The context hook's body (QA-P23-B5: declared before the hook that calls it). */
|
|
3213
3427
|
async function buildContext(event: SessionContext, role: string | undefined): Promise<void> {
|
|
3214
3428
|
// Phase 2.1 (memo §4.4 step 1-2): FIRST, before `chat.params` and before the augmenter reads `event.messages`: no held output
|
|
3215
|
-
// reaches the request, and (auto/model) child text cannot pose as a router line. Mode `off`:
|
|
3429
|
+
// reaches the request, and (auto/model) child text cannot pose as a router line. Mode `off`: the matcher (#191), and the
|
|
3430
|
+
// defang of role children's reports only.
|
|
3216
3431
|
const rawMessages = event.messages;
|
|
3217
3432
|
if (bgActive() && event.messages !== undefined) {
|
|
3218
3433
|
const sid = String(event.sessionID);
|
|
3219
3434
|
adoptSession(sid);
|
|
3220
3435
|
if (reloadFailed) {
|
|
3221
3436
|
// Memo §12: without a reloaded journal every completion not known as processed is redacted (fail closed).
|
|
3437
|
+
// #191: an untracked child this session dispatched under `off` is never held, so its report is not withheld.
|
|
3222
3438
|
const isProcessed = (child: string): boolean => {
|
|
3439
|
+
if (untrackedUnderOff(sid, child)) return true;
|
|
3223
3440
|
const attempt = inflight.byChild(child);
|
|
3224
3441
|
return attempt !== undefined && journal.hasProcessed(attempt.key);
|
|
3225
3442
|
};
|
|
@@ -3238,9 +3455,14 @@ export async function registerV2Hooks(
|
|
|
3238
3455
|
}
|
|
3239
3456
|
const hidden = applyHeldTo(sid, event.messages);
|
|
3240
3457
|
if (hidden !== undefined) event.messages = hidden;
|
|
3241
|
-
const defanged = defangMessages(event.messages);
|
|
3458
|
+
const defanged = bgMode === "off" ? defangRoleMessages(event.messages) : defangMessages(event.messages);
|
|
3242
3459
|
if (defanged !== undefined) event.messages = defanged;
|
|
3243
3460
|
}
|
|
3461
|
+
// #174: in every mode, after the defang (its neutral line is the router's own). `rawMessages` keeps the original for the scan.
|
|
3462
|
+
if (event.messages !== undefined) {
|
|
3463
|
+
const neutral = rewriteRunnerReports(event.messages);
|
|
3464
|
+
if (neutral !== undefined) event.messages = neutral;
|
|
3465
|
+
}
|
|
3244
3466
|
if (protectedAgent(event.agent)) {
|
|
3245
3467
|
try {
|
|
3246
3468
|
// Catalogs use merged session rules; remove widened tools from this
|
|
@@ -3403,10 +3625,26 @@ export async function registerV2Hooks(
|
|
|
3403
3625
|
|
|
3404
3626
|
// 3.1.7 W4: the host's retry hook is registered with the executor below (W1), only when the factory built one (M3).
|
|
3405
3627
|
registrations.push(await ctx.tool.hook("execute.before", async (event) => {
|
|
3628
|
+
// #86: the call as the host handed it, taken before the first await (a shallow copy of its input record). The checks below
|
|
3629
|
+
// resume after awaits; a host that reuses or rewrites the event, or the input record, of a parallel call meanwhile must not
|
|
3630
|
+
// make this call's arguments, authority decision or refusal text those of the other call.
|
|
3631
|
+
const handed: unknown = event.input;
|
|
3632
|
+
const call = {
|
|
3633
|
+
sessionID: event.sessionID, tool: event.tool,
|
|
3634
|
+
input: handed !== null && typeof handed === "object" && !Array.isArray(handed) ? { ...(handed as Record<string, unknown>) } : handed,
|
|
3635
|
+
};
|
|
3636
|
+
const callID = typeof event.id === "string" ? event.id : "";
|
|
3406
3637
|
// 3.1.7 M41 (always on): a plan child without its plan binding is refused every tool call (fail closed). The context hook
|
|
3407
3638
|
// checks a session's first user message; a first tool call that comes before that hook performs the same check here.
|
|
3408
3639
|
await planChildGuard.assertToolAllowed(String(event.sessionID));
|
|
3409
|
-
|
|
3640
|
+
// #161: one session-directory answer per call, taken when first needed: `scopedArgs` and the git metadata guard below share it,
|
|
3641
|
+
// and the call's `execute.after` takes it too (a known one).
|
|
3642
|
+
let callDirectory: Promise<CallDirectory> | undefined;
|
|
3643
|
+
const directoryOfCall = (): Promise<CallDirectory> => (callDirectory ??= callDirectoryOf(String(call.sessionID)).then((found) => {
|
|
3644
|
+
rememberCallDirectory(callID, String(call.sessionID), found);
|
|
3645
|
+
return found;
|
|
3646
|
+
}));
|
|
3647
|
+
const args = await scopedArgs(call, directoryOfCall);
|
|
3410
3648
|
// #84 P2.1 (P-2, handoffs 11/32/33): a role child binds to its dispatch before its tool runs, so `router_run` and
|
|
3411
3649
|
// `router_git_*` resolve the bound work root and the guard reads the dispatch budget. Tiers mode: no role table, no call.
|
|
3412
3650
|
const callerRoles = rolesOf(loadConfig(ctx.location.directory));
|
|
@@ -3423,7 +3661,8 @@ export async function registerV2Hooks(
|
|
|
3423
3661
|
// QA-G-A3-2: a refusal here is thrown before the legacy hook (and its guard) sees the call: the plugin counts it on the
|
|
3424
3662
|
// child's guard state, and the guard's stop (denied_cap) or advisory banner is added to the refusal the child sees.
|
|
3425
3663
|
const refused = (message: string, agent: string | undefined): Error => {
|
|
3426
|
-
|
|
3664
|
+
takeCallDirectory(callID, String(call.sessionID)); // #161: a refused call never reaches execute.after
|
|
3665
|
+
const guard = options.recordRefusal?.(String(event.sessionID), agent, call.tool, args);
|
|
3427
3666
|
return new Error(guard === undefined ? message : `${message}\n${guard}`);
|
|
3428
3667
|
};
|
|
3429
3668
|
if (typeof event.agent !== "string" || event.agent === "") {
|
|
@@ -3434,7 +3673,7 @@ export async function registerV2Hooks(
|
|
|
3434
3673
|
if (callerRole !== undefined) {
|
|
3435
3674
|
let refusal: string | undefined;
|
|
3436
3675
|
try {
|
|
3437
|
-
refusal = await roleToolRefusal(
|
|
3676
|
+
refusal = await roleToolRefusal(call, args, callerRole);
|
|
3438
3677
|
} catch {
|
|
3439
3678
|
refusal = "the router could not check this dispatch's authority (fail closed)";
|
|
3440
3679
|
}
|
|
@@ -3457,7 +3696,10 @@ export async function registerV2Hooks(
|
|
|
3457
3696
|
// QA-2.1-16: the refusal promises a retry; each refused attempt starts one (bounded by PENDING_RELOAD_RETRY_MS).
|
|
3458
3697
|
retryReload();
|
|
3459
3698
|
for (const target of resumeTargetsOf(event.tool, heldArgs, String(event.sessionID))) {
|
|
3460
|
-
|
|
3699
|
+
// #191: an untracked child this session dispatched under `off` was never held; its resume is not refused.
|
|
3700
|
+
if (inflight.byChild(target) === undefined && !untrackedUnderOff(String(event.sessionID), target)) {
|
|
3701
|
+
throw refused(reloadFailedResumeText(target), callerRole);
|
|
3702
|
+
}
|
|
3461
3703
|
}
|
|
3462
3704
|
}
|
|
3463
3705
|
}
|
|
@@ -3495,7 +3737,9 @@ export async function registerV2Hooks(
|
|
|
3495
3737
|
if (cached?.plan !== undefined) continue;
|
|
3496
3738
|
if (cached === undefined) {
|
|
3497
3739
|
// A restarted plan child may have lost its binding too; its launcher protocol belongs to the executor.
|
|
3498
|
-
|
|
3740
|
+
// #161: a host that has not answered within SESSION_INFO_LOOKUP_MS is a target that could not be checked (below).
|
|
3741
|
+
const context = ctx.session.context({ sessionID: child } as Parameters<typeof ctx.session.context>[0]);
|
|
3742
|
+
const first = withoutHostPreamble(firstMessageText(await sessionLookupWithin(context, SESSION_INFO_LOOKUP_MS)) ?? "");
|
|
3499
3743
|
if (first.startsWith(PLAN_CONTEXT_PREFIX) || LAUNCH_HEADER_PATTERN.test(first)) continue;
|
|
3500
3744
|
}
|
|
3501
3745
|
const binding = cached ?? await bind(child, bindingLookup, { maxOf: maxOfRoles(callerRoles) });
|
|
@@ -3508,6 +3752,7 @@ export async function registerV2Hooks(
|
|
|
3508
3752
|
if (recordRoleOrphan(child, "refused")) ingestLogger.warn(message);
|
|
3509
3753
|
else console.debug(message);
|
|
3510
3754
|
const agent = typeof args?.agent === "string" ? args.agent : String(event.agent ?? "unknown");
|
|
3755
|
+
takeCallDirectory(callID, String(call.sessionID)); // #161: a refused call never reaches execute.after
|
|
3511
3756
|
throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.staleResume(child));
|
|
3512
3757
|
}
|
|
3513
3758
|
}
|
|
@@ -3595,8 +3840,16 @@ export async function registerV2Hooks(
|
|
|
3595
3840
|
try {
|
|
3596
3841
|
const original = args && typeof args === "object" ? { ...args } : args;
|
|
3597
3842
|
const output = { args };
|
|
3843
|
+
// The git metadata guard (index.ts) resolves a write-class call's relative paths and repository against the session's own
|
|
3844
|
+
// location, as the host does. #161: this call's answer (shared with `scopedArgs`), else the session's last known directory;
|
|
3845
|
+
// `null` when none is known, which the guard refuses for a session it has not proven to be the root (index.ts).
|
|
3846
|
+
const found = roleActionOf(event.tool) === "edit" ? await directoryOfCall() : undefined;
|
|
3847
|
+
const sessionDirectory: SessionDirectory | undefined = found === undefined ? undefined : found.known ? found.directory : null;
|
|
3598
3848
|
await within(hookContext(event), async () => {
|
|
3599
|
-
await legacy["tool.execute.before"]?.({
|
|
3849
|
+
await legacy["tool.execute.before"]?.({
|
|
3850
|
+
...event, tool: legacyToolName(event.tool), callID: event.id,
|
|
3851
|
+
...(sessionDirectory === undefined ? {} : { [SESSION_DIRECTORY]: sessionDirectory }),
|
|
3852
|
+
}, output);
|
|
3600
3853
|
});
|
|
3601
3854
|
const verifying = (output as Record<PropertyKey, unknown>)[TASK_VERIFICATION] === true;
|
|
3602
3855
|
const banner = (output as Record<PropertyKey, unknown>)[DEPTH_BANNER];
|
|
@@ -3617,7 +3870,10 @@ export async function registerV2Hooks(
|
|
|
3617
3870
|
let background: boolean | undefined = verifying || roleForeground ? false : undefined;
|
|
3618
3871
|
/** QA-PDF12-6: another copy of the plugin in this process claimed the call first; its background flag stands. */
|
|
3619
3872
|
let lostClaim = false;
|
|
3620
|
-
|
|
3873
|
+
// #191: under `off` a verifying or role-routed call is tracked too (its decision is the `off` row: the same `background`
|
|
3874
|
+
// value as above), so a running acknowledgement from a host that backgrounds every child (OpenCode 2.3+) holds and
|
|
3875
|
+
// verifies a verifying call, and keeps a role call's binding and its budget and authority notices until it completes.
|
|
3876
|
+
if (event.tool === "subagent" && bgActive() && finishApi !== undefined && (bgMode !== "off" || verifying || roleForeground)) {
|
|
3621
3877
|
const parent = String(event.sessionID);
|
|
3622
3878
|
// DF-1-9: a parent the plugin never recorded (a reload, past the bound) is resolved, never assumed a root: an
|
|
3623
3879
|
// unrecorded child must not reach the `auto` rows (A-2.1-1, root parents only). A lookup that fails stays foreground;
|
|
@@ -3671,6 +3927,7 @@ export async function registerV2Hooks(
|
|
|
3671
3927
|
} catch (error) {
|
|
3672
3928
|
dispatchRouter.onCallFinished(event.id); // the hook chain rejected the call: it will never reach execute.after (2.2)
|
|
3673
3929
|
inflight.cancel(event.id);
|
|
3930
|
+
takeCallDirectory(callID, String(call.sessionID)); // #161: nor take its directory
|
|
3674
3931
|
throw error;
|
|
3675
3932
|
}
|
|
3676
3933
|
// The input the host will execute (after the legacy hook): the dispatch is registered for ingestion from it, not from what the engine decided (2.2).
|
|
@@ -3763,17 +4020,9 @@ export async function registerV2Hooks(
|
|
|
3763
4020
|
const lastAssistantText = async (child: string): Promise<{ text: string } | undefined> => {
|
|
3764
4021
|
const history = await ctx.session.context({ sessionID: child } as Parameters<typeof ctx.session.context>[0]);
|
|
3765
4022
|
const messages: readonly unknown[] = Array.isArray(history) ? history : [];
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
const message = messages[index] as { type?: unknown; role?: unknown } | undefined;
|
|
3770
|
-
if (message?.type === "assistant" || message?.role === "assistant") {
|
|
3771
|
-
const text = messageText(message);
|
|
3772
|
-
if (text !== undefined) return { text };
|
|
3773
|
-
}
|
|
3774
|
-
// DF-1-4: the newest user prompt opens the current turn; an answer before it belongs to an earlier turn (a resume).
|
|
3775
|
-
if (message?.type === "user" || message?.role === "user") break;
|
|
3776
|
-
}
|
|
4023
|
+
// The shared reader (`child-history.ts`, also the native runner's after a pending result, #167).
|
|
4024
|
+
const reply = lastAssistantReply(history);
|
|
4025
|
+
if (reply !== undefined) return { text: reply.text };
|
|
3777
4026
|
ingestLogger.warn("[router] background: the child's context holds no assistant message", {
|
|
3778
4027
|
child,
|
|
3779
4028
|
shape: Array.isArray(history) ? `array(${messages.length})` : typeof history,
|
|
@@ -3982,7 +4231,9 @@ export async function registerV2Hooks(
|
|
|
3982
4231
|
}
|
|
3983
4232
|
}
|
|
3984
4233
|
}
|
|
3985
|
-
// Phase 2.1 (memo §13): the three turn-state providers.
|
|
4234
|
+
// Phase 2.1 (memo §13): the three turn-state providers. #191: registered in every mode; under `off` they can only list the
|
|
4235
|
+
// verifying calls the host ran in the background anyway (nothing else is tracked there): on 2.0.x, only one the user
|
|
4236
|
+
// backgrounded, so a foreground result leaves them empty.
|
|
3986
4237
|
if (bgActive() && processor !== undefined) {
|
|
3987
4238
|
const completing = processor;
|
|
3988
4239
|
const unregisters = [
|
|
@@ -4087,21 +4338,17 @@ export async function registerV2Hooks(
|
|
|
4087
4338
|
knownAgent: (agent) => config.agent[agent] !== undefined,
|
|
4088
4339
|
lifetime: executorLifetime.signal,
|
|
4089
4340
|
// QA-5.1-26: a claim handover's executor goes through `adopt`, as the factory's does at start.
|
|
4341
|
+
// QA-5.1-32: `adopt` never throws; a wiring that failed partway is undone and answers false (the caller disposes it).
|
|
4090
4342
|
onExecutor: (handed) => {
|
|
4091
|
-
|
|
4092
|
-
try {
|
|
4093
|
-
adopted = adopt(handed);
|
|
4094
|
-
} catch (error) {
|
|
4095
|
-
ingestLogger.warn("[router] executor: the handed-over executor could not be wired", { error: String(error) });
|
|
4096
|
-
// Adopted before the failure: W7 disposes it, so the caller must not.
|
|
4097
|
-
return executor === handed;
|
|
4098
|
-
}
|
|
4343
|
+
const adopted = adopt(handed);
|
|
4099
4344
|
if (adopted) trackBackground(retryHookWiring);
|
|
4100
4345
|
return adopted;
|
|
4101
4346
|
},
|
|
4102
4347
|
};
|
|
4103
|
-
/** Settles once the retry hook of the adopted executor is registered (`adopt`). */
|
|
4348
|
+
/** Settles once the retry hook of the adopted executor is registered and its runtime started (`adopt`). */
|
|
4104
4349
|
let retryHookWiring: Promise<void> = Promise.resolve();
|
|
4350
|
+
/** QA-5.1-32: executors whose wiring failed (`adopt` logged the failure; the startup path logs it no second time). */
|
|
4351
|
+
const unwired = new WeakSet<V2Executor>();
|
|
4105
4352
|
/**
|
|
4106
4353
|
* QA-5.1-26: the one path an executor is adopted by: the factory's at start, or the one a claim handover assembles later
|
|
4107
4354
|
* (`host.onExecutor`). It sets `executor`, which the host events, the step tracking, the launcher metrics and the
|
|
@@ -4109,14 +4356,59 @@ export async function registerV2Hooks(
|
|
|
4109
4356
|
* provider, the executor instructions and the retry hook, and starts the runtime (`start()` is memoised: recovery runs
|
|
4110
4357
|
* once). Idempotent: the executor already adopted answers true and registers nothing again. Refused (false): another
|
|
4111
4358
|
* executor while one is adopted, or any once dispose began (its owner disposes it). The retry hook's registration is
|
|
4112
|
-
* asynchronous: `retryHookWiring` settles with it.
|
|
4359
|
+
* asynchronous: `retryHookWiring` settles with it. QA-5.1-32: never throws; a wiring that fails partway is undone (false).
|
|
4113
4360
|
*/
|
|
4114
|
-
const adopt = (built: V2Executor): boolean => {
|
|
4361
|
+
const adopt = (built: V2Executor, startup = false): boolean => {
|
|
4115
4362
|
if (executor === built) return true;
|
|
4116
4363
|
if (disposed || executor !== null) return false;
|
|
4117
4364
|
executor = built;
|
|
4118
4365
|
const unregisters: Array<() => void> = [];
|
|
4119
|
-
|
|
4366
|
+
const unregisterAll = (): void => {
|
|
4367
|
+
for (const unregister of unregisters.splice(0)) {
|
|
4368
|
+
try {
|
|
4369
|
+
unregister();
|
|
4370
|
+
} catch (error) {
|
|
4371
|
+
ingestLogger.warn("[router] executor: a registration could not be removed", { error: String(error) });
|
|
4372
|
+
}
|
|
4373
|
+
}
|
|
4374
|
+
};
|
|
4375
|
+
registrations.push({ dispose: async () => { unregisterAll(); } });
|
|
4376
|
+
let wiring: Promise<void>;
|
|
4377
|
+
try {
|
|
4378
|
+
wiring = wireExecutor(built, unregisters);
|
|
4379
|
+
} catch (error) {
|
|
4380
|
+
// QA-5.1-32: a partial adopt leaves nothing behind: the executor is not adopted and the caller disposes it. The
|
|
4381
|
+
// one visible line for this failure (the startup path below adds none).
|
|
4382
|
+
unregisterAll();
|
|
4383
|
+
executor = null;
|
|
4384
|
+
unwired.add(built);
|
|
4385
|
+
ingestLogger.warn("[router] executor: it could not be wired; it is disposed and plans are not executed", { error: String(error) });
|
|
4386
|
+
return false;
|
|
4387
|
+
}
|
|
4388
|
+
// QA-5.1-33/-34: the runtime starts once the retry hook is registered, so no plan child it launches or recovers has a
|
|
4389
|
+
// host retry the hook does not see. A failed registration of a handed-over executor still starts it (adopted means
|
|
4390
|
+
// started, QA-5.1-32), without the hook, as before; at startup the caller undoes the adopt instead (`unwireAdopted`).
|
|
4391
|
+
// Nothing starts once dispose began.
|
|
4392
|
+
const startRuntime = (): void => {
|
|
4393
|
+
if (disposed || executor !== built) return;
|
|
4394
|
+
trackBackground((async () => built.runtime.start())().catch((error: unknown) => {
|
|
4395
|
+
ingestLogger.warn("[router] executor: it could not start", { error: String(error) });
|
|
4396
|
+
}));
|
|
4397
|
+
};
|
|
4398
|
+
unwireAdopted = () => {
|
|
4399
|
+
unregisterAll();
|
|
4400
|
+
if (executor === built) executor = null;
|
|
4401
|
+
};
|
|
4402
|
+
retryHookWiring = wiring.then(startRuntime, (error: unknown) => {
|
|
4403
|
+
if (!startup) startRuntime();
|
|
4404
|
+
throw error;
|
|
4405
|
+
});
|
|
4406
|
+
return true;
|
|
4407
|
+
};
|
|
4408
|
+
/** #190: undoes the latest successful `adopt` (its registrations and `executor`); the startup path's async failure. */
|
|
4409
|
+
let unwireAdopted: () => void = () => undefined;
|
|
4410
|
+
/** `adopt`'s registrations (each one's removal goes to `unregisters`); resolves once the retry hook is registered. */
|
|
4411
|
+
const wireExecutor = (built: V2Executor, unregisters: Array<() => void>): Promise<void> => {
|
|
4120
4412
|
// W2 (3.1.7.a): every router tool call of a bound orchestrator refreshes the executor (guard 6, the ready set).
|
|
4121
4413
|
unregisters.push(childRunner.onContextCaptured((c) => {
|
|
4122
4414
|
try {
|
|
@@ -4144,7 +4436,7 @@ export async function registerV2Hooks(
|
|
|
4144
4436
|
}));
|
|
4145
4437
|
// W4 (3.1.7.c, ADR 0007 D13): the host's retry decision feeds the capacity signals; the executor stops the retry of a plan
|
|
4146
4438
|
// child only. Registered only when an executor exists (M3); on any error the decision stays unchanged.
|
|
4147
|
-
|
|
4439
|
+
return ctx.session.hook("retry", async (event) => {
|
|
4148
4440
|
try {
|
|
4149
4441
|
const sessionID = String(event.sessionID);
|
|
4150
4442
|
// QA-3.1-21: the step's `step.started` may still wait in the event loop: the key must name this step, not the last one
|
|
@@ -4168,10 +4460,6 @@ export async function registerV2Hooks(
|
|
|
4168
4460
|
if (disposed) await registration.dispose();
|
|
4169
4461
|
else registrations.push(registration);
|
|
4170
4462
|
});
|
|
4171
|
-
trackBackground(built.runtime.start().catch((error: unknown) => {
|
|
4172
|
-
ingestLogger.warn("[router] executor: it could not start", { error: String(error) });
|
|
4173
|
-
}));
|
|
4174
|
-
return true;
|
|
4175
4463
|
};
|
|
4176
4464
|
let built: V2Executor | null = null;
|
|
4177
4465
|
try {
|
|
@@ -4180,9 +4468,19 @@ export async function registerV2Hooks(
|
|
|
4180
4468
|
ingestLogger.warn("[router] executor: it could not be built; plans are not executed", { error: String(error) });
|
|
4181
4469
|
}
|
|
4182
4470
|
if (built !== null) {
|
|
4183
|
-
if (adopt(built))
|
|
4184
|
-
|
|
4185
|
-
|
|
4471
|
+
if (adopt(built, true)) {
|
|
4472
|
+
try {
|
|
4473
|
+
await retryHookWiring;
|
|
4474
|
+
} catch (error) {
|
|
4475
|
+
// #190 (L1): a retry hook the host refused asynchronously fails the wiring as a synchronous failure does: one
|
|
4476
|
+
// warning, the adopt undone, the executor disposed (never started), and the plugin starts without it.
|
|
4477
|
+
unwireAdopted();
|
|
4478
|
+
ingestLogger.warn("[router] executor: it could not be wired; it is disposed and plans are not executed", { error: String(error) });
|
|
4479
|
+
await disposeExecutor(built);
|
|
4480
|
+
}
|
|
4481
|
+
} else {
|
|
4482
|
+
// QA-5.1-32: a failed wiring was logged by `adopt`; startup goes on without the executor.
|
|
4483
|
+
if (!unwired.has(built)) ingestLogger.warn("[router] executor: the built executor was not adopted; it is disposed", {});
|
|
4186
4484
|
await disposeExecutor(built);
|
|
4187
4485
|
}
|
|
4188
4486
|
}
|
|
@@ -4194,9 +4492,13 @@ export async function registerV2Hooks(
|
|
|
4194
4492
|
dispatchRouter.onCallResult(event.id, resultChild);
|
|
4195
4493
|
const runNote = runNotes.get(event.id);
|
|
4196
4494
|
runNotes.delete(event.id);
|
|
4495
|
+
// #161: the directory this call's `execute.before` used, taken (and dropped) on every path, used by the legacy hook below.
|
|
4496
|
+
const beforeDirectory = takeCallDirectory(typeof event.id === "string" ? event.id : "", String(event.sessionID));
|
|
4197
4497
|
// Phase 2.1 (memo §4.3 steps 1-2). Timing: a non-null child binds the open start; a null child drops it.
|
|
4198
4498
|
let ackText: string | undefined;
|
|
4199
4499
|
if (event.tool === "subagent") {
|
|
4500
|
+
// #174: in every mode, so the runner-description fallback never takes this dispatch's report for the runner's.
|
|
4501
|
+
if (resultChild !== null) noteDispatchedChild(String(event.sessionID), resultChild);
|
|
4200
4502
|
const running = resultChild !== null && ((event as { result?: { output?: { status?: unknown } } }).result)?.output?.status === "running";
|
|
4201
4503
|
if (timings !== undefined) {
|
|
4202
4504
|
try {
|
|
@@ -4210,16 +4512,32 @@ export async function registerV2Hooks(
|
|
|
4210
4512
|
}
|
|
4211
4513
|
}
|
|
4212
4514
|
if (resultChild === null) inflight.cancel(event.id);
|
|
4213
|
-
// A running result
|
|
4515
|
+
// A running result of a tracked call (under `off`: a verifying or role-routed one, #191) with a root parent: register the
|
|
4516
|
+
// attempt (and its hold) BEFORE anything can render a completion.
|
|
4214
4517
|
const parent = String(event.sessionID);
|
|
4215
4518
|
const rec = running && bgActive() && finishApi !== undefined ? inflight.byCall(event.id) : undefined;
|
|
4216
4519
|
if (rec !== undefined && resultChild !== null && knownKindOf(parent) === "root") {
|
|
4217
4520
|
try {
|
|
4218
4521
|
const hold = verifyingCalls.has(event.id) && rec.verificationMode === "required" && held.available && !reloadFailed && finishApi?.canHold(parent) === true;
|
|
4219
4522
|
const handle = hold ? finishApi?.reserveHeld(parent, event.id) : undefined;
|
|
4220
|
-
|
|
4221
|
-
|
|
4222
|
-
|
|
4523
|
+
// QA-2.1-3: a reserved handle that no hold will use goes back at once; left behind, it keeps a pending slot of the
|
|
4524
|
+
// session (and router_verify answers "held" for it) until HELD_RESERVATION_TTL_MS.
|
|
4525
|
+
const releaseReserved = (reserved: string): void => {
|
|
4526
|
+
try {
|
|
4527
|
+
finishApi?.releaseHeld?.(reserved);
|
|
4528
|
+
} catch (error) {
|
|
4529
|
+
ingestLogger.warn("[router] background: the reserved handle could not be released", { error: String(error) });
|
|
4530
|
+
}
|
|
4531
|
+
};
|
|
4532
|
+
let attempt: Attempt | undefined;
|
|
4533
|
+
try {
|
|
4534
|
+
attempt = inflight.acknowledge(event.id, resultChild, {
|
|
4535
|
+
userBackgrounded: rec.decision.background !== true, ...(handle === undefined ? {} : { hold: { handle } }),
|
|
4536
|
+
});
|
|
4537
|
+
} finally {
|
|
4538
|
+
// The acknowledgement registered no attempt (it returned nothing or threw): nothing carries the handle.
|
|
4539
|
+
if (attempt === undefined && handle !== undefined) releaseReserved(handle);
|
|
4540
|
+
}
|
|
4223
4541
|
if (attempt !== undefined) {
|
|
4224
4542
|
const notRunning = `[router] Running in the background (${resultChild}).`;
|
|
4225
4543
|
const unheldText = verifyingCalls.has(event.id) || handle !== undefined
|
|
@@ -4264,11 +4582,7 @@ export async function registerV2Hooks(
|
|
|
4264
4582
|
if (handle !== undefined && !holding) {
|
|
4265
4583
|
// QA-2.1-3: no hold exists, so nothing may say "held": the attempt is a plain verifying one and the handle goes back.
|
|
4266
4584
|
delete attempt.hold;
|
|
4267
|
-
|
|
4268
|
-
finishApi?.releaseHeld?.(handle);
|
|
4269
|
-
} catch (error) {
|
|
4270
|
-
ingestLogger.warn("[router] background: the reserved handle could not be released", { error: String(error) });
|
|
4271
|
-
}
|
|
4585
|
+
releaseReserved(handle);
|
|
4272
4586
|
}
|
|
4273
4587
|
// QA-2.1-3: the acknowledgement text is chosen only after both writes settled.
|
|
4274
4588
|
ackText = holding ? `${notRunning} Its result is held until verification finishes.` : unheldText;
|
|
@@ -4391,9 +4705,12 @@ export async function registerV2Hooks(
|
|
|
4391
4705
|
},
|
|
4392
4706
|
};
|
|
4393
4707
|
await within(hookContext(event), async () => {
|
|
4708
|
+
// #161: the directory the call's `execute.before` used, so the bookkeeping does not depend on a lookup of its own; without
|
|
4709
|
+
// one (none was needed or known, or it expired) a lookup of its own, where an unknown directory makes `scopedArgs` throw
|
|
4710
|
+
// before the legacy hook runs, so no changed file is recorded against the plugin's directory.
|
|
4394
4711
|
await legacy["tool.execute.after"]?.({
|
|
4395
4712
|
...event, tool: legacyToolName(event.tool),
|
|
4396
|
-
callID: event.id, args: await scopedArgs(event),
|
|
4713
|
+
callID: event.id, args: await scopedArgs(event, beforeDirectory === undefined ? undefined : () => Promise.resolve(beforeDirectory)),
|
|
4397
4714
|
}, output);
|
|
4398
4715
|
});
|
|
4399
4716
|
const changed = output.output !== text;
|
|
@@ -4468,6 +4785,8 @@ export async function registerV2Hooks(
|
|
|
4468
4785
|
try {
|
|
4469
4786
|
const data = event.data as Record<string, any>;
|
|
4470
4787
|
hostBudget.onEvent(event.type, data); // handoff 22 (S4): step counts, step-limit tool refusals, overflow failures
|
|
4788
|
+
// #108 slice 4: a revert takes answers out of the session's context; a compaction summarizes them (this backs the hook).
|
|
4789
|
+
if (ANSWER_FORGET_EVENTS.has(event.type) && typeof data?.sessionID === "string") forgetAnswers(data.sessionID);
|
|
4471
4790
|
// QA-P23-2-A1 / QA-P23-3-1: the host names a tool result's saved full output on that session's tool-success event only.
|
|
4472
4791
|
if (HOST_TOOL_SUCCESS_EVENT.test(event.type) && data && Array.isArray(data.outputPaths)) {
|
|
4473
4792
|
rememberOutputs(data.sessionID, data.outputPaths.filter((path: unknown): path is string => typeof path === "string"));
|
|
@@ -4545,7 +4864,8 @@ export async function registerV2Hooks(
|
|
|
4545
4864
|
// QA-2.1-21: tracked, so `dispose` and the settled seam wait for the completion it starts.
|
|
4546
4865
|
// DF-1-4: a `child-ended` attempt met an end before its turn had an answer to read: this end delivers it.
|
|
4547
4866
|
if (attempt.state === "acknowledged" || attempt.state === "child-ended") trackBackground(processor.process(sid, { kind: "end-event", outcome, eventID: event.id, at }));
|
|
4548
|
-
|
|
4867
|
+
// A foreground attempt was finished in-line at its completed result: its end event is expected, not a stray one.
|
|
4868
|
+
else if (attempt.state !== "foreground") ingestLogger.warn("[router] background: an end event met an attempt that is not awaiting one", { child: sid, state: attempt.state, outcome });
|
|
4549
4869
|
} else if (sessionKinds.get(sid) !== "root") {
|
|
4550
4870
|
// A session whose kind is not yet known may be a child whose acknowledgement is still to come (bounded, TTL).
|
|
4551
4871
|
inflight.noteEarlyEnd(sid, { outcome, eventID: event.id, at });
|
|
@@ -4585,6 +4905,8 @@ export async function registerV2Hooks(
|
|
|
4585
4905
|
sessionKinds.delete(data.sessionID);
|
|
4586
4906
|
// QA-2.1-11 / QA-2.1-13: the cached directory, the failed kind lookup and the adoption mark go with the session.
|
|
4587
4907
|
sessionDirs.delete(data.sessionID);
|
|
4908
|
+
lastCallDirs.delete(data.sessionID); // #161: and its last per-call directory
|
|
4909
|
+
forgetCallDirectories(data.sessionID); // #161: and its calls' before-hook directories
|
|
4588
4910
|
failedKinds.delete(data.sessionID);
|
|
4589
4911
|
adoptedSessions.delete(data.sessionID);
|
|
4590
4912
|
refusedAdoptions.delete(data.sessionID);
|