@sema-agent/core 7.56.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 (319) hide show
  1. package/CHANGELOG.md +926 -0
  2. package/LICENSE +1 -1
  3. package/dist/agents/org-delivery-gate.js +3 -4
  4. package/dist/agents/peer-held-queue.d.ts +69 -49
  5. package/dist/agents/peer-held-queue.js +255 -106
  6. package/dist/agents/peer-session-drain.js +63 -43
  7. package/dist/agents/send-message-tool.js +3 -2
  8. package/dist/agents/subagent-steps.js +2 -4
  9. package/dist/agents/subagent.js +8 -8
  10. package/dist/brain/anthropic.js +16 -8
  11. package/dist/brain/open-responses.js +10 -8
  12. package/dist/brain/openai.js +11 -9
  13. package/dist/brain/provider-dialect.d.ts +3 -2
  14. package/dist/brain/provider-dialect.js +2 -2
  15. package/dist/brain/request-params.d.ts +6 -0
  16. package/dist/brain/request-params.js +14 -1
  17. package/dist/brain/route-adjudicator.js +2 -1
  18. package/dist/brain/stream-engine.d.ts +9 -0
  19. package/dist/brain/stream-engine.js +24 -10
  20. package/dist/brain/stream-shared.d.ts +5 -4
  21. package/dist/brain/stream-shared.js +4 -4
  22. package/dist/core/a2a.d.ts +2 -1
  23. package/dist/core/a2a.js +23 -10
  24. package/dist/core/allow-entry.d.ts +5 -11
  25. package/dist/core/allow-entry.js +19 -26
  26. package/dist/core/approval-object.d.ts +21 -5
  27. package/dist/core/approval-object.js +44 -17
  28. package/dist/core/ask-origin.d.ts +23 -4
  29. package/dist/core/ask-origin.js +5 -1
  30. package/dist/core/auto-compaction.d.ts +75 -6
  31. package/dist/core/auto-compaction.js +43 -27
  32. package/dist/core/auto-mode-directive.d.ts +29 -5
  33. package/dist/core/auto-mode-directive.js +38 -8
  34. package/dist/core/background-agent-store.d.ts +6 -2
  35. package/dist/core/background-agent-store.js +1 -1
  36. package/dist/core/checkpoint-requirements.d.ts +13 -1
  37. package/dist/core/checkpoint-requirements.js +4 -0
  38. package/dist/core/checkpoint-store.d.ts +44 -40
  39. package/dist/core/checkpoint-store.js +32 -14
  40. package/dist/core/cross-boundary-taint.js +4 -2
  41. package/dist/core/engine-notice.d.ts +4 -3
  42. package/dist/core/engine-notice.js +6 -0
  43. package/dist/core/file-history-store.d.ts +14 -8
  44. package/dist/core/file-history-store.js +14 -4
  45. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  46. package/dist/core/fs-write-gate-policy.js +7 -3
  47. package/dist/core/gate-fold.js +6 -3
  48. package/dist/core/gate-lanes.js +13 -5
  49. package/dist/core/git-worktree-env.d.ts +53 -11
  50. package/dist/core/git-worktree-env.js +96 -12
  51. package/dist/core/hooks.d.ts +6 -3
  52. package/dist/core/hooks.js +12 -5
  53. package/dist/core/human-input-projection.d.ts +1 -0
  54. package/dist/core/human-input-projection.js +3 -0
  55. package/dist/core/locked-config.d.ts +15 -1
  56. package/dist/core/locked-config.js +38 -2
  57. package/dist/core/mailbox-store.d.ts +62 -1
  58. package/dist/core/mailbox-store.js +59 -0
  59. package/dist/core/mcp-call-meta.d.ts +66 -0
  60. package/dist/core/mcp-call-meta.js +103 -0
  61. package/dist/core/mcp-connection-pool.d.ts +3 -1
  62. package/dist/core/mcp-connection-pool.js +3 -1
  63. package/dist/core/mcp-failure.d.ts +7 -1
  64. package/dist/core/mcp-failure.js +10 -0
  65. package/dist/core/mcp-name-judge.d.ts +46 -0
  66. package/dist/core/mcp-name-judge.js +61 -0
  67. package/dist/core/mcp-probe.d.ts +5 -1
  68. package/dist/core/mcp-probe.js +3 -6
  69. package/dist/core/mcp-server-link.d.ts +5 -2
  70. package/dist/core/mcp-server-spec.d.ts +46 -18
  71. package/dist/core/mcp-server-spec.js +1 -18
  72. package/dist/core/mcp.d.ts +6 -14
  73. package/dist/core/mcp.js +85 -65
  74. package/dist/core/memory-engine/consolidation-driver.js +4 -3
  75. package/dist/core/memory-engine/distiller.js +26 -17
  76. package/dist/core/memory-engine/layout.js +5 -2
  77. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  78. package/dist/core/memory-engine/scope-contract.js +80 -11
  79. package/dist/core/mode-policy.d.ts +8 -5
  80. package/dist/core/mode-policy.js +5 -4
  81. package/dist/core/mods/host.js +1 -1
  82. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  83. package/dist/core/mods/kernel/dispatch.js +10 -8
  84. package/dist/core/mods/kernel/events.d.ts +5 -1
  85. package/dist/core/mods/kernel/events.js +1 -1
  86. package/dist/core/mods/kernel/registration.d.ts +5 -1
  87. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  88. package/dist/core/mods/kernel/site-rules.js +10 -0
  89. package/dist/core/mods/package.d.ts +23 -0
  90. package/dist/core/mods/package.js +118 -0
  91. package/dist/core/mods/stations.d.ts +2 -2
  92. package/dist/core/mods/stations.js +1 -1
  93. package/dist/core/mods/tool-call.d.ts +5 -1
  94. package/dist/core/mods/tool-call.js +12 -3
  95. package/dist/core/park-selfcheck.js +2 -0
  96. package/dist/core/path-guard-rows.d.ts +20 -0
  97. package/dist/core/path-guard-rows.js +11 -0
  98. package/dist/core/peer-seat.d.ts +186 -0
  99. package/dist/core/peer-seat.js +307 -0
  100. package/dist/core/permission-rule-consent.d.ts +5 -3
  101. package/dist/core/permission-rule-consent.js +20 -15
  102. package/dist/core/permission-rule-model.d.ts +43 -2
  103. package/dist/core/permission-rule-model.js +52 -8
  104. package/dist/core/permission-rule-org.js +1 -1
  105. package/dist/core/present-plan-tool.d.ts +10 -1
  106. package/dist/core/present-plan-tool.js +46 -2
  107. package/dist/core/protocol-http-auth.d.ts +56 -31
  108. package/dist/core/protocol-http-auth.js +71 -42
  109. package/dist/core/protocol-naming.d.ts +20 -0
  110. package/dist/core/protocol-naming.js +20 -3
  111. package/dist/core/read-only-shell.d.ts +20 -5
  112. package/dist/core/read-only-shell.js +29 -14
  113. package/dist/core/redaction-marks.d.ts +16 -0
  114. package/dist/core/redaction-marks.js +16 -0
  115. package/dist/core/redaction-passes.js +8 -9
  116. package/dist/core/remote-env.d.ts +37 -1
  117. package/dist/core/remote-env.js +11 -0
  118. package/dist/core/resume-startup-cause.d.ts +24 -2
  119. package/dist/core/resume-startup-cause.js +20 -1
  120. package/dist/core/retention.d.ts +41 -15
  121. package/dist/core/retention.js +59 -12
  122. package/dist/core/rewrite-rejudge.d.ts +37 -0
  123. package/dist/core/rewrite-rejudge.js +40 -0
  124. package/dist/core/roles.js +50 -7
  125. package/dist/core/run-origin.d.ts +40 -0
  126. package/dist/core/run-origin.js +37 -0
  127. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  128. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  129. package/dist/core/runner/compact-session.d.ts +10 -0
  130. package/dist/core/runner/compact-session.js +202 -0
  131. package/dist/core/runner/compaction-call-options.d.ts +2 -2
  132. package/dist/core/runner/compaction-restate.d.ts +15 -6
  133. package/dist/core/runner/compaction-restate.js +28 -2
  134. package/dist/core/runner/compaction-seams.d.ts +21 -1
  135. package/dist/core/runner/compaction-seams.js +11 -8
  136. package/dist/core/runner/contracts.d.ts +36 -21
  137. package/dist/core/runner/derived-route-fallback.d.ts +13 -0
  138. package/dist/core/runner/derived-route-fallback.js +6 -0
  139. package/dist/core/runner/env-capability-census.d.ts +3 -2
  140. package/dist/core/runner/env-capability-census.js +9 -3
  141. package/dist/core/runner/gate-exit.d.ts +18 -4
  142. package/dist/core/runner/gate-exit.js +5 -1
  143. package/dist/core/runner/permission-rule-lanes.d.ts +7 -7
  144. package/dist/core/runner/permission-rule-lanes.js +17 -11
  145. package/dist/core/runner/prepare-acquire-reconcile.d.ts +3 -0
  146. package/dist/core/runner/prepare-acquire-reconcile.js +2 -1
  147. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  148. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  149. package/dist/core/runner/prepare-config-doors.d.ts +14 -5
  150. package/dist/core/runner/prepare-config-doors.js +16 -13
  151. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  152. package/dist/core/runner/prepare-delegation-surface.js +15 -18
  153. package/dist/core/runner/prepare-gate-stations.js +1 -1
  154. package/dist/core/runner/prepare-hands-readface.d.ts +10 -4
  155. package/dist/core/runner/prepare-hands-readface.js +6 -1
  156. package/dist/core/runner/prepare-memory.d.ts +3 -0
  157. package/dist/core/runner/prepare-memory.js +19 -23
  158. package/dist/core/runner/prepare-park-ask.d.ts +2 -0
  159. package/dist/core/runner/prepare-park-ask.js +2 -2
  160. package/dist/core/runner/prepare-policy-chain.d.ts +4 -4
  161. package/dist/core/runner/prepare-policy-chain.js +4 -6
  162. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  163. package/dist/core/runner/prepare-protocol-tools.js +3 -3
  164. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  165. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  166. package/dist/core/runner/prepare-task.d.ts +4 -1
  167. package/dist/core/runner/prepare-task.js +46 -37
  168. package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +13 -0
  169. package/dist/core/runner/prepare-tool-disclosure-mount.js +13 -7
  170. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  171. package/dist/core/runner/prepare-wiring-manifest.js +2 -2
  172. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  173. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  174. package/dist/core/runner/resume-admission.js +1 -1
  175. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  176. package/dist/core/runner/rewind-files.d.ts +2 -5
  177. package/dist/core/runner/rewind-files.js +9 -51
  178. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  179. package/dist/core/runner/run-harness-handlers.js +1 -8
  180. package/dist/core/runner/run-identity-wiring.js +1 -0
  181. package/dist/core/runner/run-leg.js +15 -22
  182. package/dist/core/runner/run-notification-lane.d.ts +2 -0
  183. package/dist/core/runner/run-notification-lane.js +5 -2
  184. package/dist/core/runner/run-recovery-lanes.js +3 -4
  185. package/dist/core/runner/run-settle-and-teardown.js +5 -11
  186. package/dist/core/runner/run-terminal-adoption.js +3 -4
  187. package/dist/core/runner/run-turn-boundary.js +3 -5
  188. package/dist/core/runner/runtask.d.ts +8 -1
  189. package/dist/core/runner/runtask.js +28 -34
  190. package/dist/core/runner/send-message-continuation.js +1 -1
  191. package/dist/core/runner/session-verb-doors.d.ts +28 -0
  192. package/dist/core/runner/session-verb-doors.js +48 -0
  193. package/dist/core/runner/session-write-ledger.d.ts +30 -0
  194. package/dist/core/runner/session-write-ledger.js +101 -0
  195. package/dist/core/runner/stream-settle-backstop.js +11 -14
  196. package/dist/core/runner/sub-agent-deny-lists.d.ts +25 -3
  197. package/dist/core/runner/sub-agent-deny-lists.js +21 -10
  198. package/dist/core/runner/teardown-bounded.d.ts +1 -0
  199. package/dist/core/runner/teardown-bounded.js +1 -0
  200. package/dist/core/runner/terminal-account.js +3 -3
  201. package/dist/core/runner/tool-end-body.js +1 -0
  202. package/dist/core/runner/tool-occurrence.d.ts +4 -1
  203. package/dist/core/runner/tool-occurrence.js +2 -1
  204. package/dist/core/runner/write-protection-station.d.ts +8 -2
  205. package/dist/core/runner/write-protection-station.js +2 -0
  206. package/dist/core/runner-deps.d.ts +4 -4
  207. package/dist/core/secret-env.d.ts +4 -0
  208. package/dist/core/secret-env.js +3 -0
  209. package/dist/core/sensitive-path-policy.js +6 -7
  210. package/dist/core/session-log-transfer.d.ts +24 -0
  211. package/dist/core/session-log-transfer.js +166 -0
  212. package/dist/core/session-policy-store.d.ts +7 -2
  213. package/dist/core/session-policy-store.js +1 -1
  214. package/dist/core/session-store.d.ts +84 -19
  215. package/dist/core/session-store.js +162 -24
  216. package/dist/core/session.d.ts +92 -1
  217. package/dist/core/shell-read-silence.js +1 -0
  218. package/dist/core/shell-wrapper-projection.d.ts +1 -1
  219. package/dist/core/steer-replay.d.ts +4 -2
  220. package/dist/core/steer-replay.js +2 -1
  221. package/dist/core/store-contracts/background-agent-store-contract.js +1 -0
  222. package/dist/core/store-contracts/checkpoint-store-contract.js +19 -1
  223. package/dist/core/store-contracts/file-history-store-contract.js +9 -0
  224. package/dist/core/store-contracts/mailbox-store-contract.js +49 -1
  225. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  226. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  227. package/dist/core/store-contracts/session-store-contract.js +236 -2
  228. package/dist/core/task-event.d.ts +68 -8
  229. package/dist/core/task-registry-agent.d.ts +8 -4
  230. package/dist/core/task-registry-agent.js +14 -8
  231. package/dist/core/task-registry-shared.d.ts +36 -6
  232. package/dist/core/task-registry-shared.js +11 -0
  233. package/dist/core/task-registry.d.ts +1 -1
  234. package/dist/core/task-registry.js +1 -1
  235. package/dist/core/task-spec.d.ts +37 -0
  236. package/dist/core/task-stream.d.ts +2 -1
  237. package/dist/core/terminal-cause.d.ts +1 -1
  238. package/dist/core/tool-catalog-entries.d.ts +6 -0
  239. package/dist/core/tool-catalog-entries.js +2 -0
  240. package/dist/core/tool-name-aliases.d.ts +32 -2
  241. package/dist/core/tool-name-aliases.js +23 -0
  242. package/dist/core/tool-name-readings.d.ts +4 -0
  243. package/dist/core/tool-name-readings.js +1 -0
  244. package/dist/core/tool-policy.d.ts +10 -6
  245. package/dist/core/tool-policy.js +4 -7
  246. package/dist/core/tool-result-store.d.ts +17 -10
  247. package/dist/core/tool-result-store.js +3 -1
  248. package/dist/core/trace.d.ts +4 -1
  249. package/dist/core/trace.js +2 -1
  250. package/dist/core/types.d.ts +1 -1
  251. package/dist/core/untrusted-egress.d.ts +18 -0
  252. package/dist/core/untrusted-egress.js +82 -12
  253. package/dist/core/wiring-manifest.d.ts +12 -3
  254. package/dist/core/wiring-manifest.js +4 -3
  255. package/dist/core/workspace-snapshot.d.ts +44 -0
  256. package/dist/core/workspace-snapshot.js +34 -0
  257. package/dist/core/write-protect.d.ts +43 -3
  258. package/dist/core/write-protect.js +43 -16
  259. package/dist/engine/execution-env/node-execution-env.js +15 -11
  260. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  261. package/dist/engine/harness/agent-harness.d.ts +12 -5
  262. package/dist/engine/harness/agent-harness.js +13 -2
  263. package/dist/engine/harness/types.d.ts +48 -7
  264. package/dist/engine/harness/types.js +5 -1
  265. package/dist/engine/llm/types.d.ts +12 -3
  266. package/dist/engine/llm/types.js +1 -1
  267. package/dist/engine/loop/agent-loop.d.ts +1 -4
  268. package/dist/engine/loop/agent-loop.js +26 -4
  269. package/dist/engine/session/import-validate.js +3 -0
  270. package/dist/engine/session/memory-repo.d.ts +17 -9
  271. package/dist/engine/session/memory-repo.js +44 -34
  272. package/dist/engine/session/repo-utils.d.ts +22 -4
  273. package/dist/engine/session/repo-utils.js +49 -1
  274. package/dist/engine/session/storage-base.d.ts +10 -1
  275. package/dist/engine/session/storage-base.js +7 -1
  276. package/dist/index.d.ts +23 -11
  277. package/dist/index.js +15 -6
  278. package/dist/internal/harness-types.d.ts +1 -1
  279. package/dist/internal/harness.d.ts +4 -3
  280. package/dist/internal/harness.js +3 -2
  281. package/dist/stores/file/checkpoint-store.d.ts +0 -4
  282. package/dist/stores/file/checkpoint-store.js +0 -1
  283. package/dist/stores/file/file-history-store.js +12 -4
  284. package/dist/stores/file/index.d.ts +4 -1
  285. package/dist/stores/file/index.js +4 -1
  286. package/dist/stores/file/mailbox-store.d.ts +2 -1
  287. package/dist/stores/file/mailbox-store.js +26 -1
  288. package/dist/stores/file/session-store.d.ts +15 -8
  289. package/dist/stores/file/session-store.js +28 -13
  290. package/dist/tools/fs/bash-readonly-classifier.d.ts +15 -19
  291. package/dist/tools/fs/bash-readonly-classifier.js +5 -10
  292. package/dist/tools/fs/fs-bash.js +10 -3
  293. package/dist/tools/fs/fs-write.d.ts +6 -3
  294. package/dist/tools/fs/fs-write.js +8 -7
  295. package/dist/tools/fs/index.d.ts +3 -0
  296. package/dist/tools/fs/index.js +1 -1
  297. package/dist/tools/fs/pattern-kill-guard.d.ts +3 -2
  298. package/dist/tools/fs/pattern-kill-guard.js +68 -36
  299. package/dist/tools/fs/safety.js +40 -8
  300. package/dist/tools/fs/search.js +6 -24
  301. package/dist/tools/fs/shell-read-check.d.ts +18 -1
  302. package/dist/tools/fs/shell-read-check.js +66 -16
  303. package/dist/tools/fs/shell-read-establish.js +2 -1
  304. package/dist/tools/fs/shell-read-identity.d.ts +12 -9
  305. package/dist/tools/fs/shell-read-identity.js +10 -5
  306. package/dist/tools/fs/shell-read-judge.d.ts +10 -1
  307. package/dist/tools/web.js +9 -7
  308. package/dist/tools/worktree.d.ts +42 -15
  309. package/dist/tools/worktree.js +60 -32
  310. package/package.json +4 -2
  311. package/test/export-surface.snapshot.json +141 -3
  312. package/wire-changes/core-stores-sql@7.57.0.json +29 -0
  313. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  314. package/wire-changes/core@7.57.0.json +1487 -0
  315. package/wire-changes/core@7.58.0.json +2188 -0
  316. package/wire-changes/mods-kernel@7.57.0.json +29 -0
  317. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  318. package/wire-changes/primitives@7.57.0.json +245 -0
  319. package/wire-changes/primitives@7.58.0.json +29 -0
