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
@@ -10,6 +10,7 @@ import { createLeaseRegistry, foldKeyPath, formatRunNote } from "../router/lease
10
10
  import type { LeaseActor, LeaseRegistry, LeaseSeams, Holder, HolderInput } from "../router/leases";
11
11
  import { toolTargets } from "../router/tool-paths";
12
12
  import { observeV2, type V2Observations } from "./v2-observations";
13
+ import { childReportClose, nextChildReportOpening } from "./child-report";
13
14
 
14
15
  // ---- constants -------------------------------------------------------------------------------
15
16
 
@@ -378,6 +379,11 @@ export type FinishAttach = (deps: {
378
379
  held: HeldSink;
379
380
  /** The lease gate before plugin verification runs (memo §2.5); absent when `routing.leases.mode` is not `enforce`. */
380
381
  leaseGate?: Pick<LeaseGuard, "waitTreeFree">;
382
+ /**
383
+ * #191: which checks wait for `leaseGate`. Absent: every plugin check. `"held"` (`routing.background.mode: "off"`): only the
384
+ * gate of a held result; a foreground check keeps the timing and result it had without a lease gate.
385
+ */
386
+ leaseGateScope?: "held";
381
387
  }) => FinishApi | undefined;
382
388
 
383
389
  // ---- in-flight registry ----------------------------------------------------------------------
@@ -497,6 +503,24 @@ export function attemptKey(childSessionID: string, callID: string): string {
497
503
  return `${childSessionID}\u0000${callID}`;
498
504
  }
499
505
 
506
+ /** Index a history once; keep the first occurrence, as the boundary lookup's former `findIndex` did. */
507
+ export function indexMessageIDs(messages: readonly unknown[]): ReadonlyMap<string, number> {
508
+ const indices = new Map<string, number>();
509
+ messages.forEach((message, index) => {
510
+ const id: unknown = message !== null && typeof message === "object" ? Reflect.get(message, "id") : undefined;
511
+ if (typeof id === "string" && !indices.has(id)) indices.set(id, index);
512
+ });
513
+ return indices;
514
+ }
515
+
516
+ /** A completion at or before the message dispatching an attempt belongs to an earlier turn, even if never scanned before. */
517
+ export function precedesDispatch(messageIndices: ReadonlyMap<string, number>, index: number, callerMessageID: string | undefined): boolean {
518
+ if (callerMessageID === undefined) return false;
519
+ // An absent caller may have been compacted out before OR after these messages; its position cannot be inferred safely.
520
+ const caller = messageIndices.get(callerMessageID);
521
+ return caller !== undefined && caller >= index;
522
+ }
523
+
500
524
  /** 3.1.7 W5: the record belongs to the plan executor (excluded from the ordinary completion and verification path). */
