opencode-model-router 2.9.1 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +482 -0
  2. package/README.md +4 -2
  3. package/package.json +12 -5
  4. package/src/compat/background.ts +56 -19
  5. package/src/compat/child-history.ts +134 -0
  6. package/src/compat/child-report.ts +185 -0
  7. package/src/compat/child-session.ts +10 -0
  8. package/src/compat/session-lookup.ts +21 -0
  9. package/src/compat/v2-client.ts +124 -6
  10. package/src/compat/v2-hooks.ts +525 -203
  11. package/src/compat/v2-observations.ts +1 -0
  12. package/src/compat/v2-vocabulary.ts +14 -0
  13. package/src/executor/create.ts +47 -28
  14. package/src/executor/git.ts +226 -30
  15. package/src/executor/integrate/checks.ts +29 -11
  16. package/src/executor/integrate/land.ts +32 -2
  17. package/src/executor/integrate/queue.ts +95 -13
  18. package/src/executor/ledger.ts +16 -12
  19. package/src/executor/lfs-restore.ts +492 -0
  20. package/src/executor/paths.ts +7 -2
  21. package/src/executor/recovery.ts +2 -1
  22. package/src/executor/runtime.ts +1062 -243
  23. package/src/executor/slots/pool.ts +120 -19
  24. package/src/executor/slots/provision.ts +111 -23
  25. package/src/executor/slots/root.ts +81 -0
  26. package/src/executor/types.ts +28 -2
  27. package/src/executor/unattended.ts +6 -1
  28. package/src/executor/verify-trees.ts +507 -0
  29. package/src/guard/enforce.ts +2 -1
  30. package/src/guard/fingerprint.ts +9 -0
  31. package/src/guard/guards.ts +7 -1
  32. package/src/index.ts +191 -31
  33. package/src/router/answer-dedup.ts +198 -0
  34. package/src/router/common-dir.ts +241 -0
  35. package/src/router/config.ts +228 -40
  36. package/src/router/diff-handles.ts +322 -0
  37. package/src/router/diff-summary.ts +318 -0
  38. package/src/router/git-metadata-guard.ts +317 -0
  39. package/src/router/git-tools.ts +1136 -49
  40. package/src/router/read-only.ts +37 -13
  41. package/src/router/role-agents.ts +100 -36
  42. package/src/router/run-summary.ts +253 -0
  43. package/src/router/run-tools.ts +177 -25
  44. package/src/router/sessions.ts +23 -1
  45. package/src/router/tool-paths.ts +62 -4
  46. package/src/routing/classify/rules.ts +93 -14
  47. package/src/routing/roles/read-set.ts +10 -1
  48. package/src/routing/roles/work-root.ts +20 -3
  49. package/src/routing/wire/hint.ts +9 -2
  50. package/src/v2.ts +3 -1
  51. package/src/verify/exec.ts +454 -2
  52. package/src/verify/head.ts +6 -1
  53. package/src/verify/pending.ts +14 -1
  54. package/src/verify/plan-task.ts +86 -26
  55. package/src/verify/reference.ts +60 -7
  56. package/src/verify/runner.ts +14 -6
  57. package/src/verify/tree.ts +34 -10
  58. package/src/verify/types.ts +44 -0
  59. package/src/verify/wiring.ts +134 -22
@@ -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();