@@ -7,7 +7,7 @@ import type { ClassicEventMap, ClassicEventName } from "./classic-events.js";
7
7
  import type { PermissionMode } from "../ask-origin.js";
8
8
  import type { RunnerDeps } from "../runner-deps.js";
9
9
  import type { TaskSpec } from "../task-spec.js";
10
- import { type ModAnswerRanks, type ModBus, type ModCallEntry, type ModMountedHandler, type ModDispatchOutcome, type ModEventPayload, type ModRegistration } from "./kernel/index.js";
10
+ import { type ModAnswerCheck, type ModAnswerRanks, type ModBus, type ModCallEntry, type ModMountedHandler, type ModDispatchOutcome, type ModEventPayload, type ModRegistration } from "./kernel/index.js";
11
11
  import { type SourcedOverlay } from "../../prompt-assembly/overlay.js";
12
12
  import type { BandId } from "../../prompt-assembly/catalog/schema.js";
13
13
  import type { ModParticipant } from "./kernel/dispatch.js";
@@ -169,7 +169,7 @@ export declare function observeClassic<K extends ClassicEventName>(bus: LegModBu
169
169
  */
170
170
  export declare function dispatchClassic<K extends ClassicEventName>(bus: LegModBus, event: K, e: ClassicEventMap[K]["e"], options: {
171
171
  readonly signal?: AbortSignal;
172
- readonly checkAnswer?: (answer: unknown) => string | undefined;
172
+ readonly checkAnswer?: ModAnswerCheck;
173
173
  readonly ranks?: ModAnswerRanks;
174
174
  }): Promise<ModDispatchOutcome | undefined>;
175
175
  /** The answer form of a classic event whose answer is an object of optional string members (`block`, `additionalContext`, …). */
@@ -142,7 +142,7 @@ export async function dispatchClassic(bus, event, e, options) {
142
142
  return await bus.dispatch(event, e, {
143
143
  bottom: engineCore,
144
144
  ...(options.signal !== undefined ? { signal: options.signal } : {}),
145
- ...(check !== undefined ? { checkAnswer: (a) => (a === ENGINE_CORE_ANSWER ? undefined : check(a)) } : {}),
145
+ ...(check !== undefined ? { checkAnswer: (a, ce, by, below, run) => (a === ENGINE_CORE_ANSWER ? undefined : check(a, ce, by, below, run)) } : {}),
146
146
  ...(options.ranks !== undefined ? { ranks: options.ranks } : {}),
147
147
  });
148
148
  }
@@ -5,7 +5,8 @@
5
5
  * handler's failure refuses the call while the body has not started and, once it has, the body's real result stands.
6
6
  *
7
7
  * `e = { tool, tool_use_id, agentId?, input }` (all four pinned — what the gate judged is what runs; a rewrite belongs to
8
- * `classic.PreToolUse`) plus the identity envelope. A handler answers:
8
+ * `classic.PreToolUse`) plus the identity envelope; a handler may hand on `requestMeta` too (a record of strings an MCP call carries
9
+ * as `_meta["sema/requestMeta"]`, judged where it is handed on — `mcp-call-meta.ts`). A handler answers:
9
10
  * - `next(e)` — the body runs; what came up is `{ result: { content, isError } }`, a frozen view of the real result;
