@sema-agent/core 7.57.0 → 7.58.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 (198) hide show
  1. package/CHANGELOG.md +385 -0
  2. package/dist/agents/subagent-steps.js +2 -4
  3. package/dist/brain/route-adjudicator.js +2 -1
  4. package/dist/core/a2a.d.ts +2 -1
  5. package/dist/core/a2a.js +23 -10
  6. package/dist/core/allow-entry.d.ts +2 -1
  7. package/dist/core/allow-entry.js +2 -1
  8. package/dist/core/ask-origin.d.ts +21 -2
  9. package/dist/core/ask-origin.js +5 -1
  10. package/dist/core/auto-compaction.d.ts +4 -0
  11. package/dist/core/auto-compaction.js +1 -1
  12. package/dist/core/auto-mode-directive.d.ts +29 -5
  13. package/dist/core/auto-mode-directive.js +38 -8
  14. package/dist/core/checkpoint-requirements.d.ts +7 -1
  15. package/dist/core/checkpoint-requirements.js +2 -0
  16. package/dist/core/checkpoint-store.d.ts +27 -11
  17. package/dist/core/checkpoint-store.js +13 -3
  18. package/dist/core/engine-notice.d.ts +1 -1
  19. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  20. package/dist/core/fs-write-gate-policy.js +7 -3
  21. package/dist/core/gate-fold.js +6 -3
  22. package/dist/core/gate-lanes.js +11 -2
  23. package/dist/core/git-worktree-env.d.ts +53 -11
  24. package/dist/core/git-worktree-env.js +96 -12
  25. package/dist/core/hooks.d.ts +4 -1
  26. package/dist/core/hooks.js +12 -5
  27. package/dist/core/human-input-projection.d.ts +1 -0
  28. package/dist/core/human-input-projection.js +3 -0
  29. package/dist/core/locked-config.d.ts +15 -1
  30. package/dist/core/locked-config.js +38 -2
  31. package/dist/core/mcp-call-meta.d.ts +66 -0
  32. package/dist/core/mcp-call-meta.js +103 -0
  33. package/dist/core/mcp-connection-pool.d.ts +3 -1
  34. package/dist/core/mcp-connection-pool.js +3 -1
  35. package/dist/core/mcp-failure.d.ts +7 -1
  36. package/dist/core/mcp-failure.js +10 -0
  37. package/dist/core/mcp-probe.d.ts +4 -0
  38. package/dist/core/mcp-probe.js +1 -1
  39. package/dist/core/mcp-server-link.d.ts +5 -2
  40. package/dist/core/mcp-server-spec.d.ts +46 -18
  41. package/dist/core/mcp-server-spec.js +1 -18
  42. package/dist/core/mcp.d.ts +6 -14
  43. package/dist/core/mcp.js +77 -37
  44. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  45. package/dist/core/memory-engine/scope-contract.js +80 -11
  46. package/dist/core/mode-policy.d.ts +8 -5
  47. package/dist/core/mode-policy.js +5 -4
  48. package/dist/core/mods/host.js +1 -1
  49. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  50. package/dist/core/mods/kernel/dispatch.js +10 -8
  51. package/dist/core/mods/kernel/events.d.ts +5 -1
  52. package/dist/core/mods/kernel/events.js +1 -1
  53. package/dist/core/mods/kernel/registration.d.ts +5 -1
  54. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  55. package/dist/core/mods/kernel/site-rules.js +10 -0
  56. package/dist/core/mods/package.d.ts +23 -0
  57. package/dist/core/mods/package.js +118 -0
  58. package/dist/core/mods/stations.d.ts +2 -2
  59. package/dist/core/mods/stations.js +1 -1
  60. package/dist/core/mods/tool-call.d.ts +5 -1
  61. package/dist/core/mods/tool-call.js +12 -3
  62. package/dist/core/path-guard-rows.d.ts +20 -0
  63. package/dist/core/path-guard-rows.js +11 -0
  64. package/dist/core/peer-seat.d.ts +186 -0
  65. package/dist/core/peer-seat.js +307 -0
  66. package/dist/core/present-plan-tool.d.ts +10 -1
  67. package/dist/core/present-plan-tool.js +46 -2
  68. package/dist/core/protocol-http-auth.d.ts +40 -29
  69. package/dist/core/protocol-http-auth.js +30 -32
  70. package/dist/core/redaction-marks.d.ts +16 -0
  71. package/dist/core/redaction-marks.js +16 -0
  72. package/dist/core/redaction-passes.js +8 -9
  73. package/dist/core/retention.d.ts +41 -15
  74. package/dist/core/retention.js +59 -12
  75. package/dist/core/rewrite-rejudge.d.ts +37 -0
  76. package/dist/core/rewrite-rejudge.js +40 -0
  77. package/dist/core/run-origin.d.ts +40 -0
  78. package/dist/core/run-origin.js +37 -0
  79. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  80. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  81. package/dist/core/runner/compaction-restate.d.ts +15 -6
  82. package/dist/core/runner/compaction-restate.js +28 -2
  83. package/dist/core/runner/contracts.d.ts +13 -5
  84. package/dist/core/runner/gate-exit.d.ts +18 -4
  85. package/dist/core/runner/gate-exit.js +5 -1
  86. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  87. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  88. package/dist/core/runner/prepare-config-doors.d.ts +8 -5
  89. package/dist/core/runner/prepare-config-doors.js +12 -10
  90. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  91. package/dist/core/runner/prepare-delegation-surface.js +15 -18
  92. package/dist/core/runner/prepare-gate-stations.js +1 -1
  93. package/dist/core/runner/prepare-hands-readface.d.ts +7 -3
  94. package/dist/core/runner/prepare-hands-readface.js +4 -1
  95. package/dist/core/runner/prepare-memory.d.ts +3 -0
  96. package/dist/core/runner/prepare-memory.js +19 -23
  97. package/dist/core/runner/prepare-policy-chain.d.ts +4 -4
  98. package/dist/core/runner/prepare-policy-chain.js +2 -2
  99. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  100. package/dist/core/runner/prepare-protocol-tools.js +3 -3
  101. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  102. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  103. package/dist/core/runner/prepare-task.js +25 -12
  104. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  105. package/dist/core/runner/prepare-wiring-manifest.js +2 -2
  106. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  107. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  108. package/dist/core/runner/resume-admission.js +1 -1
  109. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  110. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  111. package/dist/core/runner/run-harness-handlers.js +1 -8
  112. package/dist/core/runner/run-identity-wiring.js +1 -0
  113. package/dist/core/runner/run-leg.js +5 -1
  114. package/dist/core/runner/run-notification-lane.js +3 -0
  115. package/dist/core/runner/terminal-account.js +3 -3
  116. package/dist/core/runner/tool-end-body.js +1 -0
  117. package/dist/core/runner/tool-occurrence.d.ts +4 -1
  118. package/dist/core/runner/tool-occurrence.js +2 -1
  119. package/dist/core/runner/write-protection-station.d.ts +8 -2
  120. package/dist/core/runner/write-protection-station.js +2 -0
  121. package/dist/core/runner-deps.d.ts +2 -2
  122. package/dist/core/sensitive-path-policy.js +6 -7
  123. package/dist/core/session-log-transfer.d.ts +24 -0
  124. package/dist/core/session-log-transfer.js +166 -0
  125. package/dist/core/session-store.d.ts +84 -19
  126. package/dist/core/session-store.js +162 -24
  127. package/dist/core/session.d.ts +92 -1
  128. package/dist/core/shell-read-silence.js +1 -0
  129. package/dist/core/steer-replay.d.ts +4 -2
  130. package/dist/core/steer-replay.js +2 -1
  131. package/dist/core/store-contracts/checkpoint-store-contract.js +17 -0
  132. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  133. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  134. package/dist/core/store-contracts/session-store-contract.js +236 -2
  135. package/dist/core/task-event.d.ts +68 -8
  136. package/dist/core/task-registry-shared.d.ts +2 -1
  137. package/dist/core/task-spec.d.ts +37 -0
  138. package/dist/core/task-stream.d.ts +2 -1
  139. package/dist/core/terminal-cause.d.ts +1 -1
  140. package/dist/core/tool-catalog-entries.js +1 -0
  141. package/dist/core/tool-result-store.d.ts +17 -10
  142. package/dist/core/tool-result-store.js +3 -1
  143. package/dist/core/types.d.ts +1 -1
  144. package/dist/core/untrusted-egress.d.ts +0 -2
  145. package/dist/core/untrusted-egress.js +10 -14
  146. package/dist/core/wiring-manifest.d.ts +12 -3
  147. package/dist/core/wiring-manifest.js +4 -3
  148. package/dist/core/workspace-snapshot.d.ts +44 -0
  149. package/dist/core/workspace-snapshot.js +34 -0
  150. package/dist/core/write-protect.d.ts +43 -3
  151. package/dist/core/write-protect.js +43 -16
  152. package/dist/engine/execution-env/node-execution-env.js +15 -11
  153. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  154. package/dist/engine/harness/agent-harness.d.ts +5 -0
  155. package/dist/engine/harness/agent-harness.js +2 -0
  156. package/dist/engine/harness/types.d.ts +48 -7
  157. package/dist/engine/harness/types.js +5 -1
  158. package/dist/engine/llm/types.d.ts +12 -3
  159. package/dist/engine/llm/types.js +1 -1
  160. package/dist/engine/session/import-validate.js +3 -0
  161. package/dist/engine/session/memory-repo.d.ts +17 -9
  162. package/dist/engine/session/memory-repo.js +44 -34
  163. package/dist/engine/session/repo-utils.d.ts +22 -4
  164. package/dist/engine/session/repo-utils.js +49 -1
  165. package/dist/engine/session/storage-base.d.ts +10 -1
  166. package/dist/engine/session/storage-base.js +7 -1
  167. package/dist/index.d.ts +13 -6
  168. package/dist/index.js +10 -4
  169. package/dist/internal/harness-types.d.ts +1 -1
  170. package/dist/internal/harness.d.ts +2 -2
  171. package/dist/internal/harness.js +2 -2
  172. package/dist/stores/file/index.d.ts +4 -1
  173. package/dist/stores/file/index.js +4 -1
  174. package/dist/stores/file/session-store.d.ts +15 -8
  175. package/dist/stores/file/session-store.js +28 -13
  176. package/dist/tools/fs/fs-write.d.ts +6 -3
  177. package/dist/tools/fs/fs-write.js +8 -7
  178. package/dist/tools/fs/index.d.ts +3 -0
  179. package/dist/tools/fs/index.js +1 -1
  180. package/dist/tools/fs/safety.js +40 -8
  181. package/dist/tools/fs/search.js +6 -24
  182. package/dist/tools/fs/shell-read-check.d.ts +8 -1
  183. package/dist/tools/fs/shell-read-check.js +59 -15
  184. package/dist/tools/fs/shell-read-establish.js +2 -1
  185. package/dist/tools/fs/shell-read-identity.js +1 -1
  186. package/dist/tools/fs/shell-read-judge.d.ts +10 -1
  187. package/dist/tools/worktree.d.ts +42 -15
  188. package/dist/tools/worktree.js +60 -32
  189. package/package.json +4 -2
  190. package/test/export-surface.snapshot.json +63 -1
  191. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  192. package/wire-changes/core@7.58.0.json +2188 -0
  193. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  194. package/wire-changes/primitives@7.58.0.json +29 -0
  195. package/dist/primitives/credential-ref.d.ts +0 -89
  196. package/dist/primitives/credential-ref.js +0 -125
  197. package/dist/primitives/index.d.ts +0 -2
  198. package/dist/primitives/index.js +0 -1
