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.
@@ -0,0 +1,185 @@
1
+ /**
2
+ * #174: the host's report of a finished child session in its parent's history (memo §4.4, C2), in both envelopes the host
3
+ * writes:
4
+ *
5
+ * - OpenCode 2.0.x: `<subagent sessionID="X" state="S" …>BODY</subagent>`
6
+ * - OpenCode 2.3+: `<background-result kind="subagent" sessionID="X" state="S" description="…">BODY</background-result>`
7
+ * (a synthetic history entry; the host repeats the description on a line after the closing tag).
8
+ *
9
+ * The ONE matcher behind the completion scan, the held-result matcher, the `[router` defang, the fail-closed redaction and the
10
+ * compaction hook, so they cannot drift apart. Attributes may come in any order and extra ones are tolerated. The closing tag
11
+ * is the opening tag's own; an element without one runs to the end of the text, as the 2.0.x matcher did. A
12
+ * `<background-result>` of another `kind` is no child report.
13
+ *
14
+ * Pure, and used by the v2 adapter only: src/index.ts (the v1 entry) reaches this module through background.ts, whose v1 imports
15
+ * are constants and types, so loading it does nothing there.
16
+ */
17
+
18
+ export type ChildReportTag = "subagent" | "background-result";
19
+
20
+ /** The opening tag of one child report. */
21
+ export interface ChildReportOpening {
22
+ /** Where the opening tag starts (its `<`). */
23
+ readonly index: number;
24
+ /** Where the body starts (just past the opening tag's `>`); the end of the text for a tag that is not terminated. */
25
+ readonly bodyStart: number;
26
+ /** false: no `>` follows the tag name anywhere in the text (a cut-off tag). It has no body. */
27
+ readonly terminated: boolean;
28
+ readonly tag: ChildReportTag;
29
+ /** The `sessionID` attribute (never empty). */
30
+ readonly child: string;
31
+ /** The `state` attribute, when there is one (`completed`, `error`, `cancelled`, the router's own `held` …). */
32
+ readonly state: string | undefined;
33
+ /** The `description` attribute, when there is one. */
34
+ readonly description: string | undefined;
35
+ }
36
+
37
+ /** One child report: its opening tag, its body and where it ends. */
38
+ export interface ChildReport extends ChildReportOpening {
39
+ readonly body: string;
40
+ /** Just past the element: past its closing tag, or the end of the text when it has none. */
41
+ readonly end: number;
42
+ readonly closed: boolean;
43
+ }
44
+
45
+ /** Where an opening tag of either envelope may start. */
46
+ const CANDIDATE = /<(subagent|background-result)\s/g;
47
+ /**
48
+ * The strict form of an opening tag, tried first at each candidate (sticky): `name="value"` pairs only, then `>`. A value may
49
+ * hold `>` here, but no line break: a quote a crafted value leaves open cannot run into the body (the 2.3+ body starts on a
50
+ * new line) and pair with a quote there. A tag that is not of this form (a value the host did not escape, with a lone `"`)
51
+ * ends at the FIRST `>` after its name, so a lone quote can never pair with a quote of the body and carry the tag past it; its
52
+ * body may then start too early, never too late.
53
+ */
54
+ const STRICT_OPENING = /<(subagent|background-result)((?:\s+[^\s="<>]+="[^"\n\r]*")*)\s*>/y;
55
+ const ATTRIBUTE = /([^\s="<>]+)="([^"]*)"/g;
56
+
57
+ /** The closing tag of an envelope. */
58
+ export function childReportClose(tag: ChildReportTag): string {
59
+ return `</${tag}>`;
60
+ }
61
+
62
+ /** A cheap pre-check: false only when `text` cannot hold a child report. */
63
+ export function mayHoldChildReport(text: string): boolean {
64
+ return text.includes("<subagent") || text.includes("<background-result");
65
+ }
66
+
67
+ /** The opening-tag finder of one text: the first `>` at or after a position is found once for increasing positions. */
68
+ function openingScanner(text: string): (from: number, child?: string) => ChildReportOpening | undefined {
69
+ const lastGt = text.lastIndexOf(">");
70
+ let gtFrom = 0;
71
+ let gtAt = -2;
72
+ const firstGtFrom = (from: number): number => {
73
+ if (from > lastGt) return -1;
74
+ if (gtFrom <= from && gtAt >= from) return gtAt;
75
+ gtFrom = from;
76
+ gtAt = text.indexOf(">", from);
77
+ return gtAt;
78
+ };
79
+ const strict = new RegExp(STRICT_OPENING.source, "y");
80
+ const openingAt = (index: number, tag: ChildReportTag): ChildReportOpening | undefined => {
81
+ const nameEnd = index + 1 + tag.length;
82
+ let attributes: string;
83
+ let bodyStart: number;
84
+ let terminated = true;
85
+ const gt = firstGtFrom(nameEnd);
86
+ strict.lastIndex = index;
87
+ const match = gt < 0 ? null : strict.exec(text);
88
+ if (match !== null) {
89
+ attributes = match[2] ?? "";
90
+ bodyStart = index + match[0].length;
91
+ } else if (gt >= 0) {
92
+ attributes = text.slice(nameEnd, gt);
93
+ bodyStart = gt + 1;
94
+ } else {
95
+ // No `>` anywhere after the name: a cut-off tag. Its attributes are read up to the next `<`, best effort.
96
+ const lt = text.indexOf("<", nameEnd);
97
+ attributes = text.slice(nameEnd, lt < 0 ? text.length : lt);
98
+ bodyStart = text.length;
99
+ terminated = false;
100
+ }
101
+ const values = new Map<string, string>();
102
+ for (const [, name, value] of attributes.matchAll(ATTRIBUTE)) {
103
+ if (name !== undefined && value !== undefined && !values.has(name)) values.set(name, value);
104
+ }
105
+ const child = values.get("sessionID");
106
+ if (child === undefined || child === "") return undefined;
107
+ const kind = values.get("kind");
108
+ if (tag === "background-result" && kind !== undefined && kind !== "subagent") return undefined;
109
+ return { index, bodyStart, terminated, tag, child, state: values.get("state"), description: values.get("description") };
110
+ };
111
+ const candidates = new RegExp(CANDIDATE.source, "g");
112
+ return (from, child) => {
113
+ candidates.lastIndex = from;
114
+ // A candidate that is no report, or another child's, is passed by one tag name only (never by its body), so a report
115
+ // that sits inside it is still found.
116
+ for (let match = candidates.exec(text); match !== null; match = candidates.exec(text)) {
117
+ const opening = openingAt(match.index, match[1] === "background-result" ? "background-result" : "subagent");
118
+ if (opening !== undefined && (child === undefined || opening.child === child)) return opening;
119
+ }
120
+ return undefined;
121
+ };
122
+ }
123
+
124
+ /**
125
+ * The first child-report opening tag at or after `from` (of `child` only, when given). A tag with no `>` after it is returned
126
+ * with `terminated: false` (the held matcher cuts through the end of the text from it).
127
+ */
128
+ export function nextChildReportOpening(text: string, from = 0, child?: string): ChildReportOpening | undefined {
129
+ if (!mayHoldChildReport(text)) return undefined;
130
+ return openingScanner(text)(from, child);
131
+ }
132
+
133
+ function reportOf(text: string, opening: ChildReportOpening, at: number): ChildReport {
134
+ const close = childReportClose(opening.tag);
135
+ const closed = at >= opening.bodyStart;
136
+ const end = closed ? at + close.length : text.length;
137
+ return { ...opening, body: text.slice(opening.bodyStart, closed ? at : text.length), end, closed };
138
+ }
139
+
140
+ /**
141
+ * The child report a text STARTS with (after leading blanks), or undefined. It is the whole message the host writes for one
142
+ * report (C2): its body runs to the LAST closing tag of its own envelope in the text, so a closing tag and a further report
143
+ * forged inside the child's text neither end it early nor add a report.
144
+ */
145
+ export function leadingChildReport(text: string): ChildReport | undefined {
146
+ const start = text.length - text.trimStart().length;
147
+ if (!text.startsWith("<subagent", start) && !text.startsWith("<background-result", start)) return undefined;
148
+ const opening = openingScanner(text)(start);
149
+ if (opening === undefined || opening.index !== start || !opening.terminated) return undefined;
150
+ return reportOf(text, opening, text.lastIndexOf(childReportClose(opening.tag)));
151
+ }
152
+
153
+ /** Every child report of `text`, in order; a text that starts with one is that one report ({@link leadingChildReport}). */
154
+ export function childReports(text: string): ChildReport[] {
155
+ if (!mayHoldChildReport(text)) return [];
156
+ const leading = leadingChildReport(text);
157
+ if (leading !== undefined) return [leading];
158
+ const found: ChildReport[] = [];
159
+ const next = openingScanner(text);
160
+ let from = 0;
161
+ for (let opening = next(from); opening !== undefined; opening = next(from)) {
162
+ // Not terminated: no `>` follows, so no later tag is terminated either. A cut-off tag has no body.
163
+ if (!opening.terminated) break;
164
+ const report = reportOf(text, opening, text.indexOf(childReportClose(opening.tag), opening.bodyStart));
165
+ found.push(report);
166
+ from = report.end;
167
+ }
168
+ return found;
169
+ }
170
+
171
+ /**
172
+ * `text` with the body of every child report replaced by what `rewrite` returns for it (`undefined` keeps it). The tags stay,
173
+ * and so does everything outside the elements. Pure.
174
+ */
175
+ export function rewriteChildReportBodies(text: string, rewrite: (report: ChildReport) => string | undefined): string {
176
+ let out = "";
177
+ let last = 0;
178
+ for (const report of childReports(text)) {
179
+ const next = rewrite(report);
180
+ if (next === undefined || next === report.body) continue;
181
+ out += text.slice(last, report.bodyStart) + next;
182
+ last = report.bodyStart + report.body.length;
183
+ }
184
+ return last === 0 ? text : out + text.slice(last);
185
+ }
@@ -11,6 +11,16 @@ export const TASK_VERIFICATION = Symbol.for("opencode-model-router.task-verifica
11
11
  /** An advisory depth banner for this call; the v2 bridge delivers it. */
12
12
  export const DEPTH_BANNER = Symbol.for("opencode-model-router.depth-banner");
13
13
 
14
+ /**
15
+ * v2: the calling session's own directory (its location, where the host resolves its relative paths), set by the v2 bridge on
16
+ * the legacy tool.execute.before INPUT of a write-class call; the git metadata guard resolves against it. `null` (#161): the
17
+ * bridge could not learn it (its lookup failed and no directory is known), so the guard refuses the write for a session it has
18
+ * not proven to be the root. V1 hosts never set it.
19
+ */
20
+ export const SESSION_DIRECTORY = Symbol.for("opencode-model-router.session-directory");
21
+ /** The value under {@link SESSION_DIRECTORY}: the session's directory, or `null` when it is unknown. */
22
+ export type SessionDirectory = string | null;
23
+
14
24
  /** A host-owned child lifecycle, so v2 never fabricates REST sessions or IDs. */
15
25
  export interface ChildSessionRequest {
16
26
  /** v2-only read-only grading diagnostics, started after the runner's session/cwd preparation. */
@@ -4,6 +4,7 @@ import type { Plugin } from "@opencode/plugin";
4
4
  import type { ToolContext } from "@opencode/plugin/promise/tool";
5
5
  import type { SessionContext } from "@opencode/plugin/promise/session";
6
6
  import { ResumeRejectedError, type ChildSessionRequest, type ChildSessionRunner } from "./child-session";
7
+ import { historyHasEntry, lastAssistantReply, newestEntryId } from "./child-history";
7
8
  import { markRunnerDispatch, runnerDescription } from "../router/sessions";
8
9
  import {
9
10
  ContextSupersededError,
@@ -32,20 +33,57 @@ export type V2ChildRunner = ChildSessionRunner & ChildRunner & {
32
33
  export interface V2RuntimeOptions {
33
34
  /** Tests only: fixes the process identity (16 lowercase hex). */
34
35
  bootID?: string;
35
- /** Tests only: the clock behind `RetainedContextInfo.capturedAt`. */
36
+ /** Tests only: the clock behind `RetainedContextInfo.capturedAt` and the runner-child registry's expiry. */
36
37
  now?: () => number;
38
+ /** Tests only: overrides {@link RESUME_MARKER_TIMEOUT_MS}. */
39
+ resumeMarkerTimeoutMs?: number;
37
40
  }
38
41
 
39
42
  export const V2_GRADER_AGENT = "model-router-grader";
40
43
  const RETAINED_CONTEXT_LIMIT = 500;
41
44
  /** How long a delegation waits for the host to remove a child it started by mistake before it reports the error. */
42
45
  export const STRAY_CLEANUP_TIMEOUT_MS = 2_000;
46
+ const PENDING_RESULT_ERROR = "[model-router] native subagent did not return a completed child result; verification cannot use a pending result";
47
+ /**
48
+ * #167: how long a resume reads its child's history for the marker before it goes on without one. A plan-executor resume
49
+ * runs inside the executor's 30 s confirmation window (LAUNCH_CONFIRM_TIMEOUT_MS, armed before the runner is called and
50
+ * settled by the resumed child's first step), so a slow read must not spend it.
51
+ */
52
+ export const RESUME_MARKER_TIMEOUT_MS = 5_000;
53
+ /**
54
+ * #174: how long, and how many, of the children this runner started (or resumed) stay known after their run ends. Since
55
+ * OpenCode 2.3.0 the host reports every finished child to its parent, after the runner removed it too; the context hook asks
56
+ * `isRunnerChild` so that report never shows the orchestrator the child's raw text.
57
+ */
58
+ export const RUNNER_CHILD_TTL_MS = 60 * 60 * 1000;
59
+ export const MAX_RUNNER_CHILDREN = 1000;
60
+
61
+ /**
62
+ * #167: `promise`, or a rejection with `signal.reason` as soon as `signal` aborts. The promise adapter of `@opencode/plugin`
63
+ * (2.0.31 to 2.4.1) ignores request options, so a host call given `{ signal }` is not cancelled there; this ends the wait for it
64
+ * anyway. A later settlement of the abandoned promise is absorbed (no unhandled rejection), and the listener is removed.
65
+ */
66
+ function untilAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
67
+ if (signal.aborted) {
68
+ promise.catch(() => {});
69
+ return Promise.reject(signal.reason);
70
+ }
71
+ return new Promise<T>((resolve, reject) => {
72
+ const abort = (): void => reject(signal.reason);
73
+ signal.addEventListener("abort", abort, { once: true });
74
+ promise.then(
75
+ (value) => { signal.removeEventListener("abort", abort); resolve(value); },
76
+ (error: unknown) => { signal.removeEventListener("abort", abort); reject(error); },
77
+ );
78
+ });
79
+ }
43
80
 
44
81
  /** The small v1 client surface still used by the shared hooks. */
45
82
  export function createV2Runtime(ctx: Plugin.Context, options: V2RuntimeOptions = {}) {
46
83
  type ToolScope = { context: ToolContext; active: boolean; info: RetainedContextInfo };
47
84
  const refOf = (info: RetainedContextInfo): ContextRef => ({ bootID: info.bootID, epoch: info.epoch, callID: info.callID });
48
85
  const nowMs = options.now ?? Date.now;
86
+ const markerTimeoutMs = options.resumeMarkerTimeoutMs ?? RESUME_MARKER_TIMEOUT_MS;
49
87
  const currentTool = new AsyncLocalStorage<ToolScope>();
50
88
  const retainedContexts = new Map<string, ToolScope>();
51
89
  const lifetime = new AbortController();
@@ -58,6 +96,20 @@ export function createV2Runtime(ctx: Plugin.Context, options: V2RuntimeOptions =
58
96
  /** Sessions whose retained context the LRU must not evict (M23); a count per session so pins nest. */
59
97
  const pinned = new Map<string, number>();
60
98
  const captureListeners = new Set<(info: RetainedContextInfo) => void>();
99
+ /**
100
+ * #174: the children this runner started or resumed (a stray the host started instead too), each until when it is known.
101
+ * Noted when the runner learns the id and again when the run ends; never dropped by the child's removal or deletion (the
102
+ * host reports it to the parent after that). Bounded: RUNNER_CHILD_TTL_MS after the last note, MAX_RUNNER_CHILDREN oldest first out.
103
+ */
104
+ const runnerChildren = new Map<string, number>();
105
+ const noteRunnerChild = (sessionID: string): void => {
106
+ runnerChildren.delete(sessionID);
107
+ runnerChildren.set(sessionID, nowMs() + RUNNER_CHILD_TTL_MS);
108
+ for (const old of runnerChildren.keys()) {
109
+ if (runnerChildren.size <= MAX_RUNNER_CHILDREN) break;
110
+ runnerChildren.delete(old);
111
+ }
112
+ };
61
113
 
62
114
  const interrupt = async (sessionID: string, signal?: AbortSignal) => {
63
115
  activeChildren.get(sessionID)?.abort();
@@ -192,6 +244,7 @@ export function createV2Runtime(ctx: Plugin.Context, options: V2RuntimeOptions =
192
244
  ]);
193
245
  signal.throwIfAborted();
194
246
  const resumeID = request.resumeSessionID;
247
+ let resumeMarker: string | undefined;
195
248
  if (resumeID !== undefined) {
196
249
  // The host resumes any session id it is given, so ours checks that the child exists and belongs to the
197
250
  // calling session before anything is sent. Whatever the lookup says other than "my child", the caller
@@ -205,6 +258,20 @@ export function createV2Runtime(ctx: Plugin.Context, options: V2RuntimeOptions =
205
258
  throw new ResumeRejectedError(resumeID, `session lookup failed (${error instanceof Error ? error.message : String(error)})`);
206
259
  }
207
260
  if (info?.parentID !== parent) throw new ResumeRejectedError(resumeID, `it is not a child of session ${parent}`);
261
+ // #167: the newest entry before this run, so a waited result is read only from what the run adds (the previous
262
+ // turn's answer stays in the history). Unreadable, or not read within RESUME_MARKER_TIMEOUT_MS, means no marker: a
263
+ // foreground result does not need one.
264
+ const markerDeadline = new AbortController();
265
+ const markerTimer = setTimeout(() => markerDeadline.abort(new Error("[model-router] the resumed child's history was not read in time")), markerTimeoutMs);
266
+ if (typeof markerTimer === "object" && typeof markerTimer.unref === "function") markerTimer.unref();
267
+ const markerSignal = AbortSignal.any([signal, markerDeadline.signal]);
268
+ try {
269
+ resumeMarker = newestEntryId(await untilAborted(ctx.session.context({ sessionID: resumeID }, { signal: markerSignal }), markerSignal));
270
+ } catch {
271
+ signal.throwIfAborted();
272
+ } finally {
273
+ clearTimeout(markerTimer);
274
+ }
208
275
  }
209
276
  // A resumed child is known up front: the host does not create one, and a progress event for another id is an error.
210
277
  let childID: string | undefined = resumeID;
@@ -217,6 +284,7 @@ export function createV2Runtime(ctx: Plugin.Context, options: V2RuntimeOptions =
217
284
  /** Set when the host answered a resume with another child; thrown from `run` whatever the host made of the progress error. */
218
285
  let strayResume: ResumeRejectedError | undefined;
219
286
  if (resumeID !== undefined) {
287
+ noteRunnerChild(resumeID);
220
288
  activeChildren.set(resumeID, controller);
221
289
  if (request.system) childSystems.set(resumeID, request.system);
222
290
  }
@@ -259,6 +327,7 @@ export function createV2Runtime(ctx: Plugin.Context, options: V2RuntimeOptions =
259
327
  async progress(metadata) {
260
328
  const sessionID = metadata.sessionID;
261
329
  if (typeof sessionID === "string" && sessionID !== childID) {
330
+ noteRunnerChild(sessionID);
262
331
  if (childID) {
263
332
  // The host started another child than the one this call is about (a resume that did not resume, or a
264
333
  // second child): no caller knows its id, so it is stopped and removed here before the error, or it
@@ -297,19 +366,55 @@ export function createV2Runtime(ctx: Plugin.Context, options: V2RuntimeOptions =
297
366
  },
298
367
  });
299
368
  const output = result.output as { sessionID?: unknown; status?: unknown; output?: unknown } | undefined;
300
- service?.end(signal.aborted ? "interrupted" : output?.status === "completed" ? "completed" : "error");
369
+ // #174: whatever the result says, a child it names was started by this call (also one no progress event announced).
370
+ if (typeof output?.sessionID === "string" && output.sessionID !== "") noteRunnerChild(output.sessionID);
371
+ const named = childID !== undefined && output?.sessionID === childID;
372
+ let text = named && output?.status === "completed" && typeof output.output === "string" ? output.output : undefined;
373
+ // #167: our child, still at work. Since OpenCode 2.3.0 the native subagent always answers at once with `status: "running"`
374
+ // (reported on 2.4.1), whatever `background: false` says. It is waited for below; any other result is final.
375
+ const pending = named && text === undefined && output?.status === "running";
376
+ // The span ends "completed" only for a child that really completed; a pending child's span ends after its wait, or in the catch.
377
+ if (!pending) service?.end(signal.aborted ? "interrupted" : text !== undefined ? "completed" : "error");
301
378
  // A named child confirms an attempted resume even when its result failed or was aborted.
302
- if (childID && output?.sessionID === childID) await confirmChild(childID);
379
+ if (childID && named) await confirmChild(childID);
303
380
  signal.throwIfAborted();
304
381
  if (resumeID !== undefined && typeof output?.sessionID === "string" && output.sessionID !== resumeID) {
305
382
  const cleanup = await removeStray(output.sessionID);
306
383
  throw new ResumeRejectedError(resumeID, `the host started another child (${output.sessionID}) instead${cleanup}`);
307
384
  }
308
- if (!childID || output?.sessionID !== childID || output.status !== "completed" || typeof output.output !== "string") {
309
- throw new Error("[model-router] native subagent did not return a completed child result; verification cannot use a pending result");
385
+ let resumeMiss: string | undefined;
386
+ if (childID && pending) {
387
+ // Bounded by the combined signal (the grader's deadline and cancellation), even on a host whose `wait` ignores it;
388
+ // a rejected or aborted wait reaches the catch, which interrupts the child. `{ signal }` is passed for hosts that honour it.
389
+ // A resume without its marker can never be graded (see below): it fails at once rather than after the wait.
390
+ if (typeof ctx.session.wait !== "function") throw new Error(PENDING_RESULT_ERROR);
391
+ if (resumeID !== undefined && resumeMarker === undefined) {
392
+ throw new Error(`${PENDING_RESULT_ERROR} (resume: no history marker could be read before the run)`);
393
+ }
394
+ await untilAborted(ctx.session.wait({ sessionID: childID }, { signal }), signal);
395
+ signal.throwIfAborted();
396
+ const history = await untilAborted(ctx.session.context({ sessionID: childID }, { signal }), signal);
397
+ signal.throwIfAborted();
398
+ // Only the turn's newest assistant entry, with text and a completed step, is the answer (`final`): a draft before a
399
+ // tool call never is. A resume reads only entries after its marker, and only an answer to its own prompt there: a run
400
+ // that ended before taking its prompt leaves the previous turn's answer newest. A marker that is gone gives no answer.
401
+ const reply = resumeID === undefined ? lastAssistantReply(history, { final: true })
402
+ : resumeMarker === undefined ? undefined
403
+ : lastAssistantReply(history, { final: true, after: { id: resumeMarker, prompt: request.prompt } });
404
+ // A resume without an answer says which of its own checks failed (a host that rewrites the prompt shows up here).
405
+ if (reply === undefined && resumeMarker !== undefined) {
406
+ resumeMiss = historyHasEntry(history, resumeMarker) ? "no answer to this run's prompt after the marker" : "the history marker is gone";
407
+ }
408
+ // No answer, an empty one, or a turn that ended in an error or whose run ended failed or interrupted (`wait` resolves
409
+ // for those too) is never a result.
410
+ if (reply !== undefined && !reply.failed && reply.text.trim() !== "") text = reply.text;
411
+ }
412
+ if (!childID || text === undefined) {
413
+ throw new Error(resumeMiss === undefined ? PENDING_RESULT_ERROR : `${PENDING_RESULT_ERROR} (resume: ${resumeMiss})`);
310
414
  }
415
+ if (pending) service?.end("completed");
311
416
  await confirmChild(childID);
312
- return { sessionID: childID, text: output.output };
417
+ return { sessionID: childID, text };
313
418
  } catch (error) {
314
419
  service?.end(signal.aborted ? "interrupted" : "error");
315
420
  controller.abort();
@@ -319,6 +424,7 @@ export function createV2Runtime(ctx: Plugin.Context, options: V2RuntimeOptions =
319
424
  throw strayResume ?? error;
320
425
  } finally {
321
426
  withdrawMark?.(); // a hook that never fired must not leave a mark behind
427
+ if (childID) noteRunnerChild(childID); // #174: known for RUNNER_CHILD_TTL_MS after the run, whatever its end
322
428
  if (childID && activeChildren.get(childID) === controller) {
323
429
  childSystems.delete(childID);
324
430
  activeChildren.delete(childID);
@@ -381,6 +487,17 @@ export function createV2Runtime(ctx: Plugin.Context, options: V2RuntimeOptions =
381
487
  const text = childSystems.get(sessionID);
382
488
  if (text && !system.some(part => part.text === text)) system.push({ type: "text", text });
383
489
  },
490
+ /**
491
+ * #174: whether `sessionID` is a child this runner started or resumed, within RUNNER_CHILD_TTL_MS of its run (also after the
492
+ * child was removed or deleted: `forgetSession` and `childRunner.dispose` leave it known).
493
+ */
494
+ isRunnerChild(sessionID: string): boolean {
495
+ const until = runnerChildren.get(sessionID);
496
+ if (until === undefined) return false;
497
+ if (nowMs() <= until) return true;
498
+ runnerChildren.delete(sessionID);
499
+ return false;
500
+ },
384
501
  forgetSession(sessionID: string): void {
385
502
  retainedContexts.delete(sessionID);
386
503
  childSystems.delete(sessionID);
@@ -390,6 +507,7 @@ export function createV2Runtime(ctx: Plugin.Context, options: V2RuntimeOptions =
390
507
  lifetime.abort();
391
508
  captureListeners.clear();
392
509
  pinned.clear();
510
+ runnerChildren.clear();
393
511
  const sessions = [...activeChildren.keys()];
394
512
  retainedContexts.clear();
395
513
  childSystems.clear();