@sema-agent/core 7.73.0 → 7.74.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 (177) hide show
  1. package/CHANGELOG.md +246 -0
  2. package/dist/agents/list-agents-tool.js +1 -1
  3. package/dist/agents/retain-ledger.js +3 -3
  4. package/dist/agents/send-message-tool.js +4 -4
  5. package/dist/brain/anthropic.d.ts +42 -1
  6. package/dist/brain/anthropic.js +54 -4
  7. package/dist/brain/failover.d.ts +5 -0
  8. package/dist/brain/failover.js +51 -22
  9. package/dist/brain/model-lane.d.ts +12 -3
  10. package/dist/brain/model-lane.js +5 -5
  11. package/dist/brain/open-responses.js +3 -3
  12. package/dist/brain/openai.js +1 -1
  13. package/dist/brain/route-adjudicator.d.ts +33 -4
  14. package/dist/brain/route-adjudicator.js +49 -12
  15. package/dist/brain/stream-engine.js +9 -7
  16. package/dist/brain/stream-shared.d.ts +4 -3
  17. package/dist/brain/stream-shared.js +2 -2
  18. package/dist/core/allow-entry.js +1 -1
  19. package/dist/core/ask-class.d.ts +2 -2
  20. package/dist/core/ask-headline.d.ts +1 -1
  21. package/dist/core/ask-origin.d.ts +44 -4
  22. package/dist/core/ask-origin.js +29 -10
  23. package/dist/core/background-agent-store.d.ts +1 -0
  24. package/dist/core/background-agent-store.js +49 -8
  25. package/dist/core/checkpoint-row-verdict.d.ts +1 -1
  26. package/dist/core/checkpoint-row-verdict.js +2 -2
  27. package/dist/core/checkpoint-store.d.ts +2 -0
  28. package/dist/core/checkpoint-store.js +8 -2
  29. package/dist/core/config-refusal-codes.d.ts +1 -1
  30. package/dist/core/config-refusal-codes.js +1 -0
  31. package/dist/core/cron.js +9 -1
  32. package/dist/core/deployment-shape.d.ts +7 -0
  33. package/dist/core/deployment-shape.js +19 -0
  34. package/dist/core/engine-capabilities.d.ts +9 -1
  35. package/dist/core/engine-capabilities.js +1 -1
  36. package/dist/core/engine-notice.d.ts +14 -9
  37. package/dist/core/engine-version.js +1 -1
  38. package/dist/core/gate-fold.js +5 -4
  39. package/dist/core/gate-lanes.js +8 -12
  40. package/dist/core/gate-outcome.d.ts +8 -2
  41. package/dist/core/gate-outcome.js +10 -3
  42. package/dist/core/governance-codes.d.ts +8 -2
  43. package/dist/core/governance-codes.js +9 -1
  44. package/dist/core/hook-condition.d.ts +37 -0
  45. package/dist/core/hook-condition.js +567 -0
  46. package/dist/core/hooks.d.ts +2 -0
  47. package/dist/core/mode-policy.d.ts +4 -0
  48. package/dist/core/mode-policy.js +18 -2
  49. package/dist/core/model-seat.d.ts +8 -5
  50. package/dist/core/model-shell.d.ts +129 -0
  51. package/dist/core/model-shell.js +249 -0
  52. package/dist/core/mods/kernel/digest.d.ts +4 -0
  53. package/dist/core/mods/kernel/digest.js +5 -0
  54. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  55. package/dist/core/mods/kernel/dispatch.js +15 -6
  56. package/dist/core/mods/kernel/events.d.ts +21 -5
  57. package/dist/core/mods/kernel/events.js +19 -10
  58. package/dist/core/mods/kernel/hash-mirror.d.ts +1 -0
  59. package/dist/core/mods/kernel/hash-mirror.js +55 -0
  60. package/dist/core/mods/kernel/index.d.ts +1 -0
  61. package/dist/core/mods/kernel/index.js +1 -0
  62. package/dist/core/mods/kernel/package-reader.d.ts +48 -0
  63. package/dist/core/mods/kernel/package-reader.js +149 -0
  64. package/dist/core/mods/kernel/site-rules.d.ts +4 -0
  65. package/dist/core/mods/kernel/site-rules.js +13 -0
  66. package/dist/core/mods/package.d.ts +7 -3
  67. package/dist/core/mods/package.js +47 -80
  68. package/dist/core/permission-rule-org.js +13 -3
  69. package/dist/core/permission-rules.js +4 -1
  70. package/dist/core/retain-seat.d.ts +42 -0
  71. package/dist/core/retain-seat.js +76 -0
  72. package/dist/core/rewind-refusal-codes.d.ts +8 -0
  73. package/dist/core/rewind-refusal-codes.js +12 -0
  74. package/dist/core/roles.d.ts +2 -2
  75. package/dist/core/roles.js +15 -1
  76. package/dist/core/rule-store-fault.d.ts +9 -7
  77. package/dist/core/rule-store-fault.js +8 -3
  78. package/dist/core/runner/checkpoint-scope.d.ts +1 -0
  79. package/dist/core/runner/checkpoint-scope.js +4 -2
  80. package/dist/core/runner/compact-session.js +1 -1
  81. package/dist/core/runner/construction-doors.js +2 -0
  82. package/dist/core/runner/cross-boundary-lane.d.ts +8 -1
  83. package/dist/core/runner/cross-boundary-lane.js +4 -0
  84. package/dist/core/runner/gate-exit.d.ts +7 -0
  85. package/dist/core/runner/gate-exit.js +2 -1
  86. package/dist/core/runner/model-lane-seat.d.ts +3 -0
  87. package/dist/core/runner/model-lane-seat.js +4 -0
  88. package/dist/core/runner/person-path-rows.d.ts +6 -0
  89. package/dist/core/runner/person-path-rows.js +13 -0
  90. package/dist/core/runner/prepare-config-doors.js +9 -5
  91. package/dist/core/runner/prepare-gate-stations.d.ts +6 -0
  92. package/dist/core/runner/prepare-gate-stations.js +3 -1
  93. package/dist/core/runner/prepare-hands-readface.js +3 -2
  94. package/dist/core/runner/prepare-offload-wrappers.js +1 -1
  95. package/dist/core/runner/prepare-task.js +6 -3
  96. package/dist/core/runner/prepare-wiring-manifest.js +3 -4
  97. package/dist/core/runner/resume-policy-outcome.js +5 -2
  98. package/dist/core/runner/role-seat-defaulted.d.ts +3 -3
  99. package/dist/core/runner/role-seat-defaulted.js +1 -1
  100. package/dist/core/runner/rule-store-unreadable-notice.d.ts +1 -1
  101. package/dist/core/runner/rule-store-unreadable-notice.js +3 -3
  102. package/dist/core/runner/run-harness-handlers.js +1 -1
  103. package/dist/core/runner/run-leg.js +2 -2
  104. package/dist/core/runner/shell-env-withheld.d.ts +3 -2
  105. package/dist/core/runner/shell-env-withheld.js +24 -1
  106. package/dist/core/runner/sub-agent-deny-lists.js +9 -5
  107. package/dist/core/runner/tool-end-body.d.ts +1 -1
  108. package/dist/core/runner/tool-not-executed.d.ts +27 -8
  109. package/dist/core/runner/tool-not-executed.js +22 -11
  110. package/dist/core/runner/write-protection-station.d.ts +1 -1
  111. package/dist/core/runner/write-protection-station.js +1 -1
  112. package/dist/core/runner-deps.d.ts +4 -0
  113. package/dist/core/secret-env.d.ts +8 -0
  114. package/dist/core/secret-env.js +5 -2
  115. package/dist/core/shell-read-silence.d.ts +40 -2
  116. package/dist/core/shell-read-silence.js +23 -4
  117. package/dist/core/task-event.d.ts +4 -4
  118. package/dist/core/task-notification.js +6 -1
  119. package/dist/core/task-registry-agent.d.ts +1 -0
  120. package/dist/core/task-registry-agent.js +1 -1
  121. package/dist/core/task-registry.d.ts +1 -0
  122. package/dist/core/task-registry.js +4 -3
  123. package/dist/core/task-result.d.ts +5 -3
  124. package/dist/core/task-spec-members.js +8 -0
  125. package/dist/core/tool-gate-phase.d.ts +6 -3
  126. package/dist/core/tool-gate-phase.js +1 -0
  127. package/dist/core/tool-mount-facts.d.ts +7 -3
  128. package/dist/core/tool-mount-facts.js +6 -2
  129. package/dist/core/tool-mount-plan.d.ts +1 -1
  130. package/dist/core/tool-mount-plan.js +4 -3
  131. package/dist/core/tool-result-store.d.ts +37 -1
  132. package/dist/core/tool-result-store.js +168 -23
  133. package/dist/core/trace.d.ts +3 -3
  134. package/dist/engine/execution-env/node-execution-env.d.ts +75 -1
  135. package/dist/engine/execution-env/node-execution-env.js +225 -13
  136. package/dist/engine/harness/types.d.ts +25 -0
  137. package/dist/engine/llm/types.d.ts +8 -0
  138. package/dist/engine/llm/validation.d.ts +8 -1
  139. package/dist/engine/llm/validation.js +31 -2
  140. package/dist/host-env.d.ts +10 -0
  141. package/dist/host-env.js +1 -0
  142. package/dist/index.d.ts +10 -2
  143. package/dist/index.js +9 -2
  144. package/dist/internal/harness-types.d.ts +1 -1
  145. package/dist/orchestration/goal.js +1 -1
  146. package/dist/orchestration/workflow-primitives.js +10 -1
  147. package/dist/orchestration/workflow-script-runner.d.ts +2 -2
  148. package/dist/orchestration/workflow.d.ts +1 -1
  149. package/dist/orchestration/workflow.js +2 -2
  150. package/dist/shell/lex.d.ts +2 -2
  151. package/dist/shell/lex.js +1 -1
  152. package/dist/tools/fs/bash-model-shell.d.ts +23 -0
  153. package/dist/tools/fs/bash-model-shell.js +25 -0
  154. package/dist/tools/fs/bash-readonly-classifier.d.ts +6 -0
  155. package/dist/tools/fs/bash-readonly-classifier.js +3 -0
  156. package/dist/tools/fs/fs-bash.js +13 -11
  157. package/dist/tools/fs/shell-read-argv.js +1 -0
  158. package/dist/tools/fs/shell-read-check.js +39 -9
  159. package/dist/tools/fs/shell-read-plan.d.ts +2 -3
  160. package/dist/tools/fs/shell-read-plan.js +8 -5
  161. package/dist/tools/fs/shell-read-word.d.ts +8 -0
  162. package/dist/tools/fs/shell-read-word.js +13 -4
  163. package/dist/tools/monitor.js +12 -8
  164. package/dist/tools/scheduler-tools.d.ts +1 -0
  165. package/dist/tools/scheduler-tools.js +5 -2
  166. package/package.json +3 -2
  167. package/test/export-surface.snapshot.json +62 -3
  168. package/wire-changes/answers/core-stores-sql@7.74.0.json +7 -0
  169. package/wire-changes/answers/core@7.74.0.json +68 -0
  170. package/wire-changes/answers/mods-kernel@7.74.0.json +21 -0
  171. package/wire-changes/answers/primitives@7.74.0.json +7 -0
  172. package/wire-changes/answers/wiki-gate@7.74.0.json +8 -0
  173. package/wire-changes/core-stores-sql@7.74.0.json +143 -0
  174. package/wire-changes/core@7.74.0.json +2210 -0
  175. package/wire-changes/mods-kernel@7.74.0.json +421 -0
  176. package/wire-changes/primitives@7.74.0.json +174 -0
  177. package/wire-changes/wiki-gate@7.74.0.json +145 -0
