@code-yeongyu/senpi-agent-core 2026.11.3-3 → 2026.11.5-1

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 (167) hide show
  1. package/dist/agent-loop.js +20 -186
  2. package/dist/agent.d.ts +4 -0
  3. package/dist/agent.js +4 -0
  4. package/dist/conformance/index.d.ts +30 -0
  5. package/dist/conformance/index.js +21 -0
  6. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  7. package/dist/conformance/loop-core-manifest.js +18 -0
  8. package/dist/conformance/registry.js +20 -18
  9. package/dist/egress/types.d.ts +102 -0
  10. package/dist/egress/types.js +7 -0
  11. package/dist/execution/canonical-digest.d.ts +10 -0
  12. package/dist/execution/canonical-digest.js +20 -0
  13. package/dist/execution/canonical-json.d.ts +3 -0
  14. package/dist/execution/canonical-json.js +12 -0
  15. package/dist/execution/chain-count.d.ts +26 -0
  16. package/dist/execution/chain-count.js +45 -0
  17. package/dist/execution/coordinator-codec.js +13 -2
  18. package/dist/execution/coordinator-consent.d.ts +29 -0
  19. package/dist/execution/coordinator-consent.js +63 -0
  20. package/dist/execution/coordinator-plan.d.ts +1 -2
  21. package/dist/execution/coordinator-plan.js +4 -17
  22. package/dist/execution/coordinator-sequential.d.ts +15 -0
  23. package/dist/execution/coordinator-sequential.js +34 -0
  24. package/dist/execution/coordinator-types.d.ts +45 -0
  25. package/dist/execution/coordinator.d.ts +3 -1
  26. package/dist/execution/coordinator.js +35 -3
  27. package/dist/execution/device-files-node.d.ts +8 -0
  28. package/dist/execution/device-files-node.js +150 -0
  29. package/dist/execution/device-files.d.ts +109 -0
  30. package/dist/execution/device-files.js +124 -0
  31. package/dist/execution/ledger-types.d.ts +3 -1
  32. package/dist/execution/ledger.d.ts +9 -3
  33. package/dist/execution/ledger.js +8 -2
  34. package/dist/execution/loop-hook-host-hand.d.ts +33 -0
  35. package/dist/execution/loop-hook-host-hand.js +71 -0
  36. package/dist/execution/loop-hook-host-protocol.d.ts +46 -0
  37. package/dist/execution/loop-hook-host-protocol.js +47 -0
  38. package/dist/execution/loop-hook-host.d.ts +40 -0
  39. package/dist/execution/loop-hook-host.js +87 -0
  40. package/dist/execution/nested-codec.d.ts +5 -0
  41. package/dist/execution/nested-codec.js +41 -0
  42. package/dist/execution/nested-types.d.ts +92 -0
  43. package/dist/execution/nested-types.js +3 -0
  44. package/dist/execution/nested.d.ts +48 -0
  45. package/dist/execution/nested.js +206 -0
  46. package/dist/execution/plane-model.d.ts +33 -0
  47. package/dist/execution/plane-model.js +80 -0
  48. package/dist/execution/plane-session.d.ts +56 -0
  49. package/dist/execution/plane-session.js +178 -0
  50. package/dist/execution/plane.d.ts +75 -0
  51. package/dist/execution/plane.js +172 -0
  52. package/dist/execution/prepared/executor-body.d.ts +22 -0
  53. package/dist/execution/prepared/executor-body.js +73 -0
  54. package/dist/execution/prepared/executor-freeze.d.ts +17 -0
  55. package/dist/execution/prepared/executor-freeze.js +42 -0
  56. package/dist/execution/prepared/executor-pipeline.d.ts +11 -0
  57. package/dist/execution/prepared/executor-pipeline.js +26 -0
  58. package/dist/execution/prepared/executor-types.d.ts +131 -0
  59. package/dist/execution/prepared/executor-types.js +2 -0
  60. package/dist/execution/prepared/executor.d.ts +8 -0
  61. package/dist/execution/prepared/executor.js +261 -0
  62. package/dist/execution/prepared/memory-batch-store.d.ts +4 -0
  63. package/dist/execution/prepared/memory-batch-store.js +4 -0
  64. package/dist/execution/prepared/pipeline-prepared-batch.d.ts +27 -0
  65. package/dist/execution/prepared/pipeline-prepared-batch.js +175 -0
  66. package/dist/execution/prepared/pipeline-prepared.d.ts +10 -0
  67. package/dist/execution/prepared/pipeline-prepared.js +54 -0
  68. package/dist/execution/remote-device-files.d.ts +12 -0
  69. package/dist/execution/remote-device-files.js +113 -0
  70. package/dist/execution/remote-epoch-gate.d.ts +19 -0
  71. package/dist/execution/remote-epoch-gate.js +46 -0
  72. package/dist/execution/remote-epoch.d.ts +53 -0
  73. package/dist/execution/remote-epoch.js +74 -0
  74. package/dist/execution/remote-executor.d.ts +17 -0
  75. package/dist/execution/remote-executor.js +70 -18
  76. package/dist/execution/remote-file-call.d.ts +14 -0
  77. package/dist/execution/remote-file-call.js +31 -0
  78. package/dist/execution/remote-hand-ledger.d.ts +11 -3
  79. package/dist/execution/remote-hand-ledger.js +31 -15
  80. package/dist/execution/remote-link.d.ts +41 -0
  81. package/dist/execution/remote-link.js +153 -0
  82. package/dist/execution/remote-protocol.d.ts +50 -4
  83. package/dist/execution/remote-protocol.js +48 -2
  84. package/dist/execution/remote-tool-host.d.ts +23 -3
  85. package/dist/execution/remote-tool-host.js +25 -64
  86. package/dist/execution/scope-lifecycle.d.ts +81 -0
  87. package/dist/execution/scope-lifecycle.js +173 -0
  88. package/dist/execution/testing/batch-executor.js +32 -3
  89. package/dist/execution/testing/batch-harness.d.ts +25 -3
  90. package/dist/execution/testing/batch-harness.js +83 -5
  91. package/dist/execution/testing/cancel-cases.d.ts +8 -0
  92. package/dist/execution/testing/cancel-cases.js +64 -0
  93. package/dist/execution/testing/consent-cases.d.ts +14 -0
  94. package/dist/execution/testing/consent-cases.js +66 -0
  95. package/dist/execution/testing/epoch-cases.d.ts +8 -0
  96. package/dist/execution/testing/epoch-cases.js +84 -0
  97. package/dist/execution/testing/epoch-harness.d.ts +47 -0
  98. package/dist/execution/testing/epoch-harness.js +172 -0
  99. package/dist/execution/testing/epoch-registry.d.ts +3 -0
  100. package/dist/execution/testing/epoch-registry.js +17 -0
  101. package/dist/execution/testing/hand-harness.d.ts +3 -0
  102. package/dist/execution/testing/hand-harness.js +27 -22
  103. package/dist/execution/testing/hand-registry.d.ts +3 -0
  104. package/dist/execution/testing/hand-registry.js +20 -0
  105. package/dist/execution/testing/kill-epoch.d.ts +9 -0
  106. package/dist/execution/testing/kill-epoch.js +71 -0
  107. package/dist/execution/testing/kill-hook.d.ts +14 -0
  108. package/dist/execution/testing/kill-hook.js +117 -0
  109. package/dist/execution/testing/kill-nest.d.ts +6 -0
  110. package/dist/execution/testing/kill-nest.js +55 -0
  111. package/dist/execution/testing/kill-wakex.d.ts +6 -0
  112. package/dist/execution/testing/kill-wakex.js +81 -0
  113. package/dist/execution/testing/lifecycle-cases.d.ts +9 -0
  114. package/dist/execution/testing/lifecycle-cases.js +60 -0
  115. package/dist/execution/testing/lifecycle-registry.d.ts +3 -0
  116. package/dist/execution/testing/lifecycle-registry.js +19 -0
  117. package/dist/execution/testing/multi-epoch-cases.d.ts +4 -0
  118. package/dist/execution/testing/multi-epoch-cases.js +29 -0
  119. package/dist/execution/testing/multi-lifecycle-cases.d.ts +4 -0
  120. package/dist/execution/testing/multi-lifecycle-cases.js +34 -0
  121. package/dist/execution/testing/multi-seq-cases.d.ts +4 -0
  122. package/dist/execution/testing/multi-seq-cases.js +46 -0
  123. package/dist/execution/testing/nest-cases.d.ts +39 -0
  124. package/dist/execution/testing/nest-cases.js +181 -0
  125. package/dist/execution/testing/nest-registry.d.ts +3 -0
  126. package/dist/execution/testing/nest-registry.js +27 -0
  127. package/dist/execution/testing/scope-cases.d.ts +6 -0
  128. package/dist/execution/testing/scope-cases.js +49 -0
  129. package/dist/execution/testing/seq-cases.d.ts +6 -0
  130. package/dist/execution/testing/seq-cases.js +71 -0
  131. package/dist/execution/testing/seq-registry.d.ts +3 -0
  132. package/dist/execution/testing/seq-registry.js +32 -0
  133. package/dist/execution/testing/wake-exec-cases.d.ts +20 -0
  134. package/dist/execution/testing/wake-exec-cases.js +147 -0
  135. package/dist/execution/testing/wake-registry.d.ts +3 -0
  136. package/dist/execution/testing/wake-registry.js +26 -0
  137. package/dist/execution/tool-host.d.ts +23 -3
  138. package/dist/execution/tool-host.js +18 -1
  139. package/dist/execution/tool-outcome-events.d.ts +11 -0
  140. package/dist/execution/tool-outcome-events.js +47 -0
  141. package/dist/execution/wake-inbox.d.ts +25 -0
  142. package/dist/execution/wake-inbox.js +85 -0
  143. package/dist/execution/wake-outbox.d.ts +30 -0
  144. package/dist/execution/wake-outbox.js +87 -0
  145. package/dist/execution/wake-types.d.ts +45 -0
  146. package/dist/execution/wake-types.js +3 -0
  147. package/dist/harness/agent-harness.d.ts +6 -0
  148. package/dist/harness/execution/tool-host-call.d.ts +13 -0
  149. package/dist/harness/execution/tool-host-call.js +55 -0
  150. package/dist/harness/execution/tools.d.ts +2 -1
  151. package/dist/harness/execution/tools.js +32 -17
  152. package/dist/harness/runtime/drive/tools.js +1 -1
  153. package/dist/harness/runtime/harness.js +1 -0
  154. package/dist/harness/runtime/types.d.ts +1 -0
  155. package/dist/index.d.ts +27 -2
  156. package/dist/index.js +24 -1
  157. package/dist/node.d.ts +1 -0
  158. package/dist/node.js +1 -0
  159. package/dist/public-entry.d.ts +10 -0
  160. package/dist/public-entry.js +23 -0
  161. package/dist/step-commit.d.ts +24 -0
  162. package/dist/step-commit.js +24 -0
  163. package/dist/tool-name-alias.d.ts +1 -7
  164. package/dist/tool-name-alias.js +0 -17
  165. package/dist/transport/testing/multi-cases.js +8 -8
  166. package/dist/types.d.ts +37 -1
  167. package/package.json +3 -3
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The hop count of a thread chain (brain/hand split, decision K8): session A's thread tool prompts session B, B's
3
+ * prompts A again, and so on. A→B→A is allowed. Each call carries the count of the hop it makes; a session started by
4
+ * a thread call is at that call's count, and its own thread calls carry one more. The only limit is a count the user
5
+ * sets; unset means unlimited. There is no cost limit, no hidden default and no refusal for coming back to an origin.
6
+ */
7
+ /** The refusal reason of a thread call past the user's count limit. */
8
+ export declare const CHAIN_COUNT_LIMIT = "chain_count_limit";
9
+ /** A user-started session is at count 0; its first thread call is hop 1. */
10
+ export declare const CHAIN_ORIGIN = 0;
11
+ export declare class ChainCountLimitError extends Error {
12
+ readonly reason = "chain_count_limit";
13
+ readonly count: number;
14
+ readonly limit: number;
15
+ constructor(count: number, limit: number);
16
+ }
17
+ /** The count a thread call sent from a session at `sessionCount` carries. */
18
+ export declare function nextChainCount(sessionCount: number): number;
19
+ /** Parses the count a thread call carries; absent means the call starts a chain (hop 1 from a user-started session). */
20
+ export declare function decodeChainCount(value: unknown): number;
21
+ /**
22
+ * Admits a thread call that makes its chain `count` hops long. `readLimit` is read at each admission, never cached
23
+ * (on the CLI: the user's `threads.chainCountLimit` setting); `undefined` admits every call at any length.
24
+ */
25
+ export declare function admitChainCall(count: number, readLimit: () => number | undefined): number;
26
+ //# sourceMappingURL=chain-count.d.ts.map
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The hop count of a thread chain (brain/hand split, decision K8): session A's thread tool prompts session B, B's
3
+ * prompts A again, and so on. A→B→A is allowed. Each call carries the count of the hop it makes; a session started by
4
+ * a thread call is at that call's count, and its own thread calls carry one more. The only limit is a count the user
5
+ * sets; unset means unlimited. There is no cost limit, no hidden default and no refusal for coming back to an origin.
6
+ */
7
+ /** The refusal reason of a thread call past the user's count limit. */
8
+ export const CHAIN_COUNT_LIMIT = "chain_count_limit";
9
+ /** A user-started session is at count 0; its first thread call is hop 1. */
10
+ export const CHAIN_ORIGIN = 0;
11
+ export class ChainCountLimitError extends Error {
12
+ constructor(count, limit) {
13
+ super(`This thread call would be hop ${count} of its chain; your thread chain count limit is ${limit}.`);
14
+ this.reason = CHAIN_COUNT_LIMIT;
15
+ this.name = "ChainCountLimitError";
16
+ this.count = count;
17
+ this.limit = limit;
18
+ }
19
+ }
20
+ const isCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
21
+ /** The count a thread call sent from a session at `sessionCount` carries. */
22
+ export function nextChainCount(sessionCount) {
23
+ if (!isCount(sessionCount))
24
+ throw new TypeError(`not a chain count: ${String(sessionCount)}`);
25
+ return sessionCount + 1;
26
+ }
27
+ /** Parses the count a thread call carries; absent means the call starts a chain (hop 1 from a user-started session). */
28
+ export function decodeChainCount(value) {
29
+ if (value === undefined)
30
+ return nextChainCount(CHAIN_ORIGIN);
31
+ if (!isCount(value) || value === CHAIN_ORIGIN)
32
+ throw new TypeError(`malformed chain count: ${JSON.stringify(value)}`);
33
+ return value;
34
+ }
35
+ /**
36
+ * Admits a thread call that makes its chain `count` hops long. `readLimit` is read at each admission, never cached
37
+ * (on the CLI: the user's `threads.chainCountLimit` setting); `undefined` admits every call at any length.
38
+ */
39
+ export function admitChainCall(count, readLimit) {
40
+ const limit = readLimit();
41
+ if (limit !== undefined && count > limit)
42
+ throw new ChainCountLimitError(count, limit);
43
+ return count;
44
+ }
45
+ //# sourceMappingURL=chain-count.js.map
@@ -35,6 +35,7 @@ function prepareReply(value) {
35
35
  return false;
36
36
  switch (value.kind) {
37
37
  case "prepared":
38
+ case "prepared_awaiting_consent":
38
39
  return typeof value.frozenDigest === "string";
39
40
  case "blocked":
40
41
  return value.result !== undefined;
@@ -62,12 +63,22 @@ function callOutcome(value) {
62
63
  return false;
63
64
  }
64
65
  }
66
+ function consentRecord(value) {
67
+ return (object(value) &&
68
+ (value.gate === "raw" || value.gate === "frozen") &&
69
+ typeof value.digest === "string" &&
70
+ (value.answer === "approved" || value.answer === "denied" || value.answer === "expired"));
71
+ }
65
72
  function record(value) {
66
73
  if (!object(value) || !manifest(value.manifest))
67
74
  return false;
68
75
  const size = value.manifest.calls.length;
69
- const { prepares, released, outcomes, decision } = value;
70
- return ((decision === null || decision === "RELEASE" || decision === "ABORT") &&
76
+ const { prepares, released, outcomes, decision, consents } = value;
77
+ return ((consents === undefined ||
78
+ (Array.isArray(consents) &&
79
+ consents.length === size &&
80
+ consents.every((entry) => entry === null || consentRecord(entry)))) &&
81
+ (decision === null || decision === "RELEASE" || decision === "ABORT") &&
71
82
  Array.isArray(prepares) &&
72
83
  prepares.length === size &&
73
84
  prepares.every((reply) => reply === null || prepareReply(reply)) &&
@@ -0,0 +1,29 @@
1
+ import type { BatchConsent, BatchExecutor, ConsentRecord, ExecutionRef, ManifestCall, PrepareReply } from "./coordinator-types.ts";
2
+ /** What a call needs from the consent port, and how an answer is recorded before the step it decides. */
3
+ export interface ConsentStep {
4
+ readonly consent: BatchConsent;
5
+ readonly executor: BatchExecutor;
6
+ readonly ref: ExecutionRef;
7
+ readonly call: ManifestCall;
8
+ readonly leaseUntil: number;
9
+ /** The call's answered consent, if one is durable. */
10
+ readonly recorded: ConsentRecord | null;
11
+ readonly record: (answer: ConsentRecord) => Promise<void>;
12
+ }
13
+ /**
14
+ * Gate A, before preparation: a raw call that needs consent is prepared only after an approval of its request digest,
15
+ * which the executor then treats as authorized. A refusal ran nothing, so it is a blocked per-call result.
16
+ */
17
+ export declare function gateRawCall(step: ConsentStep): Promise<{
18
+ readonly blocked: PrepareReply;
19
+ } | {
20
+ readonly authorizedDigest?: string;
21
+ }>;
22
+ /**
23
+ * Gate B, after preparation: the approval binds the frozen digest and the executor releases without rerunning hooks.
24
+ * A denial is a blocked per-call result; an expiry (or an approval the lease already outran) settles the call
25
+ * `lease_expired` at the endpoint, which ABORTs the batch's unreleased calls. Nothing is ever prepared again: no
26
+ * automatic successor.
27
+ */
28
+ export declare function resolveFrozenConsent(step: ConsentStep, frozenDigest: string): Promise<PrepareReply>;
29
+ //# sourceMappingURL=coordinator-consent.d.ts.map
@@ -0,0 +1,63 @@
1
+ const denied = (gate, answer) => ({
2
+ kind: "blocked",
3
+ result: { reason: "consent_denied", gate, answer },
4
+ });
5
+ /** The executor no longer knows a call it prepared (design 5.6.2 "a lost prepared execution"): uncertain, never rerun. */
6
+ const lost = { reason: "uncertain", hooksRan: true, uncertain: true };
7
+ /**
8
+ * The approver reports the lease ran out while the call awaited Gate B. Nothing is sent to the executor: its own lease
9
+ * clock settles the call `lease_expired` (an abort would record `cancelled` while its clock is behind the brain's).
10
+ */
11
+ const expired = { reason: "lease_expired", hooksRan: true, uncertain: true };
12
+ async function answer(step, gate, digest) {
13
+ const { recorded } = step;
14
+ if (recorded !== null && recorded.gate === gate && recorded.digest === digest)
15
+ return recorded.answer;
16
+ const given = await step.consent.approve({
17
+ ...step.ref,
18
+ gate,
19
+ digest,
20
+ name: step.call.name,
21
+ leaseUntil: step.leaseUntil,
22
+ });
23
+ await step.record({ gate, digest, answer: given });
24
+ return given;
25
+ }
26
+ /**
27
+ * Gate A, before preparation: a raw call that needs consent is prepared only after an approval of its request digest,
28
+ * which the executor then treats as authorized. A refusal ran nothing, so it is a blocked per-call result.
29
+ */
30
+ export async function gateRawCall(step) {
31
+ const { call } = step;
32
+ if (!step.consent.needsConsent({ name: call.name, args: call.args }))
33
+ return {};
34
+ const given = await answer(step, "raw", call.requestDigest);
35
+ return given === "approved" ? { authorizedDigest: call.requestDigest } : { blocked: denied("raw", given) };
36
+ }
37
+ /**
38
+ * Gate B, after preparation: the approval binds the frozen digest and the executor releases without rerunning hooks.
39
+ * A denial is a blocked per-call result; an expiry (or an approval the lease already outran) settles the call
40
+ * `lease_expired` at the endpoint, which ABORTs the batch's unreleased calls. Nothing is ever prepared again: no
41
+ * automatic successor.
42
+ */
43
+ export async function resolveFrozenConsent(step, frozenDigest) {
44
+ const given = await answer(step, "frozen", frozenDigest);
45
+ if (given === "denied") {
46
+ await step.executor.abort(step.ref);
47
+ return denied("frozen", given);
48
+ }
49
+ if (given === "expired")
50
+ return { kind: "settled", outcome: expired };
51
+ const reply = await consentOn(step.executor, step.ref, frozenDigest);
52
+ if (reply.kind === "prepared")
53
+ return { kind: "prepared", frozenDigest };
54
+ if (reply.kind === "unknown_execution")
55
+ return { kind: "settled", outcome: lost };
56
+ return { kind: "settled", outcome: reply.outcome };
57
+ }
58
+ function consentOn(executor, ref, frozenDigest) {
59
+ if (executor.consent === undefined)
60
+ throw new Error(`executor answered prepared_awaiting_consent for ${ref.executionId} but cannot take consent`);
61
+ return executor.consent(ref, frozenDigest);
62
+ }
63
+ //# sourceMappingURL=coordinator-consent.js.map
@@ -1,7 +1,6 @@
1
1
  import type { BatchManifest, BatchPlan, CallOutcome, PrepareReply, SettleReply } from "./coordinator-types.ts";
2
2
  /**
3
- * Release dependencies exactly as today's scheduler assigns them (agent-loop.ts, executeToolCallsParallel): a
4
- * sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
3
+ * Release dependencies exactly as the agent loop has always ordered a batch: a sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
5
4
  * previous sequential call only.
6
5
  */
7
6
  export declare function batchDependencies(calls: readonly {
@@ -1,7 +1,7 @@
1
1
  import { TOOL_RESULT_PLACEHOLDER } from "@earendil-works/pi-ai";
2
+ import { canonicalDigest } from "./canonical-digest.js";
2
3
  /**
3
- * Release dependencies exactly as today's scheduler assigns them (agent-loop.ts, executeToolCallsParallel): a
4
- * sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
4
+ * Release dependencies exactly as the agent loop has always ordered a batch: a sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
5
5
  * previous sequential call only.
6
6
  */
7
7
  export function batchDependencies(calls) {
@@ -22,19 +22,6 @@ export function batchDependencies(calls) {
22
22
  }
23
23
  return result;
24
24
  }
25
- function canonical(value) {
26
- if (Array.isArray(value))
27
- return `[${value.map(canonical).join(",")}]`;
28
- if (value !== null && typeof value === "object") {
29
- const entries = Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
30
- return `{${entries.map(([key, inner]) => `${JSON.stringify(key)}:${canonical(inner)}`).join(",")}}`;
31
- }
32
- return JSON.stringify(value);
33
- }
34
- async function digest(value) {
35
- const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(value)));
36
- return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
37
- }
38
25
  export async function buildBatchManifest(issuer, plan) {
39
26
  const dependencies = batchDependencies(plan.calls);
40
27
  const calls = [];
@@ -45,11 +32,11 @@ export async function buildBatchManifest(issuer, plan) {
45
32
  sourceIndex,
46
33
  dependsOn: placement.dependsOn,
47
34
  wave: placement.wave,
48
- requestDigest: await digest({ name: call.name, args: call.args }),
35
+ requestDigest: await canonicalDigest({ name: call.name, args: call.args }),
49
36
  });
50
37
  }
51
38
  const { calls: _calls, ...header } = plan;
52
- return { ...header, issuer, calls, manifestDigest: await digest({ ...header, issuer, calls }) };
39
+ return { ...header, issuer, calls, manifestDigest: await canonicalDigest({ ...header, issuer, calls }) };
53
40
  }
54
41
  /**
55
42
  * A reply after which no later call is prepared and the decision is ABORT. A raw `settled` outcome other than a result
@@ -0,0 +1,15 @@
1
+ import type { BatchCoordinator } from "./coordinator.ts";
2
+ import type { BatchPlan, BatchResult } from "./coordinator-types.ts";
3
+ /** `toolExecution: "sequential"` on the coordinator (design 5.6.1 scheduler modes, S11). */
4
+ export interface SequentialCoordinator {
5
+ /**
6
+ * Runs each call as its own one-call batch, in source order: a call is prepared and run to its final outcome before
7
+ * the next is prepared, as today's sequential scheduler interleaves them. The one-call batches are durable, so running
8
+ * the same plan again after a crash returns the finished calls' stored outcomes and resumes the one in flight. A
9
+ * call whose batch ABORTs (its preparation was stopped) ends the run: the calls after it are never prepared and are
10
+ * reported `not_run`.
11
+ */
12
+ run(plan: BatchPlan): Promise<BatchResult>;
13
+ }
14
+ export declare function createSequentialCoordinator(coordinator: BatchCoordinator): SequentialCoordinator;
15
+ //# sourceMappingURL=coordinator-sequential.d.ts.map
@@ -0,0 +1,34 @@
1
+ /** The durable batch id of call `index` of `batchId`; stable across runs, so a resumed run finds it. */
2
+ const sequentialBatchId = (batchId, index) => `${batchId}#${index}`;
3
+ /**
4
+ * The cause the calls after an ABORTed call inherit, as one batch gives its unrun calls the batch's own cause: after an
5
+ * interrupted preparation they replay with today's placeholder (X12), after a stop as an aborted batch. A one-call batch
6
+ * ABORTs only on its call's preparation, so an aborting call that is not `not_run` settled at preparation, and one batch
7
+ * fails that closed as an interrupted preparation whatever the stored reason (`blocked` included, `abortCause`).
8
+ */
9
+ function inheritedCause(aborting) {
10
+ if (aborting === undefined)
11
+ return "batch_abort";
12
+ return aborting.kind === "not_run" ? aborting.cause : "interrupted_preparation";
13
+ }
14
+ export function createSequentialCoordinator(coordinator) {
15
+ return {
16
+ run: async (plan) => {
17
+ const outcomes = [];
18
+ for (const [index, call] of plan.calls.entries()) {
19
+ const single = await coordinator.run({
20
+ ...plan,
21
+ batchId: sequentialBatchId(plan.batchId, index),
22
+ calls: [call],
23
+ });
24
+ outcomes.push(...single.outcomes);
25
+ if (single.decision === "ABORT") {
26
+ const notRun = { kind: "not_run", cause: inheritedCause(single.outcomes[0]) };
27
+ return { decision: "ABORT", outcomes: [...outcomes, ...plan.calls.slice(index + 1).map(() => notRun)] };
28
+ }
29
+ }
30
+ return { decision: "RELEASE", outcomes };
31
+ },
32
+ };
33
+ }
34
+ //# sourceMappingURL=coordinator-sequential.js.map
@@ -45,6 +45,8 @@ export type PrepareRequest = {
45
45
  readonly name: string;
46
46
  readonly args: StoreValue;
47
47
  };
48
+ /** Gate A approved this raw request digest (design 5.6.1); the executor asks again only for a different frozen call. */
49
+ readonly authorizedDigest?: string;
48
50
  };
49
51
  export type ExecutionRef = {
50
52
  readonly issuer: string;
@@ -61,6 +63,11 @@ export type ExecutionRef = {
61
63
  export type PrepareReply = {
62
64
  readonly kind: "prepared";
63
65
  readonly frozenDigest: string;
66
+ }
67
+ /** Gate B: the frozen call differs from what Gate A authorized and needs consent; the approval binds this digest. */
68
+ | {
69
+ readonly kind: "prepared_awaiting_consent";
70
+ readonly frozenDigest: string;
64
71
  } | {
65
72
  readonly kind: "blocked";
66
73
  readonly result: StoreValue;
@@ -83,7 +90,43 @@ export interface BatchExecutor {
83
90
  /** Resolves once the released call has settled. */
84
91
  release(ref: ExecutionRef): Promise<SettleReply>;
85
92
  abort(ref: ExecutionRef): Promise<SettleReply>;
93
+ /**
94
+ * Applies an approval to a call awaiting consent on `frozenDigest`: `prepared`, or the call's terminal outcome (a
95
+ * lease that expired while it waited rejects the approval). Only cross-machine executors gate consent.
96
+ */
97
+ consent?(ref: ExecutionRef, frozenDigest: string): Promise<{
98
+ readonly kind: "prepared";
99
+ } | SettleReply>;
100
+ }
101
+ /** What an approver answered; `expired` is the call's lease running out first. */
102
+ export type ConsentAnswer = "approved" | "denied" | "expired";
103
+ export type ConsentRequest = ExecutionRef & {
104
+ readonly gate: "raw" | "frozen";
105
+ readonly digest: string;
106
+ readonly name: string;
107
+ readonly leaseUntil: number;
108
+ };
109
+ /**
110
+ * Consent for cross-machine executions (design 5.6.1 Gate A and Gate B). Any RPC-authorized party may answer through
111
+ * `approve`; the device is not the only approver (K2). Fused and split-local sessions configure none (K3).
112
+ */
113
+ export interface BatchConsent {
114
+ /**
115
+ * Gate A: the engine's built-in permission classification of the raw call, before any extension callback. A call that
116
+ * classifies as denied is not consent: it is prepared and the hand's own `tool_call` chain refuses it, as today.
117
+ */
118
+ needsConsent(call: {
119
+ readonly name: string;
120
+ readonly args: StoreValue;
121
+ }): boolean;
122
+ approve(request: ConsentRequest): Promise<ConsentAnswer>;
86
123
  }
124
+ /** One answered consent of a call, durable before the step it decides. */
125
+ export type ConsentRecord = {
126
+ readonly gate: "raw" | "frozen";
127
+ readonly digest: string;
128
+ readonly answer: ConsentAnswer;
129
+ };
87
130
  export type BatchDecision = "RELEASE" | "ABORT";
88
131
  export type CallOutcome = {
89
132
  readonly kind: "result";
@@ -108,6 +151,8 @@ export type BatchRecord = {
108
151
  readonly decision: BatchDecision | null;
109
152
  readonly released: readonly boolean[];
110
153
  readonly outcomes: readonly (CallOutcome | null)[];
154
+ /** Answered consents per call; absent on a record written before consent gating. */
155
+ readonly consents?: readonly (ConsentRecord | null)[];
111
156
  };
112
157
  export type BatchResult = {
113
158
  readonly decision: BatchDecision;
@@ -1,6 +1,6 @@
1
1
  import type { DurableStore } from "../durable/store.ts";
2
2
  import type { AdmissionLine } from "../durable/store-admission.ts";
3
- import type { BatchExecutor, BatchPlan, BatchRecord, BatchResult } from "./coordinator-types.ts";
3
+ import type { BatchConsent, BatchExecutor, BatchPlan, BatchRecord, BatchResult } from "./coordinator-types.ts";
4
4
  export declare class BatchManifestConflictError extends Error {
5
5
  constructor(batchId: string);
6
6
  }
@@ -11,6 +11,8 @@ export interface BatchCoordinatorOptions {
11
11
  /** The single admission line of the store's writable epoch, shared with every other writer on it. */
12
12
  readonly admission: AdmissionLine;
13
13
  readonly executor: (id: string) => BatchExecutor;
14
+ /** Gate A/B consent for cross-machine executors; absent (fused, split-local) means no consent step (K3). */
15
+ readonly consent?: BatchConsent;
14
16
  }
15
17
  export interface BatchCoordinator {
16
18
  /**
@@ -1,4 +1,5 @@
1
1
  import { decodeBatchRecord } from "./coordinator-codec.js";
2
+ import { gateRawCall, resolveFrozenConsent } from "./coordinator-consent.js";
2
3
  import { abortCause, buildBatchManifest, finished, settledOutcome } from "./coordinator-plan.js";
3
4
  const PREFIX = "execution.batch:";
4
5
  const keyOf = (issuer, batchId) => `${PREFIX}${JSON.stringify([issuer, batchId])}`;
@@ -10,7 +11,7 @@ export class BatchManifestConflictError extends Error {
10
11
  }
11
12
  const replace = (items, index, value) => items.map((item, at) => (at === index ? value : item));
12
13
  export function createBatchCoordinator(options) {
13
- const { issuer, store, epoch, admission, executor } = options;
14
+ const { issuer, store, epoch, admission, executor, consent } = options;
14
15
  const read = async (batchId) => {
15
16
  const value = await store.getDocument(keyOf(issuer, batchId));
16
17
  return value === undefined ? undefined : decodeBatchRecord(value);
@@ -53,11 +54,32 @@ export function createBatchCoordinator(options) {
53
54
  else if (record.manifest.manifestDigest !== manifest.manifestDigest) {
54
55
  throw new BatchManifestConflictError(plan.batchId);
55
56
  }
57
+ const consentStep = (gate, call) => ({
58
+ consent: gate,
59
+ executor: executor(call.executor),
60
+ ref: ref(call),
61
+ call,
62
+ leaseUntil: manifest.leaseUntil,
63
+ recorded: current().consents?.[call.sourceIndex] ?? null,
64
+ record: (answered) => persist({
65
+ ...current(),
66
+ consents: replace(current().consents ?? manifest.calls.map(() => null), call.sourceIndex, answered),
67
+ }, "consent", call),
68
+ });
69
+ const setPrepare = (call, reply) => persist({ ...current(), prepares: replace(current().prepares, call.sourceIndex, reply) }, "prepare", call);
56
70
  if (current().decision === null) {
57
71
  for (const call of manifest.calls) {
58
72
  let reply = current().prepares[call.sourceIndex] ?? null;
59
- if (reply === null) {
73
+ const gate = reply === null && consent !== undefined ? await gateRawCall(consentStep(consent, call)) : {};
74
+ if (reply === null && "blocked" in gate) {
75
+ reply = gate.blocked;
76
+ await setPrepare(call, reply);
77
+ }
78
+ else if (reply === null) {
60
79
  reply = await executor(call.executor).prepare({
80
+ ...("authorizedDigest" in gate && gate.authorizedDigest !== undefined
81
+ ? { authorizedDigest: gate.authorizedDigest }
82
+ : {}),
61
83
  ...ref(call),
62
84
  batchId: manifest.batchId,
63
85
  manifestDigest: manifest.manifestDigest,
@@ -68,11 +90,21 @@ export function createBatchCoordinator(options) {
68
90
  requestDigest: call.requestDigest,
69
91
  call: { name: call.name, args: call.args },
70
92
  });
71
- await persist({ ...current(), prepares: replace(current().prepares, call.sourceIndex, reply) }, "prepare", call);
93
+ await setPrepare(call, reply);
72
94
  }
73
95
  if (abortCause(reply) !== undefined)
74
96
  break;
75
97
  }
98
+ for (const call of manifest.calls) {
99
+ if (current().prepares.some((reply) => reply !== null && abortCause(reply) !== undefined))
100
+ break;
101
+ const reply = current().prepares[call.sourceIndex] ?? null;
102
+ if (reply?.kind !== "prepared_awaiting_consent")
103
+ continue;
104
+ if (consent === undefined)
105
+ throw new Error(`batch ${plan.batchId}: a call awaits consent but none is configured`);
106
+ await setPrepare(call, await resolveFrozenConsent(consentStep(consent, call), reply.frozenDigest));
107
+ }
76
108
  const aborted = current().prepares.some((reply) => reply !== null && abortCause(reply) !== undefined);
77
109
  await persist({ ...current(), decision: aborted ? "ABORT" : "RELEASE" }, "decision");
78
110
  }
@@ -0,0 +1,8 @@
1
+ import { type DeviceFiles } from "./device-files.ts";
2
+ /**
3
+ * The local filesystem as {@link DeviceFiles}: what a fused session's extension code uses, called directly, and what a
4
+ * hand runs a channel operation on once its grant, handlers and policy have allowed it. Reads and writes are bounded
5
+ * by {@link FILE_CHANNEL_MAX_BYTES} before any data is in memory, so both sides of a split session agree on the limit.
6
+ */
7
+ export declare function localDeviceFiles(): DeviceFiles;
8
+ //# sourceMappingURL=device-files-node.d.ts.map
@@ -0,0 +1,150 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, readdir, rename, rm } from "node:fs/promises";
4
+ import { dirname } from "node:path";
5
+ import { DeviceFileError, FILE_CHANNEL_MAX_BYTES, } from "./device-files.js";
6
+ function deviceError(error, path) {
7
+ if (error instanceof DeviceFileError)
8
+ return error;
9
+ const code = error.code;
10
+ const message = error instanceof Error ? error.message : String(error);
11
+ if (code === "ENOENT")
12
+ return new DeviceFileError("not_found", path);
13
+ if (code === "EEXIST")
14
+ return new DeviceFileError("exists", path);
15
+ if (code === "EISDIR" || code === "ENOTDIR" || code === "ENXIO")
16
+ return new DeviceFileError("not_a_file", path);
17
+ if (code === "ABORT_ERR")
18
+ return new DeviceFileError("aborted", path);
19
+ return new DeviceFileError("io", message);
20
+ }
21
+ async function guarded(path, signal, run) {
22
+ if (signal?.aborted)
23
+ throw new DeviceFileError("aborted", path);
24
+ try {
25
+ return await run();
26
+ }
27
+ catch (error) {
28
+ throw deviceError(error, path);
29
+ }
30
+ }
31
+ /**
32
+ * Opens a regular file only. The open never blocks (a named pipe with no peer would hold it, and a worker thread,
33
+ * forever), and the type is checked on the opened descriptor, so nothing can swap the path in between.
34
+ */
35
+ async function openRegular(path, flags) {
36
+ const handle = await open(path, flags | constants.O_NONBLOCK, 0o666);
37
+ try {
38
+ if (!(await handle.stat()).isFile())
39
+ throw new DeviceFileError("not_a_file", path);
40
+ return handle;
41
+ }
42
+ catch (error) {
43
+ await handle.close();
44
+ throw error;
45
+ }
46
+ }
47
+ /** Reads at most the channel limit: a file that grows past it while being read is refused, never shipped in full. */
48
+ async function readBounded(path, signal) {
49
+ const handle = await openRegular(path, constants.O_RDONLY);
50
+ try {
51
+ const chunks = [];
52
+ let total = 0;
53
+ for (;;) {
54
+ if (signal?.aborted)
55
+ throw new DeviceFileError("aborted", path);
56
+ const chunk = new Uint8Array(64 * 1024);
57
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
58
+ if (bytesRead === 0)
59
+ break;
60
+ total += bytesRead;
61
+ if (total > FILE_CHANNEL_MAX_BYTES)
62
+ throw new DeviceFileError("too_large", path);
63
+ chunks.push(chunk.subarray(0, bytesRead));
64
+ }
65
+ const bytes = new Uint8Array(total);
66
+ let offset = 0;
67
+ for (const chunk of chunks) {
68
+ bytes.set(chunk, offset);
69
+ offset += chunk.length;
70
+ }
71
+ return bytes;
72
+ }
73
+ finally {
74
+ await handle.close();
75
+ }
76
+ }
77
+ /** A fused session's `run`: a direct spawn in `cwd`, no shell, no allowlist and no hop, as the caller spawns today. */
78
+ function runDirect(request, signal) {
79
+ return new Promise((done, fail) => {
80
+ const child = spawn(request.exe, [...request.argv], {
81
+ cwd: request.cwd,
82
+ env: request.env === undefined ? process.env : { ...process.env, ...request.env },
83
+ shell: false,
84
+ windowsHide: true,
85
+ ...(signal === undefined ? {} : { signal }),
86
+ });
87
+ const out = [];
88
+ const err = [];
89
+ child.stdout.on("data", (chunk) => out.push(chunk));
90
+ child.stderr.on("data", (chunk) => err.push(chunk));
91
+ let killTimer;
92
+ const timer = request.timeoutMs === undefined
93
+ ? undefined
94
+ : setTimeout(() => {
95
+ child.kill("SIGTERM");
96
+ killTimer = setTimeout(() => child.kill("SIGKILL"), 10_000);
97
+ }, request.timeoutMs);
98
+ child.on("error", (error) => fail(new DeviceFileError(signal?.aborted ? "aborted" : "io", error.message)));
99
+ child.on("close", (code, exitSignal) => {
100
+ clearTimeout(timer);
101
+ clearTimeout(killTimer);
102
+ done({
103
+ code,
104
+ signal: exitSignal,
105
+ stdout: new Uint8Array(Buffer.concat(out)),
106
+ stderr: Buffer.concat(err).toString("utf8"),
107
+ });
108
+ });
109
+ child.stdin.on("error", () => undefined);
110
+ child.stdin.end(request.stdin === undefined ? undefined : Buffer.from(request.stdin));
111
+ });
112
+ }
113
+ function statOf(entry) {
114
+ const kind = entry.isFile() ? "file" : entry.isDirectory() ? "directory" : "other";
115
+ return { kind, size: entry.size, mtimeMs: entry.mtimeMs };
116
+ }
117
+ /**
118
+ * The local filesystem as {@link DeviceFiles}: what a fused session's extension code uses, called directly, and what a
119
+ * hand runs a channel operation on once its grant, handlers and policy have allowed it. Reads and writes are bounded
120
+ * by {@link FILE_CHANNEL_MAX_BYTES} before any data is in memory, so both sides of a split session agree on the limit.
121
+ */
122
+ export function localDeviceFiles() {
123
+ return {
124
+ read: (path, options) => guarded(path, options?.signal, () => readBounded(path, options?.signal)),
125
+ write: (path, data, options) => guarded(path, options?.signal, async () => {
126
+ if (data.byteLength > FILE_CHANNEL_MAX_BYTES)
127
+ throw new DeviceFileError("too_large", path);
128
+ await mkdir(dirname(path), { recursive: true });
129
+ const handle = await openRegular(path, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (options?.exclusive ? constants.O_EXCL : 0));
130
+ try {
131
+ await handle.writeFile(data);
132
+ }
133
+ finally {
134
+ await handle.close();
135
+ }
136
+ }),
137
+ list: (path, options) => guarded(path, options?.signal, () => readdir(path)),
138
+ stat: (path, options) => guarded(path, options?.signal, async () => statOf(await lstat(path))),
139
+ rename: (from, to, options) => guarded(from, options?.signal, () => rename(from, to)),
140
+ remove: (path, options) => guarded(path, options?.signal, async () => {
141
+ await lstat(path);
142
+ await rm(path, { recursive: true });
143
+ }),
144
+ mkdir: (path, options) => guarded(path, options?.signal, async () => {
145
+ await mkdir(path, { recursive: true });
146
+ }),
147
+ run: (request, options) => runDirect(request, options?.signal),
148
+ };
149
+ }
150
+ //# sourceMappingURL=device-files-node.js.map