opencode-model-router 2.8.0 → 2.9.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.
Files changed (90) hide show
  1. package/CHANGELOG.md +364 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
@@ -2,6 +2,7 @@ import type { PluginInput } from "@opencode-ai/plugin";
2
2
  import type { RunnerCatalogModel } from "../escalate/resume";
3
3
  import type { CatalogModel, Ingest } from "../routing/outcomes/ingest";
4
4
  import type { HostGenerate } from "../routing/classify/types";
5
+ import type { V2Observations } from "./v2-observations";
5
6
 
6
7
  /** Marks the legacy tool.execute.before output bag when verification starts for
7
8
  * that task call. V1 hosts read only output.args, so this symbol is invisible. */
@@ -12,6 +13,9 @@ export const DEPTH_BANNER = Symbol.for("opencode-model-router.depth-banner");
12
13
 
13
14
  /** A host-owned child lifecycle, so v2 never fabricates REST sessions or IDs. */
14
15
  export interface ChildSessionRequest {
16
+ /** v2-only read-only grading diagnostics, started after the runner's session/cwd preparation. */
17
+ service?: import("../executor/observations").ServiceObservation;
18
+ onServiceStart?: () => void;
15
19
  parentSessionID?: string;
16
20
  cwd?: string;
17
21
  agent?: string;
@@ -53,6 +57,8 @@ export type RouterPluginInput = PluginInput & {
53
57
  routerChildRunner?: ChildSessionRunner;
54
58
  /** Set only by src/v2.ts; absent = v1 host (A3). */
55
59
  routerHost?: "v2";
60
+ /** Diagnostic-only; supplied by v2 setup, never activated on v1. */
61
+ routerObservations?: V2Observations;
56
62
  /**
57
63
  * Set only by src/v2.ts: the host model catalog (`ctx.model.list`): prices child steps (A1) and, with its `variants`
58
64
  * and `limit`, lets the delegate ladder validate variants and size resumes (D10/D11, Phase 2.3).
@@ -0,0 +1,215 @@
1
+ import { scrubText } from "../guard/scrub";
2
+
3
+ /**
4
+ * The turn-state tail (v2 only, Phase 1.2): per-request router state that used to be pushed into the system array
5
+ * (pending list, late notices, route hint) is rendered here and appended after the last real message instead, so the
6
+ * cached prefix stays byte-identical between requests. Nothing here runs at load; the registry is created by the adapter.
7
+ */
8
+
9
+ /** Upper bound of the whole tail in UTF-16 code units: wrapper and overflow line included. */
10
+ export const TURN_STATE_MAX_CHARS = 6000;
11
+
12
+ /** The reserved provider name of the plan section. */
13
+ export const PLAN_PROVIDER_NAME = "plan";
14
+
15
+ /**
16
+ * The order the v2 adapter registers the plan section at (QA-4.1-14). The executor instructions sort right after it
17
+ * (`EXECUTOR_INSTRUCTIONS_ORDER = PLAN_PROVIDER_ORDER + 1`, src/executor/instructions.ts).
18
+ */
19
+ export const PLAN_PROVIDER_ORDER = 60;
20
+
21
+ /**
22
+ * Phase 1.2 (v2 only): the v2 adapter owns the turn-state registry and hands it to the plugin by calling the function
23
+ * stored under this key on the returned hooks object (non-enumerable; absent on v1). It lives here, not in the plugin
24
+ * entry module, because that module must export only `default` (old v1 loaders call every export). The attach function
25
+ * returns `true` when the registry was accepted.
26
+ */
27
+ export const ROUTER_TURN_STATE_ATTACH: unique symbol = Symbol.for("router.turnState.attach");
28
+
29
+ /** Set on the legacy transform's output bag when the request belongs to a root session. */
30
+ export const TURN_STATE_ROOT: unique symbol = Symbol("router.turnState.root");
31
+
32
+ export interface TurnStateProvider {
33
+ name: string;
34
+ order: number;
35
+ render(sid: string): string | undefined;
36
+ active?(sid: string): boolean;
37
+ }
38
+
39
+ export interface TurnStateRegistry {
40
+ /** Returns an idempotent unregister that removes only this registration. */
41
+ registerTurnStateProvider(provider: TurnStateProvider): () => void;
42
+ /** The tail text for the session, or `undefined` when no provider has anything to say. */
43
+ buildTurnState(sid: string): string | undefined;
44
+ /** Whether any provider reports activity for the session (a throw counts as no activity). */
45
+ hasActivity(sid: string): boolean;
46
+ }
47
+
48
+ export interface TurnStateDeps {
49
+ logger: { warn(message: string, meta?: object): void };
50
+ translate?: (text: string) => string;
51
+ }
52
+
53
+ const OPEN = "<router-state>\n";
54
+ const CLOSE = "\n</router-state>";
55
+ const PLAN_SUFFIX = " (router_plan action=status)";
56
+
57
+ /** A fresh Anthropic-style cache marker; the only place the router creates one (no TTL is ever set). */
58
+ export function routerCacheHint(): { type: "ephemeral" } {
59
+ return { type: "ephemeral" };
60
+ }
61
+
62
+ function compareProviders(a: TurnStateProvider, b: TurnStateProvider): number {
63
+ if (a.order !== b.order) return a.order < b.order ? -1 : 1;
64
+ if (a.name === b.name) return 0;
65
+ return a.name < b.name ? -1 : 1;
66
+ }
67
+
68
+ export function createTurnStateRegistry(deps: TurnStateDeps): TurnStateRegistry {
69
+ const translate = deps.translate ?? ((text: string) => text);
70
+ /** One record per registration, so a stale unregister can never remove a later registration. */
71
+ const registrations: { provider: TurnStateProvider }[] = [];
72
+ const logged = new Set<string>();
73
+
74
+ const warnOnce = (name: string, error: unknown): void => {
75
+ if (logged.has(name)) return;
76
+ logged.add(name);
77
+ const message = error instanceof Error ? error.message : String(error);
78
+ deps.logger.warn(`[router] turn state: provider "${name}" failed; section skipped`, { error: scrubText(message) });
79
+ };
80
+
81
+ const ordered = (): TurnStateProvider[] => registrations.map((entry) => entry.provider).sort(compareProviders);
82
+
83
+ const isActive = (provider: TurnStateProvider, sid: string): boolean => {
84
+ if (provider.active === undefined) return false;
85
+ try {
86
+ return provider.active(sid) === true;
87
+ } catch (error) {
88
+ warnOnce(provider.name, error);
89
+ return false;
90
+ }
91
+ };
92
+
93
+ return {
94
+ registerTurnStateProvider(provider) {
95
+ if (typeof provider !== "object" || provider === null
96
+ || typeof provider.name !== "string" || provider.name === ""
97
+ || typeof provider.order !== "number" || !Number.isFinite(provider.order)) {
98
+ throw new Error("turn state provider needs a non-empty name and a finite order");
99
+ }
100
+ if (registrations.some((entry) => entry.provider.name === provider.name)) {
101
+ throw new Error(`turn state provider "${provider.name}" is already registered`);
102
+ }
103
+ const registration = { provider };
104
+ registrations.push(registration);
105
+ return () => {
106
+ const index = registrations.indexOf(registration);
107
+ if (index >= 0) registrations.splice(index, 1);
108
+ };
109
+ },
110
+
111
+ buildTurnState(sid) {
112
+ const providers = ordered();
113
+ const sections: string[] = [];
114
+ for (const provider of providers) {
115
+ let text: string;
116
+ try {
117
+ const rendered: unknown = provider.render(sid);
118
+ if (typeof rendered !== "string") continue;
119
+ text = translate(rendered).trim();
120
+ } catch (error) {
121
+ warnOnce(provider.name, error);
122
+ continue;
123
+ }
124
+ if (text !== "") sections.push(text);
125
+ }
126
+ if (sections.length === 0) return undefined;
127
+ const body = sections.join("\n\n");
128
+ const whole = OPEN + body + CLOSE;
129
+ if (whole.length <= TURN_STATE_MAX_CHARS) return whole;
130
+
131
+ const planActive = providers.some((provider) => provider.name === PLAN_PROVIDER_NAME && isActive(provider, sid));
132
+ const lines = body.split("\n");
133
+ const totalNonBlank = lines.filter((line) => line.trim() !== "").length;
134
+ const overflowLine = (remaining: number): string =>
135
+ `… ${remaining} more ${remaining === 1 ? "line" : "lines"}${planActive ? PLAN_SUFFIX : ""}`;
136
+ // One forward pass: the largest `keep` (lines kept before the overflow line) whose result fits the bound.
137
+ let best = 0;
138
+ let runLen = 0;
139
+ let keptLen = 0;
140
+ let hasKept = false;
141
+ let seenNonBlank = 0;
142
+ for (let i = 0; i < lines.length - 1; i++) {
143
+ const line = lines[i]!;
144
+ runLen = i === 0 ? line.length : runLen + 1 + line.length;
145
+ if (line.trim() !== "") {
146
+ seenNonBlank++;
147
+ keptLen = runLen;
148
+ hasKept = true;
149
+ }
150
+ const outLen = OPEN.length + (hasKept ? keptLen + 1 : 0) + overflowLine(totalNonBlank - seenNonBlank).length + CLOSE.length;
151
+ if (outLen <= TURN_STATE_MAX_CHARS) best = i + 1;
152
+ }
153
+ if (best === 0) {
154
+ // Worst case: the wrapper and the overflow line alone (a few dozen characters, always within the bound).
155
+ return OPEN + overflowLine(totalNonBlank) + CLOSE;
156
+ }
157
+ const kept = lines.slice(0, best);
158
+ while (kept.length > 0 && kept[kept.length - 1]!.trim() === "") kept.pop();
159
+ const remaining = lines.slice(best).filter((line) => line.trim() !== "").length;
160
+ return OPEN + (kept.length > 0 ? kept.join("\n") + "\n" : "") + overflowLine(remaining) + CLOSE;
161
+ },
162
+
163
+ hasActivity(sid) {
164
+ return ordered().some((provider) => isActive(provider, sid));
165
+ },
166
+ };
167
+ }
168
+
169
+ function isRecord(value: unknown): value is Record<string, unknown> {
170
+ return typeof value === "object" && value !== null;
171
+ }
172
+
173
+ /**
174
+ * The part that carries the cache hint: the last text part with visible text (the host drops whitespace-only text),
175
+ * else the last `tool-result` or `media` part (the only other parts the host marks). None otherwise.
176
+ */
177
+ function hintTarget(message: unknown): { content: unknown[]; index: number; part: Record<string, unknown> } | undefined {
178
+ if (!isRecord(message) || !Array.isArray(message.content)) return undefined;
179
+ const content: unknown[] = message.content;
180
+ for (let index = content.length - 1; index >= 0; index--) {
181
+ const part = content[index];
182
+ if (isRecord(part) && part.type === "text" && typeof part.text === "string" && part.text.trim() !== "") return { content, index, part };
183
+ }
184
+ // No visible text: the host marks only a tool result or media part, so only such a part carries the hint. It never
185
+ // marks a tool call, signed reasoning, effort or blank text, so those get no hint (a hint there would be lost).
186
+ for (let index = content.length - 1; index >= 0; index--) {
187
+ const part = content[index];
188
+ if (isRecord(part) && (part.type === "tool-result" || part.type === "media")) return { content, index, part };
189
+ }
190
+ return undefined;
191
+ }
192
+
193
+ /**
194
+ * Appends the tail as a new last message and puts the one router cache hint on the last real message only: on its
195
+ * last non-blank text part, else on its last tool-result or media part, else nowhere (never on an earlier message, so a tool loop does not pin the
196
+ * breakpoint). Pure: host messages, content arrays and parts are never mutated; the changed message is a
197
+ * prototype-preserving copy. `undefined` tail → `undefined` (the caller leaves the messages alone).
198
+ */
199
+ export function placeTurnState<M>(messages: readonly M[], tail: string | undefined, makeTail: (text: string) => M): M[] | undefined {
200
+ if (tail === undefined) return undefined;
201
+ const next = messages.slice();
202
+ const lastIndex = next.length - 1;
203
+ if (lastIndex >= 0) {
204
+ const message = next[lastIndex];
205
+ const target = hintTarget(message);
206
+ if (target !== undefined) {
207
+ const content = target.content.slice();
208
+ content[target.index] = { ...target.part, cache: routerCacheHint() };
209
+ const copy: M = Object.assign(Object.create(Object.getPrototypeOf(message)), message, { content });
210
+ next[lastIndex] = copy;
211
+ }
212
+ }
213
+ next.push(makeTail(tail));
214
+ return next;
215
+ }
@@ -1,9 +1,40 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { randomBytes } from "node:crypto";
2
3
  import type { Plugin } from "@opencode/plugin";
3
4
  import type { ToolContext } from "@opencode/plugin/promise/tool";
4
5
  import type { SessionContext } from "@opencode/plugin/promise/session";
5
- import { ResumeRejectedError, type ChildSessionRunner } from "./child-session";
6
+ import { ResumeRejectedError, type ChildSessionRequest, type ChildSessionRunner } from "./child-session";
6
7
  import { markRunnerDispatch, runnerDescription } from "../router/sessions";
8
+ import {
9
+ ContextSupersededError,
10
+ type ChildRunner,
11
+ type ContextRef,
12
+ type RetainedContextInfo,
13
+ } from "../executor/types";
14
+
15
+ /**
16
+ * A detached run (3.1.5, memo M30): pinned to a context the executor captured earlier (`context`), owned by the
17
+ * executor's own `signal`, and never forwarding progress to the parent call. With `detached` absent the request is
18
+ * the plain one. `model.variant` also accepts `null`, the executor's spelling of "no variant".
19
+ */
20
+ export type V2RunRequest = Omit<ChildSessionRequest, "model"> & {
21
+ model?: { providerID: string; modelID: string; variant?: string | null };
22
+ detached?: true;
23
+ context?: ContextRef;
24
+ };
25
+
26
+ /** The v2 runner: the legacy child-session surface, the executor's `ChildRunner`, and pinning of retained contexts. */
27
+ export type V2ChildRunner = ChildSessionRunner & ChildRunner & {
28
+ /** Keeps the session's retained context out of the LRU until the returned function is called. Nests. */
29
+ pin(sessionID: string): () => void;
30
+ };
31
+
32
+ export interface V2RuntimeOptions {
33
+ /** Tests only: fixes the process identity (16 lowercase hex). */
34
+ bootID?: string;
35
+ /** Tests only: the clock behind `RetainedContextInfo.capturedAt`. */
36
+ now?: () => number;
37
+ }
7
38
 
8
39
  export const V2_GRADER_AGENT = "model-router-grader";
9
40
  const RETAINED_CONTEXT_LIMIT = 500;
@@ -11,13 +42,22 @@ const RETAINED_CONTEXT_LIMIT = 500;
11
42
  export const STRAY_CLEANUP_TIMEOUT_MS = 2_000;
12
43
 
13
44
  /** The small v1 client surface still used by the shared hooks. */
14
- export function createV2Runtime(ctx: Plugin.Context) {
15
- type ToolScope = { context: ToolContext; active: boolean };
45
+ export function createV2Runtime(ctx: Plugin.Context, options: V2RuntimeOptions = {}) {
46
+ type ToolScope = { context: ToolContext; active: boolean; info: RetainedContextInfo };
47
+ const refOf = (info: RetainedContextInfo): ContextRef => ({ bootID: info.bootID, epoch: info.epoch, callID: info.callID });
48
+ const nowMs = options.now ?? Date.now;
16
49
  const currentTool = new AsyncLocalStorage<ToolScope>();
17
50
  const retainedContexts = new Map<string, ToolScope>();
18
51
  const lifetime = new AbortController();
19
52
  const childSystems = new Map<string, string>();
20
53
  const activeChildren = new Map<string, AbortController>();
54
+ /** Identifies this runtime instance; part of every captured context identity (memo 3.1.1 M21). */
55
+ const bootID = options.bootID ?? randomBytes(8).toString("hex");
56
+ /** One counter per instance, shared by all sessions, so `<bootID>:<epoch>` is unique. */
57
+ let captureEpoch = 0;
58
+ /** Sessions whose retained context the LRU must not evict (M23); a count per session so pins nest. */
59
+ const pinned = new Map<string, number>();
60
+ const captureListeners = new Set<(info: RetainedContextInfo) => void>();
21
61
 
22
62
  const interrupt = async (sessionID: string, signal?: AbortSignal) => {
23
63
  activeChildren.get(sessionID)?.abort();
@@ -93,16 +133,49 @@ export function createV2Runtime(ctx: Plugin.Context) {
93
133
  }
94
134
  };
95
135
 
96
- const childRunner: ChildSessionRunner = {
97
- async run(request) {
136
+ const childRunner: V2ChildRunner = {
137
+ bootID,
138
+ retainedContext(sessionID) {
139
+ return retainedContexts.get(sessionID)?.info ?? null;
140
+ },
141
+ onContextCaptured(listener) {
142
+ captureListeners.add(listener);
143
+ return () => { captureListeners.delete(listener); };
144
+ },
145
+ pin(sessionID) {
146
+ pinned.set(sessionID, (pinned.get(sessionID) ?? 0) + 1);
147
+ let released = false;
148
+ return () => {
149
+ if (released) return;
150
+ released = true;
151
+ const left = (pinned.get(sessionID) ?? 1) - 1;
152
+ if (left > 0) pinned.set(sessionID, left);
153
+ else pinned.delete(sessionID);
154
+ };
155
+ },
156
+ async run(request: V2RunRequest) {
98
157
  lifetime.signal.throwIfAborted();
158
+ const detached = request.detached === true;
159
+ let detachedScope: ToolScope | undefined;
160
+ if (detached) {
161
+ // The executor's pinned capture, checked before any host call (memo M30.3): it is the retained entry or nothing.
162
+ const wanted = request.context;
163
+ if (!wanted || !request.signal || !request.parentSessionID) {
164
+ throw new Error("[model-router] a detached child run requires a parent session, a pinned context and a signal");
165
+ }
166
+ const entry = retainedContexts.get(request.parentSessionID);
167
+ if (!entry || entry.info.bootID !== wanted.bootID || entry.info.epoch !== wanted.epoch || entry.info.callID !== wanted.callID) {
168
+ throw new ContextSupersededError(wanted, entry ? refOf(entry.info) : null);
169
+ }
170
+ detachedScope = entry;
171
+ }
99
172
  const current = currentTool.getStore();
100
173
  // A shared background worker can run in a different caller's async
101
174
  // scope. Only a real context previously observed for the requested
102
175
  // parent may authorize that dispatch; never manufacture call/message IDs.
103
- const scope = request.parentSessionID && request.parentSessionID !== current?.context.sessionID
176
+ const scope = detachedScope ?? (request.parentSessionID && request.parentSessionID !== current?.context.sessionID
104
177
  ? retainedContexts.get(request.parentSessionID)
105
- : current;
178
+ : current);
106
179
  if (!scope) throw new Error("[model-router] v2 child dispatch requires an active tool context or a retained context matching its parent");
107
180
  const toolContext = scope.context;
108
181
  // Retained-scope permission prompts remain attributed to the originating
@@ -114,7 +187,7 @@ export function createV2Runtime(ctx: Plugin.Context) {
114
187
  // deadline and plugin lifetime govern cancellation once that call ends.
115
188
  const signal = AbortSignal.any([
116
189
  lifetime.signal, controller.signal,
117
- ...(scope.active ? [toolContext.signal] : []),
190
+ ...(scope.active && !detached ? [toolContext.signal] : []),
118
191
  ...(request.signal ? [request.signal] : []),
119
192
  ]);
120
193
  signal.throwIfAborted();
@@ -153,11 +226,24 @@ export function createV2Runtime(ctx: Plugin.Context) {
153
226
  // (Phase 3.2, H4): the host runs no plugin tool hook for a call made through `ctx.tool.list()`, so the router never sees it and the
154
227
  // mark is withdrawn below unconsumed; it is defensive, for a host that does hook such calls.
155
228
  let withdrawMark: (() => void) | undefined;
229
+ let service: ReturnType<NonNullable<ChildSessionRequest["service"]>["start"]>;
230
+ let serviceAttempted = false;
231
+ const startService = (): void => {
232
+ if (serviceAttempted || request.service === undefined) return;
233
+ serviceAttempted = true;
234
+ try {
235
+ request.onServiceStart?.();
236
+ // Native progress brackets a prompt, not provider attempts. This API exposes no retry/startup
237
+ // boundaries inside execute, so its elapsed time is insufficient intrinsic-service evidence.
238
+ service = request.service.start("service-unattributed", "grading");
239
+ } catch { /* Diagnostics only. */ }
240
+ };
156
241
  try {
157
242
  // A resumed child is registered here, before the host can run it, exactly like a created one is in `progress`.
158
243
  if (resumeID !== undefined) {
159
244
  await request.onCreated(resumeID);
160
245
  signal.throwIfAborted();
246
+ startService();
161
247
  }
162
248
  withdrawMark = markRunnerDispatch({ parentSessionID: toolContext.sessionID, agent: request.agent ?? V2_GRADER_AGENT, prompt: request.prompt });
163
249
  const result = await native.execute({
@@ -201,13 +287,17 @@ export function createV2Runtime(ctx: Plugin.Context) {
201
287
  if (typeof sessionID === "string" && sessionID === childID) await confirmChild(sessionID);
202
288
  // V2 rejects progress outside a running call. Deferred/queued graders
203
289
  // retain settled parent contexts; also tolerate settlement during progress.
204
- if (scope.active) {
290
+ if (scope.active && !detached) {
205
291
  try { await toolContext.progress(metadata); }
206
292
  catch (error) { if (scope.active) throw error; }
207
293
  }
294
+ // The native host prompts only after this progress callback: child creation, cwd move and
295
+ // registration are preparation, not grading. This callback adds no host call or await.
296
+ if (childID !== undefined) startService();
208
297
  },
209
298
  });
210
299
  const output = result.output as { sessionID?: unknown; status?: unknown; output?: unknown } | undefined;
300
+ service?.end(signal.aborted ? "interrupted" : output?.status === "completed" ? "completed" : "error");
211
301
  // A named child confirms an attempted resume even when its result failed or was aborted.
212
302
  if (childID && output?.sessionID === childID) await confirmChild(childID);
213
303
  signal.throwIfAborted();
@@ -221,14 +311,15 @@ export function createV2Runtime(ctx: Plugin.Context) {
221
311
  await confirmChild(childID);
222
312
  return { sessionID: childID, text: output.output };
223
313
  } catch (error) {
314
+ service?.end(signal.aborted ? "interrupted" : "error");
224
315
  controller.abort();
225
- if (childID) {
316
+ if (childID && activeChildren.get(childID) === controller) {
226
317
  try { await ctx.session.interrupt({ sessionID: childID }); } catch { /* keep the original dispatch failure */ }
227
318
  }
228
319
  throw strayResume ?? error;
229
320
  } finally {
230
321
  withdrawMark?.(); // a hook that never fired must not leave a mark behind
231
- if (childID) {
322
+ if (childID && activeChildren.get(childID) === controller) {
232
323
  childSystems.delete(childID);
233
324
  activeChildren.delete(childID);
234
325
  }
@@ -246,13 +337,39 @@ export function createV2Runtime(ctx: Plugin.Context) {
246
337
  return {
247
338
  client,
248
339
  childRunner,
249
- async withToolContext<T>(context: ToolContext, operation: () => Promise<T>): Promise<T> {
340
+ /**
341
+ * Runs `operation` with `context` as its tool context. `retain: false` (QA-PDF12-7) is for a context the plugin rebuilt
342
+ * from journaled data (a background finish, a restored hold): it is used for this operation only and never becomes the
343
+ * parent's retained context, so a later grader of that parent cannot inherit its caller agent.
344
+ */
345
+ async withToolContext<T>(context: ToolContext, operation: () => Promise<T>, options?: { retain?: boolean }): Promise<T> {
250
346
  lifetime.signal.throwIfAborted();
251
- const scope = { context, active: true };
252
- retainedContexts.delete(context.sessionID);
253
- retainedContexts.set(context.sessionID, scope);
254
- while (retainedContexts.size > RETAINED_CONTEXT_LIMIT) {
255
- retainedContexts.delete(retainedContexts.keys().next().value!);
347
+ const retain = options?.retain !== false;
348
+ const info: RetainedContextInfo = {
349
+ sessionID: context.sessionID,
350
+ callID: context.id,
351
+ messageID: context.messageID,
352
+ agent: context.agent,
353
+ capturedAt: new Date(nowMs()).toISOString() as RetainedContextInfo["capturedAt"],
354
+ bootID,
355
+ // A rebuilt context (retain: false) is not a capture: it neither advances the epoch nor notifies listeners.
356
+ epoch: retain ? ++captureEpoch : captureEpoch,
357
+ };
358
+ const scope: ToolScope = { context, active: true, info };
359
+ if (retain) {
360
+ retainedContexts.delete(context.sessionID);
361
+ retainedContexts.set(context.sessionID, scope);
362
+ // The least recently captured unpinned session goes first (M23); pinned sessions are skipped, so a pinned
363
+ // orchestrator can let the map exceed the limit by the number of pins.
364
+ if (retainedContexts.size > RETAINED_CONTEXT_LIMIT) {
365
+ for (const sessionID of retainedContexts.keys()) {
366
+ if (retainedContexts.size <= RETAINED_CONTEXT_LIMIT) break;
367
+ if (!pinned.has(sessionID)) retainedContexts.delete(sessionID);
368
+ }
369
+ }
370
+ for (const listener of [...captureListeners]) {
371
+ try { listener(info); } catch { /* a listener never breaks the tool call */ }
372
+ }
256
373
  }
257
374
  try {
258
375
  return await currentTool.run(scope, operation);
@@ -271,6 +388,8 @@ export function createV2Runtime(ctx: Plugin.Context) {
271
388
  },
272
389
  async dispose(): Promise<void> {
273
390
  lifetime.abort();
391
+ captureListeners.clear();
392
+ pinned.clear();
274
393
  const sessions = [...activeChildren.keys()];
275
394
  retainedContexts.clear();
276
395
  childSystems.clear();