@code-yeongyu/senpi-agent-core 2026.11.3-3 → 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 (92) hide show
  1. package/dist/agent-loop.js +7 -47
  2. package/dist/conformance/index.d.ts +23 -0
  3. package/dist/conformance/index.js +17 -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 +9 -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.js +13 -2
  10. package/dist/execution/coordinator-consent.d.ts +29 -0
  11. package/dist/execution/coordinator-consent.js +63 -0
  12. package/dist/execution/coordinator-sequential.d.ts +15 -0
  13. package/dist/execution/coordinator-sequential.js +34 -0
  14. package/dist/execution/coordinator-types.d.ts +45 -0
  15. package/dist/execution/coordinator.d.ts +3 -1
  16. package/dist/execution/coordinator.js +35 -3
  17. package/dist/execution/device-files-node.d.ts +8 -0
  18. package/dist/execution/device-files-node.js +112 -0
  19. package/dist/execution/device-files.d.ts +80 -0
  20. package/dist/execution/device-files.js +87 -0
  21. package/dist/execution/nested-codec.d.ts +5 -0
  22. package/dist/execution/nested-codec.js +41 -0
  23. package/dist/execution/nested-types.d.ts +92 -0
  24. package/dist/execution/nested-types.js +3 -0
  25. package/dist/execution/nested.d.ts +48 -0
  26. package/dist/execution/nested.js +206 -0
  27. package/dist/execution/plane-model.d.ts +33 -0
  28. package/dist/execution/plane-model.js +80 -0
  29. package/dist/execution/plane.d.ts +72 -0
  30. package/dist/execution/plane.js +172 -0
  31. package/dist/execution/remote-device-files.d.ts +12 -0
  32. package/dist/execution/remote-device-files.js +84 -0
  33. package/dist/execution/remote-executor.d.ts +10 -0
  34. package/dist/execution/remote-executor.js +49 -15
  35. package/dist/execution/remote-file-call.d.ts +14 -0
  36. package/dist/execution/remote-file-call.js +30 -0
  37. package/dist/execution/remote-link.d.ts +36 -0
  38. package/dist/execution/remote-link.js +117 -0
  39. package/dist/execution/remote-protocol.d.ts +21 -4
  40. package/dist/execution/remote-protocol.js +18 -2
  41. package/dist/execution/remote-tool-host.d.ts +11 -3
  42. package/dist/execution/remote-tool-host.js +23 -64
  43. package/dist/execution/scope-lifecycle.d.ts +81 -0
  44. package/dist/execution/scope-lifecycle.js +173 -0
  45. package/dist/execution/testing/batch-executor.js +32 -3
  46. package/dist/execution/testing/batch-harness.d.ts +25 -3
  47. package/dist/execution/testing/batch-harness.js +83 -5
  48. package/dist/execution/testing/cancel-cases.d.ts +8 -0
  49. package/dist/execution/testing/cancel-cases.js +64 -0
  50. package/dist/execution/testing/consent-cases.d.ts +14 -0
  51. package/dist/execution/testing/consent-cases.js +66 -0
  52. package/dist/execution/testing/kill-nest.d.ts +6 -0
  53. package/dist/execution/testing/kill-nest.js +55 -0
  54. package/dist/execution/testing/kill-wakex.d.ts +6 -0
  55. package/dist/execution/testing/kill-wakex.js +81 -0
  56. package/dist/execution/testing/lifecycle-cases.d.ts +9 -0
  57. package/dist/execution/testing/lifecycle-cases.js +60 -0
  58. package/dist/execution/testing/lifecycle-registry.d.ts +3 -0
  59. package/dist/execution/testing/lifecycle-registry.js +19 -0
  60. package/dist/execution/testing/multi-lifecycle-cases.d.ts +4 -0
  61. package/dist/execution/testing/multi-lifecycle-cases.js +34 -0
  62. package/dist/execution/testing/multi-seq-cases.d.ts +4 -0
  63. package/dist/execution/testing/multi-seq-cases.js +46 -0
  64. package/dist/execution/testing/nest-cases.d.ts +39 -0
  65. package/dist/execution/testing/nest-cases.js +181 -0
  66. package/dist/execution/testing/nest-registry.d.ts +3 -0
  67. package/dist/execution/testing/nest-registry.js +27 -0
  68. package/dist/execution/testing/scope-cases.d.ts +6 -0
  69. package/dist/execution/testing/scope-cases.js +49 -0
  70. package/dist/execution/testing/seq-cases.d.ts +6 -0
  71. package/dist/execution/testing/seq-cases.js +71 -0
  72. package/dist/execution/testing/seq-registry.d.ts +3 -0
  73. package/dist/execution/testing/seq-registry.js +32 -0
  74. package/dist/execution/testing/wake-exec-cases.d.ts +20 -0
  75. package/dist/execution/testing/wake-exec-cases.js +147 -0
  76. package/dist/execution/testing/wake-registry.d.ts +3 -0
  77. package/dist/execution/testing/wake-registry.js +26 -0
  78. package/dist/execution/tool-host.d.ts +10 -2
  79. package/dist/execution/tool-outcome-events.d.ts +11 -0
  80. package/dist/execution/tool-outcome-events.js +47 -0
  81. package/dist/execution/wake-inbox.d.ts +25 -0
  82. package/dist/execution/wake-inbox.js +85 -0
  83. package/dist/execution/wake-outbox.d.ts +30 -0
  84. package/dist/execution/wake-outbox.js +87 -0
  85. package/dist/execution/wake-types.d.ts +45 -0
  86. package/dist/execution/wake-types.js +3 -0
  87. package/dist/index.d.ts +13 -2
  88. package/dist/index.js +11 -1
  89. package/dist/node.d.ts +1 -0
  90. package/dist/node.js +1 -0
  91. package/dist/transport/testing/multi-cases.js +8 -8
  92. package/package.json +3 -3