@@ -0,0 +1,307 @@
1
+ import { createHash } from "node:crypto";
2
+ import { StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
3
+ import { readCredentialRef } from "@sema-agent/primitives";
4
+ import { readMember } from "./thrown-value.js";
5
+ import { resolveProtocolHttpHeaders } from "./protocol-http-auth.js";
6
+ import { holdOwnCredentialValues, isSecretEnvKey } from "./secret-env.js";
7
+ import { inlineUntrusted } from "./untrusted-text.js";
8
+ export const PEER_ANSWER_LANES = Object.freeze({ http: "headers", a2a: "headers", stdio: "env" });
9
+ export const PEER_SEAT_WAIT_MS = 30_000;
10
+ export class PeerSeatFailure extends Error {
11
+ reason;
12
+ authorizeUrl;
13
+ code;
14
+ constructor(reason, peerLabel, problem, extra) {
15
+ super(`the deployment's peer seat ${problem} for ${peerLabel} — the request was not sent`);
16
+ this.name = "PeerSeatFailure";
17
+ this.reason = reason;
18
+ this.authorizeUrl = extra?.authorizeUrl;
19
+ this.code = extra?.code ?? (reason === "answer_invalid" ? "config.peer_answer_invalid" : undefined);
20
+ }
21
+ }
22
+ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
23
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
24
+ const VALUE_BREAK = /[\r\n\0]/;
25
+ const ANSWER_MEMBERS = { carry: ["kind", "headers", "env", "expiresAt"], unauthorized: ["kind", "authorizeUrl"] };
26
+ const digestOf = (pieces) => {
27
+ const rows = (m) => Object.entries(m ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
28
+ return createHash("sha256").update(JSON.stringify([rows(pieces.headers), rows(pieces.env)])).digest("hex");
29
+ };
30
+ const NO_PIECES = Object.freeze({ digest: digestOf({}) });
31
+ function nameValues(raw, member) {
32
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
33
+ return `its ${member} is not a record of names to strings`;
34
+ const out = Object.create(null);
35
+ const folded = new Set();
36
+ for (const name of Object.keys(raw)) {
37
+ const value = raw[name];
38
+ if (typeof value !== "string")
39
+ return `its ${member} member ${inlineUntrusted(JSON.stringify(name), 80)} is not a string`;
40
+ if (!(member === "headers" ? HEADER_NAME : ENV_NAME).test(name))
41
+ return `its ${member} name ${inlineUntrusted(JSON.stringify(name), 80)} is not a ${member === "headers" ? "header" : "variable"} name`;
42
+ if (VALUE_BREAK.test(value))
43
+ return `its ${member} member ${inlineUntrusted(JSON.stringify(name), 80)} holds a line break or NUL`;
44
+ if (member === "headers") {
45
+ if (folded.has(name.toLowerCase()))
46
+ return `its headers name ${inlineUntrusted(JSON.stringify(name), 80)} twice (header names are case-insensitive)`;
47
+ folded.add(name.toLowerCase());
48
+ }
49
+ out[name] = value;
50
+ }
51
+ return Object.freeze(out);
52
+ }
53
+ export function readPeerAnswer(raw, lane) {
54
+ try {
55
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
56
+ return { problem: "answered something that is not an answer record" };
57
+ const record = raw;
58
+ const kind = record["kind"];
59
+ if (kind !== "carry" && kind !== "unauthorized")
60
+ return { problem: `answered the kind ${inlineUntrusted(JSON.stringify(kind) ?? String(kind), 80)}, which is neither "carry" nor "unauthorized"` };
61
+ const extra = Object.keys(record).find((key) => !ANSWER_MEMBERS[kind].includes(key));
62
+ if (extra !== undefined)
63
+ return { problem: `answered the member ${inlineUntrusted(JSON.stringify(extra), 80)}, which a "${kind}" answer does not have` };
64
+ if (kind === "unauthorized") {
65
+ const url = record["authorizeUrl"];
66
+ if (url !== undefined && typeof url !== "string")
67
+ return { problem: "answered an authorizeUrl that is not a string" };
68
+ return { unauthorized: url === undefined ? {} : { authorizeUrl: url } };
69
+ }
70
+ const own = PEER_ANSWER_LANES[lane];
71
+ const other = own === "headers" ? "env" : "headers";
72
+ if (record[other] !== undefined)
73
+ return { problem: `answered ${other} for a ${lane} peer, which carries ${own} only` };
74
+ const expiresAt = record["expiresAt"];
75
+ if (expiresAt !== undefined && (typeof expiresAt !== "number" || !Number.isFinite(expiresAt)))
76
+ return { problem: "answered an expiresAt that is not a finite epoch-millisecond number" };
77
+ const given = record[own];
78
+ const values = given === undefined ? undefined : nameValues(given, own);
79
+ if (typeof values === "string")
80
+ return { problem: `answered ${values}` };
81
+ const lanePieces = values === undefined ? {} : { [own]: values };
82
+ return { carry: Object.freeze({ ...lanePieces, ...(expiresAt !== undefined ? { expiresAt } : {}), digest: digestOf(lanePieces) }) };
83
+ }
84
+ catch {
85
+ return { problem: "answered a record whose members could not be read" };
86
+ }
87
+ }
88
+ async function askBounded(seat, question, signal) {
89
+ signal?.throwIfAborted();
90
+ const wait = new AbortController();
91
+ const timer = setTimeout(() => wait.abort(), PEER_SEAT_WAIT_MS);
92
+ timer.unref();
93
+ const stop = signal === undefined ? wait.signal : AbortSignal.any([signal, wait.signal]);
94
+ try {
95
+ const stopped = new Promise((_, reject) => stop.addEventListener("abort", () => reject(stop.reason), { once: true }));
96
+ stopped.catch(() => undefined);
97
+ return { answer: await Promise.race([seat(question, stop), stopped]) };
98
+ }
99
+ catch (err) {
100
+ if (signal?.aborted === true)
101
+ throw signal.reason;
102
+ return { failed: wait.signal.aborted ? "timed_out" : "threw" };
103
+ }
104
+ finally {
105
+ clearTimeout(timer);
106
+ }
107
+ }
108
+ export class PeerCarrier {
109
+ seat;
110
+ identity;
111
+ principal;
112
+ lane;
113
+ sent = [];
114
+ expiresAt;
115
+ renewed = false;
116
+ asked = false;
117
+ waiting;
118
+ rejection;
119
+ constructor(seat, identity, principal, lane, principalSent) {
120
+ this.seat = seat;
121
+ this.identity = identity;
122
+ this.principal = principal;
123
+ this.lane = lane;
124
+ if (principalSent && principal !== undefined && principal !== "")
125
+ this.sent.push(principal);
126
+ }
127
+ get label() {
128
+ return this.identity.protocol === "mcp" ? `MCP server "${inlineUntrusted(this.identity.server, 120)}"` : `A2A peer "${inlineUntrusted(this.identity.peer, 120)}"`;
129
+ }
130
+ async next(signal, destination) {
131
+ const waiting = this.waiting;
132
+ if (waiting !== undefined) {
133
+ this.waiting = undefined;
134
+ this.last = waiting;
135
+ return waiting;
136
+ }
137
+ const cause = this.asked ? "request" : "connect";
138
+ this.asked = true;
139
+ this.last = await this.ask(cause, signal, destination);
140
+ return this.last;
141
+ }
142
+ last;
143
+ async rejected(carried, signal, destination) {
144
+ this.rejection ??= this.ask("rejected", signal, destination)
145
+ .then((pieces) => {
146
+ this.waiting = pieces;
147
+ this.renewed = pieces.digest !== carried.digest;
148
+ }, () => {
149
+ this.renewed = false;
150
+ })
151
+ .finally(() => {
152
+ this.rejection = undefined;
153
+ });
154
+ await this.rejection;
155
+ }
156
+ expired(now = Date.now()) {
157
+ return this.expiresAt !== undefined && now >= this.expiresAt;
158
+ }
159
+ async ask(cause, signal, destination) {
160
+ if (this.seat === undefined)
161
+ return NO_PIECES;
162
+ const peer = this.identity.protocol === "a2a" && destination !== undefined ? { ...this.identity, destination } : this.identity;
163
+ const asked = await askBounded(this.seat, { peer, ...(this.principal !== undefined ? { principal: this.principal } : {}), cause }, signal);
164
+ if ("failed" in asked)
165
+ throw new PeerSeatFailure(asked.failed, this.label, asked.failed === "timed_out" ? `did not answer within ${PEER_SEAT_WAIT_MS} ms` : "threw");
166
+ const read = readPeerAnswer(asked.answer, this.lane);
167
+ if ("problem" in read)
168
+ throw new PeerSeatFailure("answer_invalid", this.label, read.problem);
169
+ if ("unauthorized" in read)
170
+ throw new PeerSeatFailure("unauthorized", this.label, "answered that this principal is not authorized", read.unauthorized.authorizeUrl === undefined ? undefined : { authorizeUrl: read.unauthorized.authorizeUrl });
171
+ const pieces = read.carry;
172
+ if (pieces.env !== undefined) {
173
+ const held = Object.entries(pieces.env).filter(([name, value]) => isSecretEnvKey(name, value)).map(([, value]) => value);
174
+ try {
175
+ holdOwnCredentialValues(held);
176
+ }
177
+ catch {
178
+ throw new PeerSeatFailure("answer_invalid", this.label, "answered an environment value that is the value of a variable every child on this host is handed");
179
+ }
180
+ for (const value of held)
181
+ this.remember(value);
182
+ }
183
+ if (this.lane === "stdio")
184
+ this.expiresAt = pieces.expiresAt;
185
+ for (const value of Object.values(pieces.headers ?? {}))
186
+ this.remember(value);
187
+ return pieces;
188
+ }
189
+ remember(value) {
190
+ if (value !== "" && !this.sent.includes(value))
191
+ this.sent.push(value);
192
+ }
193
+ }
194
+ export function carriedHttpHeaders(protocol, carrier, pieces, principalHeader, principal) {
195
+ try {
196
+ return resolveProtocolHttpHeaders(protocol, { ...(pieces.headers !== undefined ? { headers: { ...pieces.headers } } : {}), ...(principalHeader !== undefined ? { principalHeader } : {}) }, principal);
197
+ }
198
+ catch (err) {
199
+ if (pieces.headers === undefined)
200
+ throw err;
201
+ const message = err instanceof Error ? err.message : "";
202
+ const code = err?.code;
203
+ throw new PeerSeatFailure("answer_invalid", carrier.label, `answered headers the engine cannot send (${inlineUntrusted(message, 240)})`, typeof code === "string" ? { code } : undefined);
204
+ }
205
+ }
206
+ export function peerFetch(carrier, principalHeader, principal) {
207
+ return async (url, init) => {
208
+ const signal = init?.signal ?? undefined;
209
+ const pieces = await carrier.next(signal);
210
+ const own = carriedHttpHeaders("mcp", carrier, pieces, principalHeader, principal);
211
+ const headers = new Headers(init?.headers);
212
+ for (const [name, value] of Object.entries(own ?? {}))
213
+ headers.set(name, value);
214
+ const res = await fetch(url, { ...init, headers, redirect: "manual" });
215
+ if (res.status === 401)
216
+ await carrier.rejected(pieces, signal);
217
+ return res;
218
+ };
219
+ }
220
+ export const RETIRED_VALUE_MEMBERS = Object.freeze({ mcp: Object.freeze([Object.freeze(["transport", "headers"]), Object.freeze(["transport", "env"])]), a2a: Object.freeze([Object.freeze(["headers"])]) });
221
+ export function retiredValueMember(copy, at) {
222
+ for (const path of RETIRED_VALUE_MEMBERS[at]) {
223
+ let holder = copy;
224
+ for (const key of path.slice(0, -1))
225
+ holder = typeof holder === "object" && holder !== null && Object.hasOwn(holder, key) ? holder[key] : undefined;
226
+ const last = path[path.length - 1];
227
+ if (typeof holder === "object" && holder !== null && Object.hasOwn(holder, last) && holder[last] !== undefined)
228
+ return path;
229
+ }
230
+ return undefined;
231
+ }
232
+ export const CREDENTIALS_MEMBER = Object.freeze({ mcp: Object.freeze(["transport", "credentials"]), a2a: Object.freeze(["credentials"]) });
233
+ export function declaredCredentials(copy, at) {
234
+ let value = copy;
235
+ for (const key of CREDENTIALS_MEMBER[at])
236
+ value = typeof value === "object" && value !== null && Object.hasOwn(value, key) ? value[key] : undefined;
237
+ if (value === undefined)
238
+ return {};
239
+ const read = readCredentialRef(value);
240
+ if (read.ok)
241
+ return { ref: read.ref };
242
+ const p = read.problem;
243
+ return { problem: `${p.reason}${"kind" in p && p.kind !== undefined ? ` (kind ${JSON.stringify(p.kind)})` : ""}${"field" in p ? ` at ${JSON.stringify(p.field)}` : ""}` };
244
+ }
245
+ export function peerSeatMissing(subject, credentials, seat) {
246
+ if (credentials === undefined || seat !== undefined)
247
+ return undefined;
248
+ return Object.assign(new Error(`${subject} declares a credential reference (kind "${credentials.kind}") but the deployment wires no peer seat (RunnerDeps.peerSeat) to answer it — not dialed`), { code: "config.peer_seat_missing" });
249
+ }
250
+ export function mcpPeerTarget(spec, kind) {
251
+ const t = spec.transport;
252
+ const fingerprint = typeof spec.fingerprint === "string" ? { fingerprint: spec.fingerprint } : {};
253
+ const credentials = t.credentials !== undefined ? { credentials: t.credentials } : {};
254
+ if (kind === "stdio" && "command" in t)
255
+ return { protocol: "mcp", server: spec.name, transport: "stdio", command: t.command, args: [...(t.args ?? [])], ...credentials, ...fingerprint };
256
+ return { protocol: "mcp", server: spec.name, transport: "http", url: "url" in t ? t.url : "", ...credentials, ...fingerprint };
257
+ }
258
+ export function answeredUnauthorized(err) {
259
+ let at = err;
260
+ for (let depth = 0; depth < 6 && at instanceof Error; depth++) {
261
+ if (at instanceof StreamableHTTPError && at.code === 401)
262
+ return true;
263
+ at = at.cause;
264
+ }
265
+ return false;
266
+ }
267
+ export class Reauthorized {
268
+ error;
269
+ constructor(error) {
270
+ this.error = error;
271
+ }
272
+ }
273
+ export async function sentOnceMore(attempt, mayResend) {
274
+ const first = await attempt();
275
+ if (!(first instanceof Reauthorized))
276
+ return first;
277
+ if (!mayResend())
278
+ throw first.error;
279
+ const again = await attempt().catch((err) => {
280
+ const details = readMember(err, "details");
281
+ throw typeof details === "object" && details !== null && readMember(details, "delivered") === "no" ? first.error : err;
282
+ });
283
+ if (again instanceof Reauthorized)
284
+ throw again.error;
285
+ return again;
286
+ }
287
+ const IN_FLIGHT = new WeakMap();
288
+ export function inFlight(client, run) {
289
+ let calls = IN_FLIGHT.get(client);
290
+ if (calls === undefined)
291
+ IN_FLIGHT.set(client, (calls = new Set()));
292
+ const call = run();
293
+ const held = call.then(() => undefined, () => undefined);
294
+ calls.add(held);
295
+ void held.then(() => calls.delete(held));
296
+ return call;
297
+ }
298
+ export async function settledInFlight(client) {
299
+ await Promise.all([...(IN_FLIGHT.get(client) ?? [])]);
300
+ }
301
+ const CARRIERS = new WeakMap();
302
+ export function recordCarrier(client, carrier) {
303
+ CARRIERS.set(client, carrier);
304
+ }
305
+ export function carrierOf(client) {
306
+ return CARRIERS.get(client);
307
+ }
@@ -14,6 +14,15 @@ export declare const ENTER_PLAN_MODE_TOOL_NAME = "EnterPlanMode";
14
14
  * Exit is via `present_plan` (→ plan_review → human approve-resume), not by this tool.
15
15
  */
16
16
  export declare function createEnterPlanModeTool(enterPlanMode: () => Promise<void> | void): ToolSpec;
17
+ /** The plan file a leg declared (`TaskSpec.planFile`), as the plan-exit tool's file arm reads it: the declared spelling (the
18
+ * card's `filePath`), the same path as the seat tells it to the model (`shown` — `planFileShown`, one line, verbatim, at
19
+ * most 4096 characters: the seat refuses any other), and the seat's one reader of what the file holds (`readPlanFile`,
20
+ * advertised-writable-dirs.ts). Type-only import: this module is below the seat and must not load it. */
21
+ export interface PlanFileSource {
22
+ readonly path: string;
23
+ readonly shown: string;
24
+ readonly read: (signal?: AbortSignal) => Promise<import("./runner/advertised-writable-dirs.js").PlanFileReading>;
25
+ }
17
26
  /**
18
27
  * design/80 D-B — the first-party `present_plan` tool (CC `ExitPlanMode` parity). A THIN composition over the
19
28
  * general `ctx.requestReview()` primitive: the model calls it with a plan; the tool returns the plan as its
@@ -24,4 +33,4 @@ export declare function createEnterPlanModeTool(enterPlanMode: () => Promise<voi
24
33
  */
25
34
  export declare function createPresentPlanTool(requestReview: (opts?: {
26
35
  reason?: string;
27
- }) => void): ToolSpec;
36
+ }) => void, planFile?: PlanFileSource): ToolSpec;
@@ -1,6 +1,8 @@
1
1
  import { Type } from "typebox";