501
525
  export function isExecutorOwned(rec: CallRecord | undefined): boolean {
502
526
  return rec?.owner === "executor";
@@ -860,7 +884,6 @@ export interface HeldResults extends HeldSink {
860
884
  persisted(): PersistedRecord[];
861
885
  }
862
886
 
863
- const SUBAGENT_CLOSE = "</subagent>";
864
887
  const VERDICT_PREFIX = "<router-verdict ";
865
888
  const SYNTHETIC_ATTEMPTS = 3;
866
889
  /** = BACKGROUND_RETRY_BASE_MS (verify/pending.ts:442); kept local so this module imports nothing heavy. */
@@ -956,7 +979,7 @@ export function createHeldResults(deps: {
956
979
  byHandle.delete(entry.handle);
957
980
  const children = byParent.get(entry.parentSessionID);
958
981
  if (children === undefined) return;
959
- if (children.get(entry.childSessionID) === entry) children.delete(entry.childSessionID);
982
+ children.delete(entry.handle);
960
983
  if (children.size === 0) byParent.delete(entry.parentSessionID);
961
984
  }
962
985
 
@@ -966,7 +989,8 @@ export function createHeldResults(deps: {
966
989
  children = new Map();
967
990
  byParent.set(entry.parentSessionID, children);
968
991
  }
969
- children.set(entry.childSessionID, entry);
992
+ // Keep released attempts too: their historical completions must retain their own placeholders after a resume.
993
+ children.set(entry.handle, entry);
970
994
  byHandle.set(entry.handle, entry);
971
995
  }
972
996
 
@@ -991,18 +1015,23 @@ export function createHeldResults(deps: {
991
1015
  return [...(byParent.get(sessionID)?.values() ?? [])];
992
1016
  }
993
1017
 
994
- function applyText(sessionID: string, text: string): string {
1018
+ function applyText(sessionID: string, text: string,
1019
+ entries: ReadonlyMap<string, HoldEntry> = new Map(heldChildren(sessionID).map((entry) => [entry.childSessionID, entry]))): string {
995
1020
  if (text.startsWith(VERDICT_PREFIX)) return text;
996
1021
  let out = text;
997
- for (const entry of heldChildren(sessionID)) {
998
- const marker = `<subagent sessionID="${entry.childSessionID}"`;
1022
+ // One attempt per child, selected by the containing message's dispatch boundary in `apply`.
1023
+ const placeholders = heldChildren(sessionID).map((entry) => heldPlaceholder(entry.handle, entry.childSessionID));
1024
+ for (const entry of entries.values()) {
999
1025
  const placeholder = heldPlaceholder(entry.handle, entry.childSessionID);
1000
1026
  let from = 0;
1001
1027
  for (;;) {
1002
- const at = out.indexOf(marker, from);
1003
- if (at < 0) break;
1004
- if (out.startsWith(placeholder, at)) {
1005
- from = at + placeholder.length;
1028
+ // #174: the child's completion element in either envelope (`<subagent …>`, 2.3+ `<background-result kind="subagent" …>`).
1029
+ const opening = nextChildReportOpening(out, from, entry.childSessionID);
1030
+ if (opening === undefined) break;
1031
+ const at = opening.index;
1032
+ const prior = placeholders.find((known) => out.startsWith(known, at));
1033
+ if (prior !== undefined) {
1034
+ from = at + prior.length;
1006
1035
  continue;
1007
1036
  }
1008
1037
  if (at === 0) {
@@ -1012,12 +1041,10 @@ export function createHeldResults(deps: {
1012
1041
  }
1013
1042
  // O13: an embedded record. Cut precisely only when the known body follows verbatim, else through the end.
1014
1043
  let end = out.length;
1015
- const tagEnd = out.indexOf(">", at);
1016
- if (entry.body !== undefined && tagEnd >= 0) {
1017
- const bodyEnd = tagEnd + 1 + entry.body.length;
1018
- if (out.startsWith(entry.body, tagEnd + 1) && out.startsWith(SUBAGENT_CLOSE, bodyEnd)) {
1019
- end = bodyEnd + SUBAGENT_CLOSE.length;
1020
- }
1044
+ if (entry.body !== undefined) {
1045
+ const close = childReportClose(opening.tag);
1046
+ const bodyEnd = opening.bodyStart + entry.body.length;
1047
+ if (out.startsWith(entry.body, opening.bodyStart) && out.startsWith(close, bodyEnd)) end = bodyEnd + close.length;
1021
1048
  }
1022
1049
  out = out.slice(0, at) + placeholder + out.slice(end);
1023
1050
  from = at + placeholder.length;
@@ -1196,7 +1223,9 @@ export function createHeldResults(deps: {
1196
1223
  },
1197
1224
 
1198
1225
  isHeld(child) {
1199
- for (const children of byParent.values()) if (children.get(child)?.active === true) return true;
1226
+ for (const children of byParent.values()) {
1227
+ for (const entry of children.values()) if (entry.childSessionID === child && entry.active) return true;
1228
+ }
1200
1229
  return false;
1201
1230
  },
1202
1231
 
@@ -1205,9 +1234,17 @@ export function createHeldResults(deps: {
1205
1234
 
1206
1235
  apply<M>(sessionID: string, messages: readonly M[]): M[] | undefined {
1207
1236
  if (!byParent.has(sessionID)) return undefined;
1237
+ const messageIndices = indexMessageIDs(messages);
1238
+ const entries = heldChildren(sessionID);
1239
+ const fallback = new Map(entries.map((entry) => [entry.childSessionID, entry]));
1208
1240
  let changed = false;
1209
- const out = messages.map((message) => {
1210
- const next = redactMessage(message, (text) => applyText(sessionID, text));
1241
+ const out = messages.map((message, index) => {
1242
+ const selected = new Map(fallback);
1243
+ // With a boundary, select the latest eligible attempt. Missing/compacted boundaries still redact fail-closed.
1244
+ for (const entry of entries) {
1245
+ if (!precedesDispatch(messageIndices, index, entry.callerMessageID)) selected.set(entry.childSessionID, entry);
1246
+ }
1247
+ const next = redactMessage(message, (text) => applyText(sessionID, text, selected));
1211
1248
  if (next === undefined) return message;
1212
1249
  changed = true;
1213
1250
  return next;
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Readers of a v2 child's own history (`ctx.session.context`), shared by the adapter (`v2-hooks.ts`) and the native child
3
+ * runner (`v2-client.ts`). v2 only: OpenCode v1 never loads this module.
4
+ */
5
+
6
+ /** The text of one session-context message: its `text`, else its text parts (`content` or `parts`) joined. */
7
+ export function messageText(message: unknown): string | undefined {
8
+ if (!message || typeof message !== "object") return undefined;
9
+ const m = message as Record<string, unknown>;
10
+ if (typeof m.text === "string") return m.text;
11
+ if (typeof m.content === "string") return m.content;
12
+ const parts = Array.isArray(m.content) ? m.content : Array.isArray(m.parts) ? m.parts : undefined;
13
+ if (parts === undefined) return undefined;
14
+ const texts = parts.flatMap((part) => part && typeof part === "object" && (part as Record<string, unknown>).type === "text"
15
+ && typeof (part as Record<string, unknown>).text === "string" ? [(part as Record<string, unknown>).text as string] : []);
16
+ return texts.length > 0 ? texts.join("\n") : undefined;
17
+ }
18
+
19
+ /**
20
+ * The child's last assistant message of its current turn (after its newest user prompt, DF-1-4): walking back from the newest
21
+ * entry, the first assistant entry with text; the newest user prompt ends the walk, as an answer before it belongs to an
22
+ * earlier turn (a resume). The host's context entries are discriminated by `type` ("user" | "assistant" | "synthetic", see the
23
+ * instruction filter in the system hook); the model-facing messages of the context hook use `role`. Both name the assistant
24
+ * the same way. `failed` (#167): between that answer and the newest entry, an assistant entry carries an error, or the run's
25
+ * end marker (`{ type: "idle", outcome }`) has an outcome other than "succeeded" ("failed" | "interrupted"): the turn did not
26
+ * end in success and its text may be partial. An end marker without an outcome changes nothing.
27
+ *
28
+ * `final` (#167, the native runner's waited result; QA-2.1-18: text alone is not an end): the NEWEST assistant entry of the
29
+ * turn decides. It is the answer only when it has text and ended its step (`assistantStepCompleted`); otherwise there is no
30
+ * answer, never an earlier step's text (a draft before a tool call). Its `finish: "error"` also fails the reply.
31
+ *
32
+ * `after` (#167, a resume): `id` is the history's newest entry before this run (`newestEntryId`). Only entries after it count,
33
+ * and the answer must follow a user entry, also after it, whose text contains this run's `prompt` (trimmed; the host may put
34
+ * its preamble line before it): the host adds the prompt to the history only when the run takes it, and a resume often
35
+ * repeats the previous prompt, so the marker tells this run's entry from an identical earlier one. A run end (`idle`) between
36
+ * the newest such entry and the answer means the answer is a later run's. Without such an entry, with a run end between, or
37
+ * when the marker is no longer in the history (compacted, see `historyHasEntry`), there is no answer of this run.
38
+ */
39
+ export function lastAssistantReply(
40
+ history: unknown, options: { final?: boolean; after?: { id: string; prompt: string } } = {},
41
+ ): { text: string; failed: boolean } | undefined {
42
+ const messages: readonly unknown[] = Array.isArray(history) ? history : [];
43
+ const { after, final = false } = options;
44
+ let start = 0;
45
+ if (after !== undefined) {
46
+ const marker = entryIndex(messages, after.id);
47
+ if (marker < 0) return undefined;
48
+ start = marker + 1;
49
+ }
50
+ const isUser = (message: unknown): boolean => {
51
+ const m = message as { type?: unknown; role?: unknown } | null | undefined;
52
+ return m?.type === "user" || m?.role === "user";
53
+ };
54
+ const normalized = (text: string): string => text.replace(/\r\n/g, "\n").trim();
55
+ const ownPrompt = after === undefined ? "" : normalized(after.prompt);
56
+ const isOwnPrompt = (message: unknown): boolean =>
57
+ isUser(message) && ownPrompt !== "" && normalized(messageText(message) ?? "").includes(ownPrompt);
58
+ let failed = false;
59
+ for (let index = messages.length - 1; index >= start; index--) {
60
+ const message = messages[index] as {
61
+ type?: unknown; role?: unknown; outcome?: unknown; error?: unknown; finish?: unknown; info?: { error?: unknown; finish?: unknown };
62
+ } | undefined;
63
+ if (message?.type === "idle" && message.outcome !== undefined && message.outcome !== null && message.outcome !== "succeeded") {
64
+ failed = true;
65
+ }
66
+ if (message?.type === "assistant" || message?.role === "assistant") {
67
+ const error = message.error ?? message.info?.error;
68
+ if (error !== undefined && error !== null && error !== false) failed = true;
69
+ if (final && (message.finish ?? message.info?.finish) === "error") failed = true;
70
+ const text = messageText(message);
71
+ if (final && (text === undefined || !assistantStepCompleted(message))) return undefined;
72
+ if (text !== undefined) {
73
+ if (after !== undefined) {
74
+ // The newest own prompt before the answer; a run end (`idle`, any outcome) between them means the answer belongs to
75
+ // a later run than ours (ours ended, then another prompt was taken), so it is not this run's answer.
76
+ let own = index - 1;
77
+ while (own >= start && !isOwnPrompt(messages[own])) own--;
78
+ if (own < start) return undefined;
79
+ if (messages.slice(own + 1, index).some((m) => (m as { type?: unknown } | null | undefined)?.type === "idle")) return undefined;
80
+ }
81
+ return { text, failed };
82
+ }
83
+ }
84
+ if (isUser(message)) break;
85
+ }
86
+ return undefined;
87
+ }
88
+
89
+ /**
90
+ * 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
91
+ * than a tool-call continuation, or a completed time; and no tool part still `pending` or `running`. A step cut mid-stream has
92
+ * none of these, and a `tool-calls` finish means the child meant to go on: neither is an end, whatever text it already has.
93
+ */
94
+ export function assistantStepCompleted(message: unknown): boolean {
95
+ if (message === null || typeof message !== "object") return false;
96
+ const m = message as Record<string, unknown>;
97
+ const info = m.info !== null && typeof m.info === "object" ? m.info as Record<string, unknown> : undefined;
98
+ const parts: readonly unknown[] = Array.isArray(m.content) ? m.content : Array.isArray(m.parts) ? m.parts : [];
99
+ const toolOpen = parts.some((part) => {
100
+ if (part === null || typeof part !== "object" || (part as Record<string, unknown>).type !== "tool") return false;
101
+ const state = (part as Record<string, unknown>).state;
102
+ const status = state !== null && typeof state === "object" ? (state as Record<string, unknown>).status : state ?? (part as Record<string, unknown>).status;
103
+ // The v2 tool state is `streaming` | `running` | `completed` | `error` (`pending` is the v1 name of the first).
104
+ return status === "streaming" || status === "pending" || status === "running";
105
+ });
106
+ if (toolOpen) return false;
107
+ const finish = m.finish ?? info?.finish;
108
+ if (typeof finish === "string" && finish !== "") return finish !== "tool-calls" && finish !== "unknown";
109
+ const time = m.time ?? info?.time;
110
+ // `time.completed` is set once the step ended: epoch millis on the wire, a DateTime once decoded; either counts.
111
+ const completed = time !== null && typeof time === "object" ? (time as Record<string, unknown>).completed : undefined;
112
+ return completed !== undefined && completed !== null && completed !== "" && completed !== false;
113
+ }
114
+
115
+ /** #167: the id of a history's newest entry (every v2 context entry carries one), or undefined when it has none. */
116
+ export function newestEntryId(history: unknown): string | undefined {
117
+ return Array.isArray(history) && history.length > 0 ? entryId(history[history.length - 1]) : undefined;
118
+ }
119
+
120
+ /** #167: whether the history still holds the entry with this id (a resume's marker; gone after a compaction). */
121
+ export function historyHasEntry(history: unknown, id: string): boolean {
122
+ return Array.isArray(history) && entryIndex(history, id) >= 0;
123
+ }
124
+
125
+ function entryIndex(messages: readonly unknown[], id: string): number {
126
+ let index = messages.length - 1;
127
+ while (index >= 0 && entryId(messages[index]) !== id) index--;
128
+ return index;
129
+ }
130
+
131
+ function entryId(message: unknown): string | undefined {
132
+ const id = message !== null && typeof message === "object" ? (message as { id?: unknown }).id : undefined;
133
+ return typeof id === "string" && id !== "" ? id : undefined;
134
+ }
@@ -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. */
@@ -0,0 +1,21 @@
1
+ /**
2
+ * #161: the bound of the OpenCode v2 host's session reads, shared by the v2 adapter (compat/v2-hooks.ts) and the legacy plugin
3
+ * surface it bridges (index.ts, on the v2 host only). A leaf module: OpenCode v1 loads it with index.ts and never uses it.
4
+ */
5
+
6
+ /**
7
+ * #161: how long the shared session record (`sessionInfoOf`: the directory, parent and agent the role checks, the file leases and
8
+ * the stale-resume check read) waits for the host's `session.get`; past it the lookup counts as failed. Long on purpose, above
9
+ * 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.
10
+ */
11
+ export const SESSION_INFO_LOOKUP_MS = 10_000;
12
+
13
+ /** #161: `lookup`'s answer, or a rejection once `ms` pass without one (the host call itself is left running). */
14
+ export function sessionLookupWithin<T>(lookup: PromiseLike<T>, ms: number): Promise<T> {
15
+ let timer: ReturnType<typeof setTimeout> | undefined;
16
+ const timeout = new Promise<never>((_resolve, reject) => {
17
+ timer = setTimeout(() => reject(new Error(`session lookup timed out after ${ms} ms`)), ms);
18
+ if (typeof timer === "object" && typeof timer.unref === "function") timer.unref();
19
+ });
20
+ return Promise.race([lookup, timeout]).finally(() => clearTimeout(timer));
21
+ }