@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
@@ -184,7 +184,21 @@ export declare function judgeEntryToolFaces(copy: McpServerSpec): {
184
184
  code: string;
185
185
  };
186
186
  };
187
- /** Everything a snapshot MCP entry declares per tool, judged: its `toolAxes` ({@link judgeEntryToolAxes}), then its `toolFaces` ({@link judgeEntryToolFaces}). */
187
+ /**
188
+ * The `sessionMetaKey` question for ONE snapshot MCP entry — asked by the door and the materialization entrance like its siblings, through
189
+ * the one judge ({@link judgeSessionMetaKey}); a key that cannot ride refuses under `config.invalid_argument`, naming the server and the key.
190
+ * The entry is unchanged (a string is already the engine's own copy).
191
+ */
192
+ export declare function judgeEntrySessionMetaKey(copy: McpServerSpec): {
193
+ ok: true;
194
+ entry: McpServerSpec;
195
+ } | {
196
+ ok: false;
197
+ error: Error & {
198
+ code: string;
199
+ };
200
+ };
201
+ /** Everything a snapshot MCP entry declares beyond its plain data, judged: its `toolAxes` ({@link judgeEntryToolAxes}), its `toolFaces` ({@link judgeEntryToolFaces}), its `sessionMetaKey` ({@link judgeEntrySessionMetaKey}). */
188
202
  export declare function judgeMcpEntryDeclarations(copy: McpServerSpec): {
189
203
  ok: true;
190
204
  entry: McpServerSpec;
@@ -2,10 +2,12 @@ import { types } from "node:util";
2
2
  import { DECLARATION_PATH_RULES, NO_DECLARATION_PATH_RULES, declarationFaultOf, declarerWord, readToolAxes, receiveDeclaration, toolAxesRefusal } from "./mcp-server-spec.js";
3
3
  import { isPlainRecord, receive } from "./mods/kernel/receive.js";
4
4
  import { readToolFaces } from "./tool-face-reader.js";
5
+ import { judgeSessionMetaKey } from "./mcp-call-meta.js";
5
6
  import { CONFIG_RECEIPT_MODE } from "./own-property-receipt.js";
6
7
  import { isToolContentOrigin, TOOL_CONTENT_ORIGINS } from "./memory-engine/content-origin.js";
7
8
  import { inlineUntrusted } from "./untrusted-text.js";
8
9
  import { assertNoRetiredToolPolicyKeys } from "./retired-keys.js";
10
+ import { CREDENTIALS_MEMBER, declaredCredentials, peerSeatMissing, retiredValueMember } from "./peer-seat.js";
9
11
  export const LOCKED_KEY_REGISTRY = {
10
12
  mcp: { specFields: ["mcp"] },
11
13
  toolPolicy: { specFields: ["toolPolicy", "basePolicyForResumeEdit"] },
@@ -89,8 +91,30 @@ export function snapshotDeclaredEntry(entry, at) {
89
91
  throw entryFaultRefusal(at, declarer, received.fault.path, received.fault.problem);
90
92
  if (!isPlainRecord(received.value))
91
93
  throw unreadableDeclaration(at, declarer, "an entry", `it is ${inlineUntrusted(describeDeclared(received.value), 80)}, not an object`);
94
+ const retired = retiredValueMember(received.value, at);
95
+ if (retired !== undefined) {
96
+ throw declarationRefusal("config.credential_in_declaration", at, declarer, `declares ${retired.join(".")}, a member that carried values and is retired: a declaration names the peer and at most one opaque reference (${CREDENTIALS_MEMBER[at].join(".")}); the pieces a request carries are answered per send by the deployment's peer seat (RunnerDeps.peerSeat). The value is not repeated here.`);
97
+ }
98
+ const credentials = declaredCredentials(received.value, at);
99
+ if ("problem" in credentials) {
100
+ throw declarationRefusal("config.credential_ref_invalid", at, declarer, `declares ${CREDENTIALS_MEMBER[at].join(".")} that is not a credential reference (${inlineUntrusted(credentials.problem, 160)}).`);
101
+ }
92
102
  return received.value;
93
103
  }
104
+ function declarationRefusal(code, at, declarer, sentence) {
105
+ const refusal = codedError(code, `${declarerWord(at)}${declarer === undefined ? "" : ` ${declarerNameOf(declarer)}`} ${sentence}`);
106
+ if (declarer !== undefined)
107
+ Object.defineProperty(refusal, "declarer", { value: declarer, enumerable: true, writable: false, configurable: false });
108
+ return refusal;
109
+ }
110
+ function assertPeerSeatFor(entries, at, seat) {
111
+ for (const entry of entries ?? []) {
112
+ const read = declaredCredentials(entry, at);
113
+ const missing = "ref" in read ? peerSeatMissing(`${declarerWord(at)} ${declarerNameOf(entry.name)}`, read.ref, seat) : undefined;
114
+ if (missing !== undefined)
115
+ throw missing;
116
+ }
117
+ }
94
118
  function describeDeclared(value) {
95
119
  try {
96
120
  return JSON.stringify(value) ?? String(value);
@@ -139,9 +163,16 @@ export function judgeEntryToolFaces(copy) {
139
163
  return { ok: false, error: toolFacesRefusal(declarerNameOf(copy.name), faces.problem) };
140
164
  return { ok: true, entry: Object.freeze((faces.faces === undefined ? rest : { ...rest, toolFaces: deepFrozen(faces.faces) })) };
141
165
  }
166
+ export function judgeEntrySessionMetaKey(copy) {
167
+ const read = judgeSessionMetaKey(copy.sessionMetaKey);
168
+ if (!("problem" in read))
169
+ return { ok: true, entry: copy };
170
+ return { ok: false, error: codedError("config.invalid_argument", `${declarerWord("mcp")} ${declarerNameOf(copy.name)} declares ${inlineUntrusted(read.problem, 200)}. The key decides where the leg's session id rides on this server's requests, so it is refused rather than dropped or defaulted — a connector keyed on a session it never receives would share one state across every session.`) };
171
+ }
142
172
  export function judgeMcpEntryDeclarations(copy) {
143
173
  const axes = judgeEntryToolAxes(copy, "mcp");
144
- return axes.ok ? judgeEntryToolFaces(axes.entry) : axes;
174
+ const faces = axes.ok ? judgeEntryToolFaces(axes.entry) : axes;
175
+ return faces.ok ? judgeEntrySessionMetaKey(faces.entry) : faces;
145
176
  }
146
177
  function declaredEntriesOf(declared, at) {
147
178
  const field = at;
@@ -211,10 +242,15 @@ export function preflightLockedConfig(spec, deps, enter = ENTER_AS_IS) {
211
242
  const declaredServers = lockedKeys.has("mcp") ? undefined : spec.mcp;
212
243
  const mcp = declaredServers === undefined ? undefined : enter("taskConfig", () => snapshotAndValidateMcpEntries(declaredServers));
213
244
  const declaredPeers = spec.a2a;
245
+ const a2a = declaredPeers === undefined ? undefined : enter("taskConfig", () => snapshotAndValidateA2aEntries(declaredPeers));
246
+ enter("taskConfig", () => {
247
+ assertPeerSeatFor(mcp, "mcp", deps.peerSeat);
248
+ assertPeerSeatFor(a2a, "a2a", deps.peerSeat);
249
+ });
214
250
  return {
215
251
  lockedKeys,
216
252
  mcp,
217
- a2a: declaredPeers === undefined ? undefined : enter("taskConfig", () => snapshotAndValidateA2aEntries(declaredPeers)),
253
+ a2a,
218
254
  ...policies,
219
255
  };
220
256
  }
@@ -0,0 +1,66 @@
1
+ /** The `_meta` key carrying the executing call's id. */
2
+ export declare const MCP_TOOL_USE_ID_META_KEY = "sema/toolUseId";
3
+ /** The `_meta` key carrying the request meta the call's `tool.call` chain handed on. */
4
+ export declare const MCP_REQUEST_META_KEY = "sema/requestMeta";
5
+ /** The most UTF-8 bytes a request meta may hold, its keys and values together (the reference's bound on its values: 262144). */
6
+ export declare const MCP_REQUEST_META_MAX_BYTES = 262144;
7
+ /** A request meta as it rides: string members only. */
8
+ export type McpRequestMeta = Readonly<Record<string, string>>;
9
+ /** A judged request meta: the copy that rides (undefined when there is none, or it has no member), or why it cannot ride. */
10
+ export type RequestMetaReading = {
11
+ readonly meta: McpRequestMeta | undefined;
12
+ } | {
13
+ readonly problem: string;
14
+ };
15
+ /**
16
+ * The request meta `value` stands for. It can ride when it is a plain record (the ordinary prototype, or none) whose own members
17
+ * are all enumerable string-keyed data properties holding strings, at most {@link MCP_REQUEST_META_MAX_BYTES} UTF-8 bytes of keys
18
+ * and values together; what rides is a frozen copy of those members with no prototype (an own `__proto__` key stays a key).
19
+ */
20
+ export declare function judgeRequestMeta(value: unknown): RequestMetaReading;
21
+ /** The request meta a handler handed on in `payload`: its OWN `requestMeta` data member (one inherited from a prototype is not
22
+ * handed on, and an accessor is never run), judged by {@link judgeRequestMeta}. */
23
+ export declare function readHandedRequestMeta(payload: object): RequestMetaReading;
24
+ /** The most characters a declared session key may have. */
25
+ export declare const MCP_SESSION_META_KEY_MAX_CHARS = 128;
26
+ /** A judged session key: the key that rides (undefined when none is declared), or why it cannot. */
27
+ export type SessionMetaKeyReading = {
28
+ readonly key: string | undefined;
29
+ } | {
30
+ readonly problem: string;
31
+ };
32
+ /**
33
+ * The one judge of a declared `sessionMetaKey` ({@link import("./mcp-server-spec.js").McpServerSpec.sessionMetaKey}). It can ride when it is
34
+ * a non-empty string of at most {@link MCP_SESSION_META_KEY_MAX_CHARS} characters in the MCP `_meta` key-name format (an optional
35
+ * prefix of dot-separated labels and a slash, then a name — the format is what a conforming server accepts, and it keeps out names such
36
+ * as `__proto__` that the SDK's own request parse drops) that names no `_meta` member of anyone else's: not the SDK's `progressToken`,
37
+ * not a key under the engine's `sema/` namespace, not under a prefix MCP reserves (the prefix is the text before the first `/`; its
38
+ * labels are DNS labels, so the second one is compared with case folded). Every refusal names the key; the key is the declaration's own
39
+ * text, bounded in the sentence.
40
+ */
41
+ export declare function judgeSessionMetaKey(value: unknown): SessionMetaKeyReading;
42
+ /**
43
+ * The `_meta` of one request the engine sends a server — a `tools/call` (the executing call's id, when it has one, and the request meta,
44
+ * when there is one: the judge answers none for a record with no member, so whatever it hands here rides) or a `resources/read` (neither) —
45
+ * and, when the server declared a session key, the leg's own session id under it. THE one mint: the key was judged where the declaration
46
+ * was ({@link judgeSessionMetaKey}), so it never lands on another member; no session id (a dial with no leg) rides nothing.
47
+ */
48
+ export declare function mcpCallMeta(toolUseId: string | undefined, requestMeta: McpRequestMeta | undefined, sessionMetaKey?: string, sessionId?: string): Record<string, unknown> | undefined;
49
+ /**
50
+ * The carrier from a call's `tool.call` chain bottom to the MCP tool's `execute`, one per leg. A tool's `execute` takes the call id
51
+ * and no per-call context, so the request meta rides the body's own async chain: {@link McpRequestMetaSeat.of} answers it only to
52
+ * an `execute` that runs inside that body, for the same call id, on the same leg's seat, while the body has not settled. Two calls
53
+ * in flight (even under one id), a child leg's calls (its own seat), a direct `execute` outside any body and a timer the body left
54
+ * behind never read each other's.
55
+ */
56
+ export interface McpRequestMetaSeat {
57
+ /** Run `body` with `meta` standing for the call `toolCallId` names, on this body's async chain; it stops standing when it settles. */
58
+ hold<T>(toolCallId: string, meta: McpRequestMeta | undefined, body: () => Promise<T>): Promise<T>;
59
+ /** What stands for the call `toolCallId` names, read from inside its body. */
60
+ of(toolCallId: string): McpRequestMeta | undefined;
61
+ /** The leg's own session id: what a server that declared a session key is sent ({@link mcpCallMeta}). Absent for a seat made without one. */
62
+ readonly sessionId?: string;
63
+ }
64
+ /** What the MCP materialization reads of its leg's seat: the request meta standing for a call, and the leg's session id. */
65
+ export type McpLegMetaReader = Pick<McpRequestMetaSeat, "of" | "sessionId">;
66
+ export declare function createMcpRequestMetaSeat(sessionId?: string): McpRequestMetaSeat;
@@ -0,0 +1,103 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { types } from "node:util";
3
+ import { isPlainRecord } from "./mods/kernel/receive.js";
4
+ import { dataKind } from "./mcp-server-spec.js";
5
+ export const MCP_TOOL_USE_ID_META_KEY = "sema/toolUseId";
6
+ export const MCP_REQUEST_META_KEY = "sema/requestMeta";
7
+ export const MCP_REQUEST_META_MAX_BYTES = 262_144;
8
+ const kindOf = (v) => v === null ? "null" : Array.isArray(v) ? "a list" : typeof v === "object" ? (types.isProxy(v) ? "a Proxy" : "an object that is not a plain record") : `a ${typeof v}`;
9
+ const named = (key) => JSON.stringify(key.length > 60 ? `${key.slice(0, 60)}…` : key);
10
+ export function judgeRequestMeta(value) {
11
+ if (value === undefined)
12
+ return { meta: undefined };
13
+ if (typeof value === "object" && value !== null && types.isProxy(value))
14
+ return { problem: "requestMeta is a Proxy; it takes a plain record of strings" };
15
+ if (!isPlainRecord(value))
16
+ return { problem: `requestMeta is ${kindOf(value)}; it takes a plain record of strings` };
17
+ const descriptors = Object.getOwnPropertyDescriptors(value);
18
+ if (Object.getOwnPropertySymbols(descriptors).length > 0)
19
+ return { problem: "requestMeta has a symbol-keyed member; its members are string keys holding strings" };
20
+ const copy = Object.create(null);
21
+ let bytes = 0;
22
+ let members = 0;
23
+ for (const key of Object.getOwnPropertyNames(descriptors)) {
24
+ const d = descriptors[key];
25
+ if (!Object.hasOwn(d, "value") || d.enumerable !== true)
26
+ return { problem: `requestMeta's member ${named(key)} is not an enumerable data property (a getter is never run)` };
27
+ const v = d.value;
28
+ if (typeof v !== "string")
29
+ return { problem: `requestMeta's member ${named(key)} is ${kindOf(v)}, not a string` };
30
+ bytes += Buffer.byteLength(key, "utf8") + Buffer.byteLength(v, "utf8");
31
+ Object.defineProperty(copy, key, { value: v, enumerable: true, writable: false, configurable: false });
32
+ members += 1;
33
+ }
34
+ if (bytes > MCP_REQUEST_META_MAX_BYTES)
35
+ return { problem: `requestMeta is ${bytes} bytes of keys and values; the most is ${MCP_REQUEST_META_MAX_BYTES}` };
36
+ return { meta: members === 0 ? undefined : Object.freeze(copy) };
37
+ }
38
+ export function readHandedRequestMeta(payload) {
39
+ const d = Object.getOwnPropertyDescriptor(payload, "requestMeta");
40
+ if (d === undefined)
41
+ return { meta: undefined };
42
+ if (!Object.hasOwn(d, "value"))
43
+ return { problem: "requestMeta is an accessor (a getter is never run); it takes a plain record of strings" };
44
+ return judgeRequestMeta(d.value);
45
+ }
46
+ const SDK_PROGRESS_TOKEN_KEY = "progressToken";
47
+ const ENGINE_META_NAMESPACE = "sema/";
48
+ export const MCP_SESSION_META_KEY_MAX_CHARS = 128;
49
+ const MCP_RESERVED_LABELS = ["modelcontextprotocol", "mcp"];
50
+ const META_LABEL = /^[A-Za-z](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
51
+ const META_NAME = /^(?:[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)?$/;
52
+ export function judgeSessionMetaKey(value) {
53
+ if (value === undefined)
54
+ return { key: undefined };
55
+ if (typeof value !== "string")
56
+ return { problem: `sessionMetaKey is ${dataKind(value)}; it takes a non-empty string` };
57
+ if (value === "")
58
+ return { problem: "sessionMetaKey is the empty string; it takes a non-empty string" };
59
+ if (value.length > MCP_SESSION_META_KEY_MAX_CHARS)
60
+ return { problem: `sessionMetaKey ${named(value)} is ${value.length} characters; the most is ${MCP_SESSION_META_KEY_MAX_CHARS}` };
61
+ const slash = value.indexOf("/");
62
+ const labels = slash === -1 ? [] : value.slice(0, slash).split(".");
63
+ if (!labels.every((label) => META_LABEL.test(label)))
64
+ return { problem: `sessionMetaKey ${named(value)} has a prefix that is not dot-separated labels (a label starts with a letter, ends with a letter or digit, and holds letters, digits and hyphens) followed by a slash` };
65
+ if (!META_NAME.test(value.slice(slash + 1)))
66
+ return { problem: `sessionMetaKey ${named(value)} has a name that does not begin and end with a letter or digit, or holds a character other than letters, digits, hyphen, underscore and dot` };
67
+ if (value === SDK_PROGRESS_TOKEN_KEY)
68
+ return { problem: `sessionMetaKey ${named(value)} is the key the MCP SDK writes for its own progress token` };
69
+ if (value.startsWith(ENGINE_META_NAMESPACE))
70
+ return { problem: `sessionMetaKey ${named(value)} is under the engine's own "${ENGINE_META_NAMESPACE}" namespace` };
71
+ const second = labels[1]?.toLowerCase();
72
+ if (second !== undefined && MCP_RESERVED_LABELS.includes(second))
73
+ return { problem: `sessionMetaKey ${named(value)} is under a prefix MCP reserves (second label "${second}")` };
74
+ return { key: value };
75
+ }
76
+ export function mcpCallMeta(toolUseId, requestMeta, sessionMetaKey, sessionId) {
77
+ const meta = {
78
+ ...(typeof toolUseId === "string" && toolUseId !== "" ? { [MCP_TOOL_USE_ID_META_KEY]: toolUseId } : {}),
79
+ ...(requestMeta !== undefined ? { [MCP_REQUEST_META_KEY]: requestMeta } : {}),
80
+ ...(sessionMetaKey !== undefined && typeof sessionId === "string" && sessionId !== "" ? { [sessionMetaKey]: sessionId } : {}),
81
+ };
82
+ return Object.keys(meta).length === 0 ? undefined : meta;
83
+ }
84
+ const store = new AsyncLocalStorage();
85
+ export function createMcpRequestMetaSeat(sessionId) {
86
+ const seat = {};
87
+ return {
88
+ sessionId,
89
+ async hold(toolCallId, meta, body) {
90
+ const held = { seat, toolCallId, meta, live: true };
91
+ try {
92
+ return await store.run(held, body);
93
+ }
94
+ finally {
95
+ held.live = false;
96
+ }
97
+ },
98
+ of(toolCallId) {
99
+ const held = store.getStore();
100
+ return held !== undefined && held.live && held.seat === seat && held.toolCallId === toolCallId ? held.meta : undefined;
101
+ },
102
+ };
103
+ }
@@ -14,7 +14,9 @@
14
14
  * a revived one), so the DECLARATION stays the one source of truth — no handle is ever recorded anywhere.
15
15
  *
16
16
  * THE KEY is the server's declaration as the dial reads it (name and transport) and the principal the task runs under: a
17
- * different principal is a different identity at the server. A server that opted in to elicitation never enters the pool — the
17
+ * different principal is a different identity at the server. The transport holds no value (a declaration carries at most an
18
+ * opaque credential reference, so two references that differ never share a connection); the pieces a request carries are the
19
+ * peer seat's, asked under this same identity, so every holder of a connection sends what the one seat answers for it. A server that opted in to elicitation never enters the pool — the
18
20
  * answer to its questions belongs to the leg that is waiting on it.
19
21
  */
20
22
  import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
@@ -1,5 +1,6 @@
1
1
  import { canonicalize } from "./canonical-json.js";
2
2
  import { ConnectionListing } from "./mcp-server-link.js";
3
+ import { carrierOf } from "./peer-seat.js";
3
4
  export class McpConnectionPool {
4
5
  entries = new Map();
5
6
  dialing = new Map();
@@ -19,7 +20,8 @@ export class McpConnectionPool {
19
20
  if (this.shut)
20
21
  return undefined;
21
22
  opts?.signal?.throwIfAborted();
22
- if (opts?.fresh === true)
23
+ const held = this.entries.get(key);
24
+ if (opts?.fresh === true || (held !== undefined && carrierOf(held.client)?.expired() === true))
23
25
  this.detach(key);
24
26
  let entry = this.entries.get(key);
25
27
  if (entry === undefined || entry.closed) {
@@ -19,9 +19,13 @@ import type { AssertAllKeysHandled } from "./ask-origin.js";
19
19
  * capability, an ordinary `-32603`): the exchange happened;
20
20
  * · `invalid_config` — the declaration itself could not be dialed (a malformed `url`): a fault to
21
21
  * fix in the spec, never an outage to wait out;
22
+ * · `credential_unavailable` — the deployment's peer seat did not furnish the request (it threw, did not
23
+ * answer in time, answered something the engine cannot carry, or answered that
24
+ * the principal is not authorized): that request was not sent — a fault for the
25
+ * deployment to fix, not an outage of the server;
22
26
  * · `unknown` — the thrown value carried no structure this table reads.
23
27
  */
24
- export declare const MCP_FAILURE_KINDS: readonly ["connect_refused", "connection_failed", "connection_closed", "http_status", "not_mcp_response", "spawn_failed", "timeout", "protocol", "invalid_config", "unknown"];
28
+ export declare const MCP_FAILURE_KINDS: readonly ["connect_refused", "connection_failed", "connection_closed", "http_status", "not_mcp_response", "spawn_failed", "timeout", "protocol", "invalid_config", "credential_unavailable", "unknown"];
25
29
  export type McpFailureKind = (typeof MCP_FAILURE_KINDS)[number];
26
30
  /** The closed set of delivery verdicts ({@link McpFailure.delivered}). */
27
31
  export declare const MCP_DELIVERY_VERDICTS: readonly ["yes", "no", "unknown"];
@@ -43,6 +47,7 @@ export declare const DELIVERED_BY_KIND: {
43
47
  readonly timeout: "unknown";
44
48
  readonly protocol: "yes";
45
49
  readonly invalid_config: "no";
50
+ readonly credential_unavailable: "no";
46
51
  readonly unknown: "unknown";
47
52
  };
48
53
  /** The fence over the delivery table: `never` while every kind has a verdict. */
@@ -104,6 +109,7 @@ export declare const LIVENESS_BY_FAILURE_KIND: {
104
109
  readonly timeout: "unreachable";
105
110
  readonly protocol: "reachable";
106
111
  readonly invalid_config: undefined;
112
+ readonly credential_unavailable: undefined;
107
113
  readonly unknown: "unknown";
108
114
  };
109
115
  /** The fence over the liveness table: `never` while every kind has a verdict. */
@@ -1,6 +1,7 @@
1
1
  import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
2
2
  import { StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
3
3
  import { proxyTunnelRefusedSentence, readConnectFailure } from "../brain/errors.js";
4
+ import { PeerSeatFailure } from "./peer-seat.js";
4
5
  export const MCP_FAILURE_KINDS = Object.freeze([
5
6
  "connect_refused",
6
7
  "connection_failed",
@@ -11,6 +12,7 @@ export const MCP_FAILURE_KINDS = Object.freeze([
11
12
  "timeout",
12
13
  "protocol",
13
14
  "invalid_config",
15
+ "credential_unavailable",
14
16
  "unknown",
15
17
  ]);
16
18
  export const MCP_DELIVERY_VERDICTS = Object.freeze(["yes", "no", "unknown"]);
@@ -24,6 +26,7 @@ export const DELIVERED_BY_KIND = {
24
26
  timeout: "unknown",
25
27
  protocol: "yes",
26
28
  invalid_config: "no",
29
+ credential_unavailable: "no",
27
30
  unknown: "unknown",
28
31
  };
29
32
  export const MCP_LIVENESS_STATES = Object.freeze(["reachable", "unreachable", "unknown"]);
@@ -37,6 +40,7 @@ export const LIVENESS_BY_FAILURE_KIND = {
37
40
  timeout: "unreachable",
38
41
  protocol: "reachable",
39
42
  invalid_config: undefined,
43
+ credential_unavailable: undefined,
40
44
  unknown: "unknown",
41
45
  };
42
46
  export function livenessOf(outcome, observedAt) {
@@ -74,6 +78,11 @@ export function networkErrorCode(err, depth = 0) {
74
78
  const isNodeErrCode = (code) => code.startsWith("ERR_");
75
79
  const isDeclarationFault = (code) => code === "ERR_INVALID_URL" || (typeof code === "string" && code.startsWith("config."));
76
80
  export const FAILURE_CLASSIFIER = [
81
+ {
82
+ name: "peer seat did not furnish the request",
83
+ when: (err) => err instanceof PeerSeatFailure,
84
+ reads: () => ({ kind: "credential_unavailable" }),
85
+ },
77
86
  {
78
87
  name: "sdk connection closed",
79
88
  when: (err) => err instanceof McpError && err.code === ErrorCode.ConnectionClosed,
@@ -180,6 +189,7 @@ export function describeHttpTransportFailure(err, at = { phase: "request" }) {
180
189
  case "timeout":
181
190
  case "protocol":
182
191
  case "invalid_config":
192
+ case "credential_unavailable":
183
193
  case "unknown":
184
194
  return undefined;
185
195
  }
@@ -1,5 +1,6 @@
1
1
  import { type McpFailureKind } from "./mcp-failure.js";
2
2
  import type { McpServerSpec, OnElicit } from "./mcp-server-spec.js";
3
+ import type { PeerSeat } from "./peer-seat.js";
3
4
  import type { WiringManifestMcpEntry } from "./wiring-manifest.js";
4
5
  /** One server's probe reading, beside its manifest row. `connectMs` is wall time this probe measured
5
6
  * for THIS server's dial — the spawn/handshake, the initial `tools/list` walk and the intake, ending
@@ -56,6 +57,9 @@ export interface McpProbeOptions {
56
57
  signal?: AbortSignal;
57
58
  /** The elicitation seat, for a caller that has a human behind it. Default: decline everything. */
58
59
  onElicit?: OnElicit;
60
+ /** The peer seat a prepared leg dials with (`RunnerDeps.peerSeat`): what each request carries. Absent ⇒ nothing is carried, and a
61
+ * server whose declaration names `credentials` reads `failed` (`invalid_config`, `config.peer_seat_missing`). */
62
+ peerSeat?: PeerSeat;
59
63
  /** Abort reading, stated once: the call rejects with the signal's own reason when that reason is an
60
64
  * Error (a bare `abort()` supplies a DOMException named `AbortError`) and with this module's own
61
65
  * `AbortError` otherwise — a face that throws a string is a face no `catch` can read. A condition
@@ -74,7 +74,7 @@ export async function probeMcpServers(specs, opts = {}) {
74
74
  const entry = declared[i];
75
75
  const started = performance.now();
76
76
  const elapsed = () => Math.round(performance.now() - started);
77
- const dial = materializeMcpTools([entry], opts.principal, onElicit);
77
+ const dial = materializeMcpTools([entry], opts.principal, onElicit, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, opts.peerSeat);
78
78
  const verdict = await raceDial(dial, timeoutMs, signal);
79
79
  if (verdict.kind === "settled") {
80
80
  const found = verdict.handle.statuses.find((s) => s.name === entry.name);
@@ -131,8 +131,11 @@ export interface McpLiveConnection {
131
131
  export interface McpServerLink {
132
132
  /** The connection the materialization holds for the server now; `undefined` while it holds none (a re-dial's old one is gone and the new one has not landed, or the last dial failed). */
133
133
  live(): McpLiveConnection | undefined;
134
- /** Recover the session `lost` lost: join the re-dial running for the server, or start one while `lost` is still the live connection. Settles when there is nothing left to wait for. */
135
- recover(lost: McpLiveConnection): Promise<unknown>;
134
+ /** Replace `lost`: join the re-dial running for the server, or start one while `lost` is still the live connection. Settles when there
135
+ * is nothing left to wait for. `cause`: the server dropped the session (`session`, the default), or the peer seat's pieces the
136
+ * connection was started with expired (`expired`: the calls in flight on it settle before it is closed, and the run tree's pooled
137
+ * connection is replaced once for all its holders). */
138
+ recover(lost: McpLiveConnection, cause?: "session" | "expired"): Promise<unknown>;
136
139
  }
137
140
  /** Why a tool may not be sent on a live connection: its listing mints the tool another gate or none (`changed`), or no listing of the connection has reached it (`unreached`). */
138
141
  export type McpListingRefusal = "changed" | "unreached";
@@ -1,4 +1,5 @@
1
1
  import { type ReceiptFault } from "./mods/kernel/receive.js";
2
+ import type { CredentialRef } from "@sema-agent/primitives";
2
3
  import type { ToolContentOrigin, ToolEffect } from "./tool-spec.js";
3
4
  import type { ToolFamily, ToolHostTarget, ToolPathTarget, ToolRenderHints, ToolRuleFace } from "./tool-face.js";
4
5
  /** Definition of an MCP server to connect to for the duration of one task, then discard. */
@@ -13,24 +14,34 @@ export interface McpServerSpec {
13
14
  * declaring tier without keeping a side table keyed on names. Optional; absent stays absent.
14
15
  */
15
16
  source?: string;
17
+ /**
18
+ * Who the server is: the whole start command (stdio) or endpoint (http), and at most one opaque credential reference
19
+ * (`credentials`, read by the one reader `readCredentialRef` at every entrance — an unknown kind refuses the entry with
20
+ * `config.credential_ref_invalid`; the engine resolves nothing). A declaration carries no value: the pieces a request
21
+ * carries — an http request's credential headers, a stdio child's environment — are answered per send by the deployment's
22
+ * peer seat ({@link RunnerDeps.peerSeat}). A `credentials` reference with no seat wired refuses the entry
23
+ * (`config.peer_seat_missing`); a declaration carrying the retired value members `headers` / `env` is refused at every
24
+ * entrance (`config.credential_in_declaration`).
25
+ */
16
26
  transport: {
17
27
  kind: "stdio";
18
28
  command: string;
19
29
  args?: string[];
20
- env?: Record<string, string>;
30
+ credentials?: CredentialRef;
21
31
  } | {
22
32
  kind: "http";
23
33
  url: string;
24
- /** Static headers sent on every request (e.g. an auth bearer for the MCP server itself). */
25
- headers?: Record<string, string>;
34
+ credentials?: CredentialRef;
26
35
  /**
27
36
  * Per-task **end-user principal** header (design/62). When set, the Runner injects the running task's
28
37
  * authenticated {@link TaskSpec.principal} as this header (e.g. `"X-Agent-Principal"`) on every call to
29
38
  * this server's tools, so the MCP server can enforce per-user RBAC. Absent {@link TaskSpec.principal}
30
- * ⇒ the header is **not** sent (the MCP server must default to deny/public, never admin). A static `headers`
31
- * entry under the same name in any case refuses this server at its dial (`config.protocol_header_collision`,
32
- * header names being case-insensitive). The principal is Runner-held and the model/worker can neither read
33
- * nor set it (it is not a tool argument) — see {@link TaskSpec.principal}.
39
+ * ⇒ the header is **not** sent (the MCP server must default to deny/public, never admin). A header the
40
+ * peer seat answers under the same name in any case is the seat's fault, and that request is not sent
41
+ * (`config.protocol_header_collision`, header names being case-insensitive). The principal is Runner-held and the
42
+ * model/worker can neither read nor set it (it is not a tool argument) — see {@link TaskSpec.principal}. The name is
43
+ * neither the engine's own `MCP_ASSERTION_HEADER` nor a name the MCP transport writes itself (any case): naming one
44
+ * refuses this server at its dial.
34
45
  */
35
46
  principalHeader?: string;
36
47
  };
@@ -172,6 +183,21 @@ export interface McpServerSpec {
172
183
  * The no-run probe has no clock of its own: each startup phase carries this same bound (a caller's `timeoutMs` is an overall ceiling beside it).
173
184
  */
174
185
  startupTimeoutMs?: number;
186
+ /**
187
+ * Opt in to the sending leg's OWN session id on this server's requests: with a key declared, every `tools/call` and `resources/read` the
188
+ * engine sends this server carries `params._meta[key]` = that leg's `sessionId` (the id its events carry), over stdio and Streamable
189
+ * HTTP alike, so a connector can keep state per (principal, session). Absent ⇒ nothing is sent (a session id leaving the process is a
190
+ * correlation the deployment chooses). A delegated child is another session: its own calls carry its own id, and the engine does not
191
+ * guess a root — the principal ({@link TaskSpec.principal}) is shared by every session of one user, so it is not a tree key either.
192
+ *
193
+ * The key is judged once by {@link import("./mcp-call-meta.js").judgeSessionMetaKey} where the declaration is judged (the preparation door
194
+ * and `materializeMcpTools`): a non-string, an empty or over-long one, one outside the MCP `_meta` key-name format, one in a prefix MCP
195
+ * reserves (a prefix whose second label is `modelcontextprotocol` or `mcp`), `progressToken` (the SDK's own) or a key in the engine's
196
+ * `sema/` namespace refuses the entry with
197
+ * `config.invalid_argument` naming the key — never dropped, never defaulted. A dial with no leg (the library entrance, the no-run probe)
198
+ * has no session, so nothing rides.
199
+ */
200
+ sessionMetaKey?: string;
175
201
  }
176
202
  type ToolAxes = NonNullable<McpServerSpec["toolAxes"]>;
177
203
  /**
@@ -219,17 +245,17 @@ export type DeclarationRead = {
219
245
  * path does not say which kind of container each name came from, so a segment of digits alone is read as a list index.
220
246
  */
221
247
  export declare function declarationFaultOf(fault: ReceiptFault): DeclarationFault;
222
- /** What a declaration's own type fixes at one path, beyond being plain data: a string there, or a record of names to strings. */
248
+ /** What a declaration's own type fixes at one path, beyond being plain data: a string there. */
223
249
  export interface DeclarationPathRule {
224
250
  readonly path: readonly string[];
225
- readonly holds: "a string" | "names to strings";
251
+ readonly holds: "a string";
226
252
  /** The member must be there (a declaration with no value at the path is refused, as one with a value of another kind is). */
227
253
  readonly required?: true;
228
254
  }
229
255
  /**
230
- * Per surface, every path its declaration's type fixes beyond plain data — the declarer's `name` (a string, always there) and every record
231
- * the type writes as `Record<string, string>`: an MCP server's `transport.env` (a stdio server's environment) and `transport.headers` (an
232
- * HTTP server's headers); an A2A peer's `headers`. A path that is not its surface's (an A2A peer's `transport`) is not judged by another
256
+ * Per surface, every path its declaration's type fixes beyond plain data — the declarer's `name` (a string, always there). A declaration
257
+ * carries no record of values (its credential reference is judged by its own reader, the retired value members are refused by name —
258
+ * both after this receipt, src/core/peer-seat.ts). A path that is not its surface's (an A2A peer's `transport`) is not judged by another
233
259
  * surface's row: it is a member the surface does not read.
234
260
  */
235
261
  export declare const DECLARATION_PATH_RULES: Readonly<Record<ToolAxesSurface, readonly DeclarationPathRule[]>>;
@@ -349,16 +375,18 @@ export interface A2aServerSpec {
349
375
  /** Explicit agent-card location, when the peer does not publish at a well-known path. Set ⇒ it is used
350
376
  * ALONE (no well-known probing behind the operator's back). */
351
377
  cardUrl?: string;
352
- /** Static headers sent on every request to this peer (e.g. an auth bearer). They travel only to the
353
- * declared origins (`url`, `cardUrl`): a card naming an endpoint on another origin refuses the peer
354
- * (`config.protocol_endpoint_unbound`), and a redirect is not followed. */
355
- headers?: Record<string, string>;
378
+ /** At most one opaque credential reference, as on an MCP server's transport: the headers a send to this peer carries are
379
+ * answered per send by the deployment's peer seat ({@link RunnerDeps.peerSeat}), never declared (`headers` is retired and
380
+ * refused, `config.credential_in_declaration`). Pieces the seat answers travel only to the declared origins (`url`,
381
+ * `cardUrl`): a send carrying them to an endpoint on another origin is refused (`config.protocol_endpoint_unbound`), and it
382
+ * follows no redirect. */
383
+ credentials?: CredentialRef;
356
384
  /**
357
385
  * Per-task **end-user principal** header (design/62), same contract as the MCP side: when set, the
358
386
  * Runner injects the running task's authenticated {@link TaskSpec.principal} under this header name on
359
387
  * every call to this peer, so the peer can enforce per-user authorization. Absent principal ⇒ the
360
- * header is not sent (the peer must then default to deny/public, never admin). A static entry in
361
- * {@link headers} under the same name in any case refuses the peer (`config.protocol_header_collision`).
388
+ * header is not sent (the peer must then default to deny/public, never admin). A header the peer seat
389
+ * answers under the same name in any case is the seat's fault, and that send is not made (`config.protocol_header_collision`).
362
390
  * The principal is Runner-held: the model can neither read nor set it.
363
391
  */
364
392
  principalHeader?: string;
@@ -68,12 +68,9 @@ export function declarationFaultOf(fault) {
68
68
  export const DECLARATION_PATH_RULES = Object.freeze({
69
69
  mcp: Object.freeze([
70
70
  { path: ["name"], holds: "a string", required: true },
71
- { path: ["transport", "env"], holds: "names to strings" },
72
- { path: ["transport", "headers"], holds: "names to strings" },
73
71
  ].map((rule) => Object.freeze({ ...rule, path: Object.freeze([...rule.path]) }))),
74
72
  a2a: Object.freeze([
75
73
  { path: ["name"], holds: "a string", required: true },
76
- { path: ["headers"], holds: "names to strings" },
77
74
  ].map((rule) => Object.freeze({ ...rule, path: Object.freeze([...rule.path]) }))),
78
75
  });
79
76
  export const NO_DECLARATION_PATH_RULES = Object.freeze([]);
@@ -84,21 +81,7 @@ function declarationVocabularyFault(root, rules) {
84
81
  const stack = [];
85
82
  const ruleAt = () => rules.find((rule) => rule.path.length === path.length && rule.path.every((key, i) => key === path[i]));
86
83
  const onRuleRoute = () => rules.some((rule) => rule.path.length > path.length && path.every((key, i) => key === rule.path[i]));
87
- const ruleProblem = (rule, value) => {
88
- if (rule.holds === "a string")
89
- return typeof value === "string" ? undefined : `it is ${dataKind(value)}, not a string`;
90
- if (!isPlainRecord(value))
91
- return `it is ${dataKind(value)}, not a record of names to strings`;
92
- for (const [key, member] of Object.entries(value)) {
93
- path.push(key);
94
- if (key === "__proto__")
95
- return PROTO_MEMBER;
96
- if (member !== undefined && typeof member !== "string")
97
- return `it is ${dataKind(member)}, not a string: this record maps names to strings`;
98
- path.pop();
99
- }
100
- return undefined;
101
- };
84
+ const ruleProblem = (_rule, value) => (typeof value === "string" ? undefined : `it is ${dataKind(value)}, not a string`);
102
85
  const meet = (value) => {
103
86
  if (typeof value !== "object" || value === null || (asked.has(value) && !onRuleRoute()))
104
87
  return undefined;
@@ -1,3 +1,4 @@
1
+ import { type PeerSeat } from "./peer-seat.js";
1
2
  import { type McpInstructionsEntry, type PromptSectionDisposer } from "./prompt-section-seat.js";
2
3
  import { McpConnectionPool } from "./mcp-connection-pool.js";
3
4
  import { type McpDelivered, type McpFailureKind, type McpServerLiveness } from "./mcp-failure.js";
@@ -8,6 +9,7 @@ import type { McpServerSpec, OnElicit, ToolEffect } from "./types.js";
8
9
  import type { McpRevocationLedger } from "./mcp-server-spec.js";
9
10
  import { type HostFloor } from "./host-floor.js";
10
11
  import { type ReminderDisclosureCounts } from "./reminder-disclosure.js";
12
+ import { type McpLegMetaReader } from "./mcp-call-meta.js";
11
13
  export { resolveMcpDeclaredResultSize } from "./mcp-tool-meta.js";
12
14
  /**
13
15
  * The safety axes (design/77 §4 irreversibility, design/70 egress) derived from one materialized MCP
@@ -481,19 +483,6 @@ export * from "./image-downsample.js";
481
483
  * type, ≤10 object entries then `, ...`.
482
484
  */
483
485
  export declare function inferCompactSchema(value: unknown, depth?: number): string;
484
- /** `kind` is the dial's ONE read of `spec.transport.kind` (taken by the caller beside the dial and threaded
485
- * here, to the idle bucket and to the failure classifier alike): a nested `transport` object is the
486
- * caller's, and a getter that answered differently to two readers would otherwise connect over one
487
- * transport and be judged under another. An unknown kind takes the non-stdio branch, as it always did. */
488
- /**
489
- * The MCP HTTP transport's `fetch`: every request the transport makes — the POST, the SSE GET (initial and
490
- * resumed), the DELETE, the auth flows — goes to the endpoint the declaration NAMED and follows no redirect.
491
- * `fetch`'s default follows a 3xx silently and then reports only the last hop, which is the one shape under
492
- * which the delivery verdict would lie (a connect refusal on the redirect target reading "never sent" while
493
- * the declared endpoint had received the POST); a 3xx now surfaces as the SDK's HTTP-status error, and a
494
- * body or a credential never travels to a host the declaration did not name. Exported for its pin only.
495
- */
496
- export declare const declaredEndpointFetch: typeof fetch;
497
486
  interface McpContentItem {
498
487
  type: string;
499
488
  text?: string;
@@ -617,7 +606,10 @@ reminderDisclosure?: {
617
606
  }, poolOpts?: {
618
607
  pool: McpConnectionPool;
619
608
  ownsPool?: boolean;
620
- }, promptSections?: PromptSectionDisposer, dialable?: (spec: McpServerSpec) => boolean, signal?: AbortSignal, hostFloor?: HostFloor): Promise<MaterializedMcp>;
609
+ }, promptSections?: PromptSectionDisposer, dialable?: (spec: McpServerSpec) => boolean, signal?: AbortSignal, hostFloor?: HostFloor, peerSeat?: PeerSeat): Promise<MaterializedMcp>;
610
+ /** The runner's materialization of one leg (not index-exported): every minted tool's `tools/call` reads the leg's request-meta seat
611
+ * (`mcp-call-meta.ts`) — the request meta's only source, written only by the `tool.call` station with what its judge passed. */
612
+ export declare function materializeLegMcpTools(seat: McpLegMetaReader | undefined, ...[specs, principal, onElicit, imageResizer, reminderDisclosure, mcpRevocations, poolOpts, promptSections, dialable, signal, hostFloor, peerSeat]: Parameters<typeof materializeMcpTools>): Promise<MaterializedMcp>;
621
613
  /**
622
614
  * Fold the caller's AUTHORITATIVE per-tool override (design F: caller = trust root) over the server-hint axis.
623
615
  * Unlike server hints, the caller may RAISE or LOWER any axis: `effect` sets the repeat-safety class (lower to