@code-yeongyu/senpi-agent-core 2026.11.3-2 → 2026.11.4-2

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 (118) hide show
  1. package/dist/agent-loop.js +7 -47
  2. package/dist/conformance/index.d.ts +37 -0
  3. package/dist/conformance/index.js +25 -0
  4. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  5. package/dist/conformance/loop-core-manifest.js +1 -0
  6. package/dist/conformance/registry.js +31 -1
  7. package/dist/execution/canonical-json.d.ts +3 -0
  8. package/dist/execution/canonical-json.js +12 -0
  9. package/dist/execution/coordinator-codec.d.ts +5 -0
  10. package/dist/execution/coordinator-codec.js +104 -0
  11. package/dist/execution/coordinator-consent.d.ts +29 -0
  12. package/dist/execution/coordinator-consent.js +63 -0
  13. package/dist/execution/coordinator-plan.d.ts +33 -0
  14. package/dist/execution/coordinator-plan.js +106 -0
  15. package/dist/execution/coordinator-sequential.d.ts +15 -0
  16. package/dist/execution/coordinator-sequential.js +34 -0
  17. package/dist/execution/coordinator-types.d.ts +161 -0
  18. package/dist/execution/coordinator-types.js +2 -0
  19. package/dist/execution/coordinator.d.ts +27 -0
  20. package/dist/execution/coordinator.js +164 -0
  21. package/dist/execution/device-files-node.d.ts +8 -0
  22. package/dist/execution/device-files-node.js +112 -0
  23. package/dist/execution/device-files.d.ts +80 -0
  24. package/dist/execution/device-files.js +87 -0
  25. package/dist/execution/grant-verify.d.ts +70 -0
  26. package/dist/execution/grant-verify.js +87 -0
  27. package/dist/execution/ledger.d.ts +2 -0
  28. package/dist/execution/ledger.js +1 -0
  29. package/dist/execution/nested-codec.d.ts +5 -0
  30. package/dist/execution/nested-codec.js +41 -0
  31. package/dist/execution/nested-types.d.ts +92 -0
  32. package/dist/execution/nested-types.js +3 -0
  33. package/dist/execution/nested.d.ts +48 -0
  34. package/dist/execution/nested.js +206 -0
  35. package/dist/execution/plane-model.d.ts +33 -0
  36. package/dist/execution/plane-model.js +80 -0
  37. package/dist/execution/plane.d.ts +72 -0
  38. package/dist/execution/plane.js +172 -0
  39. package/dist/execution/remote-device-files.d.ts +12 -0
  40. package/dist/execution/remote-device-files.js +84 -0
  41. package/dist/execution/remote-executor.d.ts +74 -0
  42. package/dist/execution/remote-executor.js +193 -0
  43. package/dist/execution/remote-file-call.d.ts +14 -0
  44. package/dist/execution/remote-file-call.js +30 -0
  45. package/dist/execution/remote-hand-ledger.d.ts +40 -0
  46. package/dist/execution/remote-hand-ledger.js +137 -0
  47. package/dist/execution/remote-link.d.ts +36 -0
  48. package/dist/execution/remote-link.js +117 -0
  49. package/dist/execution/remote-protocol.d.ts +104 -0
  50. package/dist/execution/remote-protocol.js +104 -0
  51. package/dist/execution/remote-tool-host.d.ts +37 -0
  52. package/dist/execution/remote-tool-host.js +114 -0
  53. package/dist/execution/scope-lifecycle.d.ts +81 -0
  54. package/dist/execution/scope-lifecycle.js +173 -0
  55. package/dist/execution/testing/batch-cases.d.ts +6 -0
  56. package/dist/execution/testing/batch-cases.js +210 -0
  57. package/dist/execution/testing/batch-executor.d.ts +34 -0
  58. package/dist/execution/testing/batch-executor.js +170 -0
  59. package/dist/execution/testing/batch-harness.d.ts +58 -0
  60. package/dist/execution/testing/batch-harness.js +286 -0
  61. package/dist/execution/testing/batch-registry.d.ts +3 -0
  62. package/dist/execution/testing/batch-registry.js +30 -0
  63. package/dist/execution/testing/cancel-cases.d.ts +8 -0
  64. package/dist/execution/testing/cancel-cases.js +64 -0
  65. package/dist/execution/testing/consent-cases.d.ts +14 -0
  66. package/dist/execution/testing/consent-cases.js +66 -0
  67. package/dist/execution/testing/fault-hand-cases.d.ts +6 -0
  68. package/dist/execution/testing/fault-hand-cases.js +70 -0
  69. package/dist/execution/testing/hand-harness.d.ts +48 -0
  70. package/dist/execution/testing/hand-harness.js +136 -0
  71. package/dist/execution/testing/kill-batch.d.ts +12 -0
  72. package/dist/execution/testing/kill-batch.js +70 -0
  73. package/dist/execution/testing/kill-hand.d.ts +16 -0
  74. package/dist/execution/testing/kill-hand.js +75 -0
  75. package/dist/execution/testing/kill-nest.d.ts +6 -0
  76. package/dist/execution/testing/kill-nest.js +55 -0
  77. package/dist/execution/testing/kill-wakex.d.ts +6 -0
  78. package/dist/execution/testing/kill-wakex.js +81 -0
  79. package/dist/execution/testing/lifecycle-cases.d.ts +9 -0
  80. package/dist/execution/testing/lifecycle-cases.js +60 -0
  81. package/dist/execution/testing/lifecycle-registry.d.ts +3 -0
  82. package/dist/execution/testing/lifecycle-registry.js +19 -0
  83. package/dist/execution/testing/multi-hand-cases.d.ts +6 -0
  84. package/dist/execution/testing/multi-hand-cases.js +44 -0
  85. package/dist/execution/testing/multi-lifecycle-cases.d.ts +4 -0
  86. package/dist/execution/testing/multi-lifecycle-cases.js +34 -0
  87. package/dist/execution/testing/multi-seq-cases.d.ts +4 -0
  88. package/dist/execution/testing/multi-seq-cases.js +46 -0
  89. package/dist/execution/testing/nest-cases.d.ts +39 -0
  90. package/dist/execution/testing/nest-cases.js +181 -0
  91. package/dist/execution/testing/nest-registry.d.ts +3 -0
  92. package/dist/execution/testing/nest-registry.js +27 -0
  93. package/dist/execution/testing/scope-cases.d.ts +6 -0
  94. package/dist/execution/testing/scope-cases.js +49 -0
  95. package/dist/execution/testing/seq-cases.d.ts +6 -0
  96. package/dist/execution/testing/seq-cases.js +71 -0
  97. package/dist/execution/testing/seq-registry.d.ts +3 -0
  98. package/dist/execution/testing/seq-registry.js +32 -0
  99. package/dist/execution/testing/wake-exec-cases.d.ts +20 -0
  100. package/dist/execution/testing/wake-exec-cases.js +147 -0
  101. package/dist/execution/testing/wake-registry.d.ts +3 -0
  102. package/dist/execution/testing/wake-registry.js +26 -0
  103. package/dist/execution/tool-host.d.ts +10 -2
  104. package/dist/execution/tool-outcome-events.d.ts +11 -0
  105. package/dist/execution/tool-outcome-events.js +47 -0
  106. package/dist/execution/wake-inbox.d.ts +25 -0
  107. package/dist/execution/wake-inbox.js +85 -0
  108. package/dist/execution/wake-outbox.d.ts +30 -0
  109. package/dist/execution/wake-outbox.js +87 -0
  110. package/dist/execution/wake-types.d.ts +45 -0
  111. package/dist/execution/wake-types.js +3 -0
  112. package/dist/harness/env/nodejs.js +4 -0
  113. package/dist/index.d.ts +21 -1
  114. package/dist/index.js +19 -1
  115. package/dist/node.d.ts +1 -0
  116. package/dist/node.js +1 -0
  117. package/dist/transport/testing/multi-cases.js +8 -8
  118. package/package.json +3 -3
