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

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 (51) hide show
  1. package/dist/conformance/index.d.ts +14 -0
  2. package/dist/conformance/index.js +8 -0
  3. package/dist/conformance/registry.js +22 -0
  4. package/dist/execution/coordinator-codec.d.ts +5 -0
  5. package/dist/execution/coordinator-codec.js +93 -0
  6. package/dist/execution/coordinator-plan.d.ts +33 -0
  7. package/dist/execution/coordinator-plan.js +106 -0
  8. package/dist/execution/coordinator-types.d.ts +116 -0
  9. package/dist/execution/coordinator-types.js +2 -0
  10. package/dist/execution/coordinator.d.ts +25 -0
  11. package/dist/execution/coordinator.js +132 -0
  12. package/dist/execution/grant-verify.d.ts +70 -0
  13. package/dist/execution/grant-verify.js +87 -0
  14. package/dist/execution/ledger-codec.js +1 -0
  15. package/dist/execution/ledger-transition.js +8 -0
  16. package/dist/execution/ledger-types.d.ts +10 -0
  17. package/dist/execution/ledger.d.ts +2 -0
  18. package/dist/execution/ledger.js +1 -0
  19. package/dist/execution/remote-executor.d.ts +64 -0
  20. package/dist/execution/remote-executor.js +159 -0
  21. package/dist/execution/remote-hand-ledger.d.ts +40 -0
  22. package/dist/execution/remote-hand-ledger.js +137 -0
  23. package/dist/execution/remote-protocol.d.ts +87 -0
  24. package/dist/execution/remote-protocol.js +88 -0
  25. package/dist/execution/remote-tool-host.d.ts +29 -0
  26. package/dist/execution/remote-tool-host.js +155 -0
  27. package/dist/execution/testing/batch-cases.d.ts +6 -0
  28. package/dist/execution/testing/batch-cases.js +210 -0
  29. package/dist/execution/testing/batch-executor.d.ts +34 -0
  30. package/dist/execution/testing/batch-executor.js +141 -0
  31. package/dist/execution/testing/batch-harness.d.ts +36 -0
  32. package/dist/execution/testing/batch-harness.js +208 -0
  33. package/dist/execution/testing/batch-registry.d.ts +3 -0
  34. package/dist/execution/testing/batch-registry.js +30 -0
  35. package/dist/execution/testing/fault-hand-cases.d.ts +6 -0
  36. package/dist/execution/testing/fault-hand-cases.js +70 -0
  37. package/dist/execution/testing/hand-harness.d.ts +48 -0
  38. package/dist/execution/testing/hand-harness.js +136 -0
  39. package/dist/execution/testing/kill-batch.d.ts +12 -0
  40. package/dist/execution/testing/kill-batch.js +70 -0
  41. package/dist/execution/testing/kill-hand.d.ts +16 -0
  42. package/dist/execution/testing/kill-hand.js +75 -0
  43. package/dist/execution/testing/ledger-cases.js +9 -0
  44. package/dist/execution/testing/multi-hand-cases.d.ts +6 -0
  45. package/dist/execution/testing/multi-hand-cases.js +44 -0
  46. package/dist/execution/testing/prep-cases.d.ts +57 -0
  47. package/dist/execution/testing/prep-cases.js +89 -0
  48. package/dist/harness/env/nodejs.js +4 -0
  49. package/dist/index.d.ts +9 -0
  50. package/dist/index.js +8 -0
  51. package/package.json +3 -3
@@ -44,5 +44,19 @@ export type { ExecutionLedger } from "../execution/ledger.ts";
44
44
  export type { ExecutionAdmission, ExecutionCommand, ExecutionEntry, ExecutionEvent, ExecutionKey, ExecutionOutcome, ExecutionProgress, FrozenCall, LedgerReply, } from "../execution/ledger-types.ts";
45
45
  export { LEDGER_CASES } from "../execution/testing/ledger-cases.ts";
46
46
  export { KILL_LEDGER_CASES, KILL_LEDGER_DECLARATIONS } from "../execution/testing/kill-ledger.ts";
