@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
@@ -1,5 +1,6 @@
1
1
  import { TOOL_RESULT_PLACEHOLDER } from "@earendil-works/pi-ai";
2
- import { decodeRemoteMessage, encodeRemoteMessage, } from "./remote-protocol.js";
2
+ import { createRemoteDeviceFiles } from "./remote-device-files.js";
3
+ import { createHandLink } from "./remote-link.js";
3
4
  function errorResult(text) {
4
5
  return { content: [{ type: "text", text }], details: {}, isError: true };
5
6
  }
@@ -21,69 +22,32 @@ function terminalResult(placement, terminal) {
21
22
  * validates, runs the extensions' `tool_call`/`tool_result` handlers (permission checks among them) and executes each
22
23
  * call; this host keeps the loop's side: tool events, the batch's ordering, a forwarded abort and the result messages in
23
24
  * source order. A call whose send is refused (the transport closed) becomes an error result, never a retry. The one
24
- * re-send is on a hand's `hello` (it restarted with its durable record): every call still waiting is sent again, and
25
- * the hand answers each one its record already holds instead of running it a second time.
25
+ * re-send is on a durable hand's `hello` (see `createHandLink`). `deviceFiles(scope)` reaches the hand's files (S40).
26
26
  */
27
27
  export function createRemoteToolHost(options) {
28
- const { transport } = options;
29
28
  const mintId = options.mintId ?? (() => crypto.randomUUID());
30
- const pending = new Map();
31
- const settle = (executionId, result) => {
32
- const waiter = pending.get(executionId);
33
- if (waiter === undefined)
34
- return;
35
- pending.delete(executionId);
36
- waiter.resolve(result);
37
- };
38
- transport.onFrame((frame) => {
39
- let message;
40
- try {
41
- message = decodeRemoteMessage(frame.payload);
42
- }
43
- catch {
44
- return;
45
- }
46
- const ack = (executionId) => void transport.send(frame.lane, encodeRemoteMessage({ kind: "ack", executionId })).catch(() => undefined);
47
- if (message.kind === "hello") {
48
- for (const { invoke } of pending.values())
49
- void transport.send(invoke.scope.id, encodeRemoteMessage(invoke)).catch(() => undefined);
50
- return;
29
+ const link = createHandLink(options.transport, options.planes ?? {}, options.filePlanes ?? [], options.epoch);
30
+ const resultOf = (reply) => {
31
+ switch (reply.kind) {
32
+ case "settled":
33
+ return reply.result;
34
+ case "terminal":
35
+ return terminalResult(options.placement, reply.terminal);
36
+ case "refused":
37
+ return errorResult(`The hand refused this tool call: ${reply.reason}`);
38
+ case "aborted":
39
+ return errorResult(reply.sent ? "Tool execution aborted" : "Operation aborted");
40
+ case "unreachable":
41
+ return errorResult(`The hand is unreachable: ${reply.reason}`);
42
+ case "closed":
43
+ return errorResult("The hand link was closed before the call settled");
44
+ case "epoch_refused":
45
+ return errorResult(`The hand refused this session's epoch: ${reply.reason}`);
51
46
  }
52
- if (message.kind === "settled") {
53
- settle(message.executionId, message.result);
54
- ack(message.executionId);
55
- }
56
- else if (message.kind === "terminal") {
57
- settle(message.executionId, terminalResult(options.placement, message));
58
- ack(message.executionId);
59
- }
60
- else if (message.kind === "refused")
61
- settle(message.executionId, errorResult(`The hand refused this tool call: ${message.reason}`));
62
- });
63
- const dispatch = (invoke, signal) => {
64
- const settled = new Promise((resolve) => {
65
- pending.set(invoke.executionId, { invoke, resolve });
66
- });
67
- if (signal?.aborted)
68
- settle(invoke.executionId, errorResult("Operation aborted"));
69
- else {
70
- const onAbort = () => {
71
- if (!pending.has(invoke.executionId))
72
- return;
73
- void transport
74
- .send(invoke.scope.id, encodeRemoteMessage({ kind: "abort", executionId: invoke.executionId }))
75
- .catch(() => undefined);
76
- settle(invoke.executionId, errorResult("Tool execution aborted"));
77
- };
78
- signal?.addEventListener("abort", onAbort, { once: true });
79
- void settled.then(() => signal?.removeEventListener("abort", onAbort));
80
- transport.send(invoke.scope.id, encodeRemoteMessage(invoke)).catch((error) => {
81
- const reason = error instanceof Error ? error.message : String(error);
82
- settle(invoke.executionId, errorResult(`The hand is unreachable: ${reason}`));
83
- });
84
- }
85
- return { settled };
86
47
  };
48
+ const dispatch = (invoke, signal) => ({
49
+ settled: link.dispatch(invoke, signal).then(resultOf),
50
+ });
87
51
  return {
88
52
  async execute(call, hostOptions) {
89
53
  const { emit, signal } = hostOptions;
@@ -145,11 +109,8 @@ export function createRemoteToolHost(options) {
145
109
  terminate: results.length > 0 && results.every((result) => result.terminate === true),
146
110
  };
147
111
  },
148
- close() {
149
- for (const executionId of [...pending.keys()])
150
- settle(executionId, errorResult("The hand link was closed before the call settled"));
151
- transport.close();
152
- },
112
+ deviceFiles: (scope) => createRemoteDeviceFiles(link, scope, mintId),
113
+ close: () => link.close(),
153
114
  };
154
115
  }
155
116
  //# sourceMappingURL=remote-tool-host.js.map
@@ -0,0 +1,81 @@
1
+ import type { DurableStore, StoreValue } from "../durable/store.ts";
2
+ import type { AdmissionLine } from "../durable/store-admission.ts";
3
+ /** What an endpoint owns for one scope (design 5.6.6). */
4
+ export type ScopeBinding = {
5
+ readonly issuer: string;
6
+ readonly workspace: string;
7
+ readonly scope: string;
8
+ readonly generation: number;
9
+ readonly allowedRoots: readonly string[];
10
+ };
11
+ export type ScopeRecord = {
12
+ readonly binding: ScopeBinding;
13
+ readonly state: "open" | "closed";
14
+ readonly lastActiveAt: number;
15
+ /** Live resources (executions, terminals, activities) by id: an idle TTL never closes a scope that holds one. */
16
+ readonly resources: {
17
+ readonly [id: string]: string;
18
+ };
19
+ /** Every committed lifecycle event, in admission order, with the effect its handler returned. */
20
+ readonly events: readonly {
21
+ readonly seq: number;
22
+ readonly kind: string;
23
+ readonly effect: StoreValue;
24
+ }[];
25
+ /** Terminal outcomes a forced close wrote, by resource id, before the scope closed. */
26
+ readonly outcomes: {
27
+ readonly [id: string]: StoreValue;
28
+ };
29
+ };
30
+ export type ScopeRefusal = "unknown_scope" | "not_issuer" | "closed" | "live_resources" | "conflicting_scope";
31
+ /** A call for a scope that is unknown or closed: it never runs. */
32
+ export declare class ScopeUnavailableError extends Error {
33
+ readonly scope: string;
34
+ readonly reason: "unknown_scope" | "closed";
35
+ constructor(scope: string, reason: "unknown_scope" | "closed");
36
+ }
37
+ export interface ScopeLifecycleOptions {
38
+ readonly store: DurableStore;
39
+ readonly epoch: number;
40
+ readonly admission: AdmissionLine;
41
+ readonly clock: () => number;
42
+ readonly idleTtlMs: number;
43
+ }
44
+ /**
45
+ * Scope lifecycle on an endpoint (design 5.6.6). A lifecycle event is admitted only after its handler's effect commits,
46
+ * and a call submitted after it runs only then; only the issuer closes; a TTL never closes a scope with live resources;
47
+ * a forced close writes every live resource's terminal outcome before the scope closes.
48
+ */
49
+ export interface ScopeLifecycle {
50
+ open(binding: ScopeBinding): Promise<{
51
+ readonly kind: "opened";
52
+ } | {
53
+ readonly kind: "refused";
54
+ readonly reason: ScopeRefusal;
55
+ }>;
56
+ lifecycle(actor: string, scope: string, kind: string, handler: () => Promise<StoreValue>): Promise<{
57
+ readonly kind: "committed";
58
+ readonly seq: number;
59
+ } | {
60
+ readonly kind: "refused";
61
+ readonly reason: ScopeRefusal;
62
+ }>;
63
+ /** Runs `run` after every lifecycle event of the scope submitted before it has committed; throws ScopeUnavailableError for a closed or unknown scope. */
64
+ call<T>(scope: string, run: () => Promise<T>): Promise<T>;
65
+ hold(scope: string, resource: string, kind: string): Promise<void>;
66
+ release(scope: string, resource: string): Promise<void>;
67
+ close(actor: string, scope: string, options?: {
68
+ readonly force?: boolean;
69
+ readonly terminate?: (resource: string) => Promise<StoreValue>;
70
+ }): Promise<{
71
+ readonly kind: "closed";
72
+ } | {
73
+ readonly kind: "refused";
74
+ readonly reason: ScopeRefusal;
75
+ }>;
76
+ /** Closes every open scope idle longer than the TTL that holds no live resource; returns their names. */
77
+ sweepIdle(): Promise<readonly string[]>;
78
+ read(scope: string): Promise<ScopeRecord | undefined>;
79
+ }
80
+ export declare function createScopeLifecycle(options: ScopeLifecycleOptions): ScopeLifecycle;
81
+ //# sourceMappingURL=scope-lifecycle.d.ts.map
@@ -0,0 +1,173 @@
1
+ import { canonicalJson } from "./canonical-json.js";
2
+ /** A call for a scope that is unknown or closed: it never runs. */
3
+ export class ScopeUnavailableError extends Error {
4
+ constructor(scope, reason) {
5
+ super(`scope ${scope} is not open: ${reason}`);
6
+ this.name = "ScopeUnavailableError";
7
+ this.scope = scope;
8
+ this.reason = reason;
9
+ }
10
+ }
11
+ const PREFIX = "execution.scope:";
12
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
13
+ function decode(value) {
14
+ if (isObject(value) &&
15
+ isObject(value.binding) &&
16
+ (value.state === "open" || value.state === "closed") &&
17
+ typeof value.lastActiveAt === "number" &&
18
+ isObject(value.resources) &&
19
+ Array.isArray(value.events) &&
20
+ isObject(value.outcomes))
21
+ return value;
22
+ throw new Error("corrupt scope record");
23
+ }
24
+ export function createScopeLifecycle(options) {
25
+ const { store, epoch, admission, clock, idleTtlMs } = options;
26
+ const keyOf = (scope) => `${PREFIX}${JSON.stringify([scope])}`;
27
+ const read = async (scope) => {
28
+ const value = await store.getDocument(keyOf(scope));
29
+ return value === undefined ? undefined : decode(value);
30
+ };
31
+ const write = async (record, step, executionId) => {
32
+ await store.commit(epoch, [
33
+ {
34
+ op: "append",
35
+ id: store.mintId(),
36
+ kind: "execution.scope",
37
+ data: { scope: record.binding.scope, step, executionId },
38
+ },
39
+ { op: "put", key: keyOf(record.binding.scope), data: record },
40
+ ], () => { });
41
+ };
42
+ const update = (scope, decide) => admission.admit(async () => decide(await read(scope)));
43
+ /** Per scope, the last admitted lifecycle event or close: a later call, event or close waits for it. */
44
+ const tails = new Map();
45
+ const after = (scope, step) => {
46
+ const run = (tails.get(scope) ?? Promise.resolve()).then(step, step);
47
+ const settled = run.catch(() => undefined);
48
+ tails.set(scope, settled);
49
+ void settled.then(() => {
50
+ if (tails.get(scope) === settled)
51
+ tails.delete(scope);
52
+ });
53
+ return run;
54
+ };
55
+ const touch = (scope) => update(scope, async (record) => {
56
+ if (record?.state !== "open")
57
+ return record?.state;
58
+ await write({ ...record, lastActiveAt: clock() }, "active", null);
59
+ return "open";
60
+ });
61
+ /**
62
+ * Closes from the record as it is inside the admission line, so a resource held after any earlier read is seen: an
63
+ * unforced close with a live resource is refused; a forced one terminates each resource without an outcome, writes
64
+ * the outcome, and looks again until none is left.
65
+ */
66
+ const finishClose = async (scope, force, terminate) => {
67
+ for (;;) {
68
+ const step = await update(scope, async (latest) => {
69
+ if (latest === undefined)
70
+ return { kind: "refused", reason: "unknown_scope" };
71
+ if (latest.state === "closed")
72
+ return { kind: "closed" };
73
+ const pending = Object.keys(latest.resources).filter((resource) => latest.outcomes[resource] === undefined);
74
+ if (pending.length > 0 && !force)
75
+ return { kind: "refused", reason: "live_resources" };
76
+ if (pending.length > 0)
77
+ return { kind: "terminate", pending };
78
+ await write({ ...latest, state: "closed", resources: {} }, "close", null);
79
+ return { kind: "closed" };
80
+ });
81
+ if (step.kind !== "terminate")
82
+ return step;
83
+ if (terminate === undefined)
84
+ throw new Error(`forced close of ${scope} needs a terminate port`);
85
+ for (const resource of step.pending) {
86
+ const outcome = await terminate(resource);
87
+ await update(scope, async (latest) => {
88
+ if (latest === undefined || latest.state === "closed" || latest.outcomes[resource] !== undefined)
89
+ return;
90
+ await write({ ...latest, outcomes: { ...latest.outcomes, [resource]: outcome } }, "outcome", resource);
91
+ });
92
+ }
93
+ }
94
+ };
95
+ return {
96
+ read,
97
+ open: (binding) => update(binding.scope, async (record) => {
98
+ if (!Number.isFinite(binding.generation))
99
+ throw new Error(`scope ${binding.scope} has a non-finite generation`);
100
+ if (record !== undefined)
101
+ return canonicalJson(record.binding) === canonicalJson(binding) && record.state === "open"
102
+ ? { kind: "opened" }
103
+ : { kind: "refused", reason: "conflicting_scope" };
104
+ await write({ binding, state: "open", lastActiveAt: clock(), resources: {}, events: [], outcomes: {} }, "open", null);
105
+ return { kind: "opened" };
106
+ }),
107
+ lifecycle: (actor, scope, kind, handler) => after(scope, async () => {
108
+ const record = await read(scope);
109
+ if (record === undefined)
110
+ return { kind: "refused", reason: "unknown_scope" };
111
+ if (record.binding.issuer !== actor)
112
+ return { kind: "refused", reason: "not_issuer" };
113
+ if (record.state === "closed")
114
+ return { kind: "refused", reason: "closed" };
115
+ const effect = await handler();
116
+ return update(scope, async (latest) => {
117
+ if (latest === undefined || latest.state === "closed")
118
+ return { kind: "refused", reason: "closed" };
119
+ const seq = latest.events.length + 1;
120
+ await write({ ...latest, lastActiveAt: clock(), events: [...latest.events, { seq, kind, effect }] }, "lifecycle", `${kind}#${seq}`);
121
+ return { kind: "committed", seq };
122
+ });
123
+ }),
124
+ call: (scope, run) => (tails.get(scope) ?? Promise.resolve()).then(async () => {
125
+ const state = await touch(scope);
126
+ if (state !== "open")
127
+ throw new ScopeUnavailableError(scope, state === undefined ? "unknown_scope" : "closed");
128
+ return run();
129
+ }),
130
+ hold: (scope, resource, kind) => update(scope, async (record) => {
131
+ if (record?.state !== "open")
132
+ throw new ScopeUnavailableError(scope, record === undefined ? "unknown_scope" : "closed");
133
+ await write({ ...record, lastActiveAt: clock(), resources: { ...record.resources, [resource]: kind } }, "hold", resource);
134
+ }),
135
+ release: (scope, resource) => update(scope, async (record) => {
136
+ if (record === undefined || record.resources[resource] === undefined)
137
+ return;
138
+ const { [resource]: _released, ...resources } = record.resources;
139
+ await write({ ...record, lastActiveAt: clock(), resources }, "release", resource);
140
+ }),
141
+ close: (actor, scope, closeOptions = {}) => after(scope, async () => {
142
+ const record = await read(scope);
143
+ if (record === undefined)
144
+ return { kind: "refused", reason: "unknown_scope" };
145
+ if (record.binding.issuer !== actor)
146
+ return { kind: "refused", reason: "not_issuer" };
147
+ return finishClose(scope, closeOptions.force === true, closeOptions.terminate);
148
+ }),
149
+ sweepIdle: async () => {
150
+ const closed = [];
151
+ for (const { data } of await store.scanDocuments(PREFIX)) {
152
+ const candidate = decode(data);
153
+ const scope = candidate.binding.scope;
154
+ if (candidate.state !== "open" || Object.keys(candidate.resources).length > 0)
155
+ continue;
156
+ if (clock() - candidate.lastActiveAt <= idleTtlMs)
157
+ continue;
158
+ const done = await after(scope, () => update(scope, async (latest) => {
159
+ if (latest?.state !== "open" || Object.keys(latest.resources).length > 0)
160
+ return false;
161
+ if (clock() - latest.lastActiveAt <= idleTtlMs)
162
+ return false;
163
+ await write({ ...latest, state: "closed" }, "close", null);
164
+ return true;
165
+ }));
166
+ if (done)
167
+ closed.push(scope);
168
+ }
169
+ return closed;
170
+ },
171
+ };
172
+ }
173
+ //# sourceMappingURL=scope-lifecycle.js.map
@@ -2,6 +2,12 @@ import { createAdmissionLine } from "../../durable/store-admission.js";
2
2
  import { createExecutionLedger } from "../ledger.js";
3
3
  /** What the scripted `tool_call` chain decides for a tool name; unknown names are allowed. */
4
4
  const BATCH_TOOLS = { deny: "blocked", stop: "batch_abort" };
5
+ /**
6
+ * Tools whose body needs consent (design 5.6.1). `gated`'s shim changes the call, so its frozen call always differs
7
+ * from the raw one; `ask`'s shim keeps it, so a Gate A approval of the raw digest also covers the frozen call.
8
+ */
9
+ const CONSENT_TOOLS = new Set(["gated", "ask"]);
10
+ const frozenDigestOf = (name, requestDigest) => name === "ask" ? requestDigest : `${requestDigest}:frozen`;
5
11
  export class ExecutorKilledError extends Error {
6
12
  constructor(id) {
7
13
  super(`executor ${id} was killed`);
@@ -55,6 +61,8 @@ export const referenceBatchExecutor = {
55
61
  }
56
62
  if (!("call" in progress))
57
63
  throw new Error(`no stored prepare reply in state ${progress.state}`);
64
+ if (progress.state === "prepared_awaiting_consent")
65
+ return { kind: "prepared_awaiting_consent", frozenDigest: progress.call.digest };
58
66
  return { kind: "prepared", frozenDigest: progress.call.digest };
59
67
  };
60
68
  const settled = async (ref) => {
@@ -92,8 +100,9 @@ export const referenceBatchExecutor = {
92
100
  const block = { kind: "block", value: { kind: decision, name: call.name } };
93
101
  return stored(expectEntry(await apply(request, block, id), "block"));
94
102
  }
95
- const frozen = { ...call, digest: `${requestDigest}:frozen` };
96
- const freeze = { kind: "freeze", call: frozen, awaitingConsent: false };
103
+ const frozen = { ...call, digest: frozenDigestOf(call.name, requestDigest) };
104
+ const awaitingConsent = CONSENT_TOOLS.has(call.name) && request.authorizedDigest !== frozen.digest;
105
+ const freeze = { kind: "freeze", call: frozen, awaitingConsent };
97
106
  return stored(expectEntry(await apply(request, freeze, id), "freeze"));
98
107
  };
99
108
  const release = async (ref) => {
@@ -122,6 +131,18 @@ export const referenceBatchExecutor = {
122
131
  throw new Error(`abort refused: ${reply.reason}`);
123
132
  return settled(ref);
124
133
  };
134
+ const consent = async (ref, frozenDigest) => {
135
+ const entry = await ledger.read(keyOf(ref));
136
+ if (entry === undefined)
137
+ return { kind: "unknown_execution" };
138
+ if ("call" in entry.progress && entry.progress.call.digest !== frozenDigest)
139
+ throw new Error(`consent for ${ref.executionId} names another frozen call`);
140
+ const reply = await apply(ref, { kind: "consent" }, ref.issuer);
141
+ if (reply.status === "refused" && reply.reason !== "terminal" && reply.reason !== "invalid_transition")
142
+ throw new Error(`consent refused: ${reply.reason}`);
143
+ const after = await ledger.read(keyOf(ref));
144
+ return after?.progress.state === "prepared" ? { kind: "prepared" } : settled(ref);
145
+ };
125
146
  const once = (run) => {
126
147
  const inflight = new Map();
127
148
  return (input) => {
@@ -135,7 +156,15 @@ export const referenceBatchExecutor = {
135
156
  return started;
136
157
  };
137
158
  };
138
- return { prepare: once(prepare), release: once(release), abort: once(abort) };
159
+ return {
160
+ prepare: once(prepare),
161
+ release: once(release),
162
+ abort: once(abort),
163
+ consent: (ref, frozenDigest) => {
164
+ alive();
165
+ return consent(ref, frozenDigest);
166
+ },
167
+ };
139
168
  },
140
169
  };
141
170
  //# sourceMappingURL=batch-executor.js.map
@@ -1,5 +1,10 @@
1
+ import type { StoreValue } from "../../durable/store.ts";
1
2
  import { type BatchCoordinator } from "../coordinator.ts";
2
- import type { BatchPlan, CallOutcome } from "../coordinator-types.ts";
3
+ import { type NestedAdmissionControl } from "../nested.ts";
4
+ import { type ScopeLifecycle } from "../scope-lifecycle.ts";
5
+ import { type WakeInbox } from "../wake-inbox.ts";
6
+ import { type WakeOutbox } from "../wake-outbox.ts";
7
+ import type { BatchConsent, BatchExecutor, BatchPlan, CallOutcome } from "../coordinator-types.ts";
3
8
  import type { BatchCaseAdapters, PausePoint } from "./batch-executor.ts";
4
9
  /** A coordinator write named by its step and call: `manifest`, `prepare:a`, `decision`, `release:a`, `outcome:a`. */
5
10
  export type BrainKill = {
@@ -24,8 +29,25 @@ export declare function batchHarness(adapters: BatchCaseAdapters): Promise<{
24
29
  reached: Promise<void>;
25
30
  open: () => void;
26
31
  };
27
- /** A fresh brain process over the brain's durable medium, optionally dying around one of its writes. */
28
- brain: (dieAt?: BrainKill) => Promise<BatchCoordinator>;
32
+ /**
33
+ * A fresh brain process over the brain's durable medium, optionally dying around one of its writes. Two issuers
34
+ * on one harness are two sessions' brains sharing the executors.
35
+ */
36
+ brain: (dieAt?: BrainKill, issuer?: string, consent?: BatchConsent) => Promise<BatchCoordinator>;
37
+ /** The brain's nested admission over the same durable medium, optionally dying around one of its writes. */
38
+ nested: (dieAt?: BrainKill, issuer?: string) => Promise<NestedAdmissionControl>;
39
+ /** A hand's durable wake outbox on its own medium (one per hand), optionally dying around one of its writes. */
40
+ wakeOutbox: (hand: string, dieAt?: BrainKill) => Promise<WakeOutbox>;
41
+ /** The endpoint's scope lifecycle on its own medium, optionally dying around one of its writes. */
42
+ scopes: (idleTtlMs: number, dieAt?: BrainKill) => Promise<ScopeLifecycle>;
43
+ /** The `wake_expired` records a hand's outbox logged, in log order. */
44
+ wakeLog: (hand: string) => Promise<readonly StoreValue[]>;
45
+ /** The brain's wake inbox over its medium; `owner` binds each scope to its authenticated hand. */
46
+ wakeInbox: (owner: (scope: string) => string | undefined, dieAt?: BrainKill) => Promise<WakeInbox>;
47
+ /** Moves every executor's clock: a lease that ends before the new time is expired on the next ledger event. */
48
+ advance: (ms: number) => void;
49
+ /** The executor proxy for `id`, as the brain reaches it (a late approval goes through it). */
50
+ executor: (id: string) => BatchExecutor;
29
51
  /** Kill the executor process and start a new one on the same durable medium. */
30
52
  restartExecutor: (id: string) => Promise<void>;
31
53
  /** Kill the executor and start it on a new, empty medium: every execution it held is lost. */
@@ -1,5 +1,9 @@
1
1
  import { createAdmissionLine } from "../../durable/store-admission.js";
2
2
  import { createBatchCoordinator } from "../coordinator.js";
3
+ import { createNestedAdmission } from "../nested.js";
4
+ import { createScopeLifecycle } from "../scope-lifecycle.js";
5
+ import { createWakeInbox } from "../wake-inbox.js";
6
+ import { createWakeOutbox } from "../wake-outbox.js";
3
7
  const ADMITTED_AT = 100;
4
8
  const NOW = ADMITTED_AT + 1;
5
9
  export class BrainKilledError extends Error {
@@ -11,7 +15,7 @@ export class BrainKilledError extends Error {
11
15
  const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
12
16
  function labelOf(writes) {
13
17
  for (const write of writes) {
14
- if (write.op !== "append" || write.kind !== "execution.batch")
18
+ if (write.op !== "append" || !write.kind.startsWith("execution."))
15
19
  continue;
16
20
  const data = write.data;
17
21
  if (!isObject(data))
@@ -109,6 +113,7 @@ export async function batchHarness(adapters) {
109
113
  await (await adapters.store.open(medium)).claim(0, 1);
110
114
  return medium;
111
115
  };
116
+ let clock = NOW;
112
117
  const executors = new Map();
113
118
  const start = async (id, medium) => {
114
119
  const killed = new AbortController();
@@ -117,7 +122,7 @@ export async function batchHarness(adapters) {
117
122
  id,
118
123
  store,
119
124
  epoch: 1,
120
- now: () => NOW,
125
+ now: () => clock,
121
126
  trace,
122
127
  pause,
123
128
  killed: killed.signal,
@@ -134,6 +139,12 @@ export async function batchHarness(adapters) {
134
139
  prepare: (request) => current(id).prepare(request),
135
140
  release: (ref) => current(id).release(ref),
136
141
  abort: (ref) => current(id).abort(ref),
142
+ consent: (ref, frozenDigest) => {
143
+ const endpoint = current(id);
144
+ if (endpoint.consent === undefined)
145
+ throw new Error(`executor ${id} takes no consent`);
146
+ return endpoint.consent(ref, frozenDigest);
147
+ },
137
148
  });
138
149
  const kill = (id) => {
139
150
  const found = executors.get(id);
@@ -145,6 +156,8 @@ export async function batchHarness(adapters) {
145
156
  for (const id of ["e1", "e2"])
146
157
  await start(id, await claimed());
147
158
  const brainMedium = await claimed();
159
+ const wakeMedia = new Map();
160
+ let scopeMedium;
148
161
  const brainWrites = [];
149
162
  const writeWaiters = new Map();
150
163
  const onDurable = (label) => {
@@ -167,17 +180,82 @@ export async function batchHarness(adapters) {
167
180
  found.open = open;
168
181
  return { reached: found.reached.promise, open: () => open.resolve() };
169
182
  },
170
- /** A fresh brain process over the brain's durable medium, optionally dying around one of its writes. */
171
- brain: async (dieAt) => {
183
+ /**
184
+ * A fresh brain process over the brain's durable medium, optionally dying around one of its writes. Two issuers
185
+ * on one harness are two sessions' brains sharing the executors.
186
+ */
187
+ brain: async (dieAt, issuer = "brain", consent) => {
172
188
  const opened = await adapters.store.open(brainMedium);
173
189
  return createBatchCoordinator({
174
- issuer: "brain",
190
+ ...(consent === undefined ? {} : { consent }),
191
+ issuer,
175
192
  store: brainStore(opened, onDurable, dieAt),
176
193
  epoch: 1,
177
194
  admission: createAdmissionLine(),
178
195
  executor: proxy,
179
196
  });
180
197
  },
198
+ /** The brain's nested admission over the same durable medium, optionally dying around one of its writes. */
199
+ nested: async (dieAt, issuer = "brain") => {
200
+ const opened = await adapters.store.open(brainMedium);
201
+ return createNestedAdmission({
202
+ issuer,
203
+ store: brainStore(opened, onDurable, dieAt),
204
+ epoch: 1,
205
+ admission: createAdmissionLine(),
206
+ clock: () => clock,
207
+ });
208
+ },
209
+ /** A hand's durable wake outbox on its own medium (one per hand), optionally dying around one of its writes. */
210
+ wakeOutbox: async (hand, dieAt) => {
211
+ let medium = wakeMedia.get(hand);
212
+ if (medium === undefined) {
213
+ medium = await claimed();
214
+ wakeMedia.set(hand, medium);
215
+ }
216
+ return createWakeOutbox({
217
+ hand,
218
+ store: brainStore(await adapters.store.open(medium), () => { }, dieAt),
219
+ epoch: 1,
220
+ admission: createAdmissionLine(),
221
+ clock: () => clock,
222
+ });
223
+ },
224
+ /** The endpoint's scope lifecycle on its own medium, optionally dying around one of its writes. */
225
+ scopes: async (idleTtlMs, dieAt) => {
226
+ if (scopeMedium === undefined)
227
+ scopeMedium = await claimed();
228
+ return createScopeLifecycle({
229
+ store: brainStore(await adapters.store.open(scopeMedium), () => { }, dieAt),
230
+ epoch: 1,
231
+ admission: createAdmissionLine(),
232
+ clock: () => clock,
233
+ idleTtlMs,
234
+ });
235
+ },
236
+ /** The `wake_expired` records a hand's outbox logged, in log order. */
237
+ wakeLog: async (hand) => {
238
+ const medium = wakeMedia.get(hand);
239
+ if (medium === undefined)
240
+ return [];
241
+ const store = await adapters.store.open(medium);
242
+ return (await store.scanRecords({ kind: "execution.wake-expired" })).map((record) => record.data);
243
+ },
244
+ /** The brain's wake inbox over its medium; `owner` binds each scope to its authenticated hand. */
245
+ wakeInbox: async (owner, dieAt) => createWakeInbox({
246
+ issuer: "brain",
247
+ store: brainStore(await adapters.store.open(brainMedium), onDurable, dieAt),
248
+ epoch: 1,
249
+ admission: createAdmissionLine(),
250
+ clock: () => clock,
251
+ owner,
252
+ }),
253
+ /** Moves every executor's clock: a lease that ends before the new time is expired on the next ledger event. */
254
+ advance: (ms) => {
255
+ clock += ms;
256
+ },
257
+ /** The executor proxy for `id`, as the brain reaches it (a late approval goes through it). */
258
+ executor: proxy,
181
259
  /** Kill the executor process and start a new one on the same durable medium. */
182
260
  restartExecutor: async (id) => start(id, kill(id)),
183
261
  /** Kill the executor and start it on a new, empty medium: every execution it held is lost. */
@@ -0,0 +1,8 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import type { NestedCancelTarget } from "../nested-types.ts";
3
+ import type { BatchCaseAdapters } from "./batch-executor.ts";
4
+ type CancelCase = CaseImplementation<BatchCaseAdapters>;
5
+ export declare const cancelTargetOf: (childRequestId: string, executor: string) => NestedCancelTarget;
6
+ export declare const CANCEL_CASES: ReadonlyMap<string, CancelCase>;
7
+ export {};
8
+ //# sourceMappingURL=cancel-cases.d.ts.map