@@ -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
@@ -0,0 +1,161 @@
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
+ /** 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;
50
+ };
51
+ export type ExecutionRef = {
52
+ readonly issuer: string;
53
+ readonly executionId: string;
54
+ readonly generation: number;
55
+ };
56
+ /**
57
+ * The executor's durable answer to a prepare. A re-sent prepare returns the stored answer and never reruns
58
+ * preparation; a call whose endpoint already ended (for example `hand_restarted` after an executor restart during
59
+ * preparation) answers `settled` with that terminal outcome. A preparation the executor stopped itself is answered as
60
+ * `blocked` or `batch_abort`, also on a re-send, never as the raw `settled` ledger outcome: the ledger stores both
61
+ * under reason `blocked`, and only the executor can tell a blocked call from a preflight abort.
62
+ */
63
+ export type PrepareReply = {
64
+ readonly kind: "prepared";
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;
71
+ } | {
72
+ readonly kind: "blocked";
73
+ readonly result: StoreValue;
74
+ } | {
75
+ readonly kind: "batch_abort";
76
+ } | {
77
+ readonly kind: "settled";
78
+ readonly outcome: ExecutionOutcome;
79
+ };
80
+ /** Release and abort answer with the endpoint's terminal outcome; an executor that lost the call says so. */
81
+ export type SettleReply = {
82
+ readonly kind: "settled";
83
+ readonly outcome: ExecutionOutcome;
84
+ } | {
85
+ readonly kind: "unknown_execution";
86
+ };
87
+ /** The hand side of the batch protocol. Every method is replay-safe: re-sending gives the same effect. */
88
+ export interface BatchExecutor {
89
+ prepare(request: PrepareRequest): Promise<PrepareReply>;
90
+ /** Resolves once the released call has settled. */
91
+ release(ref: ExecutionRef): Promise<SettleReply>;
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>;
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
+ };
130
+ export type BatchDecision = "RELEASE" | "ABORT";
131
+ export type CallOutcome = {
132
+ readonly kind: "result";
133
+ readonly value: StoreValue;
134
+ } | {
135
+ readonly kind: "blocked";
136
+ readonly result: StoreValue;
137
+ }
138
+ /** The body never ran: the batch was aborted before this call was released. */
139
+ | {
140
+ readonly kind: "not_run";
141
+ readonly cause: "batch_abort" | "interrupted_preparation";
142
+ } | {
143
+ readonly kind: "interrupted";
144
+ readonly reason: Exclude<ExecutionOutcome["reason"], "result" | "blocked"> | "unknown_execution";
145
+ readonly uncertain: boolean;
146
+ };
147
+ /** The coordinator's durable record of one batch; every field is written before the message it causes is sent. */
148
+ export type BatchRecord = {
149
+ readonly manifest: BatchManifest;
150
+ readonly prepares: readonly (PrepareReply | null)[];
151
+ readonly decision: BatchDecision | null;
152
+ readonly released: readonly boolean[];
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)[];
156
+ };
157
+ export type BatchResult = {
158
+ readonly decision: BatchDecision;
159
+ readonly outcomes: readonly CallOutcome[];
160
+ };
161
+ //# sourceMappingURL=coordinator-types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=coordinator-types.js.map
@@ -0,0 +1,27 @@
1
+ import type { DurableStore } from "../durable/store.ts";
2
+ import type { AdmissionLine } from "../durable/store-admission.ts";
3
+ import type { BatchConsent, 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
+ /** Gate A/B consent for cross-machine executors; absent (fused, split-local) means no consent step (K3). */
15
+ readonly consent?: BatchConsent;
16
+ }
17
+ export interface BatchCoordinator {
18
+ /**
19
+ * Runs one batch to its final outcomes: manifest, prepare in source order, one decision, then release by
20
+ * dependencies or abort. A batch with a durable record resumes from it, so calling `run` again after a crash (or
21
+ * after an executor call failed) recovers instead of starting over.
22
+ */
23
+ run(plan: BatchPlan): Promise<BatchResult>;
24
+ read(batchId: string): Promise<BatchRecord | undefined>;
25
+ }
26
+ export declare function createBatchCoordinator(options: BatchCoordinatorOptions): BatchCoordinator;
27
+ //# sourceMappingURL=coordinator.d.ts.map
@@ -0,0 +1,164 @@
1
+ import { decodeBatchRecord } from "./coordinator-codec.js";
2
+ import { gateRawCall, resolveFrozenConsent } from "./coordinator-consent.js";
3
+ import { abortCause, buildBatchManifest, finished, settledOutcome } from "./coordinator-plan.js";
4
+ const PREFIX = "execution.batch:";
5
+ const keyOf = (issuer, batchId) => `${PREFIX}${JSON.stringify([issuer, batchId])}`;
6
+ export class BatchManifestConflictError extends Error {
7
+ constructor(batchId) {
8
+ super(`batch ${batchId} already has a different durable manifest`);
9
+ this.name = "BatchManifestConflictError";
10
+ }
11
+ }
12
+ const replace = (items, index, value) => items.map((item, at) => (at === index ? value : item));
13
+ export function createBatchCoordinator(options) {
14
+ const { issuer, store, epoch, admission, executor, consent } = options;
15
+ const read = async (batchId) => {
16
+ const value = await store.getDocument(keyOf(issuer, batchId));
17
+ return value === undefined ? undefined : decodeBatchRecord(value);
18
+ };
19
+ return {
20
+ read,
21
+ run: async (plan) => {
22
+ const manifest = await buildBatchManifest(issuer, plan);
23
+ const key = keyOf(issuer, plan.batchId);
24
+ let record = await read(plan.batchId);
25
+ const persist = async (next, step, call) => {
26
+ const data = { batchId: plan.batchId, step, executionId: call?.executionId ?? null };
27
+ await admission.admit(() => store.commit(epoch, [
28
+ { op: "append", id: store.mintId(), kind: "execution.batch", data },
29
+ { op: "put", key, data: next },
30
+ ], () => { }));
31
+ record = next;
32
+ };
33
+ const current = () => {
34
+ if (record === undefined)
35
+ throw new Error(`batch ${plan.batchId} has no durable record`);
36
+ return record;
37
+ };
38
+ const ref = (call) => ({
39
+ issuer,
40
+ executionId: call.executionId,
41
+ generation: manifest.generation,
42
+ });
43
+ const settle = async (call, outcome) => persist({ ...current(), outcomes: replace(current().outcomes, call.sourceIndex, outcome) }, "outcome", call);
44
+ if (record === undefined) {
45
+ const empty = manifest.calls.map(() => null);
46
+ await persist({
47
+ manifest,
48
+ prepares: empty,
49
+ decision: null,
50
+ released: manifest.calls.map(() => false),
51
+ outcomes: empty,
52
+ }, "manifest");
53
+ }
54
+ else if (record.manifest.manifestDigest !== manifest.manifestDigest) {
55
+ throw new BatchManifestConflictError(plan.batchId);
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);
70
+ if (current().decision === null) {
71
+ for (const call of manifest.calls) {
72
+ let reply = current().prepares[call.sourceIndex] ?? 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) {
79
+ reply = await executor(call.executor).prepare({
80
+ ...("authorizedDigest" in gate && gate.authorizedDigest !== undefined
81
+ ? { authorizedDigest: gate.authorizedDigest }
82
+ : {}),
83
+ ...ref(call),
84
+ batchId: manifest.batchId,
85
+ manifestDigest: manifest.manifestDigest,
86
+ scope: manifest.scope,
87
+ workspace: manifest.workspace,
88
+ admittedAt: manifest.admittedAt,
89
+ leaseUntil: manifest.leaseUntil,
90
+ requestDigest: call.requestDigest,
91
+ call: { name: call.name, args: call.args },
92
+ });
93
+ await setPrepare(call, reply);
94
+ }
95
+ if (abortCause(reply) !== undefined)
96
+ break;
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
+ }
108
+ const aborted = current().prepares.some((reply) => reply !== null && abortCause(reply) !== undefined);
109
+ await persist({ ...current(), decision: aborted ? "ABORT" : "RELEASE" }, "decision");
110
+ }
111
+ const cause = current()
112
+ .prepares.map((reply) => (reply === null ? undefined : abortCause(reply)))
113
+ .find((found) => found !== undefined) ?? "batch_abort";
114
+ for (const call of manifest.calls) {
115
+ if (current().outcomes[call.sourceIndex] !== null)
116
+ continue;
117
+ const reply = current().prepares[call.sourceIndex] ?? null;
118
+ if (reply?.kind === "settled")
119
+ await settle(call, settledOutcome(reply));
120
+ else if (reply?.kind === "blocked") {
121
+ await executor(call.executor).abort(ref(call));
122
+ await settle(call, { kind: "blocked", result: reply.result });
123
+ }
124
+ else if (current().decision === "ABORT") {
125
+ if (reply !== null)
126
+ await executor(call.executor).abort(ref(call));
127
+ await settle(call, { kind: "not_run", cause });
128
+ }
129
+ }
130
+ const inflight = new Map();
131
+ for (;;) {
132
+ for (const call of manifest.calls) {
133
+ const index = call.sourceIndex;
134
+ if (current().outcomes[index] !== null || inflight.has(index))
135
+ continue;
136
+ if (!current().released[index]) {
137
+ const ready = call.dependsOn.every((dependency) => finished(manifest.calls, current().outcomes, dependency));
138
+ if (!ready)
139
+ continue;
140
+ await persist({ ...current(), released: replace(current().released, index, true) }, "release", call);
141
+ }
142
+ inflight.set(index, executor(call.executor)
143
+ .release(ref(call))
144
+ .then((reply) => ({ index, ok: true, reply }), (error) => ({ index, ok: false, error })));
145
+ }
146
+ if (inflight.size === 0)
147
+ break;
148
+ const settled = await Promise.race(inflight.values());
149
+ inflight.delete(settled.index);
150
+ if (!settled.ok)
151
+ throw settled.error;
152
+ const call = manifest.calls[settled.index];
153
+ if (call !== undefined)
154
+ await settle(call, settledOutcome(settled.reply));
155
+ }
156
+ const { decision, outcomes } = current();
157
+ const final = outcomes.filter((outcome) => outcome !== null);
158
+ if (decision === null || final.length !== outcomes.length)
159
+ throw new Error(`batch ${plan.batchId} ended with an unsettled call`);
160
+ return { decision, outcomes: final };
161
+ },
162
+ };
163
+ }
164
+ //# sourceMappingURL=coordinator.js.map
@@ -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,112 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, mkdir, open, readdir, rename, rm } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import { DeviceFileError, FILE_CHANNEL_MAX_BYTES } from "./device-files.js";
5
+ function deviceError(error, path) {
6
+ if (error instanceof DeviceFileError)
7
+ return error;
8
+ const code = error.code;
9
+ const message = error instanceof Error ? error.message : String(error);
10
+ if (code === "ENOENT")
11
+ return new DeviceFileError("not_found", path);
12
+ if (code === "EEXIST")
13
+ return new DeviceFileError("exists", path);
14
+ if (code === "EISDIR" || code === "ENOTDIR" || code === "ENXIO")
15
+ return new DeviceFileError("not_a_file", path);
16
+ if (code === "ABORT_ERR")
17
+ return new DeviceFileError("aborted", path);
18
+ return new DeviceFileError("io", message);
19
+ }
20
+ async function guarded(path, signal, run) {
21
+ if (signal?.aborted)
22
+ throw new DeviceFileError("aborted", path);
23
+ try {
24
+ return await run();
25
+ }
26
+ catch (error) {
27
+ throw deviceError(error, path);
28
+ }
29
+ }
30
+ /**
31
+ * Opens a regular file only. The open never blocks (a named pipe with no peer would hold it, and a worker thread,
32
+ * forever), and the type is checked on the opened descriptor, so nothing can swap the path in between.
33
+ */
34
+ async function openRegular(path, flags) {
35
+ const handle = await open(path, flags | constants.O_NONBLOCK, 0o666);
36
+ try {
37
+ if (!(await handle.stat()).isFile())
38
+ throw new DeviceFileError("not_a_file", path);
39
+ return handle;
40
+ }
41
+ catch (error) {
42
+ await handle.close();
43
+ throw error;
44
+ }
45
+ }
46
+ /** Reads at most the channel limit: a file that grows past it while being read is refused, never shipped in full. */
47
+ async function readBounded(path, signal) {
48
+ const handle = await openRegular(path, constants.O_RDONLY);
49
+ try {
50
+ const chunks = [];
51
+ let total = 0;
52
+ for (;;) {
53
+ if (signal?.aborted)
54
+ throw new DeviceFileError("aborted", path);
55
+ const chunk = new Uint8Array(64 * 1024);
56
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
57
+ if (bytesRead === 0)
58
+ break;
59
+ total += bytesRead;
60
+ if (total > FILE_CHANNEL_MAX_BYTES)
61
+ throw new DeviceFileError("too_large", path);
62
+ chunks.push(chunk.subarray(0, bytesRead));
63
+ }
64
+ const bytes = new Uint8Array(total);
65
+ let offset = 0;
66
+ for (const chunk of chunks) {
67
+ bytes.set(chunk, offset);
68
+ offset += chunk.length;
69
+ }
70
+ return bytes;
71
+ }
72
+ finally {
73
+ await handle.close();
74
+ }
75
+ }
76
+ function statOf(entry) {
77
+ const kind = entry.isFile() ? "file" : entry.isDirectory() ? "directory" : "other";
78
+ return { kind, size: entry.size, mtimeMs: entry.mtimeMs };
79
+ }
80
+ /**
81
+ * The local filesystem as {@link DeviceFiles}: what a fused session's extension code uses, called directly, and what a
82
+ * hand runs a channel operation on once its grant, handlers and policy have allowed it. Reads and writes are bounded
83
+ * by {@link FILE_CHANNEL_MAX_BYTES} before any data is in memory, so both sides of a split session agree on the limit.
84
+ */
85
+ export function localDeviceFiles() {
86
+ return {
87
+ read: (path, options) => guarded(path, options?.signal, () => readBounded(path, options?.signal)),
88
+ write: (path, data, options) => guarded(path, options?.signal, async () => {
89
+ if (data.byteLength > FILE_CHANNEL_MAX_BYTES)
90
+ throw new DeviceFileError("too_large", path);
91
+ await mkdir(dirname(path), { recursive: true });
92
+ const handle = await openRegular(path, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (options?.exclusive ? constants.O_EXCL : 0));
93
+ try {
94
+ await handle.writeFile(data);
95
+ }
96
+ finally {
97
+ await handle.close();
98
+ }
99
+ }),
100
+ list: (path, options) => guarded(path, options?.signal, () => readdir(path)),
101
+ stat: (path, options) => guarded(path, options?.signal, async () => statOf(await lstat(path))),
102
+ rename: (from, to, options) => guarded(from, options?.signal, () => rename(from, to)),
103
+ remove: (path, options) => guarded(path, options?.signal, async () => {
104
+ await lstat(path);
105
+ await rm(path, { recursive: true });
106
+ }),
107
+ mkdir: (path, options) => guarded(path, options?.signal, async () => {
108
+ await mkdir(path, { recursive: true });
109
+ }),
110
+ };
111
+ }
112
+ //# sourceMappingURL=device-files-node.js.map
@@ -0,0 +1,80 @@
1
+ import type { JsonValue } from "@earendil-works/pi-ai";
2
+ /**
3
+ * The device's files, as extension code reaches them (brain/hand split, S40, senpi#5645). On a fused session this is
4
+ * the local filesystem, called directly. On a split session every operation is one message to the hand, which checks
5
+ * the session's grant, runs its own `tool_call` handlers and filesystem policy, and touches its own disk: the files
6
+ * stay on the device wherever the loop runs. There is no fallback to a direct open.
7
+ */
8
+ export interface DeviceFiles {
9
+ read(path: string, options?: DeviceFileOptions): Promise<Uint8Array>;
10
+ /** Creates parent directories. `exclusive`: fail `exists` when the file is already there (lock files). */
11
+ write(path: string, data: Uint8Array, options?: DeviceFileOptions & {
12
+ readonly exclusive?: boolean;
13
+ }): Promise<void>;
14
+ list(path: string, options?: DeviceFileOptions): Promise<readonly string[]>;
15
+ stat(path: string, options?: DeviceFileOptions): Promise<DeviceFileStat>;
16
+ rename(from: string, to: string, options?: DeviceFileOptions): Promise<void>;
17
+ /** Removes a file, or a directory with everything in it. */
18
+ remove(path: string, options?: DeviceFileOptions): Promise<void>;
19
+ /** Creates a directory and its parents; an existing directory is not an error. */
20
+ mkdir(path: string, options?: DeviceFileOptions): Promise<void>;
21
+ }
22
+ export interface DeviceFileOptions {
23
+ readonly signal?: AbortSignal;
24
+ }
25
+ export interface DeviceFileStat {
26
+ readonly kind: "file" | "directory" | "other";
27
+ readonly size: number;
28
+ readonly mtimeMs: number;
29
+ }
30
+ /** The channel's name in a hand's `hello`. */
31
+ export declare const FILE_CHANNEL = "file/1";
32
+ /** The most data one operation reads or writes, in raw bytes, in both directions. */
33
+ export declare const FILE_CHANNEL_MAX_BYTES: number;
34
+ export type DeviceFileOp = "read" | "write" | "list" | "stat" | "rename" | "remove" | "mkdir";
35
+ export declare const DEVICE_FILE_OPS: readonly DeviceFileOp[];
36
+ export type DeviceFileErrorCode = "not_found" | "not_a_file" | "exists" | "too_large" | "io" | "aborted" | "refused_by_grant" | "refused_by_policy" | "hand_unreachable" | "unsupported" | "interrupted" | "protocol";
37
+ /**
38
+ * A device file operation that did not complete. `interrupted` carries the hand's terminal reason; `uncertain` says the
39
+ * operation may have taken effect (a write may or may not have landed). Nothing is ever retried.
40
+ */
41
+ export declare class DeviceFileError extends Error {
42
+ readonly code: DeviceFileErrorCode;
43
+ readonly reason: string | undefined;
44
+ readonly uncertain: boolean;
45
+ constructor(code: DeviceFileErrorCode, message: string, detail?: {
46
+ reason?: string;
47
+ uncertain?: boolean;
48
+ });
49
+ }
50
+ /** One operation's arguments, as the hand receives them: paths are strings, written data is base64. */
51
+ export type DeviceFileArgs = {
52
+ readonly op: "read" | "list" | "stat" | "remove" | "mkdir";
53
+ readonly path: string;
54
+ } | {
55
+ readonly op: "write";
56
+ readonly path: string;
57
+ readonly data: string;
58
+ readonly exclusive: boolean;
59
+ } | {
60
+ readonly op: "rename";
61
+ readonly path: string;
62
+ readonly to: string;
63
+ };
64
+ /** One operation's outcome, carried in a settled result's `details.file`. */
65
+ export type DeviceFileOutcome = {
66
+ readonly ok: true;
67
+ readonly value: JsonValue;
68
+ } | {
69
+ readonly ok: false;
70
+ readonly code: DeviceFileErrorCode;
71
+ readonly message: string;
72
+ };
73
+ /** Parses an operation's arguments; `undefined` for anything malformed. */
74
+ export declare function decodeDeviceFileArgs(op: unknown, args: unknown): DeviceFileArgs | undefined;
75
+ export declare function encodeBase64(bytes: Uint8Array): string;
76
+ export declare function decodeBase64(text: string): Uint8Array;
77
+ /** The raw byte length a base64 string decodes to, without decoding it. */
78
+ export declare function base64Length(text: string): number;
79
+ export declare function fileOutcomeOf(details: unknown): DeviceFileOutcome | undefined;
80
+ //# sourceMappingURL=device-files.d.ts.map