47
+ export { FAULT_HAND_CASES } from "../execution/testing/fault-hand-cases.ts";
48
+ export type { HandCaseAdapters } from "../execution/testing/hand-harness.ts";
49
+ export type { KillHandDeclaration } from "../execution/testing/kill-hand.ts";
50
+ export { KILL_HAND_CASES, KILL_HAND_DECLARATIONS } from "../execution/testing/kill-hand.ts";
51
+ export { MULTI_HAND_CASES } from "../execution/testing/multi-hand-cases.ts";
47
52
  export type { KillLedgerDeclaration } from "../execution/testing/kill-ledger.ts";
53
+ export type { BatchCoordinator, BatchCoordinatorOptions } from "../execution/coordinator.ts";
54
+ export { BatchManifestConflictError, createBatchCoordinator } from "../execution/coordinator.ts";
55
+ export { interruptedReplayText } from "../execution/coordinator-plan.ts";
56
+ export type { BatchCallPlan, BatchDecision, BatchExecutor, BatchManifest, BatchPlan, BatchRecord, BatchResult, CallOutcome, ExecutionRef, ManifestCall, PrepareReply, PrepareRequest, SettleReply, } from "../execution/coordinator-types.ts";
57
+ export { BATCH_CASES } from "../execution/testing/batch-cases.ts";
58
+ export type { BatchCaseAdapters, BatchExecutorConformanceAdapter, ExecutorOpenOptions, PausePoint, } from "../execution/testing/batch-executor.ts";
59
+ export { referenceBatchExecutor } from "../execution/testing/batch-executor.ts";
60
+ export type { KillBatchDeclaration } from "../execution/testing/kill-batch.ts";
61
+ export { KILL_BATCH_CASES, KILL_BATCH_DECLARATIONS } from "../execution/testing/kill-batch.ts";
48
62
  //# sourceMappingURL=index.d.ts.map
@@ -23,4 +23,12 @@ export { TransportClosedError } from "../transport/transport.js";
23
23
  export { createExecutionLedger } from "../execution/ledger.js";
24
24
  export { LEDGER_CASES } from "../execution/testing/ledger-cases.js";
25
25
  export { KILL_LEDGER_CASES, KILL_LEDGER_DECLARATIONS } from "../execution/testing/kill-ledger.js";
26
+ export { FAULT_HAND_CASES } from "../execution/testing/fault-hand-cases.js";
27
+ export { KILL_HAND_CASES, KILL_HAND_DECLARATIONS } from "../execution/testing/kill-hand.js";
28
+ export { MULTI_HAND_CASES } from "../execution/testing/multi-hand-cases.js";
29
+ export { BatchManifestConflictError, createBatchCoordinator } from "../execution/coordinator.js";
30
+ export { interruptedReplayText } from "../execution/coordinator-plan.js";
31
+ export { BATCH_CASES } from "../execution/testing/batch-cases.js";
32
+ export { referenceBatchExecutor } from "../execution/testing/batch-executor.js";
33
+ export { KILL_BATCH_CASES, KILL_BATCH_DECLARATIONS } from "../execution/testing/kill-batch.js";
26
34
  //# sourceMappingURL=index.js.map
@@ -1,3 +1,5 @@
1
+ import { KILL_HAND_DECLARATIONS } from "../execution/testing/kill-hand.js";
2
+ import { BATCH_REGISTRY } from "../execution/testing/batch-registry.js";
1
3
  import { LEDGER_REGISTRY } from "../execution/testing/ledger-registry.js";
2
4
  export const ADAPTER_KINDS = ["store", "wake", "transport", "executor", "host"];