10
11
  * - `{ deny: <reason> }` — refused before the body: the call is not executed and the record says an extension refused it
11
12
  * (a deny once the body has started stands in place of a call that ran: a violation, the real result stands);
@@ -28,6 +29,7 @@
28
29
  import type { AgentToolResult } from "../../internal/harness-types.js";
29
30
  import type { HookInvocationIdentity } from "../hooks.js";
30
31
  import type { ToolOccurrenceTable } from "../runner/tool-occurrence.js";
32
+ import { type McpRequestMetaSeat } from "../mcp-call-meta.js";
31
33
  import { type LegModBus } from "./stations.js";
32
34
  import type { ModBus, ModCallEntry } from "./kernel/index.js";
33
35
  /** One execution as the station sees it: the call, the tool that runs (its mounted name), the arguments the gate let go. */
@@ -46,6 +48,8 @@ export interface ToolCallStationInput {
46
48
  readonly blockedToolCalls: Set<string>;
47
49
  readonly identity?: HookInvocationIdentity;
48
50
  readonly reminderMark?: string;
51
+ /** The leg's request-meta seat: what the chain handed on as `requestMeta` stands under the call's id while its body runs. */
52
+ readonly requestMeta: Pick<McpRequestMetaSeat, "hold">;
49
53
  }