@@ -5,15 +5,17 @@ import { createHash, randomUUID } from "node:crypto";
5
5
  import { closeSync, constants, createReadStream, mkdtempSync, openSync, readSync, rmSync, statSync, truncateSync, unlinkSync } from "node:fs";
6
6
  import { access, appendFile, lstat, mkdir, mkdtemp, open, readdir, readFile, readlink, rename, rm, stat, unlink, writeFile, } from "node:fs/promises";
7
7
  import { tmpdir } from "node:os";
8
- import { basename, dirname, isAbsolute, join, sep } from "node:path";
8
+ import { basename, dirname, isAbsolute, join, posix as posixPath, sep, win32 as win32Path } from "node:path";
9
9
  import { createInterface } from "node:readline";
10
10
  import { ExecutionError, err, FileError, ok, toError, } from "../harness/types.js";
11
11
  import { killProcessTree, shutdownDebug } from "./kill-tree.js";
12
- import { __resetSecretEnvScrubNoticeAnnouncement, announceSecretEnvScrub, declaredInheritEntry, hostChildEnv, hostChildEnvProblem, inheritEnvPolicyProblem, inheritedHostEnv, noteChildSpawned } from "../../core/secret-env.js";
12
+ import { __resetSecretEnvScrubNoticeAnnouncement, announceSecretEnvScrub, declaredInheritEntry, envNameKeyOn, hostChildEnv, hostChildEnvProblem, inheritEnvPolicyProblem, inheritedHostEnv, noteChildSpawned } from "../../core/secret-env.js";
13
13
  import { deliverEngineNotice } from "../../core/engine-notice.js";
14
14
  import { confineShellStart, SANDBOX_EXEC, SEATBELT_PROBE_PROFILE } from "../../core/shell-confinement.js";
15
15
  import { physicalPathOfAsync } from "../../core/physical-path.js";
16
16
  import { posixModeBitsMeaningful } from "../../core/posix-mode-face.js";
17
+ import { isAbsoluteForFamily, isWinFormPath } from "../../core/unc-spelling.js";
18
+ import { SHELL_KIND_QUESTION, SHELL_KIND_QUESTION_OPTIONS, configuredNamesKeptOut, configuredShellLayer, inheritedShellState, notStartedInThisVersion, readShellKindAnswer, shellKindQuestionEnv } from "../../core/model-shell.js";
17
19
  import { anchorAtLinkDir, walkSymlinkChain } from "./symlink-chain.js";
18
20
  import { RollingTailBuffer, markTruncated, newStreamCursorState, sliceStreamIncrement, } from "../../core/exec-output-tail.js";
19
21
  import { BackgroundShellError } from "../../core/background-shell.js";
@@ -382,7 +384,7 @@ async function pathExists(path) {
382
384
  return false;
383
385
  }
384
386
  }