@@ -0,0 +1,206 @@
1
+ import { canonicalJson } from "./canonical-json.js";
2
+ import { decodeNestedRecord } from "./nested-codec.js";
3
+ import { NESTED_LIFETIME_MS, } from "./nested-types.js";
4
+ const PREFIX = "execution.nested:";
5
+ /** A child's execution id: encoded like the record keys, so no two (parent, childRequestId) pairs can collide. */
6
+ export const nestedChildId = (parent, childRequestId) => JSON.stringify([parent, childRequestId]);
7
+ const validAmount = (value) => Number.isFinite(value) && value >= 0;
8
+ function refused(reason) {
9
+ return { kind: "refused", reason };
10
+ }
11
+ export function createNestedAdmission(options) {
12
+ const { issuer, store, epoch, admission, clock } = options;
13
+ const keyOf = (parent) => `${PREFIX}${JSON.stringify([issuer, parent])}`;
14
+ const read = async (parent) => {
15
+ const value = await store.getDocument(keyOf(parent));
16
+ return value === undefined ? undefined : decodeNestedRecord(value);
17
+ };
18
+ const write = async (record, step, executionId) => {
19
+ const data = { parent: record.parent.executionId, step, executionId };
20
+ await store.commit(epoch, [
21
+ { op: "append", id: store.mintId(), kind: "execution.nested", data },
22
+ { op: "put", key: keyOf(record.parent.executionId), data: record },
23
+ ], () => { });
24
+ };
25
+ /** Reads, decides and writes inside one admission: nothing else on the brain's store interleaves. */
26
+ const update = (parent, decide) => admission.admit(async () => decide(await read(parent)));
27
+ const live = (record) => !record.cancelled && record.phase !== "settled";
28
+ const set = (record) => record.phase === "preparation"
29
+ ? record.parent.capabilities.preparation
30
+ : [...record.parent.capabilities.preparation, ...record.parent.capabilities.body];
31
+ return {
32
+ read,
33
+ open: (parent) => update(parent.executionId, async (record) => {
34
+ if (!validAmount(parent.budget) ||
35
+ ![parent.generation, parent.admittedAt, parent.leaseUntil].every((value) => Number.isFinite(value)))
36
+ throw new Error(`nested parent ${parent.executionId} has a non-finite number`);
37
+ if (record !== undefined)
38
+ return canonicalJson(record.parent) === canonicalJson(parent)
39
+ ? { kind: "opened" }
40
+ : { kind: "refused", reason: "conflicting_parent" };
41
+ const expiresAt = Math.min(parent.leaseUntil, parent.admittedAt + NESTED_LIFETIME_MS);
42
+ const opened = {
43
+ parent,
44
+ phase: "preparation",
45
+ cancelled: false,
46
+ expiresAt,
47
+ debited: 0,
48
+ children: {},
49
+ activities: {},
50
+ cancels: {},
51
+ };
52
+ await write(opened, "open", null);
53
+ return { kind: "opened" };
54
+ }),
55
+ release: (parent) => update(parent, async (record) => {
56
+ if (record === undefined || record.phase !== "preparation" || record.cancelled)
57
+ return;
58
+ await write({ ...record, phase: "body" }, "release", null);
59
+ }),
60
+ settle: (parent) => update(parent, async (record) => {
61
+ if (record === undefined || !live(record))
62
+ return;
63
+ await write({ ...record, phase: "settled" }, "settle", null);
64
+ }),
65
+ renew: (parent, leaseUntil) => update(parent, async (record) => {
66
+ if (record === undefined)
67
+ throw new Error(`no nested set for ${parent}`);
68
+ const cap = record.parent.admittedAt + NESTED_LIFETIME_MS;
69
+ const expiresAt = Math.max(record.expiresAt, Math.min(leaseUntil, cap));
70
+ if (expiresAt !== record.expiresAt)
71
+ await write({ ...record, expiresAt }, "renew", null);
72
+ return expiresAt;
73
+ }),
74
+ registerActivity: (activity) => update(activity.parent, async (record) => {
75
+ if (record === undefined)
76
+ return { kind: "refused", reason: "unknown_parent" };
77
+ const existing = record.activities[activity.activityId];
78
+ if (existing !== undefined)
79
+ return canonicalJson({ ...existing, debited: 0, ended: false }) ===
80
+ canonicalJson({ ...activity, debited: 0, ended: false })
81
+ ? { kind: "registered" }
82
+ : { kind: "refused", reason: "conflicting_activity" };
83
+ if (!live(record) || clock() > record.expiresAt)
84
+ return { kind: "refused", reason: "parent_terminal" };
85
+ const held = set(record);
86
+ const subset = activity.executor === record.parent.executor &&
87
+ activity.scope === record.parent.scope &&
88
+ activity.targets.every((target) => held.includes(target)) &&
89
+ activity.expiresAt <= record.expiresAt &&
90
+ validAmount(activity.budget) &&
91
+ activity.budget <= record.parent.budget - record.debited;
92
+ if (!subset)
93
+ return { kind: "refused", reason: "exceeds_parent" };
94
+ const activities = {
95
+ ...record.activities,
96
+ [activity.activityId]: { ...activity, debited: 0, ended: false },
97
+ };
98
+ await write({ ...record, activities }, "activity", activity.activityId);
99
+ return { kind: "registered" };
100
+ }),
101
+ endActivity: (parent, activityId) => update(parent, async (record) => {
102
+ const activity = record?.activities[activityId];
103
+ if (record === undefined || activity === undefined || activity.ended)
104
+ return;
105
+ const activities = { ...record.activities, [activityId]: { ...activity, ended: true } };
106
+ await write({ ...record, activities }, "activity_end", activityId);
107
+ }),
108
+ admit: (request) => update(request.parent, async (record) => {
109
+ if (record === undefined)
110
+ return refused("unknown_parent");
111
+ const activity = request.activityId === undefined ? undefined : record.activities[request.activityId];
112
+ if (request.activityId !== undefined && activity === undefined)
113
+ return refused("unknown_activity");
114
+ const owner = activity ?? record.parent;
115
+ if (request.sender !== owner.executor)
116
+ return refused("not_parent_executor");
117
+ if (request.parentGeneration !== record.parent.generation)
118
+ return refused("stale_generation");
119
+ if (request.scope !== owner.scope)
120
+ return refused("scope_mismatch");
121
+ const id = nestedChildId(request.parent, request.childRequestId);
122
+ const ref = { issuer, executionId: id, generation: 1 };
123
+ const known = record.children[request.childRequestId];
124
+ if (known !== undefined)
125
+ return known.target === request.target &&
126
+ known.cost === request.cost &&
127
+ known.activityId === (request.activityId ?? null)
128
+ ? { kind: "admitted", child: ref, target: known.target, replayed: true }
129
+ : refused("conflicting_request");
130
+ if (!validAmount(request.cost))
131
+ return refused("invalid_cost");
132
+ const now = clock();
133
+ if (activity !== undefined) {
134
+ if (activity.ended || record.cancelled || now > activity.expiresAt)
135
+ return refused("activity_ended");
136
+ if (!activity.targets.includes(request.target))
137
+ return refused("not_in_nested_set");
138
+ if (activity.debited + request.cost > activity.budget)
139
+ return refused("budget_exhausted");
140
+ }
141
+ else {
142
+ if (!live(record))
143
+ return refused("parent_terminal");
144
+ if (now > record.expiresAt)
145
+ return refused("expired");
146
+ if (!set(record).includes(request.target))
147
+ return refused("not_in_nested_set");
148
+ }
149
+ if (record.debited + request.cost > record.parent.budget)
150
+ return refused("budget_exhausted");
151
+ const child = {
152
+ executionId: id,
153
+ target: request.target,
154
+ cost: request.cost,
155
+ origin: "tool",
156
+ activityId: request.activityId ?? null,
157
+ };
158
+ const activities = activity === undefined
159
+ ? record.activities
160
+ : {
161
+ ...record.activities,
162
+ [activity.activityId]: { ...activity, debited: activity.debited + request.cost },
163
+ };
164
+ await write({
165
+ ...record,
166
+ debited: record.debited + request.cost,
167
+ children: { ...record.children, [request.childRequestId]: child },
168
+ activities,
169
+ }, "admit", id);
170
+ return { kind: "admitted", child: ref, target: request.target, replayed: false };
171
+ }),
172
+ cancel: (parent) => update(parent, async (record) => {
173
+ if (record === undefined)
174
+ return [];
175
+ const targets = Object.values(record.children).map((child) => ({
176
+ ref: { issuer, executionId: child.executionId, generation: 1 },
177
+ executor: child.target,
178
+ }));
179
+ if (record.cancelled)
180
+ return targets;
181
+ const activities = Object.fromEntries(Object.entries(record.activities).map(([id, activity]) => [id, { ...activity, ended: true }]));
182
+ const cancels = Object.fromEntries(Object.values(record.children).map((child) => [child.executionId, "queued"]));
183
+ await write({ ...record, cancelled: true, activities, cancels }, "cancel", null);
184
+ return targets;
185
+ }),
186
+ deliverCancels: async (parent, send) => {
187
+ const record = await read(parent);
188
+ if (record === undefined)
189
+ return 0;
190
+ let delivered = 0;
191
+ for (const child of Object.values(record.children)) {
192
+ if (record.cancels[child.executionId] !== "queued")
193
+ continue;
194
+ await send({ ref: { issuer, executionId: child.executionId, generation: 1 }, executor: child.target });
195
+ await update(parent, async (latest) => {
196
+ if (latest === undefined || latest.cancels[child.executionId] !== "queued")
197
+ return;
198
+ await write({ ...latest, cancels: { ...latest.cancels, [child.executionId]: "delivered" } }, "cancel_delivered", child.executionId);
199
+ });
200
+ delivered += 1;
201
+ }
202
+ return delivered;
203
+ },
204
+ };
205
+ }
206
+ //# sourceMappingURL=nested.js.map
@@ -0,0 +1,33 @@
1
+ import type { AssistantMessage, Context, ThinkingLevel } from "@earendil-works/pi-ai";
2
+ import { type NestedRequest, type PlaneHandler } from "./plane.ts";
3
+ /** The plane a hand's model-backed tools (a completion, a model-backed search) use to reach a model (S31, F40). */
4
+ export declare const MODEL_PLANE = "model";
5
+ /**
6
+ * One completion a hand asks the brain for. It names a model only by provider and ID; the brain resolves it against
7
+ * its own registry and credentials, or uses the session's model when `model` is absent. Nothing a hand sends can choose
8
+ * an endpoint, a key or a header: the codec keeps only these fields.
9
+ */
10
+ export interface ModelPlaneRequest {
11
+ readonly model?: {
12
+ readonly provider: string;
13
+ readonly id: string;
14
+ };
15
+ readonly context: Context;
16
+ readonly options?: {
17
+ readonly maxTokens?: number;
18
+ readonly temperature?: number;
19
+ readonly reasoning?: ThinkingLevel;
20
+ };
21
+ }
22
+ /** Parses a request body, keeping only the fields of {@link ModelPlaneRequest}; refuses a malformed one. */
23
+ export declare function decodeModelPlaneRequest(body: unknown): ModelPlaneRequest;
24
+ /**
25
+ * The brain's model plane: `complete` runs one request with the brain's own model registry and credentials (fused and
26
+ * headless: this machine's, as today; a hosted brain's credential source is card C6) and is aborted with the request.
27
+ */
28
+ export declare function serveModelPlane(complete: (request: ModelPlaneRequest, signal: AbortSignal) => Promise<AssistantMessage>): PlaneHandler;
29
+ /** A hand's client for the model plane, over the running call's nested requests. */
30
+ export declare function createModelPlaneClient(nested: NestedRequest): {
31
+ complete(request: ModelPlaneRequest, signal?: AbortSignal): Promise<AssistantMessage>;
32
+ };
33
+ //# sourceMappingURL=plane-model.d.ts.map
@@ -0,0 +1,80 @@
1
+ import { PlaneRefusedError } from "./plane.js";
2
+ /** The plane a hand's model-backed tools (a completion, a model-backed search) use to reach a model (S31, F40). */
3
+ export const MODEL_PLANE = "model";
4
+ const REASONING = ["minimal", "low", "medium", "high", "xhigh", "max"];
5
+ const isRecord = (value) => typeof value === "object" && value !== null;
6
+ function refuse(detail) {
7
+ throw new PlaneRefusedError(`malformed_request: ${detail}`);
8
+ }
9
+ function decodeModel(value) {
10
+ if (value === undefined)
11
+ return undefined;
12
+ if (!isRecord(value) || typeof value.provider !== "string" || typeof value.id !== "string")
13
+ refuse("model");
14
+ return { provider: value.provider, id: value.id };
15
+ }
16
+ function decodeContext(value) {
17
+ if (!isRecord(value) || !Array.isArray(value.messages))
18
+ refuse("context");
19
+ if (value.systemPrompt !== undefined && typeof value.systemPrompt !== "string")
20
+ refuse("systemPrompt");
21
+ if (value.tools !== undefined && !Array.isArray(value.tools))
22
+ refuse("tools");
23
+ return {
24
+ ...(value.systemPrompt === undefined ? {} : { systemPrompt: value.systemPrompt }),
25
+ messages: value.messages,
26
+ ...(value.tools === undefined ? {} : { tools: value.tools }),
27
+ };
28
+ }
29
+ function decodeOptions(value) {
30
+ if (value === undefined)
31
+ return undefined;
32
+ if (!isRecord(value))
33
+ refuse("options");
34
+ const { maxTokens, temperature, reasoning } = value;
35
+ if (maxTokens !== undefined && (typeof maxTokens !== "number" || !Number.isSafeInteger(maxTokens) || maxTokens <= 0))
36
+ refuse("maxTokens");
37
+ if (temperature !== undefined && (typeof temperature !== "number" || !Number.isFinite(temperature)))
38
+ refuse("temperature");
39
+ if (reasoning !== undefined && !REASONING.includes(reasoning))
40
+ refuse("reasoning");
41
+ return {
42
+ ...(maxTokens === undefined ? {} : { maxTokens: maxTokens }),
43
+ ...(temperature === undefined ? {} : { temperature: temperature }),
44
+ ...(reasoning === undefined ? {} : { reasoning: reasoning }),
45
+ };
46
+ }
47
+ /** Parses a request body, keeping only the fields of {@link ModelPlaneRequest}; refuses a malformed one. */
48
+ export function decodeModelPlaneRequest(body) {
49
+ if (!isRecord(body))
50
+ refuse("body");
51
+ const model = decodeModel(body.model);
52
+ const options = decodeOptions(body.options);
53
+ return {
54
+ ...(model === undefined ? {} : { model }),
55
+ context: decodeContext(body.context),
56
+ ...(options === undefined ? {} : { options }),
57
+ };
58
+ }
59
+ /**
60
+ * The brain's model plane: `complete` runs one request with the brain's own model registry and credentials (fused and
61
+ * headless: this machine's, as today; a hosted brain's credential source is card C6) and is aborted with the request.
62
+ */
63
+ export function serveModelPlane(complete) {
64
+ return async (body, signal) => {
65
+ const message = await complete(decodeModelPlaneRequest(body), signal);
66
+ return JSON.parse(JSON.stringify(message));
67
+ };
68
+ }
69
+ /** A hand's client for the model plane, over the running call's nested requests. */
70
+ export function createModelPlaneClient(nested) {
71
+ return {
72
+ async complete(request, signal) {
73
+ const reply = await nested(MODEL_PLANE, JSON.parse(JSON.stringify(request)), signal);
74
+ if (!isRecord(reply) || reply.role !== "assistant" || !Array.isArray(reply.content))
75
+ throw new PlaneRefusedError("malformed_reply");
76
+ return reply;
77
+ },
78
+ };
79
+ }
80
+ //# sourceMappingURL=plane-model.js.map
@@ -0,0 +1,72 @@
1
+ import type { JsonValue } from "@earendil-works/pi-ai";
2
+ import type { Transport } from "../transport/transport.ts";
3
+ /**
4
+ * Nested requests from a hand back to the brain that owns the running call (brain/hand split, design 5.6.3): a
5
+ * model-backed tool's completion (S31) and, later, session-plane work. A request travels on its parent call's own scope
6
+ * lane and names that parent; the brain admits it only while the parent is live on that lane, and it is never sent
7
+ * hand-to-hand. The bodies are a plane's own payloads; this layer only carries, admits, deduplicates and cancels them.
8
+ */
9
+ export type PlaneMessage = PlaneRequest | PlaneAbort | PlaneReply | PlaneRefused;
10
+ interface PlaneAddress {
11
+ /** The execution ID of the call the request is nested in. */
12
+ readonly parent: string;
13
+ /** Unique per parent; a replayed request with the same ID gets the same answer and is served once. */
14
+ readonly childRequestId: string;
15
+ }
16
+ export interface PlaneRequest extends PlaneAddress {
17
+ readonly kind: "plane.request";
18
+ readonly plane: string;
19
+ readonly body: JsonValue;
20
+ }
21
+ export interface PlaneAbort extends PlaneAddress {
22
+ readonly kind: "plane.abort";
23
+ }
24
+ export interface PlaneReply extends PlaneAddress {
25
+ readonly kind: "plane.reply";
26
+ readonly body: JsonValue;
27
+ }
28
+ /**
29
+ * The brain did not serve the request. `parent_terminal`: its parent is not a live call; `scope_lane_mismatch`: it came
30
+ * on another scope's lane; `plane_unavailable`: the brain serves no such plane; `plane_failed: ...`: the plane's
31
+ * handler failed.
32
+ */
33
+ export interface PlaneRefused extends PlaneAddress {
34
+ readonly kind: "plane.refused";
35
+ readonly reason: string;
36
+ }
37
+ /** Serves one plane on the brain. `signal` aborts when the request or its parent call is aborted or ends. */
38
+ export type PlaneHandler = (body: JsonValue, signal: AbortSignal) => Promise<JsonValue>;
39
+ /** What a running call on a hand uses to ask the brain that owns it. Rejects with {@link PlaneRefusedError}. */
40
+ export type NestedRequest = (plane: string, body: JsonValue, signal?: AbortSignal) => Promise<JsonValue>;
41
+ export declare class PlaneRefusedError extends Error {
42
+ readonly reason: string;
43
+ constructor(reason: string);
44
+ }
45
+ export declare function encodePlaneMessage(message: PlaneMessage): Uint8Array;
46
+ /** Parses one frame payload as a plane message; anything else (a tool-call message included) is `undefined`. */
47
+ export declare function decodePlaneMessage(payload: Uint8Array): PlaneMessage | undefined;
48
+ /**
49
+ * The brain's side: admits a request (and an abort) only while its parent is a live call on the lane it came on, serves each
50
+ * (parent, child request) once and answers a replay from the stored answer, and aborts a parent's open requests when
51
+ * the parent ends. Answers are kept for the parent's life only.
52
+ */
53
+ export declare function createPlaneServer(options: {
54
+ readonly transport: Transport;
55
+ readonly planes: Readonly<Record<string, PlaneHandler>>;
56
+ /** The lane of the live call with this execution ID, or `undefined` once it ended (or never existed). */
57
+ readonly liveLane: (executionId: string) => string | undefined;
58
+ }): {
59
+ receive(lane: string, message: PlaneMessage): void;
60
+ parentEnded(executionId: string): void;
61
+ };
62
+ /** The hand's side: issues a running call's nested requests on its lane and fails them all once the call ends. */
63
+ export declare function createPlaneClient(options: {
64
+ readonly transport: Transport;
65
+ readonly mintId?: () => string;
66
+ }): {
67
+ requestFor(parent: string, lane: string, parentSignal: AbortSignal): NestedRequest;
68
+ receive(message: PlaneMessage): void;
69
+ parentEnded(parent: string): void;
70
+ };
71
+ export {};
72
+ //# sourceMappingURL=plane.d.ts.map
@@ -0,0 +1,172 @@
1
+ export class PlaneRefusedError extends Error {
2
+ constructor(reason) {
3
+ super(`The brain refused this request: ${reason}`);
4
+ this.name = "PlaneRefusedError";
5
+ this.reason = reason;
6
+ }
7
+ }
8
+ const KINDS = ["plane.request", "plane.abort", "plane.reply", "plane.refused"];
9
+ const encoder = new TextEncoder();
10
+ const decoder = new TextDecoder();
11
+ export function encodePlaneMessage(message) {
12
+ return encoder.encode(JSON.stringify(message));
13
+ }
14
+ const isRecord = (value) => typeof value === "object" && value !== null;
15
+ const isId = (value) => typeof value === "string" && value.length > 0;
16
+ /** Parses one frame payload as a plane message; anything else (a tool-call message included) is `undefined`. */
17
+ export function decodePlaneMessage(payload) {
18
+ let value;
19
+ try {
20
+ value = JSON.parse(decoder.decode(payload));
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ if (!isRecord(value) || !KINDS.includes(value.kind))
26
+ return undefined;
27
+ if (!isId(value.parent) || !isId(value.childRequestId))
28
+ return undefined;
29
+ const address = { parent: value.parent, childRequestId: value.childRequestId };
30
+ switch (value.kind) {
31
+ case "plane.request":
32
+ return isId(value.plane) && "body" in value
33
+ ? { kind: "plane.request", ...address, plane: value.plane, body: value.body }
34
+ : undefined;
35
+ case "plane.abort":
36
+ return { kind: "plane.abort", ...address };
37
+ case "plane.reply":
38
+ return "body" in value ? { kind: "plane.reply", ...address, body: value.body } : undefined;
39
+ default:
40
+ return typeof value.reason === "string"
41
+ ? { kind: "plane.refused", ...address, reason: value.reason }
42
+ : undefined;
43
+ }
44
+ }
45
+ /**
46
+ * The brain's side: admits a request (and an abort) only while its parent is a live call on the lane it came on, serves each
47
+ * (parent, child request) once and answers a replay from the stored answer, and aborts a parent's open requests when
48
+ * the parent ends. Answers are kept for the parent's life only.
49
+ */
50
+ export function createPlaneServer(options) {
51
+ const served = new Map();
52
+ const send = (lane, message) => void options.transport.send(lane, encodePlaneMessage(message)).catch(() => undefined);
53
+ const serve = (lane, request) => {
54
+ const { parent, childRequestId } = request;
55
+ const refuse = (reason) => send(lane, { kind: "plane.refused", parent, childRequestId, reason });
56
+ const parentLane = options.liveLane(parent);
57
+ if (parentLane === undefined)
58
+ return refuse("parent_terminal");
59
+ if (parentLane !== lane)
60
+ return refuse("scope_lane_mismatch");
61
+ const children = served.get(parent) ?? new Map();
62
+ served.set(parent, children);
63
+ const known = children.get(childRequestId);
64
+ if (known !== undefined) {
65
+ if (known.answer !== undefined)
66
+ send(lane, known.answer);
67
+ return;
68
+ }
69
+ const handler = Object.hasOwn(options.planes, request.plane) ? options.planes[request.plane] : undefined;
70
+ if (handler === undefined)
71
+ return refuse("plane_unavailable");
72
+ const entry = { controller: new AbortController() };
73
+ children.set(childRequestId, entry);
74
+ void handler(request.body, entry.controller.signal)
75
+ .then((body) => ({ kind: "plane.reply", parent, childRequestId, body }), (error) => ({
76
+ kind: "plane.refused",
77
+ parent,
78
+ childRequestId,
79
+ reason: `plane_failed: ${error instanceof Error ? error.message : String(error)}`,
80
+ }))
81
+ .then((answer) => {
82
+ if (served.get(parent)?.get(childRequestId) !== entry)
83
+ return;
84
+ entry.answer = answer;
85
+ send(lane, answer);
86
+ });
87
+ };
88
+ return {
89
+ receive(lane, message) {
90
+ if (message.kind === "plane.request")
91
+ serve(lane, message);
92
+ else if (message.kind === "plane.abort" && options.liveLane(message.parent) === lane)
93
+ served.get(message.parent)?.get(message.childRequestId)?.controller.abort();
94
+ },
95
+ parentEnded(executionId) {
96
+ const children = served.get(executionId);
97
+ served.delete(executionId);
98
+ for (const entry of children?.values() ?? [])
99
+ entry.controller.abort();
100
+ },
101
+ };
102
+ }
103
+ /** The hand's side: issues a running call's nested requests on its lane and fails them all once the call ends. */
104
+ export function createPlaneClient(options) {
105
+ const mintId = options.mintId ?? (() => crypto.randomUUID());
106
+ const waiting = new Map();
107
+ const live = new Set();
108
+ return {
109
+ requestFor(parent, lane, parentSignal) {
110
+ live.add(parent);
111
+ return (plane, body, signal) => new Promise((resolve, reject) => {
112
+ if (!live.has(parent) || parentSignal.aborted || signal?.aborted)
113
+ return reject(new PlaneRefusedError("parent_terminal"));
114
+ const childRequestId = mintId();
115
+ const children = waiting.get(parent) ?? new Map();
116
+ waiting.set(parent, children);
117
+ const abort = () => {
118
+ if (!children.delete(childRequestId))
119
+ return;
120
+ void options.transport
121
+ .send(lane, encodePlaneMessage({ kind: "plane.abort", parent, childRequestId }))
122
+ .catch(() => undefined);
123
+ reject(new Error("Operation aborted"));
124
+ };
125
+ const release = () => {
126
+ parentSignal.removeEventListener("abort", abort);
127
+ signal?.removeEventListener("abort", abort);
128
+ };
129
+ children.set(childRequestId, {
130
+ resolve: (value) => {
131
+ release();
132
+ resolve(value);
133
+ },
134
+ reject: (error) => {
135
+ release();
136
+ reject(error);
137
+ },
138
+ });
139
+ parentSignal.addEventListener("abort", abort, { once: true });
140
+ signal?.addEventListener("abort", abort, { once: true });
141
+ const request = { kind: "plane.request", parent, childRequestId, plane, body };
142
+ options.transport.send(lane, encodePlaneMessage(request)).catch((error) => {
143
+ if (!children.delete(childRequestId))
144
+ return;
145
+ release();
146
+ reject(new PlaneRefusedError(`brain_unreachable: ${error instanceof Error ? error.message : String(error)}`));
147
+ });
148
+ });
149
+ },
150
+ receive(message) {
151
+ if (message.kind !== "plane.reply" && message.kind !== "plane.refused")
152
+ return;
153
+ const children = waiting.get(message.parent);
154
+ const waiter = children?.get(message.childRequestId);
155
+ if (waiter === undefined)
156
+ return;
157
+ children?.delete(message.childRequestId);
158
+ if (message.kind === "plane.reply")
159
+ waiter.resolve(message.body);
160
+ else
161
+ waiter.reject(new PlaneRefusedError(message.reason));
162
+ },
163
+ parentEnded(parent) {
164
+ live.delete(parent);
165
+ const children = waiting.get(parent);
166
+ waiting.delete(parent);
167
+ for (const waiter of children?.values() ?? [])
168
+ waiter.reject(new PlaneRefusedError("parent_terminal"));
169
+ },
170
+ };
171
+ }
172
+ //# sourceMappingURL=plane.js.map
@@ -0,0 +1,12 @@
1
+ import { type DeviceFiles } from "./device-files.ts";
2
+ import type { HandLink } from "./remote-link.ts";
3
+ import type { ExecutionScope } from "./tool-host.ts";
4
+ /** How long an operation waits for the hand's `hello` before answering `unsupported` (C1). */
5
+ export declare const HELLO_WAIT_MS = 5000;
6
+ /**
7
+ * A session's {@link DeviceFiles} on a hand (S40): each operation is one `file` message on the scope's lane, after the
8
+ * hand announced the channel in its `hello` (or `unsupported`, sent nowhere). A write over the limit is refused here,
9
+ * before anything is sent; the hand checks the limit again before it reads or writes.
10
+ */
11
+ export declare function createRemoteDeviceFiles(link: HandLink, scope: ExecutionScope, mintId: () => string): DeviceFiles;
12
+ //# sourceMappingURL=remote-device-files.d.ts.map
@@ -0,0 +1,84 @@
1
+ import { DeviceFileError, decodeBase64, encodeBase64, FILE_CHANNEL, FILE_CHANNEL_MAX_BYTES, fileOutcomeOf, } from "./device-files.js";
2
+ /** How long an operation waits for the hand's `hello` before answering `unsupported` (C1). */
3
+ export const HELLO_WAIT_MS = 5000;
4
+ const GRANT_REFUSALS = new Set(["grant_missing", "grant_expired", "workspace_unknown", "capability_missing"]);
5
+ function refusalError(reason) {
6
+ if (GRANT_REFUSALS.has(reason))
7
+ return new DeviceFileError("refused_by_grant", reason);
8
+ if (reason === "hand_closed" || reason.startsWith("scope_unavailable"))
9
+ return new DeviceFileError("hand_unreachable", reason);
10
+ return new DeviceFileError("protocol", reason);
11
+ }
12
+ function valueOf(reply) {
13
+ switch (reply.kind) {
14
+ case "settled": {
15
+ const outcome = fileOutcomeOf(reply.result.details);
16
+ if (outcome === undefined)
17
+ throw new DeviceFileError("protocol", "the hand sent no file outcome");
18
+ if (!outcome.ok)
19
+ throw new DeviceFileError(outcome.code, outcome.message);
20
+ return outcome.value;
21
+ }
22
+ case "terminal": {
23
+ const { reason, uncertain } = reply.terminal;
24
+ throw new DeviceFileError("interrupted", `the operation ended without an outcome (${reason})`, {
25
+ reason,
26
+ uncertain,
27
+ });
28
+ }
29
+ case "refused":
30
+ throw refusalError(reply.reason);
31
+ case "aborted":
32
+ throw new DeviceFileError("aborted", "the operation was aborted");
33
+ case "unreachable":
34
+ throw new DeviceFileError("hand_unreachable", reply.reason);
35
+ case "closed":
36
+ throw new DeviceFileError("hand_unreachable", "the hand link was closed");
37
+ }
38
+ }
39
+ /**
40
+ * A session's {@link DeviceFiles} on a hand (S40): each operation is one `file` message on the scope's lane, after the
41
+ * hand announced the channel in its `hello` (or `unsupported`, sent nowhere). A write over the limit is refused here,
42
+ * before anything is sent; the hand checks the limit again before it reads or writes.
43
+ */
44
+ export function createRemoteDeviceFiles(link, scope, mintId) {
45
+ const call = async (op, args, signal) => {
46
+ const hello = await link.hello(HELLO_WAIT_MS, signal);
47
+ if (signal?.aborted)
48
+ throw new DeviceFileError("aborted", "the operation was aborted");
49
+ if (hello === undefined || !hello.ops.includes(FILE_CHANNEL))
50
+ throw new DeviceFileError("unsupported", "the hand serves no file channel");
51
+ return valueOf(await link.dispatch({ kind: "file", executionId: mintId(), scope, op, args }, signal));
52
+ };
53
+ return {
54
+ read: async (path, options) => {
55
+ const value = await call("read", { path }, options?.signal);
56
+ if (typeof value !== "string")
57
+ throw new DeviceFileError("protocol", "malformed read outcome");
58
+ return decodeBase64(value);
59
+ },
60
+ write: async (path, data, options) => {
61
+ if (data.byteLength > FILE_CHANNEL_MAX_BYTES)
62
+ throw new DeviceFileError("too_large", path);
63
+ const exclusive = options?.exclusive === true;
64
+ await call("write", { path, data: encodeBase64(data), exclusive }, options?.signal);
65
+ },
66
+ list: async (path, options) => {
67
+ const value = await call("list", { path }, options?.signal);
68
+ if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string"))
69
+ throw new DeviceFileError("protocol", "malformed list outcome");
70
+ return value;
71
+ },
72
+ stat: async (path, options) => (await call("stat", { path }, options?.signal)),
73
+ rename: async (from, to, options) => {
74
+ await call("rename", { path: from, to }, options?.signal);
75
+ },
76
+ remove: async (path, options) => {
77
+ await call("remove", { path }, options?.signal);
78
+ },
79
+ mkdir: async (path, options) => {
80
+ await call("mkdir", { path }, options?.signal);
81
+ },
82
+ };
83
+ }
84
+ //# sourceMappingURL=remote-device-files.js.map