@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
package/dist/core/mcp.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { __resetEnvKnobAnnouncements } from "./env-knob-announce.js";
2
2
  import { resolveEnvBudget } from "./env-budget.js";
3
3
  import { MCP_NAMESPACE } from "./protocol-table.js";
4
- import { declaredHeaderValues, remoteWords, resolveProtocolHttpHeaders } from "./protocol-http-auth.js";
4
+ import { remoteWords, resolveProtocolHttpHeaders } from "./protocol-http-auth.js";
5
+ import { PeerCarrier, Reauthorized, answeredUnauthorized, carrierOf, inFlight, mcpPeerTarget, peerFetch, peerSeatMissing, recordCarrier, sentOnceMore, settledInFlight } from "./peer-seat.js";
5
6
  import { disposeSectionEntry, sectionAnswerWarning } from "./prompt-section-seat.js";
6
7
  import { createToolNameClaims, mintNamespacePrefix, normalizeNameSegment } from "./protocol-naming.js";
7
8
  import { mcpToolDropReason, refuseCollidingMcpServerNames } from "./mcp-name-judge.js";
@@ -9,7 +10,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
9
10
  import { McpConnectionPool } from "./mcp-connection-pool.js";
10
11
  import { SessionEndingTransport, requestSite } from "./mcp-session-end.js";
11
12
  import { mcpToolGate, UNPROVEN_GATE } from "./mcp-listing-drift.js";
12
- import { ConnectionListing, Flights, IDLE_WATCHDOG_ABORT_REASON, Resendable, armMcpIdleWatchdog, callThroughLink, listingRefusal } from "./mcp-server-link.js";
13
+ import { ConnectionListing, Flights, IDLE_WATCHDOG_ABORT_REASON, Resendable, armMcpIdleWatchdog, callThroughLink, listingRefusal, reach } from "./mcp-server-link.js";
13
14
  import { underStartupBound } from "./mcp-startup-request.js";
14
15
  import { LIST_MCP_RESOURCES, MCP_RESOURCE_LIST_ALLOW, MCP_RESOURCE_READ_ALLOW, READ_MCP_RESOURCE, READ_MCP_RESOURCE_DIR, retractInstructions, tellInstructions, toldOnDial, unretractInstructions, withdrawInstructionAdds } from "./mounted-mcp.js";
15
16
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
@@ -27,6 +28,7 @@ import { delimitUntrusted, inlineUntrusted, sanitizeUntrustedText } from "./untr
27
28
  import { discloseReminderShaped, observeReminderMarkEcho } from "./reminder-disclosure.js";
28
29
  import { MARKED_BLOCK_AFTER_DATA } from "./reminder-mint.js";
29
30
  import { resolveMcpDeclaredResultSize, resolveMcpRequiresUserInteraction } from "./mcp-tool-meta.js";
31
+ import { mcpCallMeta } from "./mcp-call-meta.js";
30
32
  export { resolveMcpDeclaredResultSize } from "./mcp-tool-meta.js";
31
33
  import { withContentOrigin } from "./memory-engine/content-origin.js";
32
34
  import { judgeMcpEntryDeclarations, snapshotMcpEntries } from "./locked-config.js";
@@ -245,6 +247,8 @@ function rethrowHonestMcpError(err, ctx) {
245
247
  }
246
248
  finish(markMcpFailure(err, details()));
247
249
  }
250
+ case "credential_unavailable":
251
+ finish(markMcpFailure(new Error(`${ctx.what} was not sent to MCP server "${serverLabel}": ${inlineUntrusted(thrownText(err), 400)}. The request was not delivered, so the server did not execute it. This is the deployment's credential seat, not the server — do not retry the call until it is fixed; use an alternative if one exists.`), details()));
248
252
  case "spawn_failed":
249
253
  case "invalid_config":
250
254
  case "unknown": {
@@ -360,8 +364,7 @@ export function inferCompactSchema(value, depth = 2) {
360
364
  }
361
365
  return typeof value;
362
366
  }