385
- async function runCommand(command, args, timeoutMs) {
387
+ async function runCommand(command, args, timeoutMs, start) {
386
388
  return await new Promise((resolveLocal) => {
387
389
  let stdout = "";
388
390
  let child;
@@ -390,7 +392,8 @@ async function runCommand(command, args, timeoutMs) {
390
392
  child = spawn(command, args, {
391
393
  stdio: ["ignore", "pipe", "ignore"],
392
394
  windowsHide: true,
393
- env: inheritedHostEnv("scrub"),
395
+ env: start === undefined ? inheritedHostEnv("scrub") : start.env(),
396
+ ...(start === undefined ? {} : { cwd: start.cwd }),
394
397
  });
395
398
  }
396
399
  catch {
@@ -468,6 +471,99 @@ export async function getShellConfig(customShellPath) {
468
471
  }
469
472
  return ok({ shell: "sh", args: ["-c"] });
470
473
  }
474
+ const HOST_PROBE = {
475
+ get platform() {
476
+ return process.platform;
477
+ },
478
+ exists: pathExists,
479
+ executable: async (path) => {
480
+ try {
481
+ await access(path, constants.X_OK);
482
+ return (await stat(path)).isFile();
483
+ }
484
+ catch {
485
+ return false;
486
+ }
487
+ },
488
+ get programFiles() {
489
+ return [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]];
490
+ },
491
+ };
492
+ export function modelShellSearchPath(env, platform = process.platform) {
493
+ const key = Object.keys(env).find((k) => envNameKeyOn(k, platform) === "PATH");
494
+ const value = key === undefined ? undefined : env[key];
495
+ return value === undefined || value === "" ? [] : value.split(platform === "win32" ? ";" : ":");
496
+ }
497
+ async function programOf(name, place, probe) {
498
+ const at = probe.platform === "win32" ? win32Path : posixPath;
499
+ if (isAbsoluteCandidate(name, probe.platform))
500
+ return (await probe.exists(name)) ? name : undefined;
501
+ if (name.includes("/") || (probe.platform === "win32" && isWinFormPath(name))) {
502
+ const joined = at.resolve(place.cwd, name);
503
+ return (await probe.exists(joined)) ? joined : undefined;
504
+ }
505
+ const names = probe.platform === "win32" && !/\.exe$/i.test(name) ? [name, `${name}.exe`] : [name];
506
+ for (const dir of place.searchPath) {
507
+ if (!isAbsoluteCandidate(dir, probe.platform))
508
+ continue;
509
+ for (const candidate of names.map((n) => at.join(dir, n))) {
510
+ if (probe.platform === "win32" && isWslBashLauncher(candidate))
511
+ continue;
512
+ if (await probe.executable(candidate))
513
+ return candidate;
514
+ }
515
+ }
516
+ return undefined;
517
+ }
518
+ export async function askShellKind(path, cwd) {
519
+ return (await askShellKindOnce(path, cwd)).answer;
520
+ }
521
+ async function askShellKindOnce(path, cwd) {
522
+ const run = await runCommand(path, [...SHELL_KIND_QUESTION_OPTIONS, SHELL_KIND_QUESTION], 5000, { env: () => shellKindQuestionEnv(inheritedHostEnv("scrub")), cwd });
523
+ if (run.status === null)
524
+ return { ran: false, answer: { ok: false, reason: "gave no answer to the shell-kind question (it could not be started, timed out or was ended by a signal)" } };
525
+ return { ran: true, answer: run.status !== 0 ? { ok: false, reason: `gave no answer to the shell-kind question (it exited with status ${run.status})` } : readShellKindAnswer(run.stdout) };
526
+ }
527
+ export async function resolveModelShell(shellPath, place, probe = HOST_PROBE, ask = askShellKind) {
528
+ const refusals = [];
529
+ const asked = new Set();
530
+ const tryOne = async (path) => {
531
+ asked.add(path);
532
+ const answer = await ask(path, place.cwd);
533
+ const refused = answer.ok ? notStartedInThisVersion(answer) : answer.reason;
534
+ if (refused === undefined && answer.ok)
535
+ return answer.version;
536
+ refusals.push(`${path} ${refused}`);
537
+ return undefined;
538
+ };
539
+ const taken = (path, version) => ok({ path, version });
540
+ const unavailable = () => err(new ExecutionError("shell_unavailable", refusals.length === 0 ? "No bash shell found" : `No bash (3.2 or later, not in POSIX mode) to start commands on: ${refusals.join("; ")}`));
541
+ if (shellPath) {
542
+ const program = await programOf(shellPath, place, probe);
543
+ if (program === undefined)
544
+ return err(new ExecutionError("shell_unavailable", `Custom shell path not found: ${shellPath}`));
545
+ const version = await tryOne(program);
546
+ return version !== undefined ? taken(program, version) : unavailable();
547
+ }
548
+ const fixed = probe.platform === "win32" ? probe.programFiles.flatMap((root) => (root ? [`${root}\\Git\\bin\\bash.exe`] : [])) : ["/bin/bash"];
549
+ for (const candidate of fixed) {
550
+ if (!isAbsoluteCandidate(candidate, probe.platform) || !(await probe.exists(candidate)))
551
+ continue;
552
+ const version = await tryOne(candidate);
553
+ if (version !== undefined)
554
+ return taken(candidate, version);
555
+ }
556
+ const onPath = await programOf("bash", place, probe);
557
+ if (onPath !== undefined && !asked.has(onPath)) {
558
+ const version = await tryOne(onPath);
559
+ if (version !== undefined)
560
+ return taken(onPath, version);
561
+ }
562
+ return unavailable();
563
+ }
564
+ function isAbsoluteCandidate(path, platform) {
565
+ return isAbsoluteForFamily(platform === "win32" ? "win" : "posix", path);
566
+ }
471
567
  const EXEC_FORCE_SETTLE_GRACE_MS = 3000;
472
568
  let secretScrubSeatDefectAnnounced = false;
473
569
  export function __resetSecretScrubAnnouncement() {
@@ -565,6 +661,30 @@ function shellChildStdio(spoolFds, stdinFed) {
565
661
  const stdin = stdinFed ? "pipe" : "ignore";
566
662
  return { stdio: spoolFds ? [stdin, spoolFds[0], spoolFds[1]] : [stdin, "pipe", "pipe"] };
567
663
  }
664
+ export const MODEL_SHELL_DROPPED_KEPT = 32;
665
+ const RUN_SHELL = Symbol("NodeExecutionEnv.runShell");
666
+ const START_BACKGROUND = Symbol("NodeExecutionEnv.startBackground");
667
+ const MODEL_START = Symbol("NodeExecutionEnv.modelStart");
668
+ function withModelStart(options, start) {
669
+ const own = options === undefined ? {} : Object.getOwnPropertyDescriptors(options);
670
+ return Object.create(options === undefined ? Object.prototype : Object.getPrototypeOf(options), { ...own, [MODEL_START]: { value: start, enumerable: true } });
671
+ }
672
+ function modelStartOf(options) {
673
+ let s;
674
+ try {
675
+ s = options?.[MODEL_START];
676
+ }
677
+ catch {
678
+ return undefined;
679
+ }
680
+ return typeof s === "object" && s !== null ? s : undefined;
681
+ }
682
+ function modelStartAt(env, options) {
683
+ const carried = modelStartOf(options);
684
+ return carried === undefined || carried.owner === env ? carried : modelStartOfEnv(env);
685
+ }
686
+ let modelStartOfEnv;
687
+ let spawnEnvOf;
568
688
  export class NodeExecutionEnv {
569
689
  cwd;
570
690
  capabilities;
@@ -597,9 +717,9 @@ export class NodeExecutionEnv {
597
717
  return undefined;
598
718
  }
599
719
  }
600
- spawnEnv(extraEnv) {
720
+ spawnEnv(extraEnv, base) {
601
721
  try {
602
- return getShellEnv(this.inheritEnv, this.shellEnv, extraEnv, this.onSecretEnvScrub, this.onNotice);
722
+ return getShellEnv(this.inheritEnv, base === undefined ? this.shellEnv : base.env, extraEnv, this.onSecretEnvScrub, this.onNotice);
603
723
  }
604
724
  catch (error) {
605
725
  const entry = declaredInheritEntry(this.inheritEnv);
@@ -728,12 +848,100 @@ export class NodeExecutionEnv {
728
848
  return { ok: false, refusedBy: "environment", reason: `the read-deny table's confinement profile does not apply on this host (${failed}) — the command was not started` };
729
849
  return { ok: true, ...confined.start };
730
850
  }
731
- async exec(command, options) {
851
+ exec(command, options) {
852
+ const start = modelStartAt(this, options);
853
+ return NodeExecutionEnv.prototype[RUN_SHELL].call(this, command, options, () => start?.shellOf() ?? getShellConfig(this.shellPath), () => start?.childEnvOf() ?? spawnEnvOf(this));
854
+ }
855
+ static {
856
+ spawnEnvOf = (env) => {
857
+ const spawnEnv = env.spawnEnv;
858
+ return (extraEnv) => spawnEnv.call(env, extraEnv);
859
+ };
860
+ }
861
+ get modelShell() {
862
+ const start = () => modelStartOfEnv(this);
863
+ return {
864
+ exec: (script, options) => this.exec(script, withModelStart(options, start())),
865
+ spawnBackground: (script, options) => this.spawnBackground(script, withModelStart(options, start())),
866
+ ready: async () => {
867
+ const resolved = await start().resolvedOf();
868
+ return resolved.ok ? ok({ shell: "bash", version: resolved.value.version }) : resolved;
869
+ },
870
+ };
871
+ }
872
+ static {
873
+ modelStartOfEnv = (self) => {
874
+ let layer;
875
+ const layerOf = () => (layer ??= configuredShellLayer(self.shellEnv, "env grant 1"));
876
+ const resolvedOf = async () => {
877
+ let env;
878
+ try {
879
+ env = self.spawnEnv(undefined, { env: layerOf().kept });
880
+ }
881
+ catch (error) {
882
+ const cause = toError(error);
883
+ const failure = new ExecutionError("spawn_error", cause.message, cause);
884
+ const brief = briefOf(error);
885
+ if (brief !== undefined)
886
+ failure.briefMessage = brief;
887
+ return err(failure);
888
+ }
889
+ return self.modelShellPath(env);
890
+ };
891
+ return {
892
+ owner: self,
893
+ resolvedOf,
894
+ shellOf: async () => {
895
+ const resolved = await (self.modelShellResolved ?? resolvedOf());
896
+ return resolved.ok ? ok({ shell: resolved.value.path, args: ["-c"] }) : resolved;
897
+ },
898
+ childEnvOf: () => (extraEnv) => self.modelShellSpawnEnv(layerOf(), extraEnv),
899
+ };
900
+ };
901
+ }
902
+ modelShellResolved;
903
+ modelShellPath(env) {
904
+ if (this.modelShellResolved !== undefined)
905
+ return this.modelShellResolved;
906
+ let unanswered = false;
907
+ const ask = async (path, cwd) => {
908
+ const asked = await askShellKindOnce(path, cwd);
909
+ if (!asked.ran)
910
+ unanswered = true;
911
+ return asked.answer;
912
+ };
913
+ const resolving = resolveModelShell(this.shellPath, { cwd: this.cwd, searchPath: modelShellSearchPath(env) }, HOST_PROBE, ask).then((resolved) => {
914
+ if (!resolved.ok && unanswered && this.modelShellResolved === resolving)
915
+ this.modelShellResolved = undefined;
916
+ return resolved;
917
+ });
918
+ this.modelShellResolved = resolving;
919
+ return resolving;
920
+ }
921
+ get modelShellDropped() {
922
+ return this.modelShellDroppedRecord;
923
+ }
924
+ modelShellDroppedRecord = { entries: [], more: false };
925
+ modelShellSpawnEnv(layer, extraEnv) {
926
+ const extra = configuredShellLayer(extraEnv, "env grant 2");
927
+ const composed = inheritedShellState(this.spawnEnv(extra.kept, { env: layer.kept }), process.platform, configuredNamesKeptOut([layer, extra]));
928
+ const record = this.modelShellDroppedRecord;
929
+ for (const d of [...layer.dropped, ...extra.dropped, ...composed.dropped]) {
930
+ if (record.entries.some((e) => e.from === d.from && e.key === d.key))
931
+ continue;
932
+ if (record.entries.length >= MODEL_SHELL_DROPPED_KEPT)
933
+ record.more = true;
934
+ else
935
+ record.entries.push(d);
936
+ }
937
+ return composed.kept;
938
+ }
939
+ async [RUN_SHELL](command, options, shellOf, childEnvOf) {
732
940
  if (options?.abortSignal?.aborted) {
733
941
  return err(new ExecutionError("aborted", "aborted"));
734
942
  }
735
943
  const cwd = options?.cwd ? resolvePath(this.cwd, options.cwd) : this.cwd;
736
- const shellConfig = await getShellConfig(this.shellPath);
944
+ const shellConfig = await shellOf();
737
945
  if (!shellConfig.ok) {
738
946
  return shellConfig;
739
947
  }
@@ -842,7 +1050,7 @@ export class NodeExecutionEnv {
842
1050
  child = spawn(start.command, [...start.args], {
843
1051
  cwd,
844
1052
  detached: process.platform !== "win32",
845
- env: this.spawnEnv(options?.env),
1053
+ env: childEnvOf()(options?.env),
846
1054
  ...shellChildStdio(execSpoolFds, input !== undefined),
847
1055
  windowsHide: true,
848
1056
  });
@@ -1673,14 +1881,18 @@ export class NodeExecutionEnv {
1673
1881
  this.bgShells.set(shellId, entry);
1674
1882
  return shellId;
1675
1883
  }
1676
- async spawnBackground(command, options) {
1884
+ spawnBackground(command, options) {
1885
+ const start = modelStartAt(this, options);
1886
+ return NodeExecutionEnv.prototype[START_BACKGROUND].call(this, command, options, () => start?.shellOf() ?? getShellConfig(this.shellPath), () => start?.childEnvOf() ?? spawnEnvOf(this));
1887
+ }
1888
+ async [START_BACKGROUND](command, options, shellOf, childEnvOf) {
1677
1889
  const liveCount = [...this.bgShells.values()].filter((e) => e.status === "running").length;
1678
1890
  if (liveCount >= this.backgroundCapabilities.maxConcurrent) {
1679
1891
  return err(new BackgroundShellError("limit_exceeded", `Too many running background shells (max ${this.backgroundCapabilities.maxConcurrent}); TaskStop one first.`));
1680
1892
  }
1681
- const shellConfig = await getShellConfig(this.shellPath);
1893
+ const shellConfig = await shellOf();
1682
1894
  if (!shellConfig.ok) {
1683
- return err(new BackgroundShellError("spawn_failed", shellConfig.error.message, shellConfig.error));
1895
+ return err(Object.assign(new BackgroundShellError("spawn_failed", shellConfig.error.message, shellConfig.error), shellConfig.error.briefMessage !== undefined ? { briefMessage: shellConfig.error.briefMessage } : {}));
1684
1896
  }
1685
1897
  const start = await this.startOf(shellConfig.value, command, options);
1686
1898
  if (!start.ok)
@@ -1708,7 +1920,7 @@ export class NodeExecutionEnv {
1708
1920
  child = spawn(start.command, [...start.args], {
1709
1921
  cwd: options?.cwd ? resolvePath(this.cwd, options.cwd) : this.cwd,
1710
1922
  detached: process.platform !== "win32",
1711
- env: this.spawnEnv(options?.env),
1923
+ env: childEnvOf()(options?.env),
1712
1924
  ...shellChildStdio(spoolFds, false),
1713
1925
  windowsHide: true,
1714
1926
  });
@@ -752,6 +752,31 @@ export interface ExecutionEnv extends FileSystem, Shell {
752
752
  * hands it to the Runner's `onNotice` too, once per run, as each of its tool calls ends. Absent ⇒ the environment has not raised one, or
753
753
  * the adapter has no such refusal (a remote adapter omits it). A read: it announces nothing. */
754
754
  readonly lateDeclarationNotice?: import("../../core/engine-notice.js").EngineNotice;
755
+ /**
756
+ * The start for shell text a model wrote. The text is read, whole and unchanged, by the shell the environment started for it — in this version a bash (3.2 or later, not in POSIX mode); `ready` reports which shell it starts, `{ shell: "bash" | "zsh", version }`, from the candidate's own answer, and a start that reports zsh is not mounted in this version — with no start option or startup file of the environment's own that changes how the shell reads text — or nothing of it runs and the start fails with `shell_unavailable` (`exec`) / `spawn_failed` (`spawnBackground`). The question guards against a misconfigured candidate, not a hostile one: a candidate reports its own identity. Handing the text to any other shell is a defect of the environment. A wrapper forwards this member whole or not at all. The engine receives the member once per environment object — the first read that answers an object (the group) is kept, and every later reading and start on that environment uses that group, whose `exec` / `spawnBackground` / `ready` are still read off it at each start or reading — so a host that would hand another group gives another environment object.
757
+ */
758
+ readonly modelShell?: ExecutionEnvModelShell;
759
+ /** What the starts of {@link modelShell} did not pass to the model's shell (variables of `SHELL_STATE_ENV`), each variable once per source (`configured` or `inherited`); `more`
760
+ * says some were not kept. A record the run tells as `config.shell_state_env_dropped` as each tool call ends; absent ⇒ the adapter keeps none. */
761
+ readonly modelShellDropped?: {
762
+ readonly entries: readonly import("../../core/model-shell.js").DroppedShellState[];
763
+ readonly more: boolean;
764
+ };
765
+ }
766
+ /** The method group of {@link ExecutionEnv.modelShell}: the starts of model-written shell text, and whether the environment can make them. */
767
+ export interface ExecutionEnvModelShell {
768
+ /** Run `script` on the environment's bash, as {@link Shell.exec} runs a command: the same options, result and failure words. */
769
+ exec(script: string, options?: ExecutionEnvExecOptions): Promise<Result<ExecResult, ExecutionError>>;
770
+ /** Start `script` on the environment's bash in the background, as the background face's `spawnBackground` starts a command. Absent ⇒ this environment starts no model text in the background. */
771
+ spawnBackground?(script: string, options?: import("../../core/background-shell.js").BackgroundSpawnOptions): Promise<Result<{
772
+ shellId: import("../../core/background-shell.js").BackgroundShellId;
773
+ }, import("../../core/background-shell.js").BackgroundShellError>>;
774
+ /** Whether a start can be made: `ok` with the shell the starts run and its version as it reported them (not what a startup file the host process's own environment names would do), or the `shell_unavailable` failure every start would answer, naming why.
775
+ * A leg waits at most 5 s for it (a `ready` that blocks the thread synchronously is outside that bound). Absent ⇒ the environment answers for its starts without being asked. */
776
+ ready?(): Promise<Result<{
777
+ readonly shell: "bash" | "zsh";
778
+ readonly version: string;
779
+ }, ExecutionError>>;
755
780
  }
756
781
  /** Base fields shared by append-only session tree entries. */
757
782
  export interface SessionTreeEntryBase {
@@ -812,6 +812,14 @@ export interface ToolResultMessage<TDetails = unknown> {
812
812
  toolCallId: string;
813
813
  toolName: string;
814
814
  content: (TextContent | ImageContent | DocumentContent)[];
815
+ /**
816
+ * Per-tool metadata or engine-owned settlement marks persisted on the row. A call that never ran
817
+ * (`details.notExecuted === true`) whose `tool_end` frame carried a {@link GateOutcome} stores a structural copy as
818
+ * `details.gate` on the row the leg itself writes; a row written by recovery carries `notExecuted` without `gate`
819
+ * (absence = "not recorded", never "no gate judged it"). `gate` says what the gate decided, not why the call did
820
+ * not run. Absent on calls that ran. The engine drops a tool-written `details.gate` / `details.notExecuted` when
821
+ * writing a row; rows stored by earlier versions are not rewritten.
822
+ */
815
823
  details?: TDetails;
816
824
  isError: boolean;
817
825
  /** {@link RowRewrittenBy} */
@@ -6,5 +6,12 @@ export declare function validateToolCall(tools: Tool[], toolCall: ToolCall): unk
6
6
  export declare function toolNameIndex<T extends Tool>(tools: readonly T[] | undefined): (name: string) => T | undefined;
7
7
  /** VENDORED EDIT (design/115 P0): resolve canonical tool names first, then legacy aliases ({@link toolNameIndex} for one name). */
8
8
  export declare function findToolByName<T extends Tool>(tools: readonly T[] | undefined, name: string): T | undefined;
9
- /** Validates tool arguments against TypeBox or plain JSON-schema parameters. */
9
+ /**
10
+ * Validates tool arguments against TypeBox or plain JSON-schema parameters. A limit of the runtime met while the arguments are cloned, converted or
11
+ * checked ({@link runtimeLimitWords}) is a validation failure too — of the usual form, so every reader of the check treats it as one: the call was not
12
+ * run, and the sentence says the check ran into a limit of this runtime, not why (a deep value overflows the stack, a shallow one whose getter
13
+ * raises a length error ends the same way). The original rides on `cause` and the structured marks it carried (`details`, `errorKind`) stay on the
14
+ * error. No depth is refused: what validated before validates now. Every other error — any other class, a `RangeError` that is no limit — leaves as
15
+ * it was thrown.
16
+ */
10
17
  export declare function validateToolArguments(tool: Tool, toolCall: ToolCall): unknown;
@@ -1,6 +1,7 @@
1
1
  import { Compile } from "typebox/compile";
2
2
  import { Value } from "typebox/value";
3
3
  import { sliceHeadSafe } from "../../core/surrogate-safe-slice.js";
4
+ import { thrownIs, thrownMarksOf, thrownText } from "../../core/thrown-value.js";
4
5
  import { projectToolSchema } from "../../brain/tool-schema-projection.js";
5
6
  const validatorCache = new WeakMap();
6
7
  const TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
@@ -394,7 +395,33 @@ export function toolNameIndex(tools) {
394
395
  export function findToolByName(tools, name) {
395
396
  return toolNameIndex(tools)(name);
396
397
  }
398
+ const RUNTIME_LIMIT_PHRASES = [
399
+ "Maximum call stack size exceeded",
400
+ "Invalid array length",
401
+ "Invalid string length",
402
+ "Invalid array buffer length",
403
+ "Invalid typed array length",
404
+ "Array buffer allocation failed",
405
+ ];
406
+ function runtimeLimitWords(err) {
407
+ if (!thrownIs(err, RangeError))
408
+ return undefined;
409
+ const words = thrownText(err);
410
+ return RUNTIME_LIMIT_PHRASES.some((phrase) => words.startsWith(phrase)) ? words : undefined;
411
+ }
397
412
  export function validateToolArguments(tool, toolCall) {
413
+ try {
414
+ return checkToolArguments(tool, toolCall);
415
+ }
416
+ catch (err) {
417
+ const words = runtimeLimitWords(err);
418
+ if (words === undefined)
419
+ throw err;
420
+ const marks = thrownMarksOf(err);
421
+ throw Object.assign(new Error(validationFailureText(tool, toolCall, `- checking the arguments ran into a limit of this runtime (${words}); the call was not run`), { cause: err }), marks !== undefined ? { details: marks } : {});
422
+ }
423
+ }
424
+ function checkToolArguments(tool, toolCall) {
398
425
  const args = structuredClone(toolCall.arguments);
399
426
  Value.Convert(tool.parameters, args);
400
427
  const validator = getValidator(tool.parameters);
@@ -415,7 +442,9 @@ export function validateToolArguments(tool, toolCall) {
415
442
  if (validator.Check(args)) {
416
443
  return args;
417
444
  }
418
- const errors = synthesizeValidationIssues([...validator.Errors(args)], args);
445
+ throw new Error(validationFailureText(tool, toolCall, synthesizeValidationIssues([...validator.Errors(args)], args)));
446
+ }
447
+ function validationFailureText(tool, toolCall, body) {
419
448
  const schemaJson = (() => {
420
449
  try {
421
450
  const s = JSON.stringify(projectToolSchema(tool.parameters));
@@ -425,7 +454,7 @@ export function validateToolArguments(tool, toolCall) {
425
454
  return "(schema not serializable)";
426
455
  }
427
456
  })();
428
- throw new Error(`Validation failed for tool "${toolCall.name}":\n${errors}\n\nExpected parameter schema:\n${schemaJson}`);
457
+ return `Validation failed for tool "${toolCall.name}":\n${body}\n\nExpected parameter schema:\n${schemaJson}`;
429
458
  }
430
459
  const VALIDATION_ERROR_SCHEMA_MAX_CHARS = 4_000;
431
460
  const VALIDATION_ERROR_ISSUES_MAX_CHARS = 2_000;
@@ -13,5 +13,15 @@
13
13
  *
14
14
  * What this entry loads is the composition's own module graph (the credential vocabulary, the notice throat, the
15
15
  * member receipt), not the engine's.
16
+ *
17
+ * It also re-exports `judgeHookCondition` (plus its closed event and reason tables): the pure judge that tells a
18
+ * host's local hook selector whether an entry's `if` condition matches a tool call (definite answers for empty
19
+ * conditions, equal engine-catalog non-Monitor names without content, and strictly flat Bash commands; `untested`
20
+ * with a closed reason word everywhere else). Both its accuracy and its no-host-code promise for plain data hold
21
+ * in a realm whose built-in objects are as loaded; R-J catches a key added to, removed from, or reordered on
22
+ * `Object.prototype` or `Array.prototype` relative to module load (`untested:invalid_input`), while any other
23
+ * built-in modification, pre-load pollution, and cross-realm `null`-prototype exotic objects are outside the
24
+ * contract (`docs/KNOWN-LIMITS.md` KL-4994-a / KL-4994-b).
16
25
  */
17
26
  export { declareWithheldEnv, hostChildEnv, hostChildEnvProblem, inheritedHostEnv, inheritEnvPolicyProblem, type HostChildEnv, type HostChildInheritance, type InheritEnvPolicy, type SecretEnvFinding, type SecretEnvFindingKind, type WithheldEnvDeclaration, } from "./core/secret-env.js";
27
+ export { HOOK_CONDITION_EVENTS, HOOK_CONDITION_UNTESTED_REASONS, judgeHookCondition, type HookConditionInput, type HookConditionVerdict, } from "./core/hook-condition.js";
package/dist/host-env.js CHANGED
@@ -1 +1,2 @@
1
1
  export { declareWithheldEnv, hostChildEnv, hostChildEnvProblem, inheritedHostEnv, inheritEnvPolicyProblem, } from "./core/secret-env.js";
2
+ export { HOOK_CONDITION_EVENTS, HOOK_CONDITION_UNTESTED_REASONS, judgeHookCondition, } from "./core/hook-condition.js";
package/dist/index.d.ts CHANGED
@@ -91,6 +91,7 @@ export { askUnresolvableNotice, type AskUnresolvableFacts } from "./core/ask-unr
91
91
  export { ASK_UNRESOLVABLE_CAUSES, type AskUnresolvableCause } from "./core/ask-unresolvable-notice.js";
92
92
  export { WORKFLOW_PARK_GAPS, isWorkflowParkGap, type WorkflowParkGap } from "./core/ask-unresolvable-notice.js";
93
93
  export { TOOL_GATE_PHASES, type ToolGatePhase } from "./core/tool-gate-phase.js";
94
+ export { BRAIN_STATUS_SEATS } from "./core/tool-gate-phase.js";
94
95
  export type { ApprovalParkNotResumable } from "./core/park-resumability.js";
95
96
  export { APPROVAL_REMEDY_KINDS, type ApprovalRemedy, type ApprovalRemedyKind } from "./core/ask-origin.js";
96
97
  export { USER_INPUT_UNDRAINED_CAUSES, type UserInputUndrainedCause, USER_INPUT_UNDRAINED_FAMILIES } from "./core/engine-notice.js";
@@ -122,6 +123,7 @@ export { RESUME_AT_REFUSAL_CLASSES, RESUME_AT_REFUSAL_CLASS, isResumeAtAnchorMis
122
123
  export { RESUME_AT_OUTSIDE_WINDOW_REASONS, RESUME_AT_REMEDY_KINDS, type ResumeAtOutsideWindowDetail, type ResumeAtOutsideWindowReason, type ResumeAtRemedy, type ResumeAtRemedyKind } from "./core/resume-at-refusal.js";
123
124
  export { CONFIG_REFUSAL_INPUTS, type ConfigRefusalInput, isConfigRefusalInput, configRefusalInputOf } from "./core/config-refusal-input.js";
124
125
  export { CONFIG_REFUSAL_CODES, type ConfigRefusalCode } from "./core/config-refusal-codes.js";
126
+ export { REWIND_REFUSAL_CODES, type RewindRefusalCode } from "./core/rewind-refusal-codes.js";
125
127
  export { NOTICE_AUDIENCE, noticeAudienceOf, ENGINE_NOTICE_CODES, NOTICE_MINTER, NOTICE_ATTENTION, noticeAttentionOf, type EngineNoticeCode, type NoticeAudience, type NoticeMinter, type NoticeAttention } from "./core/governance-codes.js";
126
128
  export { NOTICE_CODE_LINEAGE, type NoticeCodeChange, type NoticeCodeBranch } from "./core/governance-codes.js";
127
129
  export { TtlSessionStore, type TtlSessionStoreOptions, type EvictPolicy } from "./core/session-store.js";
@@ -313,7 +315,8 @@ export { type ExistingTarget, type ExistingTargetKind, type ExistingTargetWithhe
313
315
  export { READ_ROOT_GRANT_LASTS, type ReadRootGrantScreen } from "./core/read-root-grant-screen.js";
314
316
  export { type AskOrigin, ASK_ORIGINS, isAskOrigin, ORIGIN_IMPLIES_REAL_APPROVAL, PERSISTED_RULE_MANDATES, type PersistedRuleMandate, isPersistedRuleMandate, screenAskClassMembers } from "./core/ask-origin.js";
315
317
  export { type AskReason, HOOK_QUESTION_CAUSES, type HookQuestionCause } from "./core/ask-origin.js";
316
- export { PERMISSION_MODES, type PermissionMode, isPermissionMode, PERMISSION_MODE_RANK, clampPermissionMode, ASK_CLASSES, type AskClass, isAskClass, MODE_ARBITRATION, type ModeArbitrationRow, ASK_FACES, type AskFace, askFaceOf, releasableAskClassesFor, MODE_RELEASE_REASONS, type ModeReleaseReason, isModeReleaseReason, RRA_EXPLAINERS, classifyAsk, foldArbitrationRow, type AskClassification, type AskClassFacts, type ToolMarkSource, arbitrateByMode, type Arbitration, fileCommandOptionsSentence } from "./core/ask-origin.js";
318
+ export { PERMISSION_MODES, type PermissionMode, isPermissionMode, PERMISSION_MODE_RANK, clampPermissionMode, ASK_CLASSES, type AskClass, isAskClass, MODE_ARBITRATION, type ModeArbitrationRow, ASK_FACES, type AskFace, askFaceOf, releasableAskClassesFor, MODE_RELEASE_REASONS, type ModeReleaseReason, isModeReleaseReason, RRA_EXPLAINERS, classifyAsk, foldArbitrationRow, type AskClassification, type AskClassFacts, type ToolMarkSource, arbitrateByMode, type Arbitration, fileCommandOptionsSentence, RELEASED_ON_CONFINED_RUNNER, confinedReleasableAskClassesFor, type ConfinedCall } from "./core/ask-origin.js";
319
+ export { DEPLOYMENT_SHAPES, type DeploymentShape } from "./core/deployment-shape.js";
317
320
  export { CROSS_BOUNDARY_TAINT_BITS, type CrossBoundaryTaintBit, CROSS_BOUNDARY_POSTURES, type CrossBoundaryPosture, BOUNDARY_LEGS, type BoundaryLeg, type BoundaryLegList, type BoundaryLegsDeclaration, type CrossBoundaryTree, type CrossBoundaryObligation, crossBoundaryObligation, CROSS_BOUNDARY_RECORD_TYPE, type CrossBoundaryRecordData, type CrossBoundaryRecordEntry, type CrossBoundaryRecordRead, readCrossBoundaryRecord, type BoundaryLegsFor, type BoundaryLegsGiven, type CrossBoundaryCall, type CrossBoundaryCheck, type CrossBoundaryExitRefusal, type CrossBoundaryTreeToken } from "./core/cross-boundary-taint.js";
318
321
  export { modePolicyOf, type ModePolicy, PERMISSION_MODE_FOLD_REASONS, type PermissionModeFoldReason, type PermissionModeReceipt, ACCEPT_EDITS_FILE_COMMANDS, modeAcceptsFileCommand, foldPermissionMode, type PermissionModeFold, type PermissionModeFoldInput, type PermissionModeArmingFacts, type PermissionModeStartWord } from "./core/mode-policy.js";
319
322
  export type { PermissionSeatInputs, PermissionSeatReading } from "./core/mode-policy.js";
@@ -558,7 +561,7 @@ export { builtinAgentDefinitions, BUILTIN_READONLY_DENY_TOOLS, EXPLORE_WHEN_TO_U
558
561
  export { createTaskServer, type TaskServerOptions, type TaskRequestBody, } from "./server/http.js";
559
562
  export { clearStaleToolResults, editBudget, type ContextEditOptions, } from "./core/context-edit.js";
560
563
  export { createOpenAIBrain, type OpenAIBrainConfig } from "./brain/openai.js";
561
- export { createAnthropicBrain, ANTHROPIC_DEFAULT_BASE_URL, type AnthropicBrainConfig } from "./brain/anthropic.js";
564
+ export { createAnthropicBrain, ANTHROPIC_DEFAULT_BASE_URL, anthropicCredentialHeadersOf, type AnthropicBrainConfig, type AnthropicCredentialHeaders } from "./brain/anthropic.js";
562
565
  export { createOpenResponsesBrain, type OpenResponsesBrainConfig } from "./brain/open-responses.js";
563
566
  export { FABLE_5_COMPAT, fable5Model } from "./brain/model-presets.js";
564
567
  export { REFERENCE_MODEL_PROMPT_TRAITS, referenceModelIdOf, referencePromptTraitsOf, type ReferenceModelId } from "./brain/reference-model-traits.js";
@@ -573,6 +576,7 @@ export { DEGRADE_REASONS, MODEL_FALLBACK_GATE_WORDS, DEFAULT_FALLBACK_GATE, type
573
576
  export { retryBackoffMs, parseRetryAfter } from "./brain/retry.js";
574
577
  export { WAITING_AFTER_MS, WAITING_EVERY_MS } from "./brain/stream-engine.js";
575
578
  export { adjudicateModelRoute, resolveRouteCredential, admitRouteRequest, rebindCredentialOrigin, type CredentialRebind, type CredentialRebindEntry, type CredentialRebindAlignment, type CredentialRebindOutcome, CREDENTIAL_REBIND_OUTCOMES, requestOriginOf, routeRefusalText, routePairingStatus, routeKeyOf, displayUrlOf, resolveRequestRoot, resolveRequestRootOf, joinRequestUrl, hasAuthCarrier, __resetCredentialOriginBindings, type RoutePairingStatus, } from "./brain/route-adjudicator.js";
579
+ export { ROUTE_PAIRING_STATUSES } from "./brain/route-adjudicator.js";
576
580
  export { ROUTE_CREDENTIAL_SOURCES, ROUTE_CARRIERS, ROUTE_CARRIER_BAGS, REQUEST_ROOT_ORIGINS, ROUTE_CREDENTIAL_PAIRING, requestRouteOf, routePairingRowOf, type RequestRoute, type RouteCarrier, type RouteCarrierBag, type RequestRootOrigin, type RouteCredentialPairingRow, } from "./brain/request-route.js";
577
581
  export type { RouteAdjudication, RouteCredential, RouteCredentialSource, RoutePairingConfig, RoutePairingPosture, RouteRefusalCode, RouteRefusalDetail, RouteUnavailableDetail, } from "./internal/llm.js";
578
582
  export { ROUTE_ADJUDICATION_CONFORMANCE_CORPUS, type RouteAdjudicationVector } from "./brain/route-conformance.js";
@@ -631,3 +635,7 @@ export { delegationOwnerSeat, type DelegationOwnerSeat, type DelegationOwnerRead
631
635
  export { CHECKPOINT_LIST_LIMITS, readCheckpointOverdueQuery, readCheckpointSessionQuery, readCheckpointDeleteGuard, checkpointDeadlinePassed, checkpointOverdueAt, checkpointRunSessionOf, storedCheckpointRowRefusal, checkpointRowUnreadable, isCheckpointRowUnreadable, deleteGuardAdmits, selectOverduePage, selectSessionPage, type CheckpointFacet, type CheckpointPage, type CheckpointOverdueQuery, type CheckpointOverdueCursor, type CheckpointOverdueQueryReading, type CheckpointSessionQuery, type CheckpointSessionCursor, type CheckpointSessionQueryReading, type CheckpointRowRead, type CheckpointDeleteGuard, } from "./core/checkpoint-queries.js";
632
636
  export { EXTERNAL_INCLUDE_POST_APPROVAL_BLOCKS, type ExternalIncludePostApprovalBlock, type InstructionIncludedEntry, type InstructionWithheldEntry, type WiringInstructions, type InstructionPreviewResult, } from "./core/instruction-preview.js";
633
637
  export { screenProjectSeat, type ProjectSeat, type ProjectSeatScreen } from "./core/project-seat.js";
638
+ export { HOOK_CONDITION_EVENTS, HOOK_CONDITION_UNTESTED_REASONS, judgeHookCondition, type HookConditionInput, type HookConditionVerdict } from "./core/hook-condition.js";
639
+ export { SHELL_STATE_ENV, shellStateEnvRowOf, type ShellStateEnvRow, type ShellStateInherited } from "./core/model-shell.js";
640
+ export type { ExecutionEnvModelShell } from "./internal/harness.js";
641
+ export { SHELL_KIND_QUESTION, SHELL_KIND_QUESTION_OPTIONS, hasModelShell, readShellKindAnswer, type DroppedShellState, type ShellKindAnswer } from "./core/model-shell.js";
package/dist/index.js CHANGED
@@ -72,6 +72,7 @@ export { askUnresolvableNotice } from "./core/ask-unresolvable-notice.js";
72
72
  export { ASK_UNRESOLVABLE_CAUSES } from "./core/ask-unresolvable-notice.js";
73
73
  export { WORKFLOW_PARK_GAPS, isWorkflowParkGap } from "./core/ask-unresolvable-notice.js";
74
74
  export { TOOL_GATE_PHASES } from "./core/tool-gate-phase.js";
75
+ export { BRAIN_STATUS_SEATS } from "./core/tool-gate-phase.js";
75
76
  export { APPROVAL_REMEDY_KINDS } from "./core/ask-origin.js";
76
77
  export { USER_INPUT_UNDRAINED_CAUSES, USER_INPUT_UNDRAINED_FAMILIES } from "./core/engine-notice.js";
77
78
  export { setDefaultEngineNoticeSeat } from "./core/engine-notice.js";
@@ -100,6 +101,7 @@ export { RESUME_AT_REFUSAL_CLASSES, RESUME_AT_REFUSAL_CLASS, isResumeAtAnchorMis
100
101
  export { RESUME_AT_OUTSIDE_WINDOW_REASONS, RESUME_AT_REMEDY_KINDS } from "./core/resume-at-refusal.js";
101
102
  export { CONFIG_REFUSAL_INPUTS, isConfigRefusalInput, configRefusalInputOf } from "./core/config-refusal-input.js";
102
103
  export { CONFIG_REFUSAL_CODES } from "./core/config-refusal-codes.js";
104
+ export { REWIND_REFUSAL_CODES } from "./core/rewind-refusal-codes.js";
103
105
  export { NOTICE_AUDIENCE, noticeAudienceOf, ENGINE_NOTICE_CODES, NOTICE_MINTER, NOTICE_ATTENTION, noticeAttentionOf } from "./core/governance-codes.js";
104
106
  export { NOTICE_CODE_LINEAGE } from "./core/governance-codes.js";
105
107
  export { TtlSessionStore } from "./core/session-store.js";
@@ -247,7 +249,8 @@ export { EXISTING_TARGET_KINDS, EXISTING_TARGET_WITHHELD_REASONS, EXISTING_TARGE
247
249
  export { READ_ROOT_GRANT_LASTS } from "./core/read-root-grant-screen.js";
248
250
  export { ASK_ORIGINS, isAskOrigin, ORIGIN_IMPLIES_REAL_APPROVAL, PERSISTED_RULE_MANDATES, isPersistedRuleMandate, screenAskClassMembers } from "./core/ask-origin.js";
249
251
  export { HOOK_QUESTION_CAUSES } from "./core/ask-origin.js";
250
- export { PERMISSION_MODES, isPermissionMode, PERMISSION_MODE_RANK, clampPermissionMode, ASK_CLASSES, isAskClass, MODE_ARBITRATION, ASK_FACES, askFaceOf, releasableAskClassesFor, MODE_RELEASE_REASONS, isModeReleaseReason, RRA_EXPLAINERS, classifyAsk, foldArbitrationRow, arbitrateByMode, fileCommandOptionsSentence } from "./core/ask-origin.js";
252
+ export { PERMISSION_MODES, isPermissionMode, PERMISSION_MODE_RANK, clampPermissionMode, ASK_CLASSES, isAskClass, MODE_ARBITRATION, ASK_FACES, askFaceOf, releasableAskClassesFor, MODE_RELEASE_REASONS, isModeReleaseReason, RRA_EXPLAINERS, classifyAsk, foldArbitrationRow, arbitrateByMode, fileCommandOptionsSentence, RELEASED_ON_CONFINED_RUNNER, confinedReleasableAskClassesFor } from "./core/ask-origin.js";
253
+ export { DEPLOYMENT_SHAPES } from "./core/deployment-shape.js";
251
254
  export { CROSS_BOUNDARY_TAINT_BITS, CROSS_BOUNDARY_POSTURES, BOUNDARY_LEGS, crossBoundaryObligation, CROSS_BOUNDARY_RECORD_TYPE, readCrossBoundaryRecord } from "./core/cross-boundary-taint.js";
252
255
  export { modePolicyOf, PERMISSION_MODE_FOLD_REASONS, ACCEPT_EDITS_FILE_COMMANDS, modeAcceptsFileCommand, foldPermissionMode } from "./core/mode-policy.js";
253
256
  export { SKILL_GRANT_ORIGINS } from "./core/skill-grant.js";
@@ -454,7 +457,7 @@ export { builtinAgentDefinitions, BUILTIN_READONLY_DENY_TOOLS, EXPLORE_WHEN_TO_U
454
457
  export { createTaskServer, } from "./server/http.js";
455
458
  export { clearStaleToolResults, editBudget, } from "./core/context-edit.js";
456
459
  export { createOpenAIBrain } from "./brain/openai.js";
457
- export { createAnthropicBrain, ANTHROPIC_DEFAULT_BASE_URL } from "./brain/anthropic.js";
460
+ export { createAnthropicBrain, ANTHROPIC_DEFAULT_BASE_URL, anthropicCredentialHeadersOf } from "./brain/anthropic.js";
458
461
  export { createOpenResponsesBrain } from "./brain/open-responses.js";
459
462
  export { FABLE_5_COMPAT, fable5Model } from "./brain/model-presets.js";
460
463
  export { REFERENCE_MODEL_PROMPT_TRAITS, referenceModelIdOf, referencePromptTraitsOf } from "./brain/reference-model-traits.js";
@@ -469,6 +472,7 @@ export { DEGRADE_REASONS, MODEL_FALLBACK_GATE_WORDS, DEFAULT_FALLBACK_GATE } fro
469
472
  export { retryBackoffMs, parseRetryAfter } from "./brain/retry.js";
470
473
  export { WAITING_AFTER_MS, WAITING_EVERY_MS } from "./brain/stream-engine.js";
471
474
  export { adjudicateModelRoute, resolveRouteCredential, admitRouteRequest, rebindCredentialOrigin, CREDENTIAL_REBIND_OUTCOMES, requestOriginOf, routeRefusalText, routePairingStatus, routeKeyOf, displayUrlOf, resolveRequestRoot, resolveRequestRootOf, joinRequestUrl, hasAuthCarrier, __resetCredentialOriginBindings, } from "./brain/route-adjudicator.js";
475
+ export { ROUTE_PAIRING_STATUSES } from "./brain/route-adjudicator.js";
472
476
  export { ROUTE_CREDENTIAL_SOURCES, ROUTE_CARRIERS, ROUTE_CARRIER_BAGS, REQUEST_ROOT_ORIGINS, ROUTE_CREDENTIAL_PAIRING, requestRouteOf, routePairingRowOf, } from "./brain/request-route.js";
473
477
  export { ROUTE_ADJUDICATION_CONFORMANCE_CORPUS } from "./brain/route-conformance.js";
474
478
  export {} from "./brain/timeout.js";
@@ -515,3 +519,6 @@ export { delegationOwnerSeat } from "./core/runner/delegation-owner.js";
515
519
  export { CHECKPOINT_LIST_LIMITS, readCheckpointOverdueQuery, readCheckpointSessionQuery, readCheckpointDeleteGuard, checkpointDeadlinePassed, checkpointOverdueAt, checkpointRunSessionOf, storedCheckpointRowRefusal, checkpointRowUnreadable, isCheckpointRowUnreadable, deleteGuardAdmits, selectOverduePage, selectSessionPage, } from "./core/checkpoint-queries.js";
516
520
  export { EXTERNAL_INCLUDE_POST_APPROVAL_BLOCKS, } from "./core/instruction-preview.js";
517
521
  export { screenProjectSeat } from "./core/project-seat.js";
522
+ export { HOOK_CONDITION_EVENTS, HOOK_CONDITION_UNTESTED_REASONS, judgeHookCondition } from "./core/hook-condition.js";
523
+ export { SHELL_STATE_ENV, shellStateEnvRowOf } from "./core/model-shell.js";
524
+ export { SHELL_KIND_QUESTION, SHELL_KIND_QUESTION_OPTIONS, hasModelShell, readShellKindAnswer } from "./core/model-shell.js";
@@ -9,7 +9,7 @@ export type { InvokedSkillRetention } from "../engine/compaction/utils.js";
9
9
  export type { AgentCoreRuntimeDeps } from "../engine/loop/runtime-deps.js";
10
10
  export type { LoopTerminalReason } from "../engine/loop/agent-loop.js";
11
11
  export type { AgentMessage, AgentTool, AgentToolResult, AgentToolUpdateCallback, ThinkingLevel, ToolExecutionMode, ToolInputValidationContext, ToolInputVerdict, } from "../engine/loop/types.js";
12
- export type { AgentHarnessEvent, CompactionSettings, ExecutionEnv, ExecutionErrorCode, FileError, FileKind, FileErrorCode, FileInfo, Result, WriteExpectation, WriteReceipt, SymlinkChain, BoundFileObject, Session, SessionCheckoutCell, SessionCheckoutDeclared, SessionCheckoutRecord, SessionCheckoutSource, SessionCheckoutStand, SessionMetadata, SessionRepo, SessionStorage, SessionTreeEntry, Skill, } from "../engine/harness/types.js";
12
+ export type { AgentHarnessEvent, CompactionSettings, ExecutionEnv, ExecutionEnvModelShell, ExecutionErrorCode, FileError, FileKind, FileErrorCode, FileInfo, Result, WriteExpectation, WriteReceipt, SymlinkChain, BoundFileObject, Session, SessionCheckoutCell, SessionCheckoutDeclared, SessionCheckoutRecord, SessionCheckoutSource, SessionCheckoutStand, SessionMetadata, SessionRepo, SessionStorage, SessionTreeEntry, Skill, } from "../engine/harness/types.js";
13
13
  export type { ExecutionEnvExecOptions, ExecResult, ReadFloor, ExecutionEnvCapabilities } from "../engine/harness/types.js";
14
14
  export type { SessionWriteOptions, CompactionEntry } from "../engine/harness/types.js";
15
15
  export type { RowAdmission, RowRaising } from "../engine/harness/types.js";
@@ -173,7 +173,7 @@ export async function runGoal(runner, spec, internals) {
173
173
  }
174
174
  let verdict;
175
175
  try {
176
- verdict = await raceAbortReject(spec.doneCheck({ result, iteration, sessionId, cumulativeTokens }, goalSignal), goalSignal);
176
+ verdict = await raceAbortReject(spec.doneCheck({ result, iteration, sessionId: result.sessionId, cumulativeTokens }, goalSignal), goalSignal);
177
177
  }
178
178
  catch {
179
179
  const s = classifyStop();
@@ -94,7 +94,16 @@ export function buildWorkflowPrimitives(ctx, governance, onAgentSpawn, parentChe
94
94
  };
95
95
  return {
96
96
  agent,
97
- parallel: (thunks) => ctx.parallel(thunks),
97
+ parallel: async (thunks, opts) => {
98
+ if (opts === null || typeof opts !== "object") {
99
+ return ctx.parallel(thunks, undefined);
100
+ }
101
+ const errors = opts.errors;
102
+ if (errors !== undefined && !Array.isArray(errors)) {
103
+ throw new TypeError("parallel: opts.errors must be an array");
104
+ }
105
+ return ctx.parallel(thunks, errors !== undefined ? { errors } : undefined);
106
+ },
98
107
  pipeline: (items, ...stages) => ctx.pipeline(items, ...stages),
99
108
  phase: (title, body) => ctx.phase(title, body),
100
109
  log: (message) => ctx.log(message),
@@ -90,8 +90,8 @@ export interface WorkflowPrimitives {
90
90
  /** Spawn one governed sub-agent. `spec` is an UNTRUSTED `WorkflowAgentSpec` (whitelist-constructed by the
91
91
  * engine, design/98 §2.5); `opts` carries `label`/`phase`/`schema`. Resolves to the task result. */
92
92
  agent(spec: unknown, opts?: unknown): Promise<unknown>;
93
- /** Run thunks concurrently (BARRIER); a thrown thunk resolves to `null`. */
94
- parallel(thunks: unknown[]): Promise<unknown[]>;
93
+ /** Run thunks concurrently (BARRIER); a thrown thunk resolves to `null`. `opts.errors`, an array, collects one entry per failed slot. */
94
+ parallel(thunks: unknown[], opts?: unknown): Promise<unknown[]>;
95
95
  /** Run each item through all stages independently (no barrier between stages). */
96
96
  pipeline(items: unknown[], ...stages: unknown[]): Promise<unknown[]>;
97
97
  /** Group work under a named phase (observability). */