2
- import { delimitUntrusted } from "./untrusted-text.js";
2
+ import { delimitUntrusted, inlineUntrusted } from "./untrusted-text.js";
3
3
  import { mountRuleFace, toolFace } from "./tool-catalog-entries.js";
4
+ import { errorResult } from "./tools.js";
5
+ const READ_REASON_MAX = 600;
4
6
  export const PRESENT_PLAN_TOOL_NAME = "ExitPlanMode";
5
7
  export const ENTER_PLAN_MODE_TOOL_NAME = "EnterPlanMode";
6
8
  const ENTER_PLAN_MODE_DESCRIPTION = `Enter PLAN MODE (read-only): stop making changes and switch to exploration/planning. For the rest of this run, every write/edit/mutating tool call ASKS the user first ("Cannot write to <path> while in plan mode."; where nobody can answer, it is refused) while read-only tools (Read, Grep, Glob, etc.) still work. When your plan is ready, call ${PRESENT_PLAN_TOOL_NAME} with it — the run PAUSES for a human to approve it, then continues (read-only lifted) so you can execute.
@@ -59,7 +61,49 @@ const PRESENT_PLAN_DESCRIPTION = [
59
61
  "If the plan is approved, the run continues (and any read-only restriction is lifted) so you can execute it;",
60
62
  "if it is rejected or edited, follow the reviewer's feedback instead of the original plan.",
61
63
  ].join(" ");
62
- export function createPresentPlanTool(requestReview) {
64
+ const PRESENT_PLAN_FILE_DESCRIPTION = (shown) => `Use this tool when you are in plan mode and have finished writing your plan to the plan file and are ready for user approval.
65
+
66
+ ## How This Tool Works
67
+ - You should have already written your plan to the plan file: ${shown}
68
+ - This tool does NOT take the plan content as a parameter - it will read the plan from the file you wrote
69
+ - This tool simply signals that you're done planning and ready for the user to review and approve; the run PAUSES for a human to approve, edit, or reject it
70
+ - The user will see the contents of your plan file when they review it
71
+
72
+ ## When to Use This Tool
73
+ IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.
74
+
75
+ ## Before Using This Tool
76
+ Ensure your plan is complete and unambiguous:
77
+ - If you have unresolved questions about requirements or approach, resolve them first (in earlier phases)
78
+ - Once your plan is finalized, use THIS tool to request approval
79
+
80
+ **Important:** Do NOT separately ask "Is this plan okay?" or "Should I proceed?" - that's exactly what THIS tool does. ExitPlanMode inherently requests user approval of your plan.`;
81
+ function createPresentPlanFileTool(requestReview, planFile) {
82
+ return {
83
+ name: PRESENT_PLAN_TOOL_NAME,
84
+ ...toolFace("exit-plan-mode-file"),
85
+ ruleFace: mountRuleFace("exit-plan-mode-file"),
86
+ description: PRESENT_PLAN_FILE_DESCRIPTION(planFile.shown),
87
+ parameters: Type.Object({}),
88
+ execute: async (_args, ctx) => {
89
+ const read = await planFile.read(ctx?.signal);
90
+ if (!read.ok)
91
+ return errorResult(`The plan file ${planFile.shown} could not be read (${inlineUntrusted(read.reason, READ_REASON_MAX)}), so plan mode was not exited. Write your plan to this file and call ExitPlanMode again.`);
92
+ if (read.text === undefined)
93
+ return errorResult(`No plan file found at ${planFile.shown}. Please write your plan to this file before calling ExitPlanMode.`);
94
+ const plan = read.text;
95
+ requestReview({ reason: "ExitPlanMode" });
96
+ return {
97
+ content: `Plan presented for human review (from ${planFile.shown}):\n\n${delimitUntrusted("plan", plan)}\n\n` +
98
+ "(The run is pausing for approval — you will continue once the plan is approved, edited, or rejected.)",
99
+ details: { type: "exit-plan-mode", plan, isAgent: false, filePath: planFile.path },
100
+ };
101
+ },
102
+ };
103
+ }
104
+ export function createPresentPlanTool(requestReview, planFile) {
105
+ if (planFile !== undefined)
106
+ return createPresentPlanFileTool(requestReview, planFile);
63
107
  return {
64
108
  name: PRESENT_PLAN_TOOL_NAME,
65
109
  ...toolFace("exit-plan-mode"),
@@ -1,49 +1,59 @@
1
1
  /**
2
- * The HTTP credentials a protocol declaration carries — its static `headers` and the per-task principal
3
- * header (`principalHeader`) — and the one rule they obey, for MCP and A2A alike: they travel only to the
4
- * endpoints the declaration names, and every header name has exactly one owner, compared the way HTTP
5
- * compares names (case-insensitively). The principal header's owner is the engine: it sends the task's
6
- * principal under that name, or nothing under it when the task has none. A static header the credential vocabulary
7
- * reads as a credential is one the engine holds from the moment it resolves it: no child spawned on this host inherits
8
- * a variable whose value equals it (`holdOwnCredentialValues`, src/core/secret-env.ts).
2
+ * The HTTP headers one send to a protocol peer carries — the pieces the deployment's peer seat answered for it
3
+ * (src/core/peer-seat.ts) and the per-task principal header the declaration names (`principalHeader`) — and the one
4
+ * rule they obey, for MCP and A2A alike: they travel only to the endpoints the declaration names, and every header name
5
+ * has exactly one owner, compared the way HTTP compares names (case-insensitively). The principal header's owner is the
6
+ * engine: it sends the task's principal under that name, or nothing under it when the task has none. A name a protocol's
7
+ * transport writes itself (an MCP request's session, protocol version, content type, accept and resume headers) is the
8
+ * protocol's: neither a seat's answer nor the principal header owns it. The hosted-connector assertion header
9
+ * ({@link MCP_ASSERTION_HEADER}) is the seat's to answer and never the principal header's name. A header the credential
10
+ * vocabulary reads as a credential is one the engine holds from the moment it resolves it: no child spawned on this host
11
+ * inherits a variable whose value equals it (`holdOwnCredentialValues`, src/core/secret-env.ts).
9
12
  *
10
- * A declaration that breaks the rule is that peer's defect: the resolver throws inside the peer's own dial,
11
- * so the peer is skipped with a coded warning and its siblings still mount. The MCP transport binds its
12
- * endpoint by dialing only the declared URL with redirects not followed (`declaredEndpointFetch`); the A2A
13
- * peer, whose card may name another endpoint, is bound by {@link assertEndpointBound} and by its follow law (a request carrying
14
- * declared headers follows no redirect, {@link carriesDeclaredHeaders}).
13
+ * A principal header that breaks the rule is that peer's defect: the resolver throws inside the peer's own dial, so the
14
+ * peer is skipped with a coded warning and its siblings still mount; an answer that breaks it is the seat's, and that send
15
+ * is not made. The MCP transport binds its endpoint by dialing only the declared URL with redirects not followed (the seat's
16
+ * fetch, `peerFetch`); the A2A peer, whose card may name another endpoint, is bound at each send that carries pieces by
17
+ * {@link assertEndpointBound} and by its follow law (a request carrying them follows no redirect, {@link carriesDeclaredHeaders}).
15
18
  */
16
19
  import type { ProtocolId } from "./protocol-table.js";
17
20
  import { type Egress } from "./untrusted-egress.js";
18
- /** The per-peer HTTP auth declaration every protocol spec carries in the same two fields. */
21
+ /**
22
+ * The HTTP header NAME a hosted connector reads the principal assertion from: the engine's one definition of that name, exported from
23
+ * the package root so a deployment, a host and a connector each read it here instead of spelling it again. The name only — the
24
+ * value (the assertion itself) is not minted or held by this constant: the deployment's peer seat answers it under this name, per
25
+ * send. It is never the principal header's name (in any letter case): a declaration naming it so is refused at its dial with
26
+ * `config.protocol_header_collision`.
27
+ */
28
+ export declare const MCP_ASSERTION_HEADER = "connector-assertion";
29
+ /** The headers one send carries: the seat's answered `headers` and the declaration's `principalHeader` name. */
19
30
  export interface ProtocolHttpAuth {
20
31
  headers?: Record<string, string>;
21
32
  principalHeader?: string;
22
33
  }
23
- /** The first header name (any case) the declaration gives two owners, with both spellings. */
24
- export declare function headerOwnershipCollision(t: ProtocolHttpAuth): {
34
+ /**
35
+ * The first header name (any case) one send to a `protocol` peer would give two owners, with both spellings: two spellings among the
36
+ * answered `headers`, an answered header under the principal header's name, a name the protocol's transport writes itself (`first` is
37
+ * then the protocol's spelling, `engineOwned` true), or a principal header named as the engine's {@link MCP_ASSERTION_HEADER}
38
+ * (`first` the engine's spelling, `engineOwned` true). The assertion header among the answered headers is the seat's to send.
39
+ */
40
+ export declare function headerOwnershipCollision(t: ProtocolHttpAuth, protocol: ProtocolId): {
25
41
  readonly first: string;
26
42
  readonly second: string;
43
+ readonly engineOwned: boolean;
27
44
  } | undefined;
28
45
  /**
29
- * Resolve the HTTP request headers for one remote peer of `protocol`: the static headers, plus the
46
+ * Resolve the HTTP request headers of one send to a peer of `protocol`: the seat's answered headers, plus the
30
47
  * principal under `principalHeader` when both are present. Throws `config.protocol_header_collision` when
31
- * one header name has two owners (two static spellings, or a static entry under the principal header's
32
- * name — which would otherwise be sent merged beside the principal, or alone when the task has none), and
33
- * on a principal carrying CR/LF. Callers invoke it INSIDE their per-peer boundary.
48
+ * one header name would have two owners ({@link headerOwnershipCollision}: two spellings of one answered name, an
49
+ * answered header under the principal header's name — which would otherwise be sent merged beside the principal, or
50
+ * alone when the task has none — a name the protocol's transport writes, or a principal header named as the engine's
51
+ * {@link MCP_ASSERTION_HEADER}), and on a principal carrying CR/LF. Callers invoke it INSIDE their per-peer boundary.
34
52
  */
35
53
  export declare function resolveProtocolHttpHeaders(protocol: ProtocolId, t: ProtocolHttpAuth, principal?: string): Readonly<Record<string, string>> | undefined;
36
54
  /** The engine's default request headers under the declared ones: a declared name, in any case, owns that header
37
55
  * (the default of the same name is not sent beside it). */
38
56
  export declare function underDeclaredHeaders(defaults: Readonly<Record<string, string>>, declared: Record<string, string> | undefined): Record<string, string>;
39
- /**
40
- * Every header VALUE one HTTP peer's requests carry, whatever the header's NAME: each string value of the declaration's static
41
- * `headers` and the principal the engine sends under `principalHeader`, as declared. The transport knows these; the credential vocabulary
42
- * can only guess by name. How an endpoint can print one back — edges dropped, its credentials part, percent-encoded — is derived from
43
- * each value by {@link requestEchoSpellings}, once, and nowhere else.
44
- * Total: a declaration whose members cannot be read yields what could be read, because it is called on a failure path.
45
- */
46
- export declare function declaredHeaderValues(transport: unknown, principal?: string): readonly string[];
47
57
  /**
48
58
  * A peer's error text with what the peer was SENT taken out of it. Both kinds of removal are found on the ORIGINAL text (so no marker is
49
59
  * rescanned and no replacement can disturb what another one reads) and the ranges they take are merged, one marker per merged range: every
@@ -75,7 +85,8 @@ export declare function remoteWords(text: string, declared: readonly string[]):
75
85
  * next hop is not a declared endpoint; A2A's follow law reads this). */
76
86
  export declare function carriesDeclaredHeaders(headers: Record<string, string> | undefined): boolean;
77
87
  /**
78
- * Refuse an endpoint a peer advertised (an A2A card's interface URL) when it lies outside every origin the
79
- * declaration names and the peer's requests carry declared headers: `config.protocol_endpoint_unbound`.
88
+ * Refuse a send to `endpoint` (an A2A card's interface URL, judged at every send) when it lies outside every origin the
89
+ * declaration names and the send carries pieces the peer seat answered: `config.protocol_endpoint_unbound`. A send that
90
+ * carries none goes where the card says.
80
91
  */
81
92
  export declare function assertEndpointBound(protocol: ProtocolId, peer: string, endpoint: string, declared: readonly string[], headers: Record<string, string> | undefined): void;
@@ -1,25 +1,42 @@
1
1
  import { authSchemeCredentials, credentialHeaderValues, holdOwnCredentialValues } from "./secret-env.js";
2
- import { readMember } from "./thrown-value.js";
3
- import { egressText, redactionMarkerSpans } from "./untrusted-egress.js";
2
+ import { egressText } from "./untrusted-egress.js";
3
+ import { REDACTION_MARK, redactionMarkerSpans } from "./redaction-marks.js";
4
4
  import { inlineUntrusted } from "./untrusted-text.js";
5
- export function headerOwnershipCollision(t) {
5
+ export const MCP_ASSERTION_HEADER = "connector-assertion";
6
+ const PROTOCOL_OWNED_HEADERS = Object.freeze({
7
+ mcp: Object.freeze(["mcp-session-id", "mcp-protocol-version", "content-type", "accept", "last-event-id"]),
8
+ a2a: Object.freeze([]),
9
+ });
10
+ const ENGINE_OWNED_HEADERS = new Map([[MCP_ASSERTION_HEADER.toLowerCase(), MCP_ASSERTION_HEADER]]);
11
+ export function headerOwnershipCollision(t, protocol) {
6
12
  const owners = new Map();
7
- for (const name of [...Object.keys(t.headers ?? {}), ...(t.principalHeader ? [t.principalHeader] : [])]) {
8
- const prior = owners.get(name.toLowerCase());
13
+ const protocolOwned = PROTOCOL_OWNED_HEADERS[protocol];
14
+ const principalHeader = t.principalHeader ? [t.principalHeader] : [];
15
+ for (const name of [...Object.keys(t.headers ?? {}), ...principalHeader]) {
16
+ const folded = name.toLowerCase();
17
+ if (protocolOwned.includes(folded))
18
+ return { first: folded, second: name, engineOwned: true };
19
+ const engine = ENGINE_OWNED_HEADERS.get(folded);
20
+ if (engine !== undefined && principalHeader[0] === name)
21
+ return { first: engine, second: name, engineOwned: true };
22
+ const prior = owners.get(folded);
9
23
  if (prior !== undefined)
10
- return { first: prior, second: name };
11
- owners.set(name.toLowerCase(), name);
24
+ return { first: prior, second: name, engineOwned: false };
25
+ owners.set(folded, name);
12
26
  }
13
27
  return undefined;
14
28
  }
15
29
  export function resolveProtocolHttpHeaders(protocol, t, principal) {
16
30
  const principalHeader = t.principalHeader;
17
- const declared = t.headers;
18
- const own = { ...(declared !== undefined ? { headers: { ...declared } } : {}), ...(principalHeader !== undefined ? { principalHeader } : {}) };
31
+ const answered = t.headers;
32
+ const own = { ...(answered !== undefined ? { headers: { ...answered } } : {}), ...(principalHeader !== undefined ? { principalHeader } : {}) };
19
33
  holdOwnCredentialValues(credentialHeaderValues(own.headers));
20
- const collision = headerOwnershipCollision(own);
34
+ const collision = headerOwnershipCollision(own, protocol);
21
35
  if (collision !== undefined) {
22
- throw Object.assign(new Error(`${protocol}: the declaration names the header "${inlineUntrusted(collision.first, 80)}" twice ("${inlineUntrusted(collision.second, 80)}" — header names are case-insensitive); ${principalHeader !== undefined && collision.second === principalHeader ? "the principal header is the engine's to send, so remove the static entry" : "keep one spelling"} — this peer is not dialed`), { code: "config.protocol_header_collision" });
36
+ const problem = collision.engineOwned
37
+ ? `the header "${inlineUntrusted(collision.second, 80)}" is the ${PROTOCOL_OWNED_HEADERS[protocol].includes(collision.first) ? "protocol's own" : "engine's"} ${collision.first} header (header names are case-insensitive) and not ${principalHeader !== undefined && collision.second === principalHeader ? "the principal header's name" : "a header an answer may set"} — remove it`
38
+ : `the header "${inlineUntrusted(collision.first, 80)}" is named twice ("${inlineUntrusted(collision.second, 80)}" — header names are case-insensitive); ${principalHeader !== undefined && collision.second === principalHeader ? "the principal header is the engine's to send, so the answer may not set it" : "keep one spelling"}`;
39
+ throw Object.assign(new Error(`${protocol}: ${problem} — this peer is not dialed`), { code: "config.protocol_header_collision" });
23
40
  }
24
41
  if (principalHeader && principal !== undefined) {
25
42
  if (/[\r\n]/.test(principal))
@@ -33,24 +50,6 @@ export function underDeclaredHeaders(defaults, declared) {
33
50
  return { ...Object.fromEntries(Object.entries(defaults).filter(([k]) => !owned.has(k.toLowerCase()))), ...declared };
34
51
  }
35
52
  const httpTrimmed = (value) => value.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
36
- export function declaredHeaderValues(transport, principal) {
37
- const out = new Set();
38
- try {
39
- const headers = readMember(transport, "headers");
40
- if (typeof headers === "object" && headers !== null) {
41
- for (const value of Object.values(headers))
42
- if (typeof value === "string")
43
- out.add(value);
44
- }
45
- }
46
- catch {
47
- }
48
- const principalHeader = readMember(transport, "principalHeader");
49
- if (typeof principalHeader === "string" && principalHeader !== "" && principal !== undefined)
50
- out.add(principal);
51
- out.delete("");
52
- return [...out];
53
- }
54
53
  function percentEncoded(value) {
55
54
  try {
56
55
  return encodeURIComponent(value);
@@ -73,7 +72,6 @@ function requestEchoSpellings(value) {
73
72
  }
74
73
  return [...spellings];
75
74
  }
76
- const ECHO_MARKER = "[redacted]";
77
75
  const COOKIE_START = String.raw `(?<![\w-])(?<cookie>(?:[Ss][Ee][Tt]-)?[Cc][Oo][Oo][Kk][Ii][Ee])(?<quote>["']?)[ \t]*:`;
78
76
  function stringEnd(text, at) {
79
77
  for (let i = at + 1; i < text.length; i++) {
@@ -118,7 +116,7 @@ export function scrubRequestEcho(text, declared) {
118
116
  kept = Math.max(kept, end);
119
117
  continue;
120
118
  }
121
- out += text.slice(kept, start) + ECHO_MARKER;
119
+ out += text.slice(kept, start) + REDACTION_MARK;
122
120
  kept = end;
123
121
  }
124
122
  return out + text.slice(kept);
@@ -207,5 +205,5 @@ export function assertEndpointBound(protocol, peer, endpoint, declared, headers)
207
205
  const at = new URL(endpoint).origin;
208
206
  if (origins.includes(at))
209
207
  return;
210
- throw Object.assign(new Error(`${protocol}: peer "${inlineUntrusted(peer, 80)}" advertises the endpoint origin ${inlineUntrusted(at, 120)}, outside the origins its declaration names (${origins.map((o) => inlineUntrusted(o, 120)).join(", ")}); the declared headers travel only to those — declare that origin as the peer's url (and the card's location as cardUrl) or drop the headers`), { code: "config.protocol_endpoint_unbound" });
208
+ throw Object.assign(new Error(`${protocol}: peer "${inlineUntrusted(peer, 80)}" advertises the endpoint origin ${inlineUntrusted(at, 120)}, outside the origins its declaration names (${origins.map((o) => inlineUntrusted(o, 120)).join(", ")}); the headers the peer seat answers travel only to those — declare that origin as the peer's url (and the card's location as cardUrl) or have the seat answer none for it`), { code: "config.protocol_endpoint_unbound" });
211
209
  }
@@ -0,0 +1,16 @@
1
+ /** The marks, by what they stand for. `whole` is the bare mark (a span removed whole — a credential value, a floor, a
2
+ * depth cut); the others name the shape that was withheld: `credentials` a URL's userinfo, `url` a whole URL, `path` an
3
+ * absolute filesystem path. A mark the engine writes is exactly one of these four. */
4
+ export declare const REDACTION_MARKS: {
5
+ readonly whole: "[redacted]";
6
+ readonly credentials: "[redacted-credentials]";
7
+ readonly url: "[redacted-url]";
8
+ readonly path: "[redacted-path]";
9
+ };
10
+ /** The bare mark — what a host compares against to tell that the engine withheld a value. */
11
+ export declare const REDACTION_MARK: "[redacted]";
12
+ /** Where the marks sit in `s`, one [start, end) span at a time, leftmost first. Lazy: a reader that stops early (a display cut stops
13
+ * at its bound) pays for the marks it looked at, not for every mark an input of a million of them holds. */
14
+ export declare function eachRedactionMarkerSpan(s: string): Generator<[number, number], void, undefined>;
15
+ /** Where the marks sit in `s`, all of them, as [start, end) spans, leftmost first. */
16
+ export declare function redactionMarkerSpans(s: string): Array<[number, number]>;
@@ -0,0 +1,16 @@
1
+ export const REDACTION_MARKS = {
2
+ whole: "[redacted]",
3
+ credentials: "[redacted-credentials]",
4
+ url: "[redacted-url]",
5
+ path: "[redacted-path]",
6
+ };
7
+ export const REDACTION_MARK = REDACTION_MARKS.whole;
8
+ const escapeLiteral = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9
+ const REDACTION_MARKER_RE = new RegExp(Object.values(REDACTION_MARKS).map(escapeLiteral).join("|"), "g");
10
+ export function* eachRedactionMarkerSpan(s) {
11
+ for (const m of s.matchAll(REDACTION_MARKER_RE))
12
+ yield [m.index, m.index + m[0].length];
13
+ }
14
+ export function redactionMarkerSpans(s) {
15
+ return [...eachRedactionMarkerSpan(s)];
16
+ }