363
- export const declaredEndpointFetch = (url, init) => fetch(url, { ...init, redirect: "manual" });
364
- function buildTransport(spec, principal, kind) {
367
+ function buildTransport(spec, principal, kind, carrier, pieces) {
365
368
  const t = spec.transport;
366
369
  if (kind === "stdio") {
367
370
  if (!("command" in t))
@@ -369,16 +372,13 @@ function buildTransport(spec, principal, kind) {
369
372
  return new StdioClientTransport({
370
373
  command: t.command,
371
374
  args: t.args,
372
- env: t.env,
375
+ ...(pieces?.env !== undefined ? { env: { ...pieces.env } } : {}),
373
376
  });
374
377
  }
375
378
  if (!("url" in t))
376
379
  throw new Error(`MCP server "${spec.name}": transport kind "${String(kind)}" carries no url`);
377
- const headers = resolveProtocolHttpHeaders(MCP_NAMESPACE.id, t, principal);
378
- return new SessionEndingTransport(new URL(t.url), {
379
- requestInit: headers ? { headers } : undefined,
380
- fetch: declaredEndpointFetch,
381
- });
380
+ resolveProtocolHttpHeaders(MCP_NAMESPACE.id, t.principalHeader !== undefined ? { principalHeader: t.principalHeader } : {}, principal);
381
+ return new SessionEndingTransport(new URL(t.url), { fetch: peerFetch(carrier, t.principalHeader, principal) });
382
382
  }
383
383
  let autoResizer;
384
384
  export async function mapContent(content, serverName, imageResizer) {
@@ -642,7 +642,10 @@ export function mcpToolSchemaProblem(schema) {
642
642
  }
643
643
  return undefined;
644
644
  }
645
- export async function materializeMcpTools(specs, principal, onElicit, imageResizer, reminderDisclosure, mcpRevocations, poolOpts, promptSections, dialable, signal, hostFloor) {
645
+ export async function materializeMcpTools(specs, principal, onElicit, imageResizer, reminderDisclosure, mcpRevocations, poolOpts, promptSections, dialable, signal, hostFloor, peerSeat) {
646
+ return materializeLegMcpTools(undefined, specs, principal, onElicit, imageResizer, reminderDisclosure, mcpRevocations, poolOpts, promptSections, dialable, signal, hostFloor, peerSeat);
647
+ }
648
+ export async function materializeLegMcpTools(seat, ...[specs, principal, onElicit, imageResizer, reminderDisclosure, mcpRevocations, poolOpts, promptSections, dialable, signal, hostFloor, peerSeat]) {
646
649
  const snapshot = snapshotMcpEntries(specs);
647
650
  const axesRefused = new WeakMap();
648
651
  const entries = snapshot.map((spec) => {
@@ -758,12 +761,12 @@ export async function materializeMcpTools(specs, principal, onElicit, imageResiz
758
761
  const gatesNow = (h) => {
759
762
  const latest = h.listing.latest();
760
763
  if (latest.at !== h.gatesAt.at)
761
- h.gatesAt = { at: latest.at, gates: intakeListedTools({ tools: [...latest.entries], unproven: latest.unproven }, h.spec, linkOf(h.name), echoOf(h.spec), imageResizer, mcpDisclosure, isServerRevoked, h.transportKind).gates };
764
+ h.gatesAt = { at: latest.at, gates: intakeListedTools({ tools: [...latest.entries], unproven: latest.unproven }, h.spec, linkOf(h.name), echoOf(h.spec), imageResizer, mcpDisclosure, isServerRevoked, h.transportKind, seat).gates };
762
765
  return h.gatesAt.gates;
763
766
  };
764
767
  const linkOf = (server) => ({
765
768
  live: () => liveOf(server),
766
- recover: (lost) => redialFlights.running(server) ?? (liveOf(server) === lost ? redialFlights.start(server, () => redialDial(server)) : Promise.resolve()),
769
+ recover: (lost, cause = "session") => redialFlights.running(server) ?? (liveOf(server) === lost ? redialFlights.start(server, () => redialDial(server, cause)) : Promise.resolve()),
767
770
  });
768
771
  const endpointRefusal = (spec, dialKind) => {
769
772
  const transport = spec.transport;
@@ -779,12 +782,27 @@ export async function materializeMcpTools(specs, principal, onElicit, imageResiz
779
782
  }
780
783
  return peerRequestRefusal(`mcp: server "${inlineUntrusted(spec.name, 120)}"`, url, hostFloor);
781
784
  };
782
- const dialServer = (spec, dialKind, dialOpts) => {
783
- const refusal = axesRefused.get(spec) ?? endpointRefusal(spec, dialKind);
784
- return refusal !== undefined ? Promise.reject(refusal) : connectServer(spec, principal, onElicit, imageResizer, mcpDisclosure, isServerRevoked, dialKind, poolOpts?.pool, { ...dialOpts, link: linkOf(spec.name), ...(signal !== undefined ? { signal } : {}) });
785
+ const dialServer = async (spec, dialKind, dialOpts) => {
786
+ const refusal = axesRefused.get(spec) ?? peerSeatMissing(`mcp: server "${inlineUntrusted(spec.name, 120)}"`, spec.transport.credentials, peerSeat) ?? endpointRefusal(spec, dialKind);
787
+ if (refusal !== undefined)
788
+ throw refusal;
789
+ const carrier = new PeerCarrier(peerSeat, mcpPeerTarget(spec, dialKind), principal, dialKind === "stdio" ? "stdio" : "http", dialKind !== "stdio" && "principalHeader" in spec.transport && spec.transport.principalHeader !== undefined);
790
+ sentOf.set(spec.name, carrier.sent);
791
+ const dial = () => connectServer(spec, principal, onElicit, imageResizer, mcpDisclosure, isServerRevoked, dialKind, poolOpts?.pool, { ...dialOpts, link: linkOf(spec.name), carrier, ...(signal !== undefined ? { signal } : {}) }, seat);
792
+ const connected = await dial().catch(async (err) => {
793
+ if (typeof err === "object" && err !== null)
794
+ sentOf.set(spec.name, (carrierOf(err) ?? carrier).sent);
795
+ const dialing = (typeof err === "object" && err !== null ? carrierOf(err) : undefined) ?? carrier;
796
+ if (!(dialing.renewed && answeredUnauthorized(err)) || signal?.aborted === true)
797
+ throw err;
798
+ return dial();
799
+ });
800
+ sentOf.set(spec.name, (carrierOf(connected.client) ?? carrier).sent);
801
+ return connected;
785
802
  };
786
803
  const prefixOf = (name) => mintNamespacePrefix(MCP_NAMESPACE, name);
787
- const echoOf = (spec) => declaredHeaderValues(spec.transport, principal);
804
+ const sentOf = new Map();
805
+ const echoOf = (spec) => sentOf.get(spec.name) ?? [];
788
806
  const heldCount = (name) => serverHandles.find((h) => h.name === name)?.tools.length ?? 0;
789
807
  const reconcileInstructions = (name, after, connected) => {
790
808
  if (!connected)
@@ -832,7 +850,7 @@ export async function materializeMcpTools(specs, principal, onElicit, imageResiz
832
850
  const declineRedial = (server, outcome, reason) => ({ server, prefix: prefixOf(server), outcome, reason, toolCount: heldCount(server), added: [], removed: [] });
833
851
  const redialFlights = new Flights();
834
852
  const ownerStopped = () => (disposing ? "this materialization is being disposed — the task is tearing down" : signal?.aborted === true ? "the run was aborted" : undefined);
835
- const redialDial = async (server) => {
853
+ const redialDial = async (server, cause = "session") => {
836
854
  const prefix = prefixOf(server);
837
855
  const declined = (outcome, reason) => declineRedial(server, outcome, reason);
838
856
  const stopped = ownerStopped();
@@ -849,13 +867,20 @@ export async function materializeMcpTools(specs, principal, onElicit, imageResiz
849
867
  if (prior) {
850
868
  prior.announce.fn = undefined;
851
869
  prior.health.observe = undefined;
852
- serverHandles.splice(hIdx, 1);
853
- const cIdx = connections.findIndex((c) => c.client === prior.client);
854
- const priorConnection = cIdx === -1 ? undefined : connections.splice(cIdx, 1)[0];
855
- await (priorConnection?.close() ?? prior.client.close()).catch(() => undefined);
870
+ if (cause !== "expired") {
871
+ serverHandles.splice(hIdx, 1);
872
+ const cIdx = connections.findIndex((c) => c.client === prior.client);
873
+ const priorConnection = cIdx === -1 ? undefined : connections.splice(cIdx, 1)[0];
874
+ await (priorConnection?.close() ?? prior.client.close()).catch(() => undefined);
875
+ }
856
876
  }
857
877
  const dialKind = readDialKind(spec);
858
- const dialed = await dialServer(spec, dialKind, { fresh: true, sections: promptSections, ...(prior !== undefined ? { carried: prior.listing.latest().entries } : {}) }).then((connected) => ({ connected }), (err) => ({ err }));
878
+ const dialed = await dialServer(spec, dialKind, { fresh: cause !== "expired", sections: promptSections, ...(prior !== undefined ? { carried: prior.listing.latest().entries } : {}) }).then((connected) => ({ connected }), (err) => ({ err }));
879
+ if (cause === "expired" && prior !== undefined) {
880
+ if (serverHandles.includes(prior))
881
+ serverHandles.splice(serverHandles.indexOf(prior), 1);
882
+ void settledInFlight(prior.client).then(() => (connections.find((c) => c.client === prior.client)?.close() ?? prior.client.close()).catch(() => undefined));
883
+ }
859
884
  const stoppedLate = ownerStopped();
860
885
  if (stoppedLate !== undefined) {
861
886
  if ("connected" in dialed)
@@ -946,7 +971,7 @@ export async function materializeMcpTools(specs, principal, onElicit, imageResiz
946
971
  results.push({ server: h.name, prefix: prefixOf(h.name), status: "failed", toolCount: h.tools.length, added: [], removed: [], error: "a later listing of this server was opened and applied while this one was in the air — this one was discarded" });
947
972
  continue;
948
973
  }
949
- const { serverTools, serverAxes, gates, dropped, accepted } = intakeListedTools({ tools: [...mergedRaw], unproven: answered.unproven }, h.spec, linkOf(h.name), echoOf(h.spec), imageResizer, mcpDisclosure, isServerRevoked, h.transportKind);
974
+ const { serverTools, serverAxes, gates, dropped, accepted } = intakeListedTools({ tools: [...mergedRaw], unproven: answered.unproven }, h.spec, linkOf(h.name), echoOf(h.spec), imageResizer, mcpDisclosure, isServerRevoked, h.transportKind, seat);
950
975
  cacheTools(accepted, answered.kept);
951
976
  const priorNames = h.tools.map((t) => t.name);
952
977
  const newNames = serverTools.map((t) => t.name);
@@ -1351,7 +1376,7 @@ function buildResourceTools(resourceServers, isServerRevoked = () => false) {
1351
1376
  let res;
1352
1377
  try {
1353
1378
  res = await rs.client
1354
- .readResource({ uri }, { signal: watchdog.combinedSignal, timeout: timeoutMs })
1379
+ .readResource(rs.readParams(uri), { signal: watchdog.combinedSignal, timeout: timeoutMs })
1355
1380
  .catch((err) => rethrowHonestMcpError(err, { server, declared: rs.declared, what, timeoutMs, writeEffect: false, signal, attributeServer: true, site, idle: { signal: watchdog.idleSignal, idleMs }, liveness: rs.health }));
1356
1381
  rs.health.observe?.("completed");
1357
1382
  }
@@ -1527,7 +1552,7 @@ async function listToolsLenient(client, options, declared) {
1527
1552
  });
1528
1553
  return { tools: walk.items, ...(walk.incomplete !== undefined ? { incomplete: walk.incomplete } : {}) };
1529
1554
  }
1530
- async function connectServer(spec, principal, onElicit, imageResizer, reminderDisclosure, isServerRevoked, transportKind, pool, dialOpts) {
1555
+ async function connectServer(spec, principal, onElicit, imageResizer, reminderDisclosure, isServerRevoked, transportKind, pool, dialOpts, seat) {
1531
1556
  const fp = spec.fingerprint;
1532
1557
  if (fp !== undefined && !(typeof fp === "string" && fp.length > 0 && fp.length <= 128)) {
1533
1558
  throw Object.assign(new Error(`MCP server "${inlineUntrusted(spec.name, 160)}": fingerprint must be a non-empty string of at most 128 characters (got ${typeof fp === "string" ? `${fp.length} characters` : typeof fp}) — not dialed`), { code: "config.mcp_fingerprint_invalid" });
@@ -1560,7 +1585,8 @@ async function connectServer(spec, principal, onElicit, imageResizer, reminderDi
1560
1585
  }
1561
1586
  });
1562
1587
  }
1563
- const transport = buildTransport(spec, principal, transportKind);
1588
+ const pieces = transportKind === "stdio" ? await dialOpts.carrier.next(stop) : undefined;
1589
+ const transport = buildTransport(spec, principal, transportKind, dialOpts.carrier, pieces);
1564
1590
  const hangUp = () => void client.close().catch(() => undefined);
1565
1591
  stop?.addEventListener("abort", hangUp, { once: true });
1566
1592
  try {
@@ -1568,11 +1594,14 @@ async function connectServer(spec, principal, onElicit, imageResizer, reminderDi
1568
1594
  }
1569
1595
  catch (err) {
1570
1596
  await client.close().catch(() => undefined);
1597
+ if (typeof err === "object" && err !== null)
1598
+ recordCarrier(err, dialOpts.carrier);
1571
1599
  throw stop?.aborted === true ? stop.reason : err;
1572
1600
  }
1573
1601
  finally {
1574
1602
  stop?.removeEventListener("abort", hangUp);
1575
1603
  }
1604
+ recordCarrier(client, dialOpts.carrier);
1576
1605
  return client;
1577
1606
  };
1578
1607
  const lease = pool !== undefined && !elicitOn ? await pool.acquire(McpConnectionPool.keyOf(spec, principal, transportKind, startupMs), dialClient, dialOpts) : undefined;
@@ -1594,10 +1623,10 @@ async function connectServer(spec, principal, onElicit, imageResizer, reminderDi
1594
1623
  const listing = lease?.listing ?? new ConnectionListing();
1595
1624
  const at = listing.open();
1596
1625
  const cacheTools = openListing();
1597
- const declared = declaredHeaderValues(spec.transport, principal);
1626
+ const declared = (carrierOf(client) ?? dialOpts.carrier).sent;
1598
1627
  const listed = await underStartupBound(startupMs, dialOpts?.signal, (options) => listToolsLenient(client, options, declared));
1599
1628
  const answered = listing.answer(at, listed.tools, listed.incomplete !== undefined, dialOpts.carried);
1600
- const { serverTools, serverAxes, gates, dropped, advisories, accepted } = intakeListedTools({ tools: [...answered.view], unproven: answered.unproven }, spec, dialOpts.link, declared, imageResizer, reminderDisclosure, isServerRevoked, transportKind);
1629
+ const { serverTools, serverAxes, gates, dropped, advisories, accepted } = intakeListedTools({ tools: [...answered.view], unproven: answered.unproven }, spec, dialOpts.link, declared, imageResizer, reminderDisclosure, isServerRevoked, transportKind, seat);
1601
1630
  cacheTools(accepted, answered.kept);
1602
1631
  const caps = client.getServerCapabilities();
1603
1632
  const resourceInfo = caps?.resources
@@ -1635,15 +1664,17 @@ async function connectServer(spec, principal, onElicit, imageResizer, reminderDi
1635
1664
  ...(instructions ? { instructions } : {}),
1636
1665
  ...(disposed?.defect !== undefined ? { instructionsDefect: disposed.defect } : {}),
1637
1666
  ...(listed.incomplete !== undefined ? { listingIncomplete: listed.incomplete } : {}),
1638
- ...(resourceInfo && (resourceInfo.listAllowed || resourceInfo.readAllowed) ? { resourceServer: { server: spec.name, client, health, transportKind: idleKindOf(transportKind), declared, ...resourceInfo } } : {}),
1667
+ ...(resourceInfo && (resourceInfo.listAllowed || resourceInfo.readAllowed) ? { resourceServer: { server: spec.name, client, health, transportKind: idleKindOf(transportKind), declared, readParams: (uri) => { const _meta = mcpCallMeta(undefined, undefined, spec.sessionMetaKey, seat?.sessionId); return { uri, ...(_meta !== undefined ? { _meta } : {}) }; }, ...resourceInfo } } : {}),
1639
1668
  };
1640
1669
  }
1641
1670
  catch (err) {
1642
1671
  await close().catch(() => undefined);
1672
+ if (typeof err === "object" && err !== null)
1673
+ recordCarrier(err, carrierOf(client) ?? dialOpts.carrier);
1643
1674
  throw err;
1644
1675
  }
1645
1676
  }
1646
- function intakeListedTools(listed, spec, link, declared, imageResizer, reminderDisclosure, isServerRevoked, transportKind) {
1677
+ function intakeListedTools(listed, spec, link, declared, imageResizer, reminderDisclosure, isServerRevoked, transportKind, seat) {
1647
1678
  const declaredContentOrigin = spec.contentOrigin;
1648
1679
  const serverTools = [];
1649
1680
  const serverAxes = [];
@@ -1719,7 +1750,7 @@ function intakeListedTools(listed, spec, link, declared, imageResizer, reminderD
1719
1750
  ...(mcpAlwaysLoad ? { mcpAlwaysLoad: true } : {}),
1720
1751
  ...gateFace,
1721
1752
  mcpRemoteName: remoteName, ...boundaryFlowFace(spec.toolAxes?.[remoteName]), permissionSeat: "passthrough",
1722
- execute: async (_toolCallId, params, signal) => {
1753
+ execute: async (toolCallId, params, signal) => {
1723
1754
  const what = `The call to tool ${inlineUntrusted(remoteName)}`;
1724
1755
  if (isServerRevoked?.(spec.name) === true) {
1725
1756
  return {
@@ -1739,12 +1770,14 @@ function intakeListedTools(listed, spec, link, declared, imageResizer, reminderD
1739
1770
  }
1740
1771
  const timeoutMs = mcpToolTimeoutMs();
1741
1772
  const idleMs = mcpIdleTimeoutMs(idleKindOf(transportKind));
1742
- const send = async (conn, resent) => {
1773
+ const callMeta = mcpCallMeta(toolCallId, seat?.of(toolCallId), spec.sessionMetaKey, seat?.sessionId);
1774
+ let answeredWith = declared;
1775
+ const attempt = async (conn, resent) => {
1743
1776
  const site = requestSite(conn.client);
1744
1777
  const watchdog = armMcpIdleWatchdog(conn.health, idleMs, signal);
1745
1778
  try {
1746
1779
  const res = await conn.client
1747
- .callTool({ name: remoteName, arguments: (params ?? {}) }, LENIENT_CALL_TOOL_RESULT_SCHEMA, {
1780
+ .callTool({ name: remoteName, arguments: (params ?? {}), ...(callMeta !== undefined ? { _meta: callMeta } : {}) }, LENIENT_CALL_TOOL_RESULT_SCHEMA, {
1748
1781
  signal: watchdog.combinedSignal,
1749
1782
  timeout: timeoutMs,
1750
1783
  resetTimeoutOnProgress: true,
@@ -1755,7 +1788,7 @@ function intakeListedTools(listed, spec, link, declared, imageResizer, reminderD
1755
1788
  try {
1756
1789
  return rethrowHonestMcpError(err, {
1757
1790
  server: spec.name,
1758
- declared,
1791
+ declared: carrierOf(conn.client)?.sent ?? declared,
1759
1792
  what,
1760
1793
  timeoutMs,
1761
1794
  writeEffect,
@@ -1772,18 +1805,25 @@ function intakeListedTools(listed, spec, link, declared, imageResizer, reminderD
1772
1805
  catch (failure) {
1773
1806
  if (sessionGone(err, site) && signal?.aborted !== true)
1774
1807
  return new Resendable(conn, failure);
1808
+ if (!writeEffect && answeredUnauthorized(err) && carrierOf(conn.client)?.renewed === true && signal?.aborted !== true)
1809
+ return new Reauthorized(failure);
1775
1810
  throw failure;
1776
1811
  }
1777
1812
  });
1778
- if (res instanceof Resendable)
1813
+ if (res instanceof Resendable || res instanceof Reauthorized)
1779
1814
  return res;
1780
1815
  conn.health.observe?.("completed");
1816
+ answeredWith = carrierOf(conn.client)?.sent ?? declared;
1781
1817
  return res;
1782
1818
  }
1783
1819
  finally {
1784
1820
  watchdog.dispose();
1785
1821
  }
1786
1822
  };
1823
+ const send = (conn, resent) => inFlight(conn.client, () => sentOnceMore(() => attempt(conn, resent), () => isServerRevoked?.(spec.name) !== true && reach(link, namespacedName, gate) === conn && signal?.aborted !== true));
1824
+ const before = link.live();
1825
+ if (before !== undefined && carrierOf(before.client)?.expired() === true)
1826
+ await link.recover(before, "expired");
1787
1827
  const res = await callThroughLink(link, namespacedName, gate, signal, send, () => throwDeadServer(spec.name, what));
1788
1828
  if (typeof res === "string")
1789
1829
  return listingRefusal(res, remoteName, spec.name);
@@ -1799,7 +1839,7 @@ function intakeListedTools(listed, spec, link, declared, imageResizer, reminderD
1799
1839
  const errScLine = structuredContentErrorLine(res.structuredContent, parts.join("\n"));
1800
1840
  if (errScLine !== undefined)
1801
1841
  parts.push(errScLine);
1802
- const body = truncateMcpErrorText(remoteWords(parts.join("\n").trim(), declared));
1842
+ const body = truncateMcpErrorText(remoteWords(parts.join("\n").trim(), answeredWith));
1803
1843
  const msg = body
1804
1844
  ? `MCP tool ${inlineUntrusted(remoteName)} reported an error. The server's error content follows as external/untrusted data:\n${delimitUntrusted(`${spec.name} tool error`, body)}`
1805
1845
  : `MCP tool ${inlineUntrusted(remoteName)} reported an error`;
@@ -1,3 +1,4 @@
1
+ import type { ExecutionEnv } from "../../internal/harness-types.js";
1
2
  /** Per-segment cap, measured AFTER encoding. A conservative portability policy adopted as contract
2
3
  * (research (d) recommendation — NOT a verified third-party hard limit; uuidv7 = 36 chars fits). */
3
4
  export declare const SCOPE_SEGMENT_MAX_ENCODED = 64;
@@ -96,6 +97,17 @@ export declare function formatProjectMarker(projectId: string): string;
96
97
  export declare function parseProjectMarker(body: string): {
97
98
  projectId: string;
98
99
  } | null;
100
+ /** What the marker walk reads through: the filesystem the task root names — the leg's execution env (any `ExecutionEnv`
101
+ * satisfies it), or the host's ({@link hostProjectMarkerFs}) for a leg that has none. */
102
+ export type ProjectMarkerFs = Pick<ExecutionEnv, "exists" | "readTextFile">;
103
+ /** The host filesystem as a {@link ProjectMarkerFs} — what a leg whose env does no I/O reads its task root through (its
104
+ * root is a host path: the deployment's `rootPath`). `exists` answers `false` only for a path that is not there; any
105
+ * other failure is an error, never an absence. Read synchronously, as the memory phase always read the marker: a leg
106
+ * with no I/O of its own gains no event-loop turn from its project read (its scheduling against sibling legs stays). */
107
+ export declare const hostProjectMarkerFs: ProjectMarkerFs;
108
+ /** The filesystem a leg's task root names: its execution env, or the host's when the env is the no-I/O placeholder (a leg
109
+ * with no env, or one handed none — the hands band's own "is there a filesystem" reading). */
110
+ export declare function projectMarkerFsOf(env: ExecutionEnv): ProjectMarkerFs;
99
111
  /**
100
112
  * design/142 §1.1 — resolve a project's identity. READS ONLY THE MARKER (复审 F2: never derives an
101
113
  * identity from a git remote; remote-URL normalization is a scaffold-side minting heuristic, not an
@@ -104,10 +116,39 @@ export declare function parseProjectMarker(body: string): {
104
116
  * repo root is fail-loud (`config.memory_project_marker_nested`) — monorepo sub-project identity
105
117
  * is a future need-signal, not a silent second identity;
106
118
  * - outside git, the given rootDir IS the project root (path-form local projects).
107
- * Returns null when no marker exists (callers fall through the resolution ladder: explicit
108
- * declaration → path fallback with a warning).
119
+ * Read through `fs` — the filesystem `rootDir` names (a remote env's marker lives in that env). A lookup
120
+ * the filesystem could not answer, or a marker it could not read, is `config.memory_project_marker` (never "no marker").
121
+ * Returns null when no marker exists. The leg's verdict over this read is {@link resolveSessionProject}.
109
122
  */
110
- export declare function resolveProjectId(rootDir: string): {
123
+ export declare function resolveProjectId(fs: ProjectMarkerFs, rootDir: string): Promise<{
111
124
  projectId: string;
112
125
  markerDir: string;
113
- } | null;
126
+ } | null>;
127
+ /** A leg's project identity. `marker` = the checkout's `.sema/project` (a declaration, when present,
128
+ * equals it); `declared` = `TaskSpec.projectId` in a checkout that carries no marker. */
129
+ export interface SessionProject {
130
+ readonly id: string;
131
+ readonly source: "marker" | "declared";
132
+ }
133
+ /** The ONE verdict every reader of a leg's project identity reads (the `workspace_changed` frame, memory v2). */
134
+ export interface SessionProjectVerdict {
135
+ /** The root the verdict was decided on (the leg's task root): a reader keeping facts about ANOTHER root (memory's
136
+ * per-partition marker hint) reads the verdict as a fact about this root only. */
137
+ readonly root: string;
138
+ /** ABSENT = no marker and no declaration, or the marker could not be read ({@link markerFault} says why). */
139
+ readonly project?: SessionProject;
140
+ /** Why the marker could not be read (nested / corrupt / unreadable), on a leg that declared no project — reported by
141
+ * the caller, NOT thrown here: only a reader that consumes project identity refuses with it (memory v2 `proj:` /
142
+ * `userproj:` keys). A leg that DECLARED a project consumes it, so there the fault is thrown. */
143
+ readonly markerFault?: Error & {
144
+ code: string;
145
+ };
146
+ }
147
+ /**
148
+ * The leg's ONE project-identity judge, called once per leg on the task root. The marker decides when the
149
+ * checkout carries one; `declared` (`TaskSpec.projectId`) is the identity only where it does not. Refuses the leg when
150
+ * `declared` is not a UUID (`config.project_id_invalid`), when it names a different project than the marker
151
+ * (`config.project_identity_mismatch` — never file the session under the wrong project), and when the marker cannot be
152
+ * read while a declaration needs checking against it (the marker's own code).
153
+ */
154
+ export declare function resolveSessionProject(fs: ProjectMarkerFs, taskRoot: string, declared: string | undefined): Promise<SessionProjectVerdict>;
@@ -1,5 +1,8 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { lstatSync, readFileSync } from "node:fs";
2
2
  import { dirname, join, resolve } from "node:path";
3
+ import { err, FileError, ok } from "../../internal/harness.js";
4
+ import { StubExecutionEnv } from "../stub-env.js";
5
+ import { thrownText } from "../thrown-value.js";
3
6
  import { canonicalize } from "./layout.js";
4
7
  function pathSegmentsDualFamily(p) {
5
8
  return p.split(/[\\/]/).filter(Boolean);
@@ -178,10 +181,54 @@ export function parseProjectMarker(body) {
178
181
  return null;
179
182
  return { projectId };
180
183
  }
181
- function gitRootOf(dir) {
184
+ export const hostProjectMarkerFs = {
185
+ exists(path) {
186
+ try {
187
+ return Promise.resolve(ok(lstatSync(path, { throwIfNoEntry: false }) !== undefined));
188
+ }
189
+ catch (e) {
190
+ const code = e.code;
191
+ return Promise.resolve(code === "ENOTDIR" ? ok(false) : err(new FileError("unknown", `could not stat ${path}: ${thrownText(e)}`, path)));
192
+ }
193
+ },
194
+ readTextFile(path) {
195
+ try {
196
+ return Promise.resolve(ok(readFileSync(path, "utf8")));
197
+ }
198
+ catch (e) {
199
+ return Promise.resolve(err(new FileError("unknown", `could not read ${path}: ${thrownText(e)}`, path)));
200
+ }
201
+ },
202
+ };
203
+ export function projectMarkerFsOf(env) {
204
+ return env instanceof StubExecutionEnv ? hostProjectMarkerFs : env;
205
+ }
206
+ function identityError(code, message) {
207
+ const e = new Error(message);
208
+ e.code = code;
209
+ return e;
210
+ }
211
+ async function readOrFault(path, read) {
212
+ let r;
213
+ try {
214
+ r = await read();
215
+ }
216
+ catch (e) {
217
+ r = { ok: false, error: { message: thrownText(e) } };
218
+ }
219
+ if (!r.ok)
220
+ throw identityError("config.memory_project_marker", `project marker lookup could not read ${path}: ${r.error.message}`);
221
+ return r.value;
222
+ }
223
+ const existsOrFault = (fs, path) => readOrFault(path, () => fs.exists(path));
224
+ function isMarkerFault(e) {
225
+ const code = e instanceof Error ? e.code : undefined;
226
+ return code === "config.memory_project_marker" || code === "config.memory_project_marker_nested";
227
+ }
228
+ async function gitRootOf(fs, dir) {
182
229
  let cur = resolve(dir);
183
230
  for (;;) {
184
- if (existsSync(join(cur, ".git")))
231
+ if (await existsOrFault(fs, join(cur, ".git")))
185
232
  return cur;
186
233
  const parent = dirname(cur);
187
234
  if (parent === cur)
@@ -189,18 +236,16 @@ function gitRootOf(dir) {
189
236
  cur = parent;
190
237
  }
191
238
  }
192
- export function resolveProjectId(rootDir) {
239
+ export async function resolveProjectId(fs, rootDir) {
193
240
  const dir = resolve(rootDir);
194
- const gitRoot = gitRootOf(dir);
241
+ const gitRoot = await gitRootOf(fs, dir);
195
242
  const projectRoot = gitRoot ?? dir;
196
243
  if (gitRoot !== undefined) {
197
244
  let cur = dir;
198
245
  while (cur !== gitRoot) {
199
- if (existsSync(join(cur, PROJECT_MARKER_PATH))) {
200
- const e = new Error(`nested project marker: ${join(cur, PROJECT_MARKER_PATH)} sits below the repo root (${gitRoot}) — ` +
246
+ if (await existsOrFault(fs, join(cur, PROJECT_MARKER_PATH))) {
247
+ throw identityError("config.memory_project_marker_nested", `nested project marker: ${join(cur, PROJECT_MARKER_PATH)} sits below the repo root (${gitRoot}) — ` +
201
248
  `v1 supports ONE marker at the repo root (design/142 §1.1); remove the nested marker or split the repo.`);
202
- e.code = "config.memory_project_marker_nested";
203
- throw e;
204
249
  }
205
250
  const parent = dirname(cur);
206
251
  if (parent === cur)
@@ -209,10 +254,34 @@ export function resolveProjectId(rootDir) {
209
254
  }
210
255
  }
211
256
  const markerFile = join(projectRoot, PROJECT_MARKER_PATH);
212
- if (!existsSync(markerFile))
257
+ if (!(await existsOrFault(fs, markerFile)))
213
258
  return null;
214
- const parsed = parseProjectMarker(readFileSync(markerFile, "utf8"));
259
+ const parsed = parseProjectMarker(await readOrFault(markerFile, () => fs.readTextFile(markerFile)));
215
260
  if (!parsed)
216
261
  return null;
217
262
  return { projectId: parsed.projectId, markerDir: projectRoot };
218
263
  }
264
+ export async function resolveSessionProject(fs, taskRoot, declared) {
265
+ if (declared !== undefined && (typeof declared !== "string" || !UUID_RE.test(declared))) {
266
+ const shown = typeof declared === "string" ? JSON.stringify(declared.slice(0, 64)) : typeof declared;
267
+ throw identityError("config.project_id_invalid", `TaskSpec.projectId must be a project UUID (the id a \`.sema/project\` marker carries), got ${shown}; the leg is refused rather than filed under no project.`);
268
+ }
269
+ const declaredId = declared?.toLowerCase();
270
+ let marker;
271
+ try {
272
+ marker = await resolveProjectId(fs, taskRoot);
273
+ }
274
+ catch (e) {
275
+ if (!isMarkerFault(e) || declaredId !== undefined)
276
+ throw e;
277
+ return { root: taskRoot, markerFault: e };
278
+ }
279
+ if (marker !== null) {
280
+ if (declaredId !== undefined && declaredId !== marker.projectId) {
281
+ throw identityError("config.project_identity_mismatch", `TaskSpec.projectId declares ${declaredId}, but this checkout's project marker ${join(marker.markerDir, PROJECT_MARKER_PATH)} carries ${marker.projectId} — ` +
282
+ `the leg is refused rather than filed under the wrong project. Declare the marker's id, or correct the marker.`);
283
+ }
284
+ return { root: taskRoot, project: { id: marker.projectId, source: "marker" } };
285
+ }
286
+ return declaredId !== undefined ? { root: taskRoot, project: { id: declaredId, source: "declared" } } : { root: taskRoot };
287
+ }
@@ -61,14 +61,17 @@ export declare function modePolicyOf(mode: PermissionMode): ModePolicy;
61
61
  */
62
62
  export declare function modeAcceptsFileCommand(mode: PermissionMode, toolName: string, args: unknown): boolean;
63
63
  /** What the mode gate policy resolves paths against. `acceptDirs` = the leg's WRITE ROOTS (the task root plus every additional
64
- * working directory), the set `acceptEdits` allows writes inside — absent ⇒ the root alone; `exemptDirs` = the task's scratchpad,
65
- * never asked about; `roster` = the leg's live tool roster (who defined the called tool and its effect) and `readOnlyDeclared` =
66
- * whether the mounted tool of that name declares itself read-only, both read per call by {@link planRefusesWrite}. */
64
+ * working directory), the set `acceptEdits` allows writes inside — absent ⇒ the root alone; `roster` = the leg's live tool roster
65
+ * (who defined the called tool and its effect) and `readOnlyDeclared` = whether the mounted tool of that name declares itself
66
+ * read-only, both read per call by {@link planRefusesWrite}. What the gate never asks about is not a seat here: it is the run's
67
+ * advertised writable seat (scratchpad, memory root, session plan file), stamped on every request as
68
+ * `advertisedWritableRoots` — the fence's own admission, so the gate holds no second copy of it. */
67
69
  export interface ModeGateSeats {
68
70
  env: ExecutionEnv;
69
71
  rootPath: string;
70
- acceptDirs?: readonly string[];
71
- exemptDirs?: readonly string[];
72
+ /** A getter is read per call: the leg's live write roots (canonical identities), which move with its write location (an
73
+ * EnterWorktree switch). */
74
+ acceptDirs?: readonly string[] | (() => readonly string[]);
72
75
  roster?: {
73
76
  readonly current: ToolRoster | undefined;
74
77
  };
@@ -66,10 +66,11 @@ export function planRefusesWrite(req, roster, readOnlyDeclared) {
66
66
  }
67
67
  const planAsk = (message) => ({ action: "ask", message, decisionReason: "mode" });
68
68
  export function createModeGatePolicy(modeRef, seats) {
69
- const exemptDirs = seats.exemptDirs !== undefined && seats.exemptDirs.length > 0 ? { exemptDirs: seats.exemptDirs } : {};
70
- const askGate = createFsWriteGatePolicy({ env: seats.env, rootPath: seats.rootPath, ...exemptDirs, defaultWrite: "ask" });
71
- const acceptRootGate = createFsWriteGatePolicy({ env: seats.env, rootPath: seats.rootPath, acceptDirs: seats.acceptDirs !== undefined && seats.acceptDirs.length > 0 ? [...seats.acceptDirs] : [seats.rootPath], ...exemptDirs, defaultWrite: "ask" });
72
- const planGate = createFsWriteGatePolicy({ env: seats.env, rootPath: seats.rootPath, ...exemptDirs, defaultWrite: "ask", defaultAsk: (path, note) => planAsk(`Cannot write to ${path} while in plan mode.${note ?? ""}`) });
69
+ const askGate = createFsWriteGatePolicy({ env: seats.env, rootPath: seats.rootPath, defaultWrite: "ask" });
70
+ const acceptSeat = seats.acceptDirs;
71
+ const acceptDirs = typeof acceptSeat === "function" ? acceptSeat : acceptSeat !== undefined && acceptSeat.length > 0 ? [...acceptSeat] : [seats.rootPath];
72
+ const acceptRootGate = createFsWriteGatePolicy({ env: seats.env, rootPath: seats.rootPath, acceptDirs, defaultWrite: "ask" });
73
+ const planGate = createFsWriteGatePolicy({ env: seats.env, rootPath: seats.rootPath, defaultWrite: "ask", defaultAsk: (path, note) => planAsk(`Cannot write to ${path} while in plan mode.${note ?? ""}`) });
73
74
  return {
74
75
  async check(req, signal) {
75
76
  const gate = modePolicyOf(modeRef.current).writeGate;
@@ -16,6 +16,6 @@ export function registrationRefusedNotice(record, sessionId) {
16
16
  return {
17
17
  code: REGISTRATION_REFUSED,
18
18
  message: `extension "${record.name}" (${record.seat} seat) was not mounted: ${record.refusedBy} refused it — ${record.reason}`,
19
- detail: { name: record.name, seat: record.seat, tier: record.tier, refusedBy: record.refusedBy, reason: record.reason, sessionId },
19
+ detail: { name: record.name, seat: record.seat, tier: record.tier, ...(record.provenance !== undefined ? { provenance: record.provenance } : {}), refusedBy: record.refusedBy, reason: record.reason, sessionId },
20
20
  };
21
21
  }
@@ -68,6 +68,9 @@ export interface ModDispatchOptions {
68
68
  readonly origin?: ModOrigin;
69
69
  /** The raiser's reading of an answer; an answer it refuses is a violation of the site. */
70
70
  readonly checkAnswer?: ModAnswerCheck;
71
+ /** The raiser's reading of what a handler hands on (a payload other than the dispatch's own `e`, received, its pinned keys
72
+ * judged); a payload it refuses is a violation of the site — the other direction of {@link checkAnswer}. */
73
+ readonly checkHandOn?: (payload: ModEventPayload) => string | undefined;
71
74
  /** The station's ranking of its answers — named by every dispatch of an event whose failure column refuses (one that
72
75
  * names none is not run), and read by the seat-trust law. */
73
76
  readonly ranks?: ModAnswerRanks;
@@ -1,7 +1,7 @@
1
1
  import { CATCH_BUDGET_MS, createSelfBudget, POST_ABORT_GRACE_MS, RUNAWAY_AFTER_MS, unrefTimer, watchRunaway } from "./budget.js";
2
2
  import { expandOnSide, failureRefuses, isModEventName, MOD_SEATS, nextToRefusal, stationOn } from "./events.js";
3
3
  import { ENGINE_ORIGIN, modsInvalid, screenModSeats, } from "./registration.js";
4
- import { answerUpward, answerViolation, detachedCopy, engineObjectsOnce, handedOn, matcherMatches, matcherViolation, methodAnswerViolation, NEXT_IN_FLIGHT, receiveAnswer, receiveEvent, receivePayload, sealedObjects, } from "./site-rules.js";
4
+ import { answerUpward, answerViolation, detachedCopy, engineObjectsOnce, handedOn, handOnViolation, matcherMatches, matcherViolation, methodAnswerViolation, NEXT_IN_FLIGHT, receiveAnswer, receiveEvent, receivePayload, sealedObjects, } from "./site-rules.js";
5
5
  const TIER_RANK = { prepend: 0, user: 1, append: 2, builtin: 3, core: 4 };
6
6
  const bypassed = (floors, tier) => floors.some((f) => TIER_RANK[f.from] < TIER_RANK[tier] && TIER_RANK[tier] < TIER_RANK[f.to]);
7
7
  export async function admitMods(input) {
@@ -31,23 +31,22 @@ export async function admitMods(input) {
31
31
  });
32
32
  if (outcome.kind === "aborted")
33
33
  throw input.signal?.reason ?? new Error("admission aborted");
34
+ const whose = { name: cand.name, seat: cand.seat, tier: cand.tier, ...(cand.provenance !== undefined ? { provenance: cand.provenance } : {}) };
34
35
  if (outcome.kind === "failed") {
35
- records.push(Object.freeze({ name: cand.name, seat: cand.seat, tier: cand.tier, refusedBy: outcome.registration, reason: `${outcome.registration} failed: ${outcome.reason}` }));
36
+ records.push(Object.freeze({ ...whose, refusedBy: outcome.registration, reason: `${outcome.registration} failed: ${outcome.reason}` }));
36
37
  continue;
37
38
  }
38
39
  const refused = refusalOf(outcome.answer);
39
40
  if (refused !== undefined) {
40
- records.push(Object.freeze({ name: cand.name, seat: cand.seat, tier: cand.tier, refusedBy: outcome.answeredBy ?? "engine", reason: refused }));
41
+ records.push(Object.freeze({ ...whose, refusedBy: outcome.answeredBy ?? "engine", reason: refused }));
41
42
  continue;
42
43
  }
43
44
  const own = mountOne(cand, input.side, describe);
44
45
  mounted.push(...own);
45
46
  const events = unique(own.map((h) => h.pattern));
46
- const observe = unique(own.filter((h) => h.observe).map((h) => h.pattern));
47
+ const observe = Object.freeze(events.filter((p) => own.every((h) => h.pattern !== p || h.observe)));
47
48
  records.push(Object.freeze({
48
- name: cand.name,
49
- seat: cand.seat,
50
- tier: cand.tier,
49
+ ...whose,
51
50
  events,
52
51
  ...(observe.length > 0 ? { observe } : {}),
53
52
  ...(outcome.skipped.length > 0 ? { skipped: outcome.skipped } : {}),
@@ -376,7 +375,10 @@ function createBus(side, mounted, bottoms, entries, report, records, describe, i
376
375
  if (passed === e0)
377
376
  return { snap: e0 };
378
377
  const handed = handedOn(st.pinned, e0, passed, engines(), isProxy);
379
- return "violation" in handed ? handed : { snap: handed.payload };
378
+ if ("violation" in handed)
379
+ return handed;
380
+ const why = handOnViolation(handed.payload, options.checkHandOn);
381
+ return why !== undefined ? { violation: why } : { snap: handed.payload };
380
382
  };
381
383
  const trustFloors = new Map();
382
384
  const NO_FLOOR = Object.freeze(MOD_SEATS.map(() => 0));