50
54
  /** The station over the leg's bus, or undefined when no handler hangs on `tool.call` (nothing is raised; the body runs). */
51
55
  export declare function createToolCallStation(input: ToolCallStationInput): ToolCallStation | undefined;
@@ -3,6 +3,7 @@ import { toolFace } from "../tool-catalog-entries.js";
3
3
  import { declaredDelegationNameOf } from "../delegation-name.js";
4
4
  import { describeThrown } from "../tool-policy.js";
5
5
  import { extensionWords } from "../untrusted-egress.js";
6
+ import { readHandedRequestMeta } from "../mcp-call-meta.js";
6
7
  import { ENGINE_ORIGIN } from "./kernel/index.js";
7
8
  import { isPlainRecord } from "./kernel/receive.js";
8
9
  import { NEXT_IN_FLIGHT } from "./kernel/site-rules.js";
@@ -60,8 +61,16 @@ export function createToolCallStation(input) {
60
61
  const e = { ...classicEventBase(input.identity), tool: call.toolName, tool_use_id: call.toolCallId, input: judgedInputOf(call.args) };
61
62
  const bodies = new Map();
62
63
  let body;
63
- const bottom = async () => {
64
- body = run();
64
+ const judged = new WeakMap();
65
+ const checkHandOn = (payload) => {
66
+ const read = readHandedRequestMeta(payload);
67
+ if ("problem" in read)
68
+ return `next() handed on a requestMeta the call cannot carry: ${read.problem}`;
69
+ judged.set(payload, read.meta);
70
+ return undefined;
71
+ };
72
+ const bottom = async (handed) => {
73
+ body = input.requestMeta.hold(call.toolCallId, judged.get(handed), run);
65
74
  const result = await body;
66
75
  const view = viewOf(result);
67
76
  bodies.set(view, result);
@@ -83,7 +92,7 @@ export function createToolCallStation(input) {
83
92
  };
84
93
  let outcome;
85
94
  try {
86
- outcome = await input.bus.dispatch("tool.call", e, { bottom, checkAnswer, ranks: RANKS, ...(signal !== undefined ? { signal } : {}) });
95
+ outcome = await input.bus.dispatch("tool.call", e, { bottom, checkAnswer, checkHandOn, ranks: RANKS, ...(signal !== undefined ? { signal } : {}) });
87
96
  }
88
97
  catch (err) {
89
98
  if (body !== undefined)
@@ -81,6 +81,8 @@ function syntheticCheckpoint(scope, fidelity) {
81
81
  askClass: "denial_limit_fallback",
82
82
  classes: ["denial_limit_fallback"],
83
83
  engineMounted: true,
84
+ targets: { protective: "/park-selfcheck/target", declared: null },
85
+ targetReads: { ["0".repeat(64)]: "f".repeat(64) },
84
86
  batchToolCallIds: [`${scope}:call`],
85
87
  completedCallIds: [],
86
88
  },
@@ -88,6 +88,26 @@ export interface PathRowsHit<R> {
88
88
  readonly viewKind?: GuardViewKind;
89
89
  readonly unreadable?: string;
90
90
  }
91
+ /** WHICH reading of the target met a tightening row, in the word every guard that writes about the hit records: `spelling`
92
+ * — the path as written (its placed spelling); `target` — where it really lands; `chain` — a hop of its leaf's symlink
93
+ * chain. A hit with no view (an unreadable hold) and a `home` view — the read-deny home station's, which no write guard
94
+ * mints — read as the spelling. */
95
+ export type GuardHitVia = "spelling" | "target" | "chain";
96
+ /** The ONE reading of a hit's view kind as its {@link GuardHitVia}, for every guard that records or words a hit. */
97
+ export declare function guardHitVia(kind: GuardViewKind | undefined): GuardHitVia;
98
+ /** Which spellings of the leg's current managed checkout a view is placed against (write-protect's current-tree reading): the
99
+ * canonical view against the checkout's canonical identity alone, every other view against every spelling of it. */
100
+ export type CheckoutReading = "canonical-only" | "every-spelling";
101
+ /** The ONE reading of a view kind as the {@link CheckoutReading} its current-tree placement uses (a new {@link GuardViewKind} must pick one). */
102
+ export declare function checkoutReadingOf(kind: GuardViewKind): CheckoutReading;
103
+ /**
104
+ * What a guard's sentence says about WHERE the row was met — one clause for every guard's sentence, said when the reading that
105
+ * met it is not the spelling. `target` and `chain` are one fact to whoever reads the sentence (the person approving, the
106
+ * auto-mode classifier, the model refused): the row was met by following the path on disk, at its real target or at a link on
107
+ * the way. Two wordings of that one fact let the wording, not the fact, move an answer. The clause says which reading met the
108
+ * row and nothing about the spelling: a spelling the identity exemption kept from voting may name the row too.
109
+ */
110
+ export declare function guardHitReachClause(via: GuardHitVia): string | undefined;
91
111
  /**
92
112
  * THE one judgment of guarded rows over a target's views, for every table and every lane: rows outer, views inner — the
93
113
  * first row (in the caller's order) that some view reaches is the answer. `tighten` (deny / ask): any present view reaching
@@ -8,6 +8,17 @@ export function viewSpellings(views) {
8
8
  export function spelledViews(spellings, kind) {
9
9
  return { views: spellings.map((path, i) => ({ path, kind: kind ?? (i === 0 ? "lexical" : "canonical") })) };
10
10
  }
11
+ const GUARD_HIT_VIA = { lexical: "spelling", canonical: "target", hop: "chain", home: "spelling" };
12
+ export function guardHitVia(kind) {
13
+ return kind === undefined ? "spelling" : GUARD_HIT_VIA[kind];
14
+ }
15
+ const CHECKOUT_READING = { lexical: "every-spelling", canonical: "canonical-only", hop: "every-spelling", home: "every-spelling" };
16
+ export function checkoutReadingOf(kind) {
17
+ return CHECKOUT_READING[kind];
18
+ }
19
+ export function guardHitReachClause(via) {
20
+ return via === "spelling" ? undefined : "matched where the path resolves on disk (its real target or a link on the way)";
21
+ }
11
22
  export function judgePathRows(rows, views, direction) {
12
23
  if (direction === "allow") {
13
24
  if (views.unreadable !== undefined || views.views.length === 0)
@@ -0,0 +1,186 @@
1
+ import { type CredentialRef } from "@sema-agent/primitives";
2
+ import type { McpServerSpec } from "./mcp-server-spec.js";
3
+ import type { ProtocolId } from "./protocol-table.js";
4
+ /** Why the seat is asked: the first send of a connection, any later send, or the send after a 401. */
5
+ export type PeerAskCause = "connect" | "request" | "rejected";
6
+ /**
7
+ * Who the request goes to, as the declaration names it — the whole of it, so the seat can bind an answer to the reference, the
8
+ * principal, the protocol and the destination (or the whole start command): an http MCP server's url, a stdio one's command and
9
+ * arguments, an A2A peer's declared urls and THIS send's destination.
10
+ */
11
+ export type PeerSeatTarget = {
12
+ readonly protocol: "mcp";
13
+ readonly server: string;
14
+ readonly transport: "http";
15
+ readonly url: string;
16
+ readonly credentials?: CredentialRef;
17
+ readonly fingerprint?: string;
18
+ } | {
19
+ readonly protocol: "mcp";
20
+ readonly server: string;
21
+ readonly transport: "stdio";
22
+ readonly command: string;
23
+ readonly args: readonly string[];
24
+ readonly credentials?: CredentialRef;
25
+ readonly fingerprint?: string;
26
+ } | {
27
+ readonly protocol: "a2a";
28
+ readonly peer: string;
29
+ readonly url: string;
30
+ readonly cardUrl?: string;
31
+ readonly destination: string;
32
+ readonly credentials?: CredentialRef;
33
+ };
34
+ /** One question to the seat. `principal` is part of the connection's identity; the session is not. */
35
+ export interface PeerQuestion {
36
+ readonly peer: PeerSeatTarget;
37
+ readonly principal?: string;
38
+ readonly cause: PeerAskCause;
39
+ }
40
+ /**
41
+ * The seat's answer: the pieces to carry (`headers` for an http request and an A2A send, `env` for a stdio child — the member of the
42
+ * other lane is refused; `expiresAt`, epoch ms, is read by a stdio child only), or that the principal is not authorized here.
43
+ */
44
+ export type PeerAnswer = {
45
+ readonly kind: "carry";
46
+ readonly headers?: Readonly<Record<string, string>>;
47
+ readonly env?: Readonly<Record<string, string>>;
48
+ readonly expiresAt?: number;
49
+ } | {
50
+ readonly kind: "unauthorized";
51
+ readonly authorizeUrl?: string;
52
+ };
53
+ /**
54
+ * The deployment's peer seat (`RunnerDeps.peerSeat`, TRUSTED). It owes the binding the engine cannot judge: answer only for the
55
+ * reference, principal, protocol and destination (or start command) it was asked about — never one token for every peer.
56
+ */
57
+ export type PeerSeat = (question: PeerQuestion, signal: AbortSignal) => Promise<PeerAnswer>;
58
+ /** Which answer member each transport carries. */
59
+ export declare const PEER_ANSWER_LANES: Readonly<{
60
+ readonly http: "headers";
61
+ readonly a2a: "headers";
62
+ readonly stdio: "env";
63
+ }>;
64
+ export type PeerLane = keyof typeof PEER_ANSWER_LANES;
65
+ /** How long one ask may take before the send goes without it (`credential_unavailable`). */
66
+ export declare const PEER_SEAT_WAIT_MS = 30000;
67
+ /** Why a send went without its pieces. */
68
+ export type PeerSeatFailureReason = "threw" | "timed_out" | "answer_invalid" | "unauthorized";
69
+ /**
70
+ * A send the seat did not furnish: nothing was sent. The text names the peer and the reason, never a value and never the seat's own
71
+ * error text (deployment code may put a credential in it); `authorizeUrl` is the seat's own, when it answered `unauthorized`.
72
+ */
73
+ export declare class PeerSeatFailure extends Error {
74
+ readonly reason: PeerSeatFailureReason;
75
+ readonly authorizeUrl: string | undefined;
76
+ /** An answer the engine cannot carry is the deployment's configuration fault: `config.peer_answer_invalid`, or the ownership law's
77
+ * own code (`config.protocol_header_collision`) when it names a header it may not. A seat that threw, timed out or refused has none. */
78
+ readonly code: string | undefined;
79
+ constructor(reason: PeerSeatFailureReason, peerLabel: string, problem: string, extra?: {
80
+ authorizeUrl?: string;
81
+ code?: string;
82
+ });
83
+ }
84
+ /** What one send carries, as the engine took it from an answer, and its digest (whether a re-ask changed anything). */
85
+ export interface CarriedPieces {
86
+ readonly headers?: Readonly<Record<string, string>>;
87
+ readonly env?: Readonly<Record<string, string>>;
88
+ readonly expiresAt?: number;
89
+ readonly digest: string;
90
+ }
91
+ /** The seat's answer for `lane`, read once: the pieces, the `unauthorized` answer, or the problem (which member did not fit). */
92
+ export declare function readPeerAnswer(raw: unknown, lane: PeerLane): {
93
+ readonly carry: CarriedPieces;
94
+ } | {
95
+ readonly unauthorized: {
96
+ readonly authorizeUrl?: string;
97
+ };
98
+ } | {
99
+ readonly problem: string;
100
+ };
101
+ /**
102
+ * One connection's (or one A2A peer's) asks of the seat. `next` answers each send: a 401's re-ask answer when one is waiting (carried
103
+ * once), else the seat's answer to this send. `rejected` is the one re-ask after a 401 (concurrent rejections share it); `renewed` says
104
+ * whether that re-ask answered pieces that differ from what the rejected send carried — the call layer sends a repeat-safe call again
105
+ * only then. `sent` is every value a send carried and the principal sent beside them: a remote's words are read without them.
106
+ */
107
+ export declare class PeerCarrier {
108
+ private readonly seat;
109
+ private readonly identity;
110
+ private readonly principal;
111
+ private readonly lane;
112
+ readonly sent: string[];
113
+ /** When the pieces a stdio child was started with stop being good; `undefined` when the answer said nothing. */
114
+ expiresAt: number | undefined;
115
+ renewed: boolean;
116
+ private asked;
117
+ private waiting;
118
+ private rejection;
119
+ constructor(seat: PeerSeat | undefined, identity: PeerSeatTarget, principal: string | undefined, lane: PeerLane, principalSent: boolean);
120
+ /** The peer as the refusal sentences name it. */
121
+ get label(): string;
122
+ /** The pieces the next send carries (see the class note). A seat failure throws {@link PeerSeatFailure}. */
123
+ next(signal?: AbortSignal, destination?: string): Promise<CarriedPieces>;
124
+ /** The pieces the latest send carried (`undefined` before the first). */
125
+ last: CarriedPieces | undefined;
126
+ /** A send that carried `carried` was answered 401: ask once more (`rejected`); the next send carries that answer. Never throws —
127
+ * a re-ask that fails leaves `renewed` false, so the 401 is the call's answer, and the next send asks afresh. */
128
+ rejected(carried: CarriedPieces, signal?: AbortSignal, destination?: string): Promise<void>;
129
+ /** Whether the pieces a stdio child was started with have stopped being good. */
130
+ expired(now?: number): boolean;
131
+ private ask;
132
+ private remember;
133
+ }
134
+ /**
135
+ * The http request headers one send carries: the seat's pieces and the principal under `principalHeader`, judged by the one ownership
136
+ * law ({@link resolveProtocolHttpHeaders}: one owner per name; an MCP request's protocol-owned names are the SDK's). A collision of the
137
+ * answer is the seat's fault ({@link PeerSeatFailure}); the declaration's own principal header was judged when the peer was dialed.
138
+ */
139
+ export declare function carriedHttpHeaders(protocol: ProtocolId, carrier: PeerCarrier, pieces: CarriedPieces, principalHeader: string | undefined, principal: string | undefined): Readonly<Record<string, string>> | undefined;
140
+ /**
141
+ * The MCP HTTP transport's `fetch` under the seat: every request the transport makes (the POST, the SSE GET, the DELETE) asks the
142
+ * carrier first, carries what it answered, goes only to the endpoint the declaration named (no redirect is followed — a 3xx is the
143
+ * answer) and, answered 401, has the carrier ask once more for the next send.
144
+ */
145
+ export declare function peerFetch(carrier: PeerCarrier, principalHeader: string | undefined, principal: string | undefined): typeof fetch;
146
+ /** The member of a declaration that would carry a value (retired: values come from the seat). */
147
+ export declare const RETIRED_VALUE_MEMBERS: Readonly<{
148
+ readonly mcp: readonly (readonly string[])[];
149
+ readonly a2a: readonly (readonly string[])[];
150
+ }>;
151
+ /** The first retired value member a received copy holds (a member holding `undefined` is absent), as its path. */
152
+ export declare function retiredValueMember(copy: Readonly<Record<string, unknown>>, at: keyof typeof RETIRED_VALUE_MEMBERS): readonly string[] | undefined;
153
+ /** Where a declaration's credential reference sits on each surface. */
154
+ export declare const CREDENTIALS_MEMBER: Readonly<{
155
+ readonly mcp: readonly string[];
156
+ readonly a2a: readonly string[];
157
+ }>;
158
+ /** The credential reference a received copy holds (absent ⇒ `undefined`), judged by the one reader; a problem as a sentence. */
159
+ export declare function declaredCredentials(copy: object, at: keyof typeof CREDENTIALS_MEMBER): {
160
+ readonly ref?: CredentialRef;
161
+ } | {
162
+ readonly problem: string;
163
+ };
164
+ /** A declaration that names a credential reference while no seat is wired: nobody would answer it (`config.peer_seat_missing`). */
165
+ export declare function peerSeatMissing(subject: string, credentials: CredentialRef | undefined, seat: PeerSeat | undefined): (Error & {
166
+ code: string;
167
+ }) | undefined;
168
+ /** Who an MCP server is, as the seat is asked about it: its name, the whole start command or endpoint, its reference, its mount identity. */
169
+ export declare function mcpPeerTarget(spec: McpServerSpec, kind: "stdio" | "http" | undefined): PeerSeatTarget;
170
+ /** Whether a failure is the HTTP endpoint answering 401 (the SDK's status error, on the thrown value or its cause chain). Structure only. */
171
+ export declare function answeredUnauthorized(err: unknown): boolean;
172
+ /** A call answered 401 after which the seat's re-ask answered other pieces: its failure as it would have been thrown then. */
173
+ export declare class Reauthorized {
174
+ readonly error: unknown;
175
+ constructor(error: unknown);
176
+ }
177
+ /**
178
+ * The call layer's one re-send after a 401: `attempt` once; when it answers {@link Reauthorized} and `mayResend`
179
+ * (the revocation probe and `reach`, asked again) holds, once more, carrying what the re-ask answered. A re-send the seat could not furnish
180
+ * ends with the first attempt's failure, whose delivery verdict stands for the call (one of its attempts was sent).
181
+ */
182
+ export declare function sentOnceMore<R>(attempt: () => Promise<R | Reauthorized>, mayResend: () => boolean): Promise<R>;
183
+ export declare function inFlight<T>(client: object, run: () => Promise<T>): Promise<T>;
184
+ export declare function settledInFlight(client: object): Promise<void>;
185
+ export declare function recordCarrier(client: object, carrier: PeerCarrier): void;
186
+ export declare function carrierOf(client: object): PeerCarrier | undefined;
@@ -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
+ }