3
5
  /**
@@ -27,6 +29,24 @@ const wakeCase = (id, impl, expected) => ({
27
29
  adapters: ["store", "wake"],
28
30
  expected,
29
31
  });
32
+ const HAND_INTRO = "#5482";
33
+ const handCase = (id, impl, expected) => ({
34
+ id,
35
+ impl,
36
+ intro: HAND_INTRO,
37
+ adapters: ["store", "transport", "executor"],
38
+ expected,
39
+ });
40
+ const KILL_HAND_IMPL = "packages/agent/src/execution/testing/kill-hand.ts";
41
+ const MULTI_HAND_IMPL = "packages/agent/src/execution/testing/multi-hand-cases.ts";
42
+ const FAULT_HAND_IMPL = "packages/agent/src/execution/testing/fault-hand-cases.ts";
43
+ const HAND_REGISTRY = [
44
+ ...KILL_HAND_DECLARATIONS.map(({ id, expected }) => handCase(id, KILL_HAND_IMPL, expected)),
45
+ handCase("MULTI-HAND-01", MULTI_HAND_IMPL, "N scopes batch at once on one hand; each scope's calls start in lane order"),
46
+ handCase("MULTI-KILL-01", MULTI_HAND_IMPL, "cross-machine: a hand killed with several scopes in flight; each ends hand_restarted, uncertain, never rerun"),
47
+ ...["slow", "lossy", "laggy", "flap", "drop-reattach"].map((profile, index) => handCase(`FAULT-HAND-0${index + 1}`, FAULT_HAND_IMPL, `${profile} profile: every call settles with its unfaulted result, runs once, per-scope order kept`)),
48
+ handCase("FAULT-HAND-MULTI-01", FAULT_HAND_IMPL, "hand unreachable past the resume window: dependent calls pause, then each scope resumes exactly once"),
49
+ ];
30
50
  const storeCase = (id, impl, expected) => ({
31
51
  id,
32
52
  impl,
@@ -36,6 +56,7 @@ const storeCase = (id, impl, expected) => ({
36
56
  });
37
57
  export const CONFORMANCE_REGISTRY = [
38
58
  ...LEDGER_REGISTRY,
59
+ ...BATCH_REGISTRY,
39
60
  storeCase("STORE-01", STORE_CASES_IMPL, "a commit adopts once, after its batch is durable; every instance sees each batch whole"),
40
61
  storeCase("STORE-02", STORE_CASES_IMPL, "a cut at every write point of a commit leaves nothing of it durable, with no adopt and no seq burned"),
41
62
  storeCase("STORE-03", STORE_CASES_IMPL, "concurrent admissions run one at a time in admission order; a refused mutation releases the line"),
@@ -73,5 +94,6 @@ export const CONFORMANCE_REGISTRY = [
73
94
  faultCase(3, "laggy"),
74
95
  faultCase(4, "flap"),
75
96
  faultCase(5, "drop-reattach"),
97
+ ...HAND_REGISTRY,
76
98
  ];
77
99
  //# sourceMappingURL=registry.js.map
@@ -0,0 +1,5 @@
1
+ import type { StoreValue } from "../durable/store.ts";
2
+ import type { BatchRecord } from "./coordinator-types.ts";
3
+ /** Stored JSON crosses its schema boundary once, on read. A corrupt record must never look like a missing batch. */
4
+ export declare function decodeBatchRecord(value: StoreValue): BatchRecord;
5
+ //# sourceMappingURL=coordinator-codec.d.ts.map
@@ -0,0 +1,93 @@
1
+ function object(value) {
2
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3
+ }
4
+ function strings(value, keys) {
5
+ return keys.every((key) => typeof value[key] === "string");
6
+ }
7
+ function numbers(value, keys) {
8
+ return keys.every((key) => typeof value[key] === "number" && Number.isFinite(value[key]));
9
+ }
10
+ function terminal(value) {
11
+ if (!object(value) || typeof value.hooksRan !== "boolean" || typeof value.uncertain !== "boolean")
12
+ return false;
13
+ return value.reason === "result" || value.reason === "blocked"
14
+ ? value.value !== undefined
15
+ : ["cancelled", "lease_expired", "hand_restarted", "uncertain"].includes(String(value.reason));
16
+ }
17
+ function manifestCall(value) {
18
+ return (object(value) &&
19
+ strings(value, ["executionId", "executor", "name", "requestDigest"]) &&
20
+ numbers(value, ["sourceIndex", "wave"]) &&
21
+ typeof value.sequential === "boolean" &&
22
+ value.args !== undefined &&
23
+ Array.isArray(value.dependsOn) &&
24
+ value.dependsOn.every((dependency) => typeof dependency === "number"));
25
+ }
26
+ function manifest(value) {
27
+ return (object(value) &&
28
+ strings(value, ["batchId", "scope", "workspace", "issuer", "manifestDigest"]) &&
29
+ numbers(value, ["generation", "admittedAt", "leaseUntil"]) &&
30
+ Array.isArray(value.calls) &&
31
+ value.calls.every(manifestCall));
32
+ }
33
+ function prepareReply(value) {
34
+ if (!object(value))
35
+ return false;
36
+ switch (value.kind) {
37
+ case "prepared":
38
+ return typeof value.frozenDigest === "string";
39
+ case "blocked":
40
+ return value.result !== undefined;
41
+ case "batch_abort":
42
+ return true;
43
+ case "settled":
44
+ return terminal(value.outcome);
45
+ default:
46
+ return false;
47
+ }
48
+ }
49
+ function callOutcome(value) {
50
+ if (!object(value))
51
+ return false;
52
+ switch (value.kind) {
53
+ case "result":
54
+ return value.value !== undefined;
55
+ case "blocked":
56
+ return value.result !== undefined;
57
+ case "not_run":
58
+ return value.cause === "batch_abort" || value.cause === "interrupted_preparation";
59
+ case "interrupted":
60
+ return typeof value.reason === "string" && typeof value.uncertain === "boolean";
61
+ default:
62
+ return false;
63
+ }
64
+ }
65
+ function record(value) {
66
+ if (!object(value) || !manifest(value.manifest))
67
+ return false;
68
+ const size = value.manifest.calls.length;
69
+ const { prepares, released, outcomes, decision } = value;
70
+ return ((decision === null || decision === "RELEASE" || decision === "ABORT") &&
71
+ Array.isArray(prepares) &&
72
+ prepares.length === size &&
73
+ prepares.every((reply) => reply === null || prepareReply(reply)) &&
74
+ Array.isArray(released) &&
75
+ released.length === size &&
76
+ released.every((mark) => typeof mark === "boolean") &&
77
+ Array.isArray(outcomes) &&
78
+ outcomes.length === size &&
79
+ outcomes.every((outcome) => outcome === null || callOutcome(outcome)));
80
+ }
81
+ class BatchRecordCorruptError extends Error {
82
+ constructor() {
83
+ super("invalid durable batch record");
84
+ this.name = "BatchRecordCorruptError";
85
+ }
86
+ }
87
+ /** Stored JSON crosses its schema boundary once, on read. A corrupt record must never look like a missing batch. */
88
+ export function decodeBatchRecord(value) {
89
+ if (!record(value))
90
+ throw new BatchRecordCorruptError();
91
+ return value;
92
+ }
93
+ //# sourceMappingURL=coordinator-codec.js.map
@@ -0,0 +1,33 @@
1
+ import type { BatchManifest, BatchPlan, CallOutcome, PrepareReply, SettleReply } from "./coordinator-types.ts";
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
5
+ * previous sequential call only.
6
+ */
7
+ export declare function batchDependencies(calls: readonly {
8
+ readonly sequential: boolean;
9
+ }[]): {
10
+ readonly dependsOn: number[];
11
+ readonly wave: number;
12
+ }[];
13
+ export declare function buildBatchManifest(issuer: string, plan: BatchPlan): Promise<BatchManifest>;
14
+ /**
15
+ * A reply after which no later call is prepared and the decision is ABORT. A raw `settled` outcome other than a result
16
+ * fails closed, `blocked` included: the ledger stores a blocked call and a preflight abort under the same reason, and
17
+ * an executor that stopped a preparation itself answers `blocked` or `batch_abort` instead.
18
+ */
19
+ export declare function abortCause(reply: PrepareReply): "batch_abort" | "interrupted_preparation" | undefined;
20
+ /**
21
+ * Whether `index` and everything it transitively depends on have final outcomes. A call that settled at preparation
22
+ * still finishes only after its own dependencies, as today's scheduler awaits them before every call's outcome.
23
+ */
24
+ export declare function finished(calls: readonly {
25
+ readonly dependsOn: readonly number[];
26
+ }[], outcomes: readonly unknown[], index: number): boolean;
27
+ export declare function settledOutcome(reply: SettleReply): CallOutcome;
28
+ /**
29
+ * What the model is shown for a call whose run was cut short, so a replay equals today's (plan X12, K4): today's
30
+ * pair-repair placeholder, never a rerun. Undefined for a call that settled, was blocked, or was aborted by a hook.
31
+ */
32
+ export declare function interruptedReplayText(outcome: CallOutcome): string | undefined;
33
+ //# sourceMappingURL=coordinator-plan.d.ts.map
@@ -0,0 +1,106 @@
1
+ import { TOOL_RESULT_PLACEHOLDER } from "@earendil-works/pi-ai";
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
5
+ * previous sequential call only.
6
+ */
7
+ export function batchDependencies(calls) {
8
+ const result = [];
9
+ let previousSequential;
10
+ let parallelSince = [];
11
+ for (const [index, call] of calls.entries()) {
12
+ const anchor = previousSequential === undefined ? [] : [previousSequential];
13
+ const dependsOn = call.sequential ? [...anchor, ...parallelSince] : anchor;
14
+ const wave = Math.max(-1, ...dependsOn.map((dependency) => result[dependency]?.wave ?? -1)) + 1;
15
+ result.push({ dependsOn, wave });
16
+ if (call.sequential) {
17
+ previousSequential = index;
18
+ parallelSince = [];
19
+ }
20
+ else
21
+ parallelSince.push(index);
22
+ }
23
+ return result;
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
+ export async function buildBatchManifest(issuer, plan) {
39
+ const dependencies = batchDependencies(plan.calls);
40
+ const calls = [];
41
+ for (const [sourceIndex, call] of plan.calls.entries()) {
42
+ const placement = dependencies[sourceIndex] ?? { dependsOn: [], wave: 0 };
43
+ calls.push({
44
+ ...call,
45
+ sourceIndex,
46
+ dependsOn: placement.dependsOn,
47
+ wave: placement.wave,
48
+ requestDigest: await digest({ name: call.name, args: call.args }),
49
+ });
50
+ }
51
+ const { calls: _calls, ...header } = plan;
52
+ return { ...header, issuer, calls, manifestDigest: await digest({ ...header, issuer, calls }) };
53
+ }
54
+ /**
55
+ * A reply after which no later call is prepared and the decision is ABORT. A raw `settled` outcome other than a result
56
+ * fails closed, `blocked` included: the ledger stores a blocked call and a preflight abort under the same reason, and
57
+ * an executor that stopped a preparation itself answers `blocked` or `batch_abort` instead.
58
+ */
59
+ export function abortCause(reply) {
60
+ if (reply.kind === "batch_abort")
61
+ return "batch_abort";
62
+ if (reply.kind === "settled" && reply.outcome.reason !== "result")
63
+ return "interrupted_preparation";
64
+ return undefined;
65
+ }
66
+ /**
67
+ * Whether `index` and everything it transitively depends on have final outcomes. A call that settled at preparation
68
+ * still finishes only after its own dependencies, as today's scheduler awaits them before every call's outcome.
69
+ */
70
+ export function finished(calls, outcomes, index) {
71
+ const done = new Map();
72
+ const visit = (at) => {
73
+ const known = done.get(at);
74
+ if (known !== undefined)
75
+ return known;
76
+ const result = outcomes[at] !== null && (calls[at]?.dependsOn ?? []).every((dependency) => visit(dependency));
77
+ done.set(at, result);
78
+ return result;
79
+ };
80
+ return visit(index);
81
+ }
82
+ export function settledOutcome(reply) {
83
+ if (reply.kind === "unknown_execution")
84
+ return { kind: "interrupted", reason: "unknown_execution", uncertain: true };
85
+ const { outcome } = reply;
86
+ switch (outcome.reason) {
87
+ case "result":
88
+ return { kind: "result", value: outcome.value };
89
+ case "blocked":
90
+ return { kind: "blocked", result: outcome.value };
91
+ default:
92
+ return { kind: "interrupted", reason: outcome.reason, uncertain: outcome.uncertain };
93
+ }
94
+ }
95
+ /**
96
+ * What the model is shown for a call whose run was cut short, so a replay equals today's (plan X12, K4): today's
97
+ * pair-repair placeholder, never a rerun. Undefined for a call that settled, was blocked, or was aborted by a hook.
98
+ */
99
+ export function interruptedReplayText(outcome) {
100
+ if (outcome.kind === "interrupted")
101
+ return TOOL_RESULT_PLACEHOLDER;
102
+ if (outcome.kind === "not_run" && outcome.cause === "interrupted_preparation")
103
+ return TOOL_RESULT_PLACEHOLDER;
104
+ return undefined;
105
+ }
106
+ //# sourceMappingURL=coordinator-plan.js.map
@@ -0,0 +1,116 @@
1
+ import type { StoreValue } from "../durable/store.ts";
2
+ import type { ExecutionOutcome } from "./ledger-types.ts";
3
+ /** One model call of an assistant message, in source order, as the brain plans it. */
4
+ export type BatchCallPlan = {
5
+ readonly executionId: string;
6
+ readonly executor: string;
7
+ readonly name: string;
8
+ readonly args: StoreValue;
9
+ /** The tool's `executionMode` is `"sequential"`, the same test today's scheduler applies. */
10
+ readonly sequential: boolean;
11
+ };
12
+ export type BatchPlan = {
13
+ readonly batchId: string;
14
+ readonly scope: string;
15
+ readonly workspace: string;
16
+ readonly generation: number;
17
+ readonly admittedAt: number;
18
+ readonly leaseUntil: number;
19
+ readonly calls: readonly BatchCallPlan[];
20
+ };
21
+ export type ManifestCall = BatchCallPlan & {
22
+ readonly sourceIndex: number;
23
+ /** Source indexes this call waits for before its release, computed as today's scheduler computes them. */
24
+ readonly dependsOn: readonly number[];
25
+ readonly wave: number;
26
+ readonly requestDigest: string;
27
+ };
28
+ export type BatchManifest = Omit<BatchPlan, "calls"> & {
29
+ readonly issuer: string;
30
+ readonly manifestDigest: string;
31
+ readonly calls: readonly ManifestCall[];
32
+ };
33
+ export type PrepareRequest = {
34
+ readonly issuer: string;
35
+ readonly executionId: string;
36
+ readonly generation: number;
37
+ readonly batchId: string;
38
+ readonly manifestDigest: string;
39
+ readonly scope: string;
40
+ readonly workspace: string;
41
+ readonly admittedAt: number;
42
+ readonly leaseUntil: number;
43
+ readonly requestDigest: string;
44
+ readonly call: {
45
+ readonly name: string;
46
+ readonly args: StoreValue;
47
+ };
48
+ };
49
+ export type ExecutionRef = {
50
+ readonly issuer: string;
51
+ readonly executionId: string;
52
+ readonly generation: number;
53
+ };
54
+ /**
55
+ * The executor's durable answer to a prepare. A re-sent prepare returns the stored answer and never reruns
56
+ * preparation; a call whose endpoint already ended (for example `hand_restarted` after an executor restart during
57
+ * preparation) answers `settled` with that terminal outcome. A preparation the executor stopped itself is answered as
58
+ * `blocked` or `batch_abort`, also on a re-send, never as the raw `settled` ledger outcome: the ledger stores both
59
+ * under reason `blocked`, and only the executor can tell a blocked call from a preflight abort.
60
+ */
61
+ export type PrepareReply = {
62
+ readonly kind: "prepared";
63
+ readonly frozenDigest: string;
64
+ } | {
65
+ readonly kind: "blocked";
66
+ readonly result: StoreValue;
67
+ } | {
68
+ readonly kind: "batch_abort";
69
+ } | {
70
+ readonly kind: "settled";
71
+ readonly outcome: ExecutionOutcome;
72
+ };
73
+ /** Release and abort answer with the endpoint's terminal outcome; an executor that lost the call says so. */
74
+ export type SettleReply = {
75
+ readonly kind: "settled";
76
+ readonly outcome: ExecutionOutcome;
77
+ } | {
78
+ readonly kind: "unknown_execution";
79
+ };
80
+ /** The hand side of the batch protocol. Every method is replay-safe: re-sending gives the same effect. */
81
+ export interface BatchExecutor {
82
+ prepare(request: PrepareRequest): Promise<PrepareReply>;
83
+ /** Resolves once the released call has settled. */
84
+ release(ref: ExecutionRef): Promise<SettleReply>;
85
+ abort(ref: ExecutionRef): Promise<SettleReply>;
86
+ }
87
+ export type BatchDecision = "RELEASE" | "ABORT";
88
+ export type CallOutcome = {
89
+ readonly kind: "result";
90
+ readonly value: StoreValue;
91
+ } | {
92
+ readonly kind: "blocked";
93
+ readonly result: StoreValue;
94
+ }
95
+ /** The body never ran: the batch was aborted before this call was released. */
96
+ | {
97
+ readonly kind: "not_run";
98
+ readonly cause: "batch_abort" | "interrupted_preparation";
99
+ } | {
100
+ readonly kind: "interrupted";
101
+ readonly reason: Exclude<ExecutionOutcome["reason"], "result" | "blocked"> | "unknown_execution";
102
+ readonly uncertain: boolean;
103
+ };
104
+ /** The coordinator's durable record of one batch; every field is written before the message it causes is sent. */
105
+ export type BatchRecord = {
106
+ readonly manifest: BatchManifest;
107
+ readonly prepares: readonly (PrepareReply | null)[];
108
+ readonly decision: BatchDecision | null;
109
+ readonly released: readonly boolean[];
110
+ readonly outcomes: readonly (CallOutcome | null)[];
111
+ };
112
+ export type BatchResult = {
113
+ readonly decision: BatchDecision;
114
+ readonly outcomes: readonly CallOutcome[];
115
+ };
116
+ //# sourceMappingURL=coordinator-types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=coordinator-types.js.map
@@ -0,0 +1,25 @@
1
+ import type { DurableStore } from "../durable/store.ts";
2
+ import type { AdmissionLine } from "../durable/store-admission.ts";
3
+ import type { BatchExecutor, BatchPlan, BatchRecord, BatchResult } from "./coordinator-types.ts";
4
+ export declare class BatchManifestConflictError extends Error {
5
+ constructor(batchId: string);
6
+ }
7
+ export interface BatchCoordinatorOptions {
8
+ readonly issuer: string;
9
+ readonly store: DurableStore;
10
+ readonly epoch: number;
11
+ /** The single admission line of the store's writable epoch, shared with every other writer on it. */
12
+ readonly admission: AdmissionLine;
13
+ readonly executor: (id: string) => BatchExecutor;
14
+ }
15
+ export interface BatchCoordinator {
16
+ /**
17
+ * Runs one batch to its final outcomes: manifest, prepare in source order, one decision, then release by
18
+ * dependencies or abort. A batch with a durable record resumes from it, so calling `run` again after a crash (or
19
+ * after an executor call failed) recovers instead of starting over.
20
+ */
21
+ run(plan: BatchPlan): Promise<BatchResult>;
22
+ read(batchId: string): Promise<BatchRecord | undefined>;
23
+ }
24
+ export declare function createBatchCoordinator(options: BatchCoordinatorOptions): BatchCoordinator;
25
+ //# sourceMappingURL=coordinator.d.ts.map
@@ -0,0 +1,132 @@
1
+ import { decodeBatchRecord } from "./coordinator-codec.js";
2
+ import { abortCause, buildBatchManifest, finished, settledOutcome } from "./coordinator-plan.js";
3
+ const PREFIX = "execution.batch:";
4
+ const keyOf = (issuer, batchId) => `${PREFIX}${JSON.stringify([issuer, batchId])}`;
5
+ export class BatchManifestConflictError extends Error {
6
+ constructor(batchId) {
7
+ super(`batch ${batchId} already has a different durable manifest`);
8
+ this.name = "BatchManifestConflictError";
9
+ }
10
+ }
11
+ const replace = (items, index, value) => items.map((item, at) => (at === index ? value : item));
12
+ export function createBatchCoordinator(options) {
13
+ const { issuer, store, epoch, admission, executor } = options;
14
+ const read = async (batchId) => {
15
+ const value = await store.getDocument(keyOf(issuer, batchId));
16
+ return value === undefined ? undefined : decodeBatchRecord(value);
17
+ };
18
+ return {
19
+ read,
20
+ run: async (plan) => {
21
+ const manifest = await buildBatchManifest(issuer, plan);
22
+ const key = keyOf(issuer, plan.batchId);
23
+ let record = await read(plan.batchId);
24
+ const persist = async (next, step, call) => {
25
+ const data = { batchId: plan.batchId, step, executionId: call?.executionId ?? null };
26
+ await admission.admit(() => store.commit(epoch, [
27
+ { op: "append", id: store.mintId(), kind: "execution.batch", data },
28
+ { op: "put", key, data: next },
29
+ ], () => { }));
30
+ record = next;
31
+ };
32
+ const current = () => {
33
+ if (record === undefined)
34
+ throw new Error(`batch ${plan.batchId} has no durable record`);
35
+ return record;
36
+ };
37
+ const ref = (call) => ({
38
+ issuer,
39
+ executionId: call.executionId,
40
+ generation: manifest.generation,
41
+ });
42
+ const settle = async (call, outcome) => persist({ ...current(), outcomes: replace(current().outcomes, call.sourceIndex, outcome) }, "outcome", call);
43
+ if (record === undefined) {
44
+ const empty = manifest.calls.map(() => null);
45
+ await persist({
46
+ manifest,
47
+ prepares: empty,
48
+ decision: null,
49
+ released: manifest.calls.map(() => false),
50
+ outcomes: empty,
51
+ }, "manifest");
52
+ }
53
+ else if (record.manifest.manifestDigest !== manifest.manifestDigest) {
54
+ throw new BatchManifestConflictError(plan.batchId);
55
+ }
56
+ if (current().decision === null) {
57
+ for (const call of manifest.calls) {
58
+ let reply = current().prepares[call.sourceIndex] ?? null;
59
+ if (reply === null) {
60
+ reply = await executor(call.executor).prepare({
61
+ ...ref(call),
62
+ batchId: manifest.batchId,
63
+ manifestDigest: manifest.manifestDigest,
64
+ scope: manifest.scope,
65
+ workspace: manifest.workspace,
66
+ admittedAt: manifest.admittedAt,
67
+ leaseUntil: manifest.leaseUntil,
68
+ requestDigest: call.requestDigest,
69
+ call: { name: call.name, args: call.args },
70
+ });
71
+ await persist({ ...current(), prepares: replace(current().prepares, call.sourceIndex, reply) }, "prepare", call);
72
+ }
73
+ if (abortCause(reply) !== undefined)
74
+ break;
75
+ }
76
+ const aborted = current().prepares.some((reply) => reply !== null && abortCause(reply) !== undefined);
77
+ await persist({ ...current(), decision: aborted ? "ABORT" : "RELEASE" }, "decision");
78
+ }
79
+ const cause = current()
80
+ .prepares.map((reply) => (reply === null ? undefined : abortCause(reply)))
81
+ .find((found) => found !== undefined) ?? "batch_abort";
82
+ for (const call of manifest.calls) {
83
+ if (current().outcomes[call.sourceIndex] !== null)
84
+ continue;
85
+ const reply = current().prepares[call.sourceIndex] ?? null;
86
+ if (reply?.kind === "settled")
87
+ await settle(call, settledOutcome(reply));
88
+ else if (reply?.kind === "blocked") {
89
+ await executor(call.executor).abort(ref(call));
90
+ await settle(call, { kind: "blocked", result: reply.result });
91
+ }
92
+ else if (current().decision === "ABORT") {
93
+ if (reply !== null)
94
+ await executor(call.executor).abort(ref(call));
95
+ await settle(call, { kind: "not_run", cause });
96
+ }
97
+ }
98
+ const inflight = new Map();
99
+ for (;;) {
100
+ for (const call of manifest.calls) {
101
+ const index = call.sourceIndex;
102
+ if (current().outcomes[index] !== null || inflight.has(index))
103
+ continue;
104
+ if (!current().released[index]) {
105
+ const ready = call.dependsOn.every((dependency) => finished(manifest.calls, current().outcomes, dependency));
106
+ if (!ready)
107
+ continue;
108
+ await persist({ ...current(), released: replace(current().released, index, true) }, "release", call);
109
+ }
110
+ inflight.set(index, executor(call.executor)
111
+ .release(ref(call))
112
+ .then((reply) => ({ index, ok: true, reply }), (error) => ({ index, ok: false, error })));
113
+ }
114
+ if (inflight.size === 0)
115
+ break;
116
+ const settled = await Promise.race(inflight.values());
117
+ inflight.delete(settled.index);
118
+ if (!settled.ok)
119
+ throw settled.error;
120
+ const call = manifest.calls[settled.index];
121
+ if (call !== undefined)
122
+ await settle(call, settledOutcome(settled.reply));
123
+ }
124
+ const { decision, outcomes } = current();
125
+ const final = outcomes.filter((outcome) => outcome !== null);
126
+ if (decision === null || final.length !== outcomes.length)
127
+ throw new Error(`batch ${plan.batchId} ended with an unsettled call`);
128
+ return { decision, outcomes: final };
129
+ },
130
+ };
131
+ }
132
+ //# sourceMappingURL=coordinator.js.map