opencode-model-router 2.9.1 → 2.10.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.
@@ -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 { DEPTH_BANNER, TASK_VERIFICATION } from "./child-session";
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, gitMetadataSegment, readSetEligible, readSetPredicate, type InReadSet,
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";
@@ -281,19 +283,6 @@ function translateAdded(before: string, after: string): string {
281
283
  // #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
284
  // ---------------------------------------------------------------------------
283
285
 
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
286
  /**
298
287
  * Handoff 32: `SessionLookup.firstText` — the text parts of the session's first user message, joined (the binding reads the
299
288
  * nonce from its last line). A context without a user message falls back to its first message with text.
@@ -642,7 +631,7 @@ export function toolCallPaths(tool: string, args: unknown): string[] | undefined
642
631
  export function editsGitMetadata(path: string, target: string, root: string): boolean {
643
632
  const base = root.replace(/[\\/]+$/, "");
644
633
  const below = target.length > base.length ? target.slice(base.length) : "";
645
- return [path, below].some((text) => text.split(/[\\/]/).some(gitMetadataSegment));
634
+ return namesGitMetadata(path, below);
646
635
  }
647
636
 
648
637
  /**
@@ -943,10 +932,12 @@ export function normalizeAgentOptions(options: Readonly<Record<string, unknown>>
943
932
  }
944
933
 
945
934
  /** Register the existing router engine on the public OpenCode 2 domain APIs. */
946
- /** One host completion element `<subagent sessionID="X" state="S">body</subagent>` in a message text (memo §4.4, C2). */
947
- interface CompletionElement { child: string; state: "completed" | "error" | "cancelled"; body: string }
948
- // Further attributes after `state` (the host may add some) are tolerated and kept.
949
- const COMPLETION_ELEMENT = /<subagent sessionID="([^"]+)" state="([^"]+)"[^>]*>([\s\S]*?)(?:<\/subagent>|$)/g;
935
+ /**
936
+ * One host completion element in a message text (memo §4.4, C2): `<subagent sessionID="X" state="S">body</subagent>` (2.0.x)
937
+ * or `<background-result kind="subagent" sessionID="X" state="S" …>body</background-result>` (2.3+, #174). Both are matched
938
+ * by child-report.ts only; further attributes (the host may add some) are tolerated and kept.
939
+ */
940
+ export interface CompletionElement { child: string; state: "completed" | "error" | "cancelled"; body: string; description: string | undefined }
950
941
 
951
942
  /** QA-2.1-8: the refusal of a resume while the pending journal is not reloaded (the session may be held). */
952
943
  export function reloadFailedResumeText(child: string): string {
@@ -988,37 +979,31 @@ type ChildEndState =
988
979
  | { outcome: "succeeded" | "failed" | "interrupted"; text?: string }
989
980
  | { outcome: "lost"; text?: undefined; incomplete?: boolean };
990
981
 
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
982
  /**
1018
983
  * QA-2.1-11: a failed session-directory lookup is not repeated for this long (the lease guard calls it per tool call).
1019
984
  * 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
985
  */
1021
986
  export const SESSION_DIR_NEGATIVE_TTL_MS = 2_000;
987
+ /**
988
+ * #161: how long the shared session record (`sessionInfoOf`: the directory, parent and agent the role checks, the file leases and
989
+ * the stale-resume check read) waits for the host's `session.get`; past it the lookup counts as failed. Long on purpose, above
990
+ * background.ts's 5 s LOOKUP_TIMEOUT_MS: a miss refuses a role agent's call, so a slow but healthy host must not cause one.
991
+ */
992
+ export const SESSION_INFO_LOOKUP_MS = 10_000;
993
+ /**
994
+ * #161: how long a tool call waits for the session's current location (its one fresh `session.get`, shared by `scopedArgs` and
995
+ * the git metadata guard). Short: a miss falls back to the session record's directory.
996
+ */
997
+ export const CALL_DIRECTORY_LOOKUP_MS = 2_000;
998
+ /** #161: `lookup`'s answer, or a rejection once `ms` pass without one (the host call itself is left running). */
999
+ function sessionLookupWithin<T>(lookup: PromiseLike<T>, ms: number): Promise<T> {
1000
+ let timer: ReturnType<typeof setTimeout> | undefined;
1001
+ const timeout = new Promise<never>((_resolve, reject) => {
1002
+ timer = setTimeout(() => reject(new Error(`session lookup timed out after ${ms} ms`)), ms);
1003
+ if (typeof timer === "object" && typeof timer.unref === "function") timer.unref();
1004
+ });
1005
+ return Promise.race([lookup, timeout]).finally(() => clearTimeout(timer));
1006
+ }
1022
1007
  /**
1023
1008
  * QA-2.1-25: a failed session-kind lookup is not repeated for this long. Short on purpose: the failure answers `unknown` (root
1024
1009
  * 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 +1030,16 @@ const MAX_SESSION_DIRS = 1000;
1045
1030
  const MAX_ADOPTED_SESSIONS = 5000;
1046
1031
  /** DF-1-4: the children whose completion elements are remembered, and the elements kept per child. */
1047
1032
  const MAX_SEEN_COMPLETION_CHILDREN = 1000;
1033
+ /** #174: dispatched children remembered against the runner-description fallback; unknown children warned about once each. */
1034
+ const MAX_DISPATCHED_CHILDREN = 5000;
1035
+ const MAX_WARNED_COMPLETION_CHILDREN = 1000;
1048
1036
  const MAX_SEEN_COMPLETION_ELEMENTS = 64;
1049
1037
  /** QA-2.1-8: a failed pending-journal reload is tried again at most this often (fail closed meanwhile). */
1050
1038
  export const PENDING_RELOAD_RETRY_MS = 30_000;
1051
1039
  /** QA-2.1-8: `dispose` waits at most this long for the background work in flight (verdict posts, recoveries). */
1052
1040
  const BACKGROUND_DRAIN_MS = 5_000;
1041
+ /** Host-facing executor wait: allow the runtime's 10 s per-plan queue bound plus runtime/pool teardown headroom. */
1042
+ const EXECUTOR_DISPOSE_MS = 30_000;
1053
1043
  /**
1054
1044
  * Non-enumerable slot on the cleanup function `registerV2Hooks` returns: `() => Promise<void>` that resolves once no background
1055
1045
  * work is in flight (verdict posts, recoveries, reloads, including work they start). Lets integration tests await what an
@@ -1058,16 +1048,16 @@ const BACKGROUND_DRAIN_MS = 5_000;
1058
1048
  export const V2_BACKGROUND_SETTLED: unique symbol = Symbol("opencode-model-router.v2.background-settled");
1059
1049
  // QA-2.1-26: a module-private `Symbol()` (not the global registry `Symbol.for`): only code importing this module reaches the seam.
1060
1050
 
1061
- /** The completion elements of a text part that STARTS with one (the host writes a completion as a whole message, C2). */
1062
- function completionElementsOf(text: string): CompletionElement[] {
1063
- if (!text.trimStart().startsWith("<subagent sessionID=\"")) return [];
1064
- const found: CompletionElement[] = [];
1065
- for (const m of text.matchAll(COMPLETION_ELEMENT)) {
1066
- const state = m[2];
1067
- if (state !== "completed" && state !== "error" && state !== "cancelled") continue;
1068
- found.push({ child: m[1] ?? "", state, body: m[3] ?? "" });
1069
- }
1070
- return found;
1051
+ /**
1052
+ * The completion element of a text part that STARTS with one (the host writes a completion as a whole message, C2): that one
1053
+ * element only, its body running to the last closing tag of its envelope (#174: a closing tag or a further report forged in the
1054
+ * child's text neither cuts it nor adds an element). Exported for tests.
1055
+ */
1056
+ export function completionElementsOf(text: string): CompletionElement[] {
1057
+ const report = leadingChildReport(text);
1058
+ const state = report?.state;
1059
+ if (report === undefined || (state !== "completed" && state !== "error" && state !== "cancelled")) return [];
1060
+ return [{ child: report.child, state, body: report.body, description: report.description }];
1071
1061
  }
1072
1062
 
1073
1063
  /**
@@ -1080,27 +1070,32 @@ function completionMessageKey(message: object, index: number): string {
1080
1070
  return `at:${index}`;
1081
1071
  }
1082
1072
 
1083
- /** Applies `defang` to the body of every `<subagent …>` element of a text (a pure rewrite; the element tags stay). */
1073
+ /** Applies `defang` to the body of every completion element of a text, in either envelope (a pure rewrite; the element tags stay). */
1084
1074
  function defangSubagentBodies(text: string, defang: (body: string) => string): string {
1085
- if (!text.includes("<subagent sessionID=\"")) return text;
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
- });
1075
+ return rewriteChildReportBodies(text, (report) => defang(report.body));
1093
1076
  }
1094
1077
 
1095
1078
  /** Memo §12 (fail closed): replaces the body of every completion element whose child `isProcessed` rejects. Pure; the element tags stay. */
1096
1079
  function redactUnprocessedElements(text: string, isProcessed: (child: string) => boolean): string {
1097
- if (!text.includes("<subagent sessionID=\"")) return text;
1098
- return text.replace(COMPLETION_ELEMENT, (whole: string, child: string, _state: string, was: string) => {
1099
- if (isProcessed(child)) return whole;
1100
- const body = `[router] The result of session ${child} is withheld: the router could not restore its verification state.`;
1101
- const closed = whole.endsWith("</subagent>");
1102
- const open = whole.slice(0, whole.length - was.length - (closed ? "</subagent>".length : 0));
1103
- return `${open}${body}${closed ? "</subagent>" : ""}`;
1080
+ return rewriteChildReportBodies(text, (report) => isProcessed(report.child) ? undefined
1081
+ : `[router] The result of session ${report.child} is withheld: the router could not restore its verification state.`);
1082
+ }
1083
+
1084
+ /** #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. */
1085
+ export const RUNNER_CHILD_REPORT_TEXT = "[router] internal child finished; its result is handled by the router.";
1086
+
1087
+ /**
1088
+ * #174: `text` with the body of every completion element whose child `isRunnerReport` accepts replaced by
1089
+ * {@link RUNNER_CHILD_REPORT_TEXT} (the body's leading and trailing blanks kept). Pure; the element tags stay.
1090
+ */
1091
+ export function rewriteRunnerChildReports(text: string, isRunnerReport: (report: ChildReport) => boolean): string {
1092
+ return rewriteChildReportBodies(text, (report) => {
1093
+ if (!isRunnerReport(report)) return undefined;
1094
+ const trimmed = report.body.trim();
1095
+ if (trimmed === "") return RUNNER_CHILD_REPORT_TEXT;
1096
+ const lead = report.body.slice(0, report.body.length - report.body.trimStart().length);
1097
+ const trail = report.body.slice(report.body.trimEnd().length);
1098
+ return `${lead}${RUNNER_CHILD_REPORT_TEXT}${trail}`;
1104
1099
  });
1105
1100
  }
1106
1101
 
@@ -1166,7 +1161,7 @@ export type V2ExecutorFactory = (host: V2ExecutorHost) => V2Executor | null;
1166
1161
  export async function registerV2Hooks(
1167
1162
  ctx: Context,
1168
1163
  hooks: Hooks,
1169
- runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession" | "childRunner">>,
1164
+ runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession" | "childRunner" | "isRunnerChild">>,
1170
1165
  /**
1171
1166
  * `ingest`: the plugin instance's telemetry ingest (M6, QA-2.1-7); without one the adapter ingests nothing.
1172
1167
  * `isBypassed`: the plugin's `/bypass` state (#84 P2.1: the role path's router-gate condition, S10/P-9).
@@ -1662,9 +1657,12 @@ export async function registerV2Hooks(
1662
1657
  };
1663
1658
  /**
1664
1659
  * 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 (a session's location
1666
- * and parent do not move), concurrent lookups share one host call, and a failed lookup is remembered for
1667
- * SESSION_DIR_NEGATIVE_TTL_MS so a tool hook does not pay a failing `ctx.session.get` per call. Bounded; forgotten with the session.
1660
+ * parent (cross-repo P1.5: the orchestrator whose working set widens R). QA-2.1-11: cached per session — the first answer, which
1661
+ * the role checks, the file leases and the stale-resume check keep; the host's session move can change the location later, so
1662
+ * `scopedArgs` and the git metadata guard look it up afresh per call ({@link callDirectoryOf}) and fall back to this record.
1663
+ * Concurrent lookups share one host call, and a failed lookup is remembered for SESSION_DIR_NEGATIVE_TTL_MS so a tool hook does
1664
+ * 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
1665
+ * lookup, so a hung one is never cached for good. Bounded; forgotten with the session.
1668
1666
  */
1669
1667
  type SessionInfo = { directory: string; parentID: string | undefined; agent?: string };
1670
1668
  const sessionDirs = new Map<string, { at: number; info: Promise<SessionInfo>; failed: boolean }>();
@@ -1675,15 +1673,17 @@ export async function registerV2Hooks(
1675
1673
  at: Date.now(), failed: false, info: Promise.resolve<SessionInfo>({ directory: ctx.location.directory, parentID: undefined }),
1676
1674
  };
1677
1675
  entry.info = (async () => {
1678
- const session = await ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]) as unknown as {
1679
- location?: { directory?: unknown }; parentID?: unknown; agent?: unknown;
1680
- };
1681
- const directory = session?.location?.directory;
1682
- const parentID = session?.parentID;
1676
+ const lookup = ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]);
1677
+ const answer: unknown = await sessionLookupWithin(lookup, SESSION_INFO_LOOKUP_MS);
1678
+ // #161: an answer that is no session record is a failed lookup, never a session located in the plugin's directory.
1679
+ if (answer === null || typeof answer !== "object") throw new Error("the host returned no session");
1680
+ const session = answer as { location?: { directory?: unknown }; parentID?: unknown; agent?: unknown };
1681
+ const directory = session.location?.directory;
1682
+ const parentID = session.parentID;
1683
1683
  return {
1684
1684
  directory: typeof directory === "string" && directory !== "" ? directory : ctx.location.directory,
1685
1685
  parentID: typeof parentID === "string" && parentID !== "" ? parentID : undefined,
1686
- agent: typeof session?.agent === "string" && session.agent !== "" ? session.agent : undefined,
1686
+ agent: typeof session.agent === "string" && session.agent !== "" ? session.agent : undefined,
1687
1687
  };
1688
1688
  })();
1689
1689
  entry.info.catch(() => {
@@ -1698,6 +1698,39 @@ export async function registerV2Hooks(
1698
1698
  };
1699
1699
  /** The directory half of {@link sessionInfoOf} (the work-lease wiring's `sessionDir`). */
1700
1700
  const sessionDirectoryOf = (sessionID: string): Promise<string> => sessionInfoOf(sessionID).then((info) => info.directory);
1701
+ /** #161: a session's directory as one tool call sees it; `known: false` when its lookup failed and no directory is known. */
1702
+ type CallDirectory = { readonly known: true; readonly directory: string } | { readonly known: false; readonly error: unknown };
1703
+ /** #161: per session, the directory of its last successful {@link callDirectoryOf} lookup. Bounded; forgotten with the session. */
1704
+ const lastCallDirs = new Map<string, string>();
1705
+ /**
1706
+ * #161: the session's directory for one tool call: its current location, looked up afresh within CALL_DIRECTORY_LOOKUP_MS (the
1707
+ * host's session move changes it; a session that answers without one is in the plugin's directory, as in {@link sessionInfoOf};
1708
+ * an answer that is no session record is a failed lookup). When that lookup fails or gives up, the last known directory: the
1709
+ * last successful lookup's, else the session record's (no host call once it is settled; else its shared lookup, bounded by
1710
+ * SESSION_INFO_LOOKUP_MS) — right unless the session moved since. Unknown only when none is known. Never throws.
1711
+ */
1712
+ const callDirectoryOf = async (sessionID: string): Promise<CallDirectory> => {
1713
+ let failure: unknown;
1714
+ try {
1715
+ const session: unknown = await sessionLookupWithin(ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]), CALL_DIRECTORY_LOOKUP_MS);
1716
+ if (session === null || typeof session !== "object") throw new Error("the host returned no session");
1717
+ const named = (session as { location?: { directory?: unknown } }).location?.directory;
1718
+ const directory = typeof named === "string" && named !== "" ? named : ctx.location.directory;
1719
+ lastCallDirs.delete(sessionID);
1720
+ lastCallDirs.set(sessionID, directory);
1721
+ while (lastCallDirs.size > MAX_SESSION_DIRS) lastCallDirs.delete(lastCallDirs.keys().next().value!);
1722
+ return { known: true, directory };
1723
+ } catch (error) {
1724
+ failure = error;
1725
+ }
1726
+ const last = lastCallDirs.get(sessionID);
1727
+ if (last !== undefined) return { known: true, directory: last };
1728
+ try {
1729
+ return { known: true, directory: await sessionDirectoryOf(sessionID) };
1730
+ } catch {
1731
+ return { known: false, error: failure };
1732
+ }
1733
+ };
1701
1734
  /**
1702
1735
  * 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
1736
  * orchestrator's working set (the session that dispatched it: its dispatch record, else the session's parent) and the
@@ -1870,11 +1903,20 @@ export async function registerV2Hooks(
1870
1903
  /** QA-PDF12-7: a context rebuilt from journaled data runs its operation but never becomes the parent's retained context. */
1871
1904
  const withinRebuilt = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
1872
1905
  runtime ? runtime.withToolContext(context, operation, { retain: false }) : operation();
1873
- const scopedArgs = async (event: { tool: string; input: unknown; sessionID: any }): Promise<any> => {
1906
+ /** `directoryOf`: the call's session directory (execute.before passes its per-call answer; default: a lookup of its own). */
1907
+ const scopedArgs = async (
1908
+ event: { tool: string; input: unknown; sessionID: any },
1909
+ directoryOf: () => Promise<CallDirectory> = () => callDirectoryOf(String(event.sessionID)),
1910
+ ): Promise<any> => {
1874
1911
  const args = taskArgs(event.tool, event.input);
1875
1912
  if (["read", "write", "edit"].includes(event.tool) && typeof args?.filePath === "string" && !isAbsolute(args.filePath)) {
1876
- const session = await ctx.session.get({ sessionID: event.sessionID });
1877
- args.filePath = resolve(session.location?.directory ?? ctx.location.directory, args.filePath);
1913
+ // #161: the host resolves the path against the session's location; when it is unknown (the lookup failed or gave up, and no
1914
+ // directory is known) the call fails, as a failed lookup always did, instead of resolving against the plugin's directory.
1915
+ const found = await directoryOf();
1916
+ if (!found.known) {
1917
+ 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).`);
1918
+ }
1919
+ args.filePath = resolve(found.directory, args.filePath);
1878
1920
  }
1879
1921
  return args;
1880
1922
  };
@@ -2183,15 +2225,62 @@ export async function registerV2Hooks(
2183
2225
  };
2184
2226
  const syntheticRaw: unknown = Reflect.get(ctx.session, "synthetic");
2185
2227
  const syntheticOk = typeof syntheticRaw === "function";
2228
+ /**
2229
+ * #174: whether a completion element reports one of the router's own children (an LLM grader, a `router_delegate` producer, a
2230
+ * plan-executor task: every child the native child runner started). The runner's registry is the signal: it still knows the
2231
+ * child after the run ended and the child was removed. The runner's fixed `description` is a fallback only (a registry that
2232
+ * does not know the child: another runtime, or past its bound), and only for a child neither the in-flight registry nor the
2233
+ * record of dispatched children knows: an orchestrator may title its own dispatch alike, and its report must reach it unchanged.
2234
+ */
2235
+ const isRunnerReport = (report: Pick<ChildReport, "child" | "description">): boolean => {
2236
+ if (runtime?.isRunnerChild?.(report.child) === true) return true;
2237
+ return report.description !== undefined && isRunnerDescription(report.description)
2238
+ && !dispatchedChildren.has(report.child) && inflight.byChild(report.child) === undefined;
2239
+ };
2240
+ /**
2241
+ * #174: the children of the `subagent` calls this adapter's tool hooks saw (orchestrator and role dispatches, in every mode).
2242
+ * The runner's own native calls reach no tool hook, so a child in here is never given the runner-description fallback above.
2243
+ * Bounded, oldest first out.
2244
+ */
2245
+ const dispatchedChildren = new Set<string>();
2246
+ const noteDispatchedChild = (child: string): void => {
2247
+ dispatchedChildren.delete(child);
2248
+ dispatchedChildren.add(child);
2249
+ for (const old of dispatchedChildren) {
2250
+ if (dispatchedChildren.size <= MAX_DISPATCHED_CHILDREN) break;
2251
+ dispatchedChildren.delete(old);
2252
+ }
2253
+ };
2186
2254
  /** The held store, for the compaction hook registered before it exists. */
2187
2255
  let heldRef: HeldResults | undefined;
2188
- /** Memo §4.4 step 5: the compaction hook runs the same matcher over the messages being summarised (C15). Registered only when mode ≠ off. */
2256
+ /**
2257
+ * Memo §4.4 step 5: the compaction hook runs the same matcher over the messages being summarised (C15) when mode ≠ off.
2258
+ * #174: it is registered in every mode, for the runner-child rewrite the context hook also makes in every mode.
2259
+ */
2189
2260
  let compactionRegistered = false;
2190
- if (bgMode !== "off") {
2191
- try {
2192
- registrations.push(await ctx.session.hook("compaction", async (event) => {
2193
- const messages = event.messages;
2194
- if (heldRef === undefined || !Array.isArray(messages)) return;
2261
+ try {
2262
+ registrations.push(await ctx.session.hook("compaction", async (event) => {
2263
+ const messages = event.messages;
2264
+ if (!Array.isArray(messages)) return;
2265
+ /** `rewrite` over the text parts of the messages being summarised; a changed message is replaced by a copy. */
2266
+ const rewriteTexts = (rewrite: (text: string) => string): void => {
2267
+ messages.forEach((source, index) => {
2268
+ const content: unknown = (source as { content?: unknown }).content;
2269
+ if (!Array.isArray(content)) return;
2270
+ let touched = false;
2271
+ const next = content.map((part: unknown) => {
2272
+ const text: unknown = part !== null && typeof part === "object" ? Reflect.get(part, "text") : undefined;
2273
+ const type: unknown = part !== null && typeof part === "object" ? Reflect.get(part, "type") : undefined;
2274
+ if (typeof text !== "string" || (type !== undefined && type !== "text")) return part;
2275
+ const rewritten = rewrite(text);
2276
+ if (rewritten === text) return part;
2277
+ touched = true;
2278
+ return { ...(part as object), text: rewritten };
2279
+ });
2280
+ if (touched) messages[index] = Object.assign(Object.create(Object.getPrototypeOf(source)), source, { content: next });
2281
+ });
2282
+ };
2283
+ if (bgMode !== "off" && heldRef !== undefined) {
2195
2284
  adoptSession(String(event.sessionID));
2196
2285
  if (finishApi !== undefined && reloadFailed) {
2197
2286
  // QA-2.1-8: fail closed exactly like the context hook (memo §12): a summary must not carry a completion this process
@@ -2200,35 +2289,23 @@ export async function registerV2Hooks(
2200
2289
  const attempt = inflight.byChild(child);
2201
2290
  return attempt !== undefined && journal.hasProcessed(attempt.key);
2202
2291
  };
2203
- messages.forEach((source, index) => {
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
- });
2292
+ rewriteTexts((text) => redactUnprocessedElements(text, isProcessed));
2218
2293
  }
2219
- const shaped = messages.map((source) => ({ source, parts: (source as { content?: unknown }).content }));
2294
+ const shaped = messages.map((source) => ({ source, id: (source as { id?: unknown }).id, parts: (source as { content?: unknown }).content }));
2220
2295
  const result = heldRef.apply(String(event.sessionID), shaped);
2221
- if (result === undefined) return;
2222
- result.forEach((entry, index) => {
2296
+ result?.forEach((entry, index) => {
2223
2297
  if (entry.parts !== (entry.source as { content?: unknown }).content) {
2224
2298
  messages[index] = Object.assign(Object.create(Object.getPrototypeOf(entry.source)), entry.source, { content: entry.parts });
2225
2299
  }
2226
2300
  });
2227
- }));
2228
- compactionRegistered = true;
2229
- } catch (error) {
2230
- ingestLogger.warn("[router] background: the compaction hook could not be registered; held results are unavailable", { error: String(error) });
2231
- }
2301
+ }
2302
+ // #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).
2303
+ rewriteTexts((text) => rewriteRunnerChildReports(text, isRunnerReport));
2304
+ }));
2305
+ compactionRegistered = bgMode !== "off";
2306
+ } catch (error) {
2307
+ // Under `off` nothing depends on it but the #174 rewrite of summaries; as before #174, a failure there is not logged.
2308
+ if (bgMode !== "off") ingestLogger.warn("[router] background: the compaction hook could not be registered; held results are unavailable", { error: String(error) });
2232
2309
  }
2233
2310
  const held: HeldResults = createHeldResults({
2234
2311
  observations: options.observations,
@@ -2693,7 +2770,25 @@ export async function registerV2Hooks(
2693
2770
  const ownedExecutor = executor;
2694
2771
  executor = null;
2695
2772
  hostEventListeners.clear();
2696
- if (ownedExecutor !== null) await disposeExecutor(ownedExecutor);
2773
+ if (ownedExecutor !== null) {
2774
+ let executorTimer: ReturnType<typeof setTimeout> | undefined;
2775
+ const finished = await Promise.race([
2776
+ // Keep observing the original disposal: it logs late errors and alone owns release of the repository claim.
2777
+ disposeExecutor(ownedExecutor).then(() => true),
2778
+ new Promise<false>((resolve) => { executorTimer = setTimeout(() => resolve(false), EXECUTOR_DISPOSE_MS); }),
2779
+ ]);
2780
+ if (executorTimer !== undefined) clearTimeout(executorTimer);
2781
+ if (!finished) {
2782
+ 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)`);
2783
+ // W7: runtime disposal was attempted first. Still abort launcher-owned controllers before their runner goes away.
2784
+ // This is idempotent, has no internal waits, and may be called again when the original disposal eventually ends.
2785
+ try {
2786
+ await ownedExecutor.launcher.dispose();
2787
+ } catch (error) {
2788
+ ingestLogger.warn("[router] executor: the launcher could not be disposed", { error: String(error) });
2789
+ }
2790
+ }
2791
+ }
2697
2792
  executorLifetime.abort();
2698
2793
  for (const dispose of bgDisposers.reverse()) {
2699
2794
  try {
@@ -3084,20 +3179,20 @@ export async function registerV2Hooks(
3084
3179
  Object.assign(Object.create(Object.getPrototypeOf(source)), source, { content });
3085
3180
  /** The held-result matcher over context messages (copies; `undefined` = unchanged). */
3086
3181
  const applyHeldTo = (sid: string, messages: readonly ContextMessage[]): ContextMessage[] | undefined => {
3087
- const shaped = messages.map((source) => ({ source, parts: source.content }));
3182
+ const shaped = messages.map((source) => ({ source, id: Reflect.get(source, "id"), parts: source.content }));
3088
3183
  const result = held.apply(sid, shaped);
3089
3184
  if (result === undefined) return undefined;
3090
3185
  return result.map((entry) => (entry.parts === entry.source.content ? entry.source : withContent(entry.source, entry.parts)));
3091
3186
  };
3092
- /** Auto/model: `[router` line starts in every `<subagent …>` element body are defanged (parity with `defangChildResult`). */
3093
- const defangMessages = (messages: readonly ContextMessage[]): ContextMessage[] | undefined => {
3187
+ /** `rewrite` over every text part of the messages (copies of the changed messages and parts only; `undefined` = unchanged). */
3188
+ const rewriteTextParts = (messages: readonly ContextMessage[], rewrite: (text: string) => string): ContextMessage[] | undefined => {
3094
3189
  let changed = false;
3095
3190
  const next = messages.map((message) => {
3096
3191
  if (!Array.isArray(message.content)) return message;
3097
3192
  let touched = false;
3098
3193
  const content = message.content.map((part) => {
3099
3194
  if (part.type !== "text") return part;
3100
- const text = defangSubagentBodies(part.text, defangRouterLines);
3195
+ const text = rewrite(part.text);
3101
3196
  if (text === part.text) return part;
3102
3197
  touched = true;
3103
3198
  return { ...part, text };
@@ -3108,12 +3203,24 @@ export async function registerV2Hooks(
3108
3203
  });
3109
3204
  return changed ? next : undefined;
3110
3205
  };
3206
+ /** Auto/model: `[router` line starts in every completion element body (either envelope) are defanged (parity with `defangChildResult`). */
3207
+ const defangMessages = (messages: readonly ContextMessage[]): ContextMessage[] | undefined =>
3208
+ rewriteTextParts(messages, (text) => defangSubagentBodies(text, defangRouterLines));
3209
+ /**
3210
+ * #174: since OpenCode 2.3.0 the host reports every finished child to its parent, the router's own children too: their raw
3211
+ * text (a grader's JSON, a producer's answer) is not for the orchestrator. Their element bodies become one neutral line in
3212
+ * this request snapshot only (the stored history keeps them); the envelope stays.
3213
+ */
3214
+ const rewriteRunnerReports = (messages: readonly ContextMessage[]): ContextMessage[] | undefined =>
3215
+ rewriteTextParts(messages, (text) => rewriteRunnerChildReports(text, isRunnerReport));
3111
3216
  /**
3112
3217
  * 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
3218
  * message id, part and element index; never their content); bounded. Per adapter copy and lost on restart: a `child-ended`
3114
3219
  * attempt is read again on its parent's next request, so a skipped element never leaves it waiting for the sweep.
3115
3220
  */
3116
3221
  const seenCompletionElements = new Map<string, Set<string>>();
3222
+ /** #174: the children of a completion element with no attempt of its parent that were warned about (once each); bounded. */
3223
+ const warnedCompletionChildren = new Set<string>();
3117
3224
  /** Records a completion element of `child`; true only the first time it is seen. */
3118
3225
  const noteCompletionElement = (child: string, signature: string): boolean => {
3119
3226
  let seen = seenCompletionElements.get(child);
@@ -3151,6 +3258,7 @@ export async function registerV2Hooks(
3151
3258
  */
3152
3259
  const scanCompletions = async (sid: string, messages: readonly ContextMessage[]): Promise<void> => {
3153
3260
  if (processor === undefined) return;
3261
+ const messageIndices = indexMessageIDs(messages);
3154
3262
  const waits: string[] = [];
3155
3263
  const scanned: Array<{ child: string; signature: string }> = [];
3156
3264
  /** The children an element of this request started processing for. */
@@ -3163,9 +3271,18 @@ export async function registerV2Hooks(
3163
3271
  for (const [elementIndex, element] of completionElementsOf(part.text).entries()) {
3164
3272
  const attempt = inflight.byChild(element.child);
3165
3273
  if (attempt === undefined || attempt.parentSessionID !== sid) {
3166
- ingestLogger.warn("[router] background: a completion element names a child with no attempt of this parent", {
3167
- parent: sid, child: element.child, state: element.state, attempt: attempt === undefined ? "none" : attempt.parentSessionID,
3168
- });
3274
+ // #174: the host reports the router's own children too (nothing to process, nothing to say); any other child is
3275
+ // warned about once, not on every request whose history still holds its element.
3276
+ if (!isRunnerReport(element) && !warnedCompletionChildren.has(element.child)) {
3277
+ warnedCompletionChildren.add(element.child);
3278
+ for (const old of warnedCompletionChildren) {
3279
+ if (warnedCompletionChildren.size <= MAX_WARNED_COMPLETION_CHILDREN) break;
3280
+ warnedCompletionChildren.delete(old);
3281
+ }
3282
+ ingestLogger.warn("[router] background: a completion element names a child with no attempt of this parent", {
3283
+ parent: sid, child: element.child, state: element.state, attempt: attempt === undefined ? "none" : attempt.parentSessionID,
3284
+ });
3285
+ }
3169
3286
  continue;
3170
3287
  }
3171
3288
  // DF-1-4: the parent's history keeps the completion element of every earlier turn of a resumed child. An element is
@@ -3176,6 +3293,11 @@ export async function registerV2Hooks(
3176
3293
  // state and body: a resumed turn's byte-identical answer is a new element.
3177
3294
  const signature = `${messageKey}\0${partIndex}\0${elementIndex}`;
3178
3295
  scanned.push({ child: element.child, signature });
3296
+ // A first scan can happen only after resume: seen-element caches alone cannot establish attempt ownership.
3297
+ if (precedesDispatch(messageIndices, messageIndex, attempt.callerMessageID)) {
3298
+ noteCompletionElement(element.child, signature);
3299
+ continue;
3300
+ }
3179
3301
  const open = attempt.state === "acknowledged" || attempt.state === "child-ended";
3180
3302
  if (open && !noteCompletionElement(element.child, signature)) continue;
3181
3303
  if (!open && attempt.state !== "processing") noteCompletionElement(element.child, signature);
@@ -3241,6 +3363,11 @@ export async function registerV2Hooks(
3241
3363
  const defanged = defangMessages(event.messages);
3242
3364
  if (defanged !== undefined) event.messages = defanged;
3243
3365
  }
3366
+ // #174: in every mode, after the defang (its neutral line is the router's own). `rawMessages` keeps the original for the scan.
3367
+ if (event.messages !== undefined) {
3368
+ const neutral = rewriteRunnerReports(event.messages);
3369
+ if (neutral !== undefined) event.messages = neutral;
3370
+ }
3244
3371
  if (protectedAgent(event.agent)) {
3245
3372
  try {
3246
3373
  // Catalogs use merged session rules; remove widened tools from this
@@ -3403,10 +3530,21 @@ export async function registerV2Hooks(
3403
3530
 
3404
3531
  // 3.1.7 W4: the host's retry hook is registered with the executor below (W1), only when the factory built one (M3).
3405
3532
  registrations.push(await ctx.tool.hook("execute.before", async (event) => {
3533
+ // #86: the call as the host handed it, taken before the first await (a shallow copy of its input record). The checks below
3534
+ // resume after awaits; a host that reuses or rewrites the event, or the input record, of a parallel call meanwhile must not
3535
+ // make this call's arguments, authority decision or refusal text those of the other call.
3536
+ const handed: unknown = event.input;
3537
+ const call = {
3538
+ sessionID: event.sessionID, tool: event.tool,
3539
+ input: handed !== null && typeof handed === "object" && !Array.isArray(handed) ? { ...(handed as Record<string, unknown>) } : handed,
3540
+ };
3406
3541
  // 3.1.7 M41 (always on): a plan child without its plan binding is refused every tool call (fail closed). The context hook
3407
3542
  // checks a session's first user message; a first tool call that comes before that hook performs the same check here.
3408
3543
  await planChildGuard.assertToolAllowed(String(event.sessionID));
3409
- const args = await scopedArgs(event);
3544
+ // #161: one session-directory answer per call, taken when first needed: `scopedArgs` and the git metadata guard below share it.
3545
+ let callDirectory: Promise<CallDirectory> | undefined;
3546
+ const directoryOfCall = (): Promise<CallDirectory> => (callDirectory ??= callDirectoryOf(String(call.sessionID)));
3547
+ const args = await scopedArgs(call, directoryOfCall);
3410
3548
  // #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
3549
  // `router_git_*` resolve the bound work root and the guard reads the dispatch budget. Tiers mode: no role table, no call.
3412
3550
  const callerRoles = rolesOf(loadConfig(ctx.location.directory));
@@ -3423,7 +3561,7 @@ export async function registerV2Hooks(
3423
3561
  // 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
3562
  // child's guard state, and the guard's stop (denied_cap) or advisory banner is added to the refusal the child sees.
3425
3563
  const refused = (message: string, agent: string | undefined): Error => {
3426
- const guard = options.recordRefusal?.(String(event.sessionID), agent, event.tool, args);
3564
+ const guard = options.recordRefusal?.(String(event.sessionID), agent, call.tool, args);
3427
3565
  return new Error(guard === undefined ? message : `${message}\n${guard}`);
3428
3566
  };
3429
3567
  if (typeof event.agent !== "string" || event.agent === "") {
@@ -3434,7 +3572,7 @@ export async function registerV2Hooks(
3434
3572
  if (callerRole !== undefined) {
3435
3573
  let refusal: string | undefined;
3436
3574
  try {
3437
- refusal = await roleToolRefusal(event, args, callerRole);
3575
+ refusal = await roleToolRefusal(call, args, callerRole);
3438
3576
  } catch {
3439
3577
  refusal = "the router could not check this dispatch's authority (fail closed)";
3440
3578
  }
@@ -3595,8 +3733,16 @@ export async function registerV2Hooks(
3595
3733
  try {
3596
3734
  const original = args && typeof args === "object" ? { ...args } : args;
3597
3735
  const output = { args };
3736
+ // The git metadata guard (index.ts) resolves a write-class call's relative paths and repository against the session's own
3737
+ // location, as the host does. #161: this call's answer (shared with `scopedArgs`), else the session's last known directory;
3738
+ // `null` when none is known, which the guard refuses for a session it has not proven to be the root (index.ts).
3739
+ const found = roleActionOf(event.tool) === "edit" ? await directoryOfCall() : undefined;
3740
+ const sessionDirectory: SessionDirectory | undefined = found === undefined ? undefined : found.known ? found.directory : null;
3598
3741
  await within(hookContext(event), async () => {
3599
- await legacy["tool.execute.before"]?.({ ...event, tool: legacyToolName(event.tool), callID: event.id }, output);
3742
+ await legacy["tool.execute.before"]?.({
3743
+ ...event, tool: legacyToolName(event.tool), callID: event.id,
3744
+ ...(sessionDirectory === undefined ? {} : { [SESSION_DIRECTORY]: sessionDirectory }),
3745
+ }, output);
3600
3746
  });
3601
3747
  const verifying = (output as Record<PropertyKey, unknown>)[TASK_VERIFICATION] === true;
3602
3748
  const banner = (output as Record<PropertyKey, unknown>)[DEPTH_BANNER];
@@ -3763,17 +3909,9 @@ export async function registerV2Hooks(
3763
3909
  const lastAssistantText = async (child: string): Promise<{ text: string } | undefined> => {
3764
3910
  const history = await ctx.session.context({ sessionID: child } as Parameters<typeof ctx.session.context>[0]);
3765
3911
  const messages: readonly unknown[] = Array.isArray(history) ? history : [];
3766
- for (let index = messages.length - 1; index >= 0; index--) {
3767
- // The host's context entries are discriminated by `type` ("user" | "assistant" | "synthetic", see the instruction filter in
3768
- // the system hook); the model-facing messages of the context hook use `role`. Both name the assistant the same way.
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
- }
3912
+ // The shared reader (`child-history.ts`, also the native runner's after a pending result, #167).
3913
+ const reply = lastAssistantReply(history);
3914
+ if (reply !== undefined) return { text: reply.text };
3777
3915
  ingestLogger.warn("[router] background: the child's context holds no assistant message", {
3778
3916
  child,
3779
3917
  shape: Array.isArray(history) ? `array(${messages.length})` : typeof history,
@@ -4197,6 +4335,8 @@ export async function registerV2Hooks(
4197
4335
  // Phase 2.1 (memo §4.3 steps 1-2). Timing: a non-null child binds the open start; a null child drops it.
4198
4336
  let ackText: string | undefined;
4199
4337
  if (event.tool === "subagent") {
4338
+ // #174: in every mode, so the runner-description fallback never takes this dispatch's report for the runner's.
4339
+ if (resultChild !== null) noteDispatchedChild(resultChild);
4200
4340
  const running = resultChild !== null && ((event as { result?: { output?: { status?: unknown } } }).result)?.output?.status === "running";
4201
4341
  if (timings !== undefined) {
4202
4342
  try {
@@ -4217,9 +4357,24 @@ export async function registerV2Hooks(
4217
4357
  try {
4218
4358
  const hold = verifyingCalls.has(event.id) && rec.verificationMode === "required" && held.available && !reloadFailed && finishApi?.canHold(parent) === true;
4219
4359
  const handle = hold ? finishApi?.reserveHeld(parent, event.id) : undefined;
4220
- const attempt = inflight.acknowledge(event.id, resultChild, {
4221
- userBackgrounded: rec.decision.background !== true, ...(handle === undefined ? {} : { hold: { handle } }),
4222
- });
4360
+ // 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
4361
+ // session (and router_verify answers "held" for it) until HELD_RESERVATION_TTL_MS.
4362
+ const releaseReserved = (reserved: string): void => {
4363
+ try {
4364
+ finishApi?.releaseHeld?.(reserved);
4365
+ } catch (error) {
4366
+ ingestLogger.warn("[router] background: the reserved handle could not be released", { error: String(error) });
4367
+ }
4368
+ };
4369
+ let attempt: Attempt | undefined;
4370
+ try {
4371
+ attempt = inflight.acknowledge(event.id, resultChild, {
4372
+ userBackgrounded: rec.decision.background !== true, ...(handle === undefined ? {} : { hold: { handle } }),
4373
+ });
4374
+ } finally {
4375
+ // The acknowledgement registered no attempt (it returned nothing or threw): nothing carries the handle.
4376
+ if (attempt === undefined && handle !== undefined) releaseReserved(handle);
4377
+ }
4223
4378
  if (attempt !== undefined) {
4224
4379
  const notRunning = `[router] Running in the background (${resultChild}).`;
4225
4380
  const unheldText = verifyingCalls.has(event.id) || handle !== undefined
@@ -4264,11 +4419,7 @@ export async function registerV2Hooks(
4264
4419
  if (handle !== undefined && !holding) {
4265
4420
  // 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
4421
  delete attempt.hold;
4267
- try {
4268
- finishApi?.releaseHeld?.(handle);
4269
- } catch (error) {
4270
- ingestLogger.warn("[router] background: the reserved handle could not be released", { error: String(error) });
4271
- }
4422
+ releaseReserved(handle);
4272
4423
  }
4273
4424
  // QA-2.1-3: the acknowledgement text is chosen only after both writes settled.
4274
4425
  ackText = holding ? `${notRunning} Its result is held until verification finishes.` : unheldText;
@@ -4391,6 +4542,8 @@ export async function registerV2Hooks(
4391
4542
  },
4392
4543
  };
4393
4544
  await within(hookContext(event), async () => {
4545
+ // #161: no store keeps the before-hook's directory per call, so this is a lookup of its own; an unknown directory makes
4546
+ // `scopedArgs` throw before the legacy hook runs, so no changed file is recorded against the plugin's directory.
4394
4547
  await legacy["tool.execute.after"]?.({
4395
4548
  ...event, tool: legacyToolName(event.tool),
4396
4549
  callID: event.id, args: await scopedArgs(event),
@@ -4585,6 +4738,7 @@ export async function registerV2Hooks(
4585
4738
  sessionKinds.delete(data.sessionID);
4586
4739
  // QA-2.1-11 / QA-2.1-13: the cached directory, the failed kind lookup and the adoption mark go with the session.
4587
4740
  sessionDirs.delete(data.sessionID);
4741
+ lastCallDirs.delete(data.sessionID); // #161: and its last per-call directory
4588
4742
  failedKinds.delete(data.sessionID);
4589
4743
  adoptedSessions.delete(data.sessionID);
4590
4744
  refusedAdoptions.delete(data.sessionID);