@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,104 @@
1
+ import type { ImageContent, JsonValue, TextContent } from "@earendil-works/pi-ai";
2
+ import type { AgentToolResult } from "../types.ts";
3
+ import { type DeviceFileOp } from "./device-files.ts";
4
+ import type { ExecutionScope } from "./tool-host.ts";
5
+ /**
6
+ * The wire messages between a session's remote ToolHost and the hand that runs its tool calls (brain/hand split, S27a).
7
+ * One transport lane per execution scope; a transport never inspects these payloads.
8
+ *
9
+ * The hand receives the model's raw call (name and arguments, before preparation, validation and hooks) and runs all of
10
+ * those steps itself. `sessionRef` is what the session chose to say about itself: the hand passes it to nothing.
11
+ */
12
+ export type RemoteHandMessage = RemoteInvoke | RemoteAbort | RemoteAck | RemoteSettled | RemoteTerminal | RemoteRefused | RemoteHello | RemoteFile;
13
+ /** The lane a hand announces itself on; execution scope lanes carry everything else. */
14
+ export declare const HAND_CONTROL_LANE = "hand.control";
15
+ /**
16
+ * Every hand announces itself once per process start (after re-sending the outcomes its durable record holds that the
17
+ * session has not acknowledged). Only a `durable` hand gets the calls still waiting re-sent: its record answers a call
18
+ * it already holds and runs only a call whose admission never became durable; a hand without a record would run them
19
+ * again or refuse them as duplicates. `ops` names the channels it serves beside tool calls (`file/1`, S40). An older
20
+ * hand sends neither field and announces itself only with a record, so it reads as durable with no channels.
21
+ */
22
+ export interface RemoteHello {
23
+ readonly kind: "hello";
24
+ readonly instance: string;
25
+ readonly durable: boolean;
26
+ readonly ops: readonly string[];
27
+ }
28
+ /**
29
+ * One device file operation (S40), a message kind of its own: the tool host never sends it, and an `invoke` named like
30
+ * an operation is an unknown tool. It shares the invoke's admission (lane, grant, scope binding, execution ID) and is
31
+ * answered like a call (`settled` with the outcome in `details.file`, `refused`, `terminal`).
32
+ */
33
+ export interface RemoteFile {
34
+ readonly kind: "file";
35
+ readonly executionId: string;
36
+ readonly scope: ExecutionScope;
37
+ readonly op: DeviceFileOp;
38
+ readonly args: JsonValue;
39
+ }
40
+ export interface RemoteInvoke {
41
+ readonly kind: "invoke";
42
+ /** Unique per call per session; a hand runs one execution ID at most once. */
43
+ readonly executionId: string;
44
+ readonly batchId: string;
45
+ /** Position in the batch, in the model's source order. */
46
+ readonly index: number;
47
+ readonly scope: ExecutionScope;
48
+ readonly toolCallId: string;
49
+ readonly name: string;
50
+ readonly arguments: unknown;
51
+ readonly sessionRef?: string;
52
+ }
53
+ export interface RemoteAbort {
54
+ readonly kind: "abort";
55
+ readonly executionId: string;
56
+ }
57
+ /** The session has its outcome: the hand may forget it (a later replay is `result_expired`). */
58
+ export interface RemoteAck {
59
+ readonly kind: "ack";
60
+ readonly executionId: string;
61
+ }
62
+ /** The reasons a call can end on a hand without a tool result (the endpoint state machine's terminal reasons). */
63
+ export type RemoteTerminalReason = "cancelled" | "lease_expired" | "hand_restarted" | "uncertain";
64
+ /**
65
+ * The call ended without a tool result, for example because the hand restarted while it ran. `uncertain` says its
66
+ * effects may have happened; `hooksRan` says its `tool_call` handlers may have run. It is never run again.
67
+ */
68
+ export interface RemoteTerminal {
69
+ readonly kind: "terminal";
70
+ readonly executionId: string;
71
+ readonly reason: RemoteTerminalReason;
72
+ readonly uncertain: boolean;
73
+ readonly hooksRan: boolean;
74
+ }
75
+ /** The call ran to an outcome on the hand (an `isError` result included: a blocked, invalid or failing call). */
76
+ export interface RemoteSettled {
77
+ readonly kind: "settled";
78
+ readonly executionId: string;
79
+ readonly result: RemoteToolResult;
80
+ }
81
+ /** The hand refused the call before anything ran (duplicate execution, scope binding, an unopenable scope). */
82
+ export interface RemoteRefused {
83
+ readonly kind: "refused";
84
+ readonly executionId: string;
85
+ readonly reason: string;
86
+ }
87
+ /** The serializable part of an {@link AgentToolResult}. */
88
+ export interface RemoteToolResult {
89
+ readonly content: (TextContent | ImageContent)[];
90
+ readonly details: JsonValue | undefined;
91
+ readonly isError: boolean;
92
+ readonly structuredContent?: JsonValue;
93
+ readonly terminate?: boolean;
94
+ readonly addedToolNames?: readonly string[];
95
+ }
96
+ export declare class RemoteProtocolError extends Error {
97
+ constructor(message: string);
98
+ }
99
+ export declare function encodeRemoteMessage(message: RemoteHandMessage): Uint8Array;
100
+ /** Parses one frame payload. Anything that is not exactly one of the messages is refused; nothing guesses. */
101
+ export declare function decodeRemoteMessage(payload: Uint8Array): RemoteHandMessage;
102
+ /** What a hand sends back for a tool result, keeping only what crosses the wire. */
103
+ export declare function toRemoteToolResult(result: AgentToolResult<unknown>): RemoteToolResult;
104
+ //# sourceMappingURL=remote-protocol.d.ts.map
@@ -0,0 +1,104 @@
1
+ import { DEVICE_FILE_OPS } from "./device-files.js";
2
+ /** The lane a hand announces itself on; execution scope lanes carry everything else. */
3
+ export const HAND_CONTROL_LANE = "hand.control";
4
+ export class RemoteProtocolError extends Error {
5
+ constructor(message) {
6
+ super(`remote_protocol: ${message}`);
7
+ this.name = "RemoteProtocolError";
8
+ }
9
+ }
10
+ const TERMINAL_REASONS = ["cancelled", "lease_expired", "hand_restarted", "uncertain"];
11
+ const encoder = new TextEncoder();
12
+ const decoder = new TextDecoder();
13
+ export function encodeRemoteMessage(message) {
14
+ return encoder.encode(JSON.stringify(message));
15
+ }
16
+ const isRecord = (value) => typeof value === "object" && value !== null;
17
+ const isString = (value) => typeof value === "string" && value.length > 0;
18
+ /** Parses one frame payload. Anything that is not exactly one of the messages is refused; nothing guesses. */
19
+ export function decodeRemoteMessage(payload) {
20
+ let value;
21
+ try {
22
+ value = JSON.parse(decoder.decode(payload));
23
+ }
24
+ catch {
25
+ throw new RemoteProtocolError("payload is not JSON");
26
+ }
27
+ if (isRecord(value) && value.kind === "hello") {
28
+ const { instance, durable, ops } = value;
29
+ if (!isString(instance))
30
+ throw new RemoteProtocolError("malformed hello");
31
+ if (durable !== undefined && typeof durable !== "boolean")
32
+ throw new RemoteProtocolError("malformed hello");
33
+ if (ops !== undefined && (!Array.isArray(ops) || !ops.every(isString)))
34
+ throw new RemoteProtocolError("malformed hello");
35
+ return { kind: "hello", instance, durable: durable ?? true, ops: ops ?? [] };
36
+ }
37
+ if (!isRecord(value) || !isString(value.executionId))
38
+ throw new RemoteProtocolError("no execution ID");
39
+ switch (value.kind) {
40
+ case "invoke": {
41
+ const scope = value.scope;
42
+ if (!isString(value.batchId) ||
43
+ typeof value.index !== "number" ||
44
+ !Number.isSafeInteger(value.index) ||
45
+ value.index < 0 ||
46
+ !isRecord(scope) ||
47
+ !isString(scope.id) ||
48
+ typeof scope.root !== "string" ||
49
+ !isString(value.toolCallId) ||
50
+ !isString(value.name) ||
51
+ (value.sessionRef !== undefined && typeof value.sessionRef !== "string"))
52
+ throw new RemoteProtocolError("malformed invoke");
53
+ return value;
54
+ }
55
+ case "file": {
56
+ const scope = value.scope;
57
+ if (!isRecord(scope) ||
58
+ !isString(scope.id) ||
59
+ typeof scope.root !== "string" ||
60
+ !DEVICE_FILE_OPS.includes(value.op) ||
61
+ !isRecord(value.args))
62
+ throw new RemoteProtocolError("malformed file operation");
63
+ return value;
64
+ }
65
+ case "abort":
66
+ return value;
67
+ case "ack":
68
+ return value;
69
+ case "terminal":
70
+ if (!TERMINAL_REASONS.includes(value.reason) ||
71
+ typeof value.uncertain !== "boolean" ||
72
+ typeof value.hooksRan !== "boolean")
73
+ throw new RemoteProtocolError("malformed terminal outcome");
74
+ return value;
75
+ case "settled": {
76
+ const result = value.result;
77
+ if (!isRecord(result) || !Array.isArray(result.content) || typeof result.isError !== "boolean")
78
+ throw new RemoteProtocolError("malformed result");
79
+ return value;
80
+ }
81
+ case "refused":
82
+ if (typeof value.reason !== "string")
83
+ throw new RemoteProtocolError("malformed refusal");
84
+ return value;
85
+ default:
86
+ throw new RemoteProtocolError("unknown message kind");
87
+ }
88
+ }
89
+ /** The JSON form a value takes on the wire (what the session receives), so a result's types say what arrives. */
90
+ function asJson(value) {
91
+ return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
92
+ }
93
+ /** What a hand sends back for a tool result, keeping only what crosses the wire. */
94
+ export function toRemoteToolResult(result) {
95
+ return {
96
+ content: result.content ?? [],
97
+ details: asJson(result.details),
98
+ isError: result.isError === true,
99
+ ...(result.structuredContent === undefined ? {} : { structuredContent: result.structuredContent }),
100
+ ...(result.terminate === undefined ? {} : { terminate: result.terminate }),
101
+ ...(result.addedToolNames?.length ? { addedToolNames: [...result.addedToolNames] } : {}),
102
+ };
103
+ }
104
+ //# sourceMappingURL=remote-protocol.js.map
@@ -0,0 +1,37 @@
1
+ import type { Transport } from "../transport/transport.ts";
2
+ import type { DeviceFiles } from "./device-files.ts";
3
+ import type { PlaneHandler } from "./plane.ts";
4
+ import type { ExecutionScope, ToolHost } from "./tool-host.ts";
5
+ /**
6
+ * Where the hand runs relative to the session. It decides what a call that ended without a result (the hand restarted
7
+ * while it ran) looks like to the model, and is always stated, never inferred:
8
+ * - `split-local`: one machine. Recovery equals today's: the call gets today's placeholder result and is not run again.
9
+ * - `cross-machine`: the endpoint contract. The call is reported as uncertain, never run again.
10
+ */
11
+ export type HandPlacement = "split-local" | "cross-machine";
12
+ export interface RemoteToolHostOptions {
13
+ /** The session's end of the link to the hand; lanes are execution scope IDs. */
14
+ readonly transport: Transport;
15
+ readonly placement: HandPlacement;
16
+ /** What the session says about itself; the hand never acts on it (R16). */
17
+ readonly sessionRef?: string;
18
+ readonly mintId?: () => string;
19
+ /**
20
+ * The planes this session serves to its running calls' nested requests (S31), keyed by plane name (`MODEL_PLANE`).
21
+ * A request is admitted only while its parent call is live on the lane it came on; absent: every request is refused
22
+ * `plane_unavailable`.
23
+ */
24
+ readonly planes?: Readonly<Record<string, PlaneHandler>>;
25
+ }
26
+ /**
27
+ * The ToolHost that runs a session's tool calls on a hand (brain/hand split, S27a). The hand resolves, prepares,
28
+ * validates, runs the extensions' `tool_call`/`tool_result` handlers (permission checks among them) and executes each
29
+ * call; this host keeps the loop's side: tool events, the batch's ordering, a forwarded abort and the result messages in
30
+ * source order. A call whose send is refused (the transport closed) becomes an error result, never a retry. The one
31
+ * re-send is on a durable hand's `hello` (see `createHandLink`). `deviceFiles(scope)` reaches the hand's files (S40).
32
+ */
33
+ export declare function createRemoteToolHost(options: RemoteToolHostOptions): ToolHost & {
34
+ deviceFiles(scope: ExecutionScope): DeviceFiles;
35
+ close(): void;
36
+ };
37
+ //# sourceMappingURL=remote-tool-host.d.ts.map
@@ -0,0 +1,114 @@
1
+ import { TOOL_RESULT_PLACEHOLDER } from "@earendil-works/pi-ai";
2
+ import { createRemoteDeviceFiles } from "./remote-device-files.js";
3
+ import { createHandLink } from "./remote-link.js";
4
+ function errorResult(text) {
5
+ return { content: [{ type: "text", text }], details: {}, isError: true };
6
+ }
7
+ function terminalResult(placement, terminal) {
8
+ if (placement === "split-local")
9
+ return { content: [{ type: "text", text: TOOL_RESULT_PLACEHOLDER }], details: {}, isError: false };
10
+ const { reason, uncertain, hooksRan } = terminal;
11
+ const effects = uncertain ? "Its effects are uncertain." : "It had no effect.";
12
+ return {
13
+ content: [
14
+ { type: "text", text: `The tool call ended without a result (${reason}) and was not run again. ${effects}` },
15
+ ],
16
+ details: { outcome: reason, uncertain, hooksRan },
17
+ isError: true,
18
+ };
19
+ }
20
+ /**
21
+ * The ToolHost that runs a session's tool calls on a hand (brain/hand split, S27a). The hand resolves, prepares,
22
+ * validates, runs the extensions' `tool_call`/`tool_result` handlers (permission checks among them) and executes each
23
+ * call; this host keeps the loop's side: tool events, the batch's ordering, a forwarded abort and the result messages in
24
+ * source order. A call whose send is refused (the transport closed) becomes an error result, never a retry. The one
25
+ * re-send is on a durable hand's `hello` (see `createHandLink`). `deviceFiles(scope)` reaches the hand's files (S40).
26
+ */
27
+ export function createRemoteToolHost(options) {
28
+ const mintId = options.mintId ?? (() => crypto.randomUUID());
29
+ const link = createHandLink(options.transport, options.planes ?? {});
30
+ const resultOf = (reply) => {
31
+ switch (reply.kind) {
32
+ case "settled":
33
+ return reply.result;
34
+ case "terminal":
35
+ return terminalResult(options.placement, reply.terminal);
36
+ case "refused":
37
+ return errorResult(`The hand refused this tool call: ${reply.reason}`);
38
+ case "aborted":
39
+ return errorResult(reply.sent ? "Tool execution aborted" : "Operation aborted");
40
+ case "unreachable":
41
+ return errorResult(`The hand is unreachable: ${reply.reason}`);
42
+ case "closed":
43
+ return errorResult("The hand link was closed before the call settled");
44
+ }
45
+ };
46
+ const dispatch = (invoke, signal) => ({
47
+ settled: link.dispatch(invoke, signal).then(resultOf),
48
+ });
49
+ return {
50
+ async execute(call, hostOptions) {
51
+ const { emit, signal } = hostOptions;
52
+ const batchId = mintId();
53
+ const invokeOf = (raw, index) => ({
54
+ kind: "invoke",
55
+ executionId: mintId(),
56
+ batchId,
57
+ index,
58
+ scope: call.scope,
59
+ toolCallId: raw.id,
60
+ name: raw.name,
61
+ arguments: raw.arguments,
62
+ ...(options.sessionRef === undefined ? {} : { sessionRef: options.sessionRef }),
63
+ });
64
+ const finish = async (raw, result) => {
65
+ await emit({
66
+ type: "tool_execution_end",
67
+ toolCallId: raw.id,
68
+ toolName: raw.name,
69
+ result,
70
+ isError: result.isError,
71
+ });
72
+ return result;
73
+ };
74
+ const outcomes = [];
75
+ for (const [index, raw] of call.calls.entries()) {
76
+ await emit({ type: "tool_execution_start", toolCallId: raw.id, toolName: raw.name, args: raw.arguments });
77
+ const outcome = dispatch(invokeOf(raw, index), signal).settled.then((result) => finish(raw, result));
78
+ outcomes.push(outcome);
79
+ if (call.mode === "sequential") {
80
+ await outcome;
81
+ if (signal?.aborted)
82
+ break;
83
+ }
84
+ }
85
+ const results = await Promise.all(outcomes);
86
+ const messages = [];
87
+ for (const [index, result] of results.entries()) {
88
+ const raw = call.calls[index];
89
+ if (raw === undefined)
90
+ continue;
91
+ const message = {
92
+ role: "toolResult",
93
+ toolCallId: raw.id,
94
+ toolName: raw.name,
95
+ content: result.content,
96
+ details: result.details,
97
+ ...(result.addedToolNames?.length ? { addedToolNames: [...result.addedToolNames] } : {}),
98
+ isError: result.isError,
99
+ timestamp: Date.now(),
100
+ };
101
+ await emit({ type: "message_start", message });
102
+ await emit({ type: "message_end", message });
103
+ messages.push(message);
104
+ }
105
+ return {
106
+ messages,
107
+ terminate: results.length > 0 && results.every((result) => result.terminate === true),
108
+ };
109
+ },
110
+ deviceFiles: (scope) => createRemoteDeviceFiles(link, scope, mintId),
111
+ close: () => link.close(),
112
+ };
113
+ }
114
+ //# sourceMappingURL=remote-tool-host.js.map
@@ -0,0 +1,81 @@
1
+ import type { DurableStore, StoreValue } from "../durable/store.ts";
2
+ import type { AdmissionLine } from "../durable/store-admission.ts";
3
+ /** What an endpoint owns for one scope (design 5.6.6). */
4
+ export type ScopeBinding = {
5
+ readonly issuer: string;
6
+ readonly workspace: string;
7
+ readonly scope: string;
8
+ readonly generation: number;
9
+ readonly allowedRoots: readonly string[];
10
+ };
11
+ export type ScopeRecord = {
12
+ readonly binding: ScopeBinding;
13
+ readonly state: "open" | "closed";
14
+ readonly lastActiveAt: number;
15
+ /** Live resources (executions, terminals, activities) by id: an idle TTL never closes a scope that holds one. */
16
+ readonly resources: {
17
+ readonly [id: string]: string;
18
+ };
19
+ /** Every committed lifecycle event, in admission order, with the effect its handler returned. */
20
+ readonly events: readonly {
21
+ readonly seq: number;
22
+ readonly kind: string;
23
+ readonly effect: StoreValue;
24
+ }[];
25
+ /** Terminal outcomes a forced close wrote, by resource id, before the scope closed. */
26
+ readonly outcomes: {
27
+ readonly [id: string]: StoreValue;
28
+ };
29
+ };
30
+ export type ScopeRefusal = "unknown_scope" | "not_issuer" | "closed" | "live_resources" | "conflicting_scope";
31
+ /** A call for a scope that is unknown or closed: it never runs. */
32
+ export declare class ScopeUnavailableError extends Error {
33
+ readonly scope: string;
34
+ readonly reason: "unknown_scope" | "closed";
35
+ constructor(scope: string, reason: "unknown_scope" | "closed");
36
+ }
37
+ export interface ScopeLifecycleOptions {
38
+ readonly store: DurableStore;
39
+ readonly epoch: number;
40
+ readonly admission: AdmissionLine;
41
+ readonly clock: () => number;
42
+ readonly idleTtlMs: number;
43
+ }
44
+ /**
45
+ * Scope lifecycle on an endpoint (design 5.6.6). A lifecycle event is admitted only after its handler's effect commits,
46
+ * and a call submitted after it runs only then; only the issuer closes; a TTL never closes a scope with live resources;
47
+ * a forced close writes every live resource's terminal outcome before the scope closes.
48
+ */
49
+ export interface ScopeLifecycle {
50
+ open(binding: ScopeBinding): Promise<{
51
+ readonly kind: "opened";
52
+ } | {
53
+ readonly kind: "refused";
54
+ readonly reason: ScopeRefusal;
55
+ }>;
56
+ lifecycle(actor: string, scope: string, kind: string, handler: () => Promise<StoreValue>): Promise<{
57
+ readonly kind: "committed";
58
+ readonly seq: number;
59
+ } | {
60
+ readonly kind: "refused";
61
+ readonly reason: ScopeRefusal;
62
+ }>;
63
+ /** Runs `run` after every lifecycle event of the scope submitted before it has committed; throws ScopeUnavailableError for a closed or unknown scope. */
64
+ call<T>(scope: string, run: () => Promise<T>): Promise<T>;
65
+ hold(scope: string, resource: string, kind: string): Promise<void>;
66
+ release(scope: string, resource: string): Promise<void>;
67
+ close(actor: string, scope: string, options?: {
68
+ readonly force?: boolean;
69
+ readonly terminate?: (resource: string) => Promise<StoreValue>;
70
+ }): Promise<{
71
+ readonly kind: "closed";
72
+ } | {
73
+ readonly kind: "refused";
74
+ readonly reason: ScopeRefusal;
75
+ }>;
76
+ /** Closes every open scope idle longer than the TTL that holds no live resource; returns their names. */
77
+ sweepIdle(): Promise<readonly string[]>;
78
+ read(scope: string): Promise<ScopeRecord | undefined>;
79
+ }
80
+ export declare function createScopeLifecycle(options: ScopeLifecycleOptions): ScopeLifecycle;
81
+ //# sourceMappingURL=scope-lifecycle.d.ts.map
@@ -0,0 +1,173 @@
1
+ import { canonicalJson } from "./canonical-json.js";
2
+ /** A call for a scope that is unknown or closed: it never runs. */
3
+ export class ScopeUnavailableError extends Error {
4
+ constructor(scope, reason) {
5
+ super(`scope ${scope} is not open: ${reason}`);
6
+ this.name = "ScopeUnavailableError";
7
+ this.scope = scope;
8
+ this.reason = reason;
9
+ }
10
+ }
11
+ const PREFIX = "execution.scope:";
12
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
13
+ function decode(value) {
14
+ if (isObject(value) &&
15
+ isObject(value.binding) &&
16
+ (value.state === "open" || value.state === "closed") &&
17
+ typeof value.lastActiveAt === "number" &&
18
+ isObject(value.resources) &&
19
+ Array.isArray(value.events) &&
20
+ isObject(value.outcomes))
21
+ return value;
22
+ throw new Error("corrupt scope record");
23
+ }
24
+ export function createScopeLifecycle(options) {
25
+ const { store, epoch, admission, clock, idleTtlMs } = options;
26
+ const keyOf = (scope) => `${PREFIX}${JSON.stringify([scope])}`;
27
+ const read = async (scope) => {
28
+ const value = await store.getDocument(keyOf(scope));
29
+ return value === undefined ? undefined : decode(value);
30
+ };
31
+ const write = async (record, step, executionId) => {
32
+ await store.commit(epoch, [
33
+ {
34
+ op: "append",
35
+ id: store.mintId(),
36
+ kind: "execution.scope",
37
+ data: { scope: record.binding.scope, step, executionId },
38
+ },
39
+ { op: "put", key: keyOf(record.binding.scope), data: record },
40
+ ], () => { });
41
+ };
42
+ const update = (scope, decide) => admission.admit(async () => decide(await read(scope)));
43
+ /** Per scope, the last admitted lifecycle event or close: a later call, event or close waits for it. */
44
+ const tails = new Map();
45
+ const after = (scope, step) => {
46
+ const run = (tails.get(scope) ?? Promise.resolve()).then(step, step);
47
+ const settled = run.catch(() => undefined);
48
+ tails.set(scope, settled);
49
+ void settled.then(() => {
50
+ if (tails.get(scope) === settled)
51
+ tails.delete(scope);
52
+ });
53
+ return run;
54
+ };
55
+ const touch = (scope) => update(scope, async (record) => {
56
+ if (record?.state !== "open")
57
+ return record?.state;
58
+ await write({ ...record, lastActiveAt: clock() }, "active", null);
59
+ return "open";
60
+ });
61
+ /**
62
+ * Closes from the record as it is inside the admission line, so a resource held after any earlier read is seen: an
63
+ * unforced close with a live resource is refused; a forced one terminates each resource without an outcome, writes
64
+ * the outcome, and looks again until none is left.
65
+ */
66
+ const finishClose = async (scope, force, terminate) => {
67
+ for (;;) {
68
+ const step = await update(scope, async (latest) => {
69
+ if (latest === undefined)
70
+ return { kind: "refused", reason: "unknown_scope" };
71
+ if (latest.state === "closed")
72
+ return { kind: "closed" };
73
+ const pending = Object.keys(latest.resources).filter((resource) => latest.outcomes[resource] === undefined);
74
+ if (pending.length > 0 && !force)
75
+ return { kind: "refused", reason: "live_resources" };
76
+ if (pending.length > 0)
77
+ return { kind: "terminate", pending };
78
+ await write({ ...latest, state: "closed", resources: {} }, "close", null);
79
+ return { kind: "closed" };
80
+ });
81
+ if (step.kind !== "terminate")
82
+ return step;
83
+ if (terminate === undefined)
84
+ throw new Error(`forced close of ${scope} needs a terminate port`);
85
+ for (const resource of step.pending) {
86
+ const outcome = await terminate(resource);
87
+ await update(scope, async (latest) => {
88
+ if (latest === undefined || latest.state === "closed" || latest.outcomes[resource] !== undefined)
89
+ return;
90
+ await write({ ...latest, outcomes: { ...latest.outcomes, [resource]: outcome } }, "outcome", resource);
91
+ });
92
+ }
93
+ }
94
+ };
95
+ return {
96
+ read,
97
+ open: (binding) => update(binding.scope, async (record) => {
98
+ if (!Number.isFinite(binding.generation))
99
+ throw new Error(`scope ${binding.scope} has a non-finite generation`);
100
+ if (record !== undefined)
101
+ return canonicalJson(record.binding) === canonicalJson(binding) && record.state === "open"
102
+ ? { kind: "opened" }
103
+ : { kind: "refused", reason: "conflicting_scope" };
104
+ await write({ binding, state: "open", lastActiveAt: clock(), resources: {}, events: [], outcomes: {} }, "open", null);
105
+ return { kind: "opened" };
106
+ }),
107
+ lifecycle: (actor, scope, kind, handler) => after(scope, async () => {
108
+ const record = await read(scope);
109
+ if (record === undefined)
110
+ return { kind: "refused", reason: "unknown_scope" };
111
+ if (record.binding.issuer !== actor)
112
+ return { kind: "refused", reason: "not_issuer" };
113
+ if (record.state === "closed")
114
+ return { kind: "refused", reason: "closed" };
115
+ const effect = await handler();
116
+ return update(scope, async (latest) => {
117
+ if (latest === undefined || latest.state === "closed")
118
+ return { kind: "refused", reason: "closed" };
119
+ const seq = latest.events.length + 1;
120
+ await write({ ...latest, lastActiveAt: clock(), events: [...latest.events, { seq, kind, effect }] }, "lifecycle", `${kind}#${seq}`);
121
+ return { kind: "committed", seq };
122
+ });
123
+ }),
124
+ call: (scope, run) => (tails.get(scope) ?? Promise.resolve()).then(async () => {
125
+ const state = await touch(scope);
126
+ if (state !== "open")
127
+ throw new ScopeUnavailableError(scope, state === undefined ? "unknown_scope" : "closed");
128
+ return run();
129
+ }),
130
+ hold: (scope, resource, kind) => update(scope, async (record) => {
131
+ if (record?.state !== "open")
132
+ throw new ScopeUnavailableError(scope, record === undefined ? "unknown_scope" : "closed");
133
+ await write({ ...record, lastActiveAt: clock(), resources: { ...record.resources, [resource]: kind } }, "hold", resource);
134
+ }),
135
+ release: (scope, resource) => update(scope, async (record) => {
136
+ if (record === undefined || record.resources[resource] === undefined)
137
+ return;
138
+ const { [resource]: _released, ...resources } = record.resources;
139
+ await write({ ...record, lastActiveAt: clock(), resources }, "release", resource);
140
+ }),
141
+ close: (actor, scope, closeOptions = {}) => after(scope, async () => {
142
+ const record = await read(scope);
143
+ if (record === undefined)
144
+ return { kind: "refused", reason: "unknown_scope" };
145
+ if (record.binding.issuer !== actor)
146
+ return { kind: "refused", reason: "not_issuer" };
147
+ return finishClose(scope, closeOptions.force === true, closeOptions.terminate);
148
+ }),
149
+ sweepIdle: async () => {
150
+ const closed = [];
151
+ for (const { data } of await store.scanDocuments(PREFIX)) {
152
+ const candidate = decode(data);
153
+ const scope = candidate.binding.scope;
154
+ if (candidate.state !== "open" || Object.keys(candidate.resources).length > 0)
155
+ continue;
156
+ if (clock() - candidate.lastActiveAt <= idleTtlMs)
157
+ continue;
158
+ const done = await after(scope, () => update(scope, async (latest) => {
159
+ if (latest?.state !== "open" || Object.keys(latest.resources).length > 0)
160
+ return false;
161
+ if (clock() - latest.lastActiveAt <= idleTtlMs)
162
+ return false;
163
+ await write({ ...latest, state: "closed" }, "close", null);
164
+ return true;
165
+ }));
166
+ if (done)
167
+ closed.push(scope);
168
+ }
169
+ return closed;
170
+ },
171
+ };
172
+ }
173
+ //# sourceMappingURL=scope-lifecycle.js.map
@@ -0,0 +1,6 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import type { BatchCaseAdapters } from "./batch-executor.ts";
3
+ type BatchCase = CaseImplementation<BatchCaseAdapters>;
4
+ export declare const BATCH_CASES: ReadonlyMap<string, BatchCase>;
5
+ export {};
6
+ //# sourceMappingURL=batch-cases.d.ts.map