@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
@@ -21,8 +21,12 @@
21
21
  * reaches the host's entry, the dispatch records whether its bottom started, a re-entered guard with no `.catch`
22
22
  * refuses, the one side lock over `uses` and `on`, answers received as data, the seat-trust law, `prompt.mention`
23
23
  * on the engine's side, and `tool.call` with the `refuse_until_run` failure answer, callable.
24
+ * 4: a station may judge what a handler hands on (the dispatch's `checkHandOn`: its sentence is the handler's violation, as a
25
+ * changed pinned key is), `tool.call` takes one member more than its own — `requestMeta`, a record of strings, judged there —
26
+ * and an admission record carries the registration's `provenance` as the host gave it and lists in `observe` only the patterns
27
+ * on which every handler it hung watches.
24
28
  */
25
- export declare const KERNEL_CONTRACT_VERSION = 3;
29
+ export declare const KERNEL_CONTRACT_VERSION = 4;
26
30
  /** The five tiers in run order (CC names). `builtin` and `core` are the engine's own. */
27
31
  export declare const MOD_TIERS: readonly ["prepend", "user", "append", "builtin", "core"];
28
32
  export type ModTier = (typeof MOD_TIERS)[number];
@@ -1,4 +1,4 @@
1
- export const KERNEL_CONTRACT_VERSION = 3;
1
+ export const KERNEL_CONTRACT_VERSION = 4;
2
2
  export const MOD_TIERS = Object.freeze(["prepend", "user", "append", "builtin", "core"]);
3
3
  export const MOD_SEATS = Object.freeze(["deployment", "task"]);
4
4
  export const MOD_EVENT_SIDES = Object.freeze(["engine", "surface", "both"]);
@@ -118,11 +118,14 @@ export interface ModRegistration<D extends ModDollarBase = ModDollarBase> {
118
118
  readonly options?: unknown;
119
119
  register(on: On<D>, options: unknown): void;
120
120
  }
121
- /** One admission result: mounted (with the patterns it actually hung) or refused (by whom, why). */
121
+ /** One admission result: mounted (with the patterns it actually hung, and among them the ones on which every handler it
122
+ * hung watches) or refused (by whom, why). `provenance` is the registration's own label, carried as the host gave it on
123
+ * either arm — absent when the host gave none. */
122
124
  export type ModAdmissionRecord = {
123
125
  readonly name: string;
124
126
  readonly seat: ModSeat;
125
127
  readonly tier: ModTier;
128
+ readonly provenance?: string;
126
129
  readonly events: readonly string[];
127
130
  readonly observe?: readonly string[];
128
131
  /** Judges skipped while this registration was judged (their failure or site violation), as the dispatch listed them. */
@@ -131,6 +134,7 @@ export type ModAdmissionRecord = {
131
134
  readonly name: string;
132
135
  readonly seat: ModSeat;
133
136
  readonly tier: ModTier;
137
+ readonly provenance?: string;
134
138
  readonly refusedBy: string;
135
139
  readonly reason: string;
136
140
  };
@@ -109,6 +109,9 @@ export declare function pinnedHandOn(pinned: readonly string[], held: ModEventPa
109
109
  };
110
110
  /** Why a handler's answer breaks the site, or undefined. No answer at all is never an answer. */
111
111
  export declare function answerViolation(answer: unknown, check: ModAnswerCheck | undefined, e: ModEventPayload, by: ModAnswerer, below: readonly unknown[], run: ModDispatchRun): string | undefined;
112
+ /** A station's reading of what a handler hands on: its sentence, or undefined (no check, or the payload passes). A check that
113
+ * throws is a sentence too — the station could not read the payload, so it is not handed on. */
114
+ export declare function handOnViolation(payload: ModEventPayload, check: ((payload: ModEventPayload) => string | undefined) | undefined): string | undefined;
112
115
  /**
113
116
  * A `$` method's answer form: `{ value }` (the call's result) or `{ deny }` (the call throws). A `{ deny }` given after
114
117
  * the handler's `next` was answered with something that is not a deny — or while that `next` is still running — breaks
@@ -203,6 +203,16 @@ export function answerViolation(answer, check, e, by, below, run) {
203
203
  return "returned an answer the station cannot read";
204
204
  }
205
205
  }
206
+ export function handOnViolation(payload, check) {
207
+ if (check === undefined)
208
+ return undefined;
209
+ try {
210
+ return check(payload);
211
+ }
212
+ catch {
213
+ return "handed on an event the station cannot read";
214
+ }
215
+ }
206
216
  const denyOf = (a) => (typeof a === "object" && a !== null && Object.prototype.hasOwnProperty.call(a, "deny") ? Reflect.get(a, "deny") : undefined);
207
217
  export function methodAnswerViolation(answer, _e, _by, below = []) {
208
218
  if (!isPlainRecord(answer))
@@ -0,0 +1,23 @@
1
+ import { type ModRegistrationTier } from "./kernel/index.js";
2
+ import type { EngineModRegistration } from "./classic-events.js";
3
+ /** The host's facts about a package it loads: never read from the package itself. */
4
+ export interface ModPackageHost {
5
+ /** The tier the host seats it in (a deployment seat requires one; the task seat takes `user` or none). */
6
+ readonly tier?: ModRegistrationTier;
7
+ /** The host's provenance label, handed to admission and carried on the admission record as given. */
8
+ readonly provenance?: string;
9
+ /** The values handed to the package's `register(on, options)`. */
10
+ readonly options?: unknown;
11
+ }
12
+ /** A package read into a registration, with the identity of the bytes it was read from. */
13
+ export interface ModPackageRegistration extends EngineModRegistration {
14
+ /**
15
+ * The sha256 (lowercase hex) of the three files this reader read, in this order — `plugin.json`, `hooks.json`, the
16
+ * hooks module — taken as the newline-joined sha256 of each file's bytes. One changed byte in any of the three changes
17
+ * it. The module is imported from those bytes, so this names the module that runs; what its code loads beyond them (an
18
+ * absolute URL, a file it reads) is not among them.
19
+ */
20
+ readonly digest: string;
21
+ }
22
+ /** Read the package at `dir` into a registration the host seats in `RunnerDeps.mods` or `TaskSpec.mods`. */
23
+ export declare function loadModPackage(dir: string, host?: ModPackageHost): Promise<ModPackageRegistration>;
@@ -0,0 +1,118 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { open, stat } from "node:fs/promises";
4
+ import { extname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { KERNEL_CONTRACT_VERSION } from "./kernel/index.js";
6
+ import { modsInvalid } from "./kernel/registration.js";
7
+ import { physicalPathOfAsync } from "../physical-path.js";
8
+ import { describeThrown } from "../tool-policy.js";
9
+ import { extensionWords } from "../untrusted-egress.js";
10
+ const PLUGIN_FILE = join(".claude-plugin", "plugin.json");
11
+ const HOOKS_FILE = join("hooks", "hooks.json");
12
+ const PLUGIN_KEYS = ["name", "version", "description", "author"];
13
+ const HOOKS_KEYS = ["modules", "contract", "uses", "description"];
14
+ const MODULE_EXTENSION = ".mjs";
15
+ const MODULE_URL_HEAD = "data:text/javascript;base64,";
16
+ const MODULE_URL_TEXT = /data:text\/javascript;base64,[A-Za-z0-9+/=]*/g;
17
+ export async function loadModPackage(dir, host = {}) {
18
+ const root = await realRoot(dir);
19
+ const refuse = (file, why) => modsInvalid(`mod package ${root}: ${file}: ${why}`);
20
+ const pluginFile = await packageFile(root, PLUGIN_FILE, refuse);
21
+ const plugin = jsonRecord(pluginFile.bytes, PLUGIN_FILE, PLUGIN_KEYS, refuse);
22
+ const hooksFile = await packageFile(root, HOOKS_FILE, refuse);
23
+ const hooks = jsonRecord(hooksFile.bytes, HOOKS_FILE, HOOKS_KEYS, refuse);
24
+ const contract = hooks["contract"];
25
+ if (contract !== KERNEL_CONTRACT_VERSION) {
26
+ throw refuse(HOOKS_FILE, `contract is ${kind(contract)}; this engine's mods kernel is contract ${KERNEL_CONTRACT_VERSION}, and a package loads only under the contract it was written against`);
27
+ }
28
+ const modules = hooks["modules"];
29
+ if (!Array.isArray(modules) || modules.length !== 1 || typeof modules[0] !== "string")
30
+ throw refuse(HOOKS_FILE, `modules is ${kind(modules)}; it lists exactly one path, relative to hooks.json`);
31
+ const given = modules[0];
32
+ const shown = extensionWords(given, 120);
33
+ if (given === "" || isAbsolute(given))
34
+ throw refuse(HOOKS_FILE, `modules names "${shown}"; the path is relative to hooks.json`);
35
+ if (extname(given) !== MODULE_EXTENSION)
36
+ throw refuse(HOOKS_FILE, `modules names "${shown}"; a hooks module is an ES module named ${MODULE_EXTENSION}`);
37
+ const moduleFile = await packageFile(root, join("hooks", given), (_file, why) => refuse(HOOKS_FILE, `modules names "${shown}": ${why}`));
38
+ const digest = sha256([pluginFile.bytes, hooksFile.bytes, moduleFile.bytes].map(sha256).join("\n"));
39
+ let ns;
40
+ try {
41
+ ns = await import(`${MODULE_URL_HEAD}${moduleFile.bytes.toString("base64")}`);
42
+ }
43
+ catch (err) {
44
+ const said = describeThrown(err).replace(MODULE_URL_TEXT, moduleFile.inside);
45
+ throw refuse(moduleFile.inside, `could not be imported (${said}); a hooks module is imported from its own bytes, so it is one self-contained file: a relative or package import has nothing to resolve from`);
46
+ }
47
+ return Object.freeze({
48
+ name: plugin["name"],
49
+ uses: hooks["uses"],
50
+ ...(host.tier !== undefined ? { tier: host.tier } : {}),
51
+ ...(host.provenance !== undefined ? { provenance: host.provenance } : {}),
52
+ ...(host.options !== undefined ? { options: host.options } : {}),
53
+ register: (typeof ns === "object" && ns !== null ? Reflect.get(ns, "register") : undefined),
54
+ digest,
55
+ });
56
+ }
57
+ async function realRoot(dir) {
58
+ try {
59
+ const root = await physicalPathOfAsync(resolve(dir));
60
+ if ((await stat(root)).isDirectory())
61
+ return root;
62
+ }
63
+ catch {
64
+ }
65
+ throw modsInvalid(`mod package ${dir}: not a directory`);
66
+ }
67
+ async function packageFile(root, file, refuse) {
68
+ let real;
69
+ try {
70
+ real = await physicalPathOfAsync(resolve(root, file));
71
+ }
72
+ catch {
73
+ throw refuse(file, "is not in the package; a mod package carries it");
74
+ }
75
+ const inside = relative(root, real);
76
+ if (inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside))
77
+ throw refuse(file, "resolves outside the package");
78
+ let handle;
79
+ try {
80
+ handle = await open(real, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
81
+ if (!(await handle.stat()).isFile())
82
+ throw new Error("not a regular file");
83
+ return { inside, bytes: await handle.readFile() };
84
+ }
85
+ catch (err) {
86
+ throw refuse(file, `could not be read as a regular file of the package (${describeThrown(err)})`);
87
+ }
88
+ finally {
89
+ await handle?.close();
90
+ }
91
+ }
92
+ function jsonRecord(bytes, file, keys, refuse) {
93
+ let parsed;
94
+ try {
95
+ parsed = JSON.parse(bytes.toString("utf8"));
96
+ }
97
+ catch {
98
+ throw refuse(file, "is not JSON");
99
+ }
100
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
101
+ throw refuse(file, `is ${kind(parsed)}; it is a JSON object`);
102
+ const extra = Object.keys(parsed).find((k) => !keys.includes(k));
103
+ if (extra !== undefined)
104
+ throw refuse(file, `carries "${extensionWords(extra, 60)}", which a mod package does not state here (it takes ${keys.join(", ")})`);
105
+ return parsed;
106
+ }
107
+ function sha256(data) {
108
+ return createHash("sha256").update(data).digest("hex");
109
+ }
110
+ function kind(v) {
111
+ if (v === undefined)
112
+ return "absent";
113
+ if (v === null)
114
+ return "null";
115
+ if (Array.isArray(v))
116
+ return `a list of ${v.length}`;
117
+ return typeof v === "number" || typeof v === "boolean" ? String(v) : `a ${typeof v}`;
118
+ }
@@ -7,7 +7,7 @@ import type { ClassicEventMap, ClassicEventName } from "./classic-events.js";
7
7
  import type { PermissionMode } from "../ask-origin.js";
8
8
  import type { RunnerDeps } from "../runner-deps.js";
9
9
  import type { TaskSpec } from "../task-spec.js";
10
- import { type ModAnswerRanks, type ModBus, type ModCallEntry, type ModMountedHandler, type ModDispatchOutcome, type ModEventPayload, type ModRegistration } from "./kernel/index.js";
10
+ import { type ModAnswerCheck, type ModAnswerRanks, type ModBus, type ModCallEntry, type ModMountedHandler, type ModDispatchOutcome, type ModEventPayload, type ModRegistration } from "./kernel/index.js";
11
11
  import { type SourcedOverlay } from "../../prompt-assembly/overlay.js";
12
12
  import type { BandId } from "../../prompt-assembly/catalog/schema.js";
13
13
  import type { ModParticipant } from "./kernel/dispatch.js";
@@ -169,7 +169,7 @@ export declare function observeClassic<K extends ClassicEventName>(bus: LegModBu
169
169
  */
170
170
  export declare function dispatchClassic<K extends ClassicEventName>(bus: LegModBus, event: K, e: ClassicEventMap[K]["e"], options: {
171
171
  readonly signal?: AbortSignal;
172
- readonly checkAnswer?: (answer: unknown) => string | undefined;
172
+ readonly checkAnswer?: ModAnswerCheck;
173
173
  readonly ranks?: ModAnswerRanks;
174
174
  }): Promise<ModDispatchOutcome | undefined>;
175
175
  /** The answer form of a classic event whose answer is an object of optional string members (`block`, `additionalContext`, …). */
@@ -142,7 +142,7 @@ export async function dispatchClassic(bus, event, e, options) {
142
142
  return await bus.dispatch(event, e, {
143
143
  bottom: engineCore,
144
144
  ...(options.signal !== undefined ? { signal: options.signal } : {}),
145
- ...(check !== undefined ? { checkAnswer: (a) => (a === ENGINE_CORE_ANSWER ? undefined : check(a)) } : {}),
145
+ ...(check !== undefined ? { checkAnswer: (a, ce, by, below, run) => (a === ENGINE_CORE_ANSWER ? undefined : check(a, ce, by, below, run)) } : {}),
146
146
  ...(options.ranks !== undefined ? { ranks: options.ranks } : {}),
147
147
  });
148
148
  }
@@ -5,7 +5,8 @@
5
5
  * handler's failure refuses the call while the body has not started and, once it has, the body's real result stands.
6
6
  *
7
7
  * `e = { tool, tool_use_id, agentId?, input }` (all four pinned — what the gate judged is what runs; a rewrite belongs to
8
- * `classic.PreToolUse`) plus the identity envelope. A handler answers:
8
+ * `classic.PreToolUse`) plus the identity envelope; a handler may hand on `requestMeta` too (a record of strings an MCP call carries
9
+ * as `_meta["sema/requestMeta"]`, judged where it is handed on — `mcp-call-meta.ts`). A handler answers:
9
10
  * - `next(e)` — the body runs; what came up is `{ result: { content, isError } }`, a frozen view of the real result;
10
11
  * - `{ deny: <reason> }` — refused before the body: the call is not executed and the record says an extension refused it
11
12
  * (a deny once the body has started stands in place of a call that ran: a violation, the real result stands);
@@ -28,6 +29,7 @@
28
29
  import type { AgentToolResult } from "../../internal/harness-types.js";
29
30
  import type { HookInvocationIdentity } from "../hooks.js";
30
31
  import type { ToolOccurrenceTable } from "../runner/tool-occurrence.js";
32
+ import { type McpRequestMetaSeat } from "../mcp-call-meta.js";
31
33
  import { type LegModBus } from "./stations.js";
32
34
  import type { ModBus, ModCallEntry } from "./kernel/index.js";
33
35
  /** One execution as the station sees it: the call, the tool that runs (its mounted name), the arguments the gate let go. */
@@ -46,6 +48,8 @@ export interface ToolCallStationInput {
46
48
  readonly blockedToolCalls: Set<string>;
47
49
  readonly identity?: HookInvocationIdentity;
48
50
  readonly reminderMark?: string;
51
+ /** The leg's request-meta seat: what the chain handed on as `requestMeta` stands under the call's id while its body runs. */
52
+ readonly requestMeta: Pick<McpRequestMetaSeat, "hold">;
49
53
  }
50
54
  /** The station over the leg's bus, or undefined when no handler hangs on `tool.call` (nothing is raised; the body runs). */
51
55
  export declare function createToolCallStation(input: ToolCallStationInput): ToolCallStation | undefined;
@@ -3,6 +3,7 @@ import { toolFace } from "../tool-catalog-entries.js";
3
3
  import { declaredDelegationNameOf } from "../delegation-name.js";
4
4
  import { describeThrown } from "../tool-policy.js";
5
5
  import { extensionWords } from "../untrusted-egress.js";
6
+ import { readHandedRequestMeta } from "../mcp-call-meta.js";
6
7
  import { ENGINE_ORIGIN } from "./kernel/index.js";
7
8
  import { isPlainRecord } from "./kernel/receive.js";
8
9
  import { NEXT_IN_FLIGHT } from "./kernel/site-rules.js";
@@ -60,8 +61,16 @@ export function createToolCallStation(input) {
60
61
  const e = { ...classicEventBase(input.identity), tool: call.toolName, tool_use_id: call.toolCallId, input: judgedInputOf(call.args) };
61
62
  const bodies = new Map();
62
63
  let body;
63
- const bottom = async () => {
64
- body = run();
64
+ const judged = new WeakMap();
65
+ const checkHandOn = (payload) => {
66
+ const read = readHandedRequestMeta(payload);
67
+ if ("problem" in read)
68
+ return `next() handed on a requestMeta the call cannot carry: ${read.problem}`;
69
+ judged.set(payload, read.meta);
70
+ return undefined;
71
+ };
72
+ const bottom = async (handed) => {
73
+ body = input.requestMeta.hold(call.toolCallId, judged.get(handed), run);
65
74
  const result = await body;
66
75
  const view = viewOf(result);
67
76
  bodies.set(view, result);
@@ -83,7 +92,7 @@ export function createToolCallStation(input) {
83
92
  };
84
93
  let outcome;
85
94
  try {
86
- outcome = await input.bus.dispatch("tool.call", e, { bottom, checkAnswer, ranks: RANKS, ...(signal !== undefined ? { signal } : {}) });
95
+ outcome = await input.bus.dispatch("tool.call", e, { bottom, checkAnswer, checkHandOn, ranks: RANKS, ...(signal !== undefined ? { signal } : {}) });
87
96
  }
88
97
  catch (err) {
89
98
  if (body !== undefined)
@@ -88,6 +88,26 @@ export interface PathRowsHit<R> {
88
88
  readonly viewKind?: GuardViewKind;
89
89
  readonly unreadable?: string;
90
90
  }
91
+ /** WHICH reading of the target met a tightening row, in the word every guard that writes about the hit records: `spelling`
92
+ * — the path as written (its placed spelling); `target` — where it really lands; `chain` — a hop of its leaf's symlink
93
+ * chain. A hit with no view (an unreadable hold) and a `home` view — the read-deny home station's, which no write guard
94
+ * mints — read as the spelling. */
95
+ export type GuardHitVia = "spelling" | "target" | "chain";
96
+ /** The ONE reading of a hit's view kind as its {@link GuardHitVia}, for every guard that records or words a hit. */
97
+ export declare function guardHitVia(kind: GuardViewKind | undefined): GuardHitVia;
98
+ /** Which spellings of the leg's current managed checkout a view is placed against (write-protect's current-tree reading): the
99
+ * canonical view against the checkout's canonical identity alone, every other view against every spelling of it. */
100
+ export type CheckoutReading = "canonical-only" | "every-spelling";
101
+ /** The ONE reading of a view kind as the {@link CheckoutReading} its current-tree placement uses (a new {@link GuardViewKind} must pick one). */
102
+ export declare function checkoutReadingOf(kind: GuardViewKind): CheckoutReading;
103
+ /**
104
+ * What a guard's sentence says about WHERE the row was met — one clause for every guard's sentence, said when the reading that
105
+ * met it is not the spelling. `target` and `chain` are one fact to whoever reads the sentence (the person approving, the
106
+ * auto-mode classifier, the model refused): the row was met by following the path on disk, at its real target or at a link on
107
+ * the way. Two wordings of that one fact let the wording, not the fact, move an answer. The clause says which reading met the
108
+ * row and nothing about the spelling: a spelling the identity exemption kept from voting may name the row too.
109
+ */
110
+ export declare function guardHitReachClause(via: GuardHitVia): string | undefined;
91
111
  /**
92
112
  * THE one judgment of guarded rows over a target's views, for every table and every lane: rows outer, views inner — the
93
113
  * first row (in the caller's order) that some view reaches is the answer. `tighten` (deny / ask): any present view reaching
@@ -8,6 +8,17 @@ export function viewSpellings(views) {
8
8
  export function spelledViews(spellings, kind) {
9
9
  return { views: spellings.map((path, i) => ({ path, kind: kind ?? (i === 0 ? "lexical" : "canonical") })) };
10
10
  }
11
+ const GUARD_HIT_VIA = { lexical: "spelling", canonical: "target", hop: "chain", home: "spelling" };
12
+ export function guardHitVia(kind) {
13
+ return kind === undefined ? "spelling" : GUARD_HIT_VIA[kind];
14
+ }
15
+ const CHECKOUT_READING = { lexical: "every-spelling", canonical: "canonical-only", hop: "every-spelling", home: "every-spelling" };
16
+ export function checkoutReadingOf(kind) {
17
+ return CHECKOUT_READING[kind];
18
+ }
19
+ export function guardHitReachClause(via) {
20
+ return via === "spelling" ? undefined : "matched where the path resolves on disk (its real target or a link on the way)";
21
+ }
11
22
  export function judgePathRows(rows, views, direction) {
12
23
  if (direction === "allow") {
13
24
  if (views.unreadable !== undefined || views.views.length === 0)
@@ -0,0 +1,186 @@
1
+ import { type CredentialRef } from "@sema-agent/primitives";
2
+ import type { McpServerSpec } from "./mcp-server-spec.js";
3
+ import type { ProtocolId } from "./protocol-table.js";
4
+ /** Why the seat is asked: the first send of a connection, any later send, or the send after a 401. */
5
+ export type PeerAskCause = "connect" | "request" | "rejected";
6
+ /**
7
+ * Who the request goes to, as the declaration names it — the whole of it, so the seat can bind an answer to the reference, the
8
+ * principal, the protocol and the destination (or the whole start command): an http MCP server's url, a stdio one's command and
9
+ * arguments, an A2A peer's declared urls and THIS send's destination.
10
+ */
11
+ export type PeerSeatTarget = {
12
+ readonly protocol: "mcp";
13
+ readonly server: string;
14
+ readonly transport: "http";
15
+ readonly url: string;
16
+ readonly credentials?: CredentialRef;
17
+ readonly fingerprint?: string;
18
+ } | {
19
+ readonly protocol: "mcp";
20
+ readonly server: string;
21
+ readonly transport: "stdio";
22
+ readonly command: string;
23
+ readonly args: readonly string[];
24
+ readonly credentials?: CredentialRef;
25
+ readonly fingerprint?: string;
26
+ } | {
27
+ readonly protocol: "a2a";
28
+ readonly peer: string;
29
+ readonly url: string;
30
+ readonly cardUrl?: string;
31
+ readonly destination: string;
32
+ readonly credentials?: CredentialRef;
33
+ };
34
+ /** One question to the seat. `principal` is part of the connection's identity; the session is not. */
35
+ export interface PeerQuestion {
36
+ readonly peer: PeerSeatTarget;
37
+ readonly principal?: string;
38
+ readonly cause: PeerAskCause;
39
+ }
40
+ /**
41
+ * The seat's answer: the pieces to carry (`headers` for an http request and an A2A send, `env` for a stdio child — the member of the
42
+ * other lane is refused; `expiresAt`, epoch ms, is read by a stdio child only), or that the principal is not authorized here.
43
+ */
44
+ export type PeerAnswer = {
45
+ readonly kind: "carry";
46
+ readonly headers?: Readonly<Record<string, string>>;
47
+ readonly env?: Readonly<Record<string, string>>;
48
+ readonly expiresAt?: number;
49
+ } | {
50
+ readonly kind: "unauthorized";
51
+ readonly authorizeUrl?: string;
52
+ };
53
+ /**
54
+ * The deployment's peer seat (`RunnerDeps.peerSeat`, TRUSTED). It owes the binding the engine cannot judge: answer only for the
55
+ * reference, principal, protocol and destination (or start command) it was asked about — never one token for every peer.
56
+ */
57
+ export type PeerSeat = (question: PeerQuestion, signal: AbortSignal) => Promise<PeerAnswer>;
58
+ /** Which answer member each transport carries. */
59
+ export declare const PEER_ANSWER_LANES: Readonly<{
60
+ readonly http: "headers";
61
+ readonly a2a: "headers";
62
+ readonly stdio: "env";
63
+ }>;
64
+ export type PeerLane = keyof typeof PEER_ANSWER_LANES;
65
+ /** How long one ask may take before the send goes without it (`credential_unavailable`). */
66
+ export declare const PEER_SEAT_WAIT_MS = 30000;
67
+ /** Why a send went without its pieces. */
68
+ export type PeerSeatFailureReason = "threw" | "timed_out" | "answer_invalid" | "unauthorized";
69
+ /**
70
+ * A send the seat did not furnish: nothing was sent. The text names the peer and the reason, never a value and never the seat's own
71
+ * error text (deployment code may put a credential in it); `authorizeUrl` is the seat's own, when it answered `unauthorized`.
72
+ */
73
+ export declare class PeerSeatFailure extends Error {
74
+ readonly reason: PeerSeatFailureReason;
75
+ readonly authorizeUrl: string | undefined;
76
+ /** An answer the engine cannot carry is the deployment's configuration fault: `config.peer_answer_invalid`, or the ownership law's
77
+ * own code (`config.protocol_header_collision`) when it names a header it may not. A seat that threw, timed out or refused has none. */
78
+ readonly code: string | undefined;
79
+ constructor(reason: PeerSeatFailureReason, peerLabel: string, problem: string, extra?: {
80
+ authorizeUrl?: string;
81
+ code?: string;
82
+ });
83
+ }
84
+ /** What one send carries, as the engine took it from an answer, and its digest (whether a re-ask changed anything). */
85
+ export interface CarriedPieces {
86
+ readonly headers?: Readonly<Record<string, string>>;
87
+ readonly env?: Readonly<Record<string, string>>;
88
+ readonly expiresAt?: number;
89
+ readonly digest: string;
90
+ }
91
+ /** The seat's answer for `lane`, read once: the pieces, the `unauthorized` answer, or the problem (which member did not fit). */
92
+ export declare function readPeerAnswer(raw: unknown, lane: PeerLane): {
93
+ readonly carry: CarriedPieces;
94
+ } | {
95
+ readonly unauthorized: {
96
+ readonly authorizeUrl?: string;
97
+ };
98
+ } | {
99
+ readonly problem: string;
100
+ };
101
+ /**
102
+ * One connection's (or one A2A peer's) asks of the seat. `next` answers each send: a 401's re-ask answer when one is waiting (carried
103
+ * once), else the seat's answer to this send. `rejected` is the one re-ask after a 401 (concurrent rejections share it); `renewed` says
104
+ * whether that re-ask answered pieces that differ from what the rejected send carried — the call layer sends a repeat-safe call again
105
+ * only then. `sent` is every value a send carried and the principal sent beside them: a remote's words are read without them.
106
+ */
107
+ export declare class PeerCarrier {
108
+ private readonly seat;
109
+ private readonly identity;
110
+ private readonly principal;
111
+ private readonly lane;
112
+ readonly sent: string[];
113
+ /** When the pieces a stdio child was started with stop being good; `undefined` when the answer said nothing. */
114
+ expiresAt: number | undefined;
115
+ renewed: boolean;
116
+ private asked;
117
+ private waiting;
118
+ private rejection;
119
+ constructor(seat: PeerSeat | undefined, identity: PeerSeatTarget, principal: string | undefined, lane: PeerLane, principalSent: boolean);
120
+ /** The peer as the refusal sentences name it. */
121
+ get label(): string;
122
+ /** The pieces the next send carries (see the class note). A seat failure throws {@link PeerSeatFailure}. */
123
+ next(signal?: AbortSignal, destination?: string): Promise<CarriedPieces>;
124
+ /** The pieces the latest send carried (`undefined` before the first). */
125
+ last: CarriedPieces | undefined;
126
+ /** A send that carried `carried` was answered 401: ask once more (`rejected`); the next send carries that answer. Never throws —
127
+ * a re-ask that fails leaves `renewed` false, so the 401 is the call's answer, and the next send asks afresh. */
128
+ rejected(carried: CarriedPieces, signal?: AbortSignal, destination?: string): Promise<void>;
129
+ /** Whether the pieces a stdio child was started with have stopped being good. */
130
+ expired(now?: number): boolean;
131
+ private ask;
132
+ private remember;
133
+ }
134
+ /**
135
+ * The http request headers one send carries: the seat's pieces and the principal under `principalHeader`, judged by the one ownership
136
+ * law ({@link resolveProtocolHttpHeaders}: one owner per name; an MCP request's protocol-owned names are the SDK's). A collision of the
137
+ * answer is the seat's fault ({@link PeerSeatFailure}); the declaration's own principal header was judged when the peer was dialed.
138
+ */
139
+ export declare function carriedHttpHeaders(protocol: ProtocolId, carrier: PeerCarrier, pieces: CarriedPieces, principalHeader: string | undefined, principal: string | undefined): Readonly<Record<string, string>> | undefined;
140
+ /**
141
+ * The MCP HTTP transport's `fetch` under the seat: every request the transport makes (the POST, the SSE GET, the DELETE) asks the
142
+ * carrier first, carries what it answered, goes only to the endpoint the declaration named (no redirect is followed — a 3xx is the
143
+ * answer) and, answered 401, has the carrier ask once more for the next send.
144
+ */
145
+ export declare function peerFetch(carrier: PeerCarrier, principalHeader: string | undefined, principal: string | undefined): typeof fetch;
146
+ /** The member of a declaration that would carry a value (retired: values come from the seat). */
147
+ export declare const RETIRED_VALUE_MEMBERS: Readonly<{
148
+ readonly mcp: readonly (readonly string[])[];
149
+ readonly a2a: readonly (readonly string[])[];
150
+ }>;
151
+ /** The first retired value member a received copy holds (a member holding `undefined` is absent), as its path. */
152
+ export declare function retiredValueMember(copy: Readonly<Record<string, unknown>>, at: keyof typeof RETIRED_VALUE_MEMBERS): readonly string[] | undefined;
153
+ /** Where a declaration's credential reference sits on each surface. */
154
+ export declare const CREDENTIALS_MEMBER: Readonly<{
155
+ readonly mcp: readonly string[];
156
+ readonly a2a: readonly string[];
157
+ }>;
158
+ /** The credential reference a received copy holds (absent ⇒ `undefined`), judged by the one reader; a problem as a sentence. */
159
+ export declare function declaredCredentials(copy: object, at: keyof typeof CREDENTIALS_MEMBER): {
160
+ readonly ref?: CredentialRef;
161
+ } | {
162
+ readonly problem: string;
163
+ };
164
+ /** A declaration that names a credential reference while no seat is wired: nobody would answer it (`config.peer_seat_missing`). */
165
+ export declare function peerSeatMissing(subject: string, credentials: CredentialRef | undefined, seat: PeerSeat | undefined): (Error & {
166
+ code: string;
167
+ }) | undefined;
168
+ /** Who an MCP server is, as the seat is asked about it: its name, the whole start command or endpoint, its reference, its mount identity. */
169
+ export declare function mcpPeerTarget(spec: McpServerSpec, kind: "stdio" | "http" | undefined): PeerSeatTarget;
170
+ /** Whether a failure is the HTTP endpoint answering 401 (the SDK's status error, on the thrown value or its cause chain). Structure only. */
171
+ export declare function answeredUnauthorized(err: unknown): boolean;
172
+ /** A call answered 401 after which the seat's re-ask answered other pieces: its failure as it would have been thrown then. */
173
+ export declare class Reauthorized {
174
+ readonly error: unknown;
175
+ constructor(error: unknown);
176
+ }
177
+ /**
178
+ * The call layer's one re-send after a 401: `attempt` once; when it answers {@link Reauthorized} and `mayResend`
179
+ * (the revocation probe and `reach`, asked again) holds, once more, carrying what the re-ask answered. A re-send the seat could not furnish
180
+ * ends with the first attempt's failure, whose delivery verdict stands for the call (one of its attempts was sent).
181
+ */
182
+ export declare function sentOnceMore<R>(attempt: () => Promise<R | Reauthorized>, mayResend: () => boolean): Promise<R>;
183
+ export declare function inFlight<T>(client: object, run: () => Promise<T>): Promise<T>;
184
+ export declare function settledInFlight(client: object): Promise<void>;
185
+ export declare function recordCarrier(client: object, carrier: PeerCarrier): void;
186
+ export declare function carrierOf(client: object): PeerCarrier | undefined;