@code-yeongyu/senpi-agent-core 2026.11.4-2 → 2026.11.5-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/agent-loop.js +14 -140
  2. package/dist/agent.d.ts +4 -0
  3. package/dist/agent.js +4 -0
  4. package/dist/conformance/index.d.ts +7 -0
  5. package/dist/conformance/index.js +4 -0
  6. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  7. package/dist/conformance/loop-core-manifest.js +17 -0
  8. package/dist/conformance/registry.js +11 -17
  9. package/dist/egress/types.d.ts +102 -0
  10. package/dist/egress/types.js +7 -0
  11. package/dist/execution/canonical-digest.d.ts +10 -0
  12. package/dist/execution/canonical-digest.js +20 -0
  13. package/dist/execution/chain-count.d.ts +26 -0
  14. package/dist/execution/chain-count.js +45 -0
  15. package/dist/execution/coordinator-plan.d.ts +1 -2
  16. package/dist/execution/coordinator-plan.js +4 -17
  17. package/dist/execution/device-files-node.js +39 -1
  18. package/dist/execution/device-files.d.ts +30 -1
  19. package/dist/execution/device-files.js +38 -1
  20. package/dist/execution/ledger-types.d.ts +3 -1
  21. package/dist/execution/ledger.d.ts +9 -3
  22. package/dist/execution/ledger.js +8 -2
  23. package/dist/execution/loop-hook-host-hand.d.ts +33 -0
  24. package/dist/execution/loop-hook-host-hand.js +71 -0
  25. package/dist/execution/loop-hook-host-protocol.d.ts +46 -0
  26. package/dist/execution/loop-hook-host-protocol.js +47 -0
  27. package/dist/execution/loop-hook-host.d.ts +40 -0
  28. package/dist/execution/loop-hook-host.js +87 -0
  29. package/dist/execution/plane-session.d.ts +56 -0
  30. package/dist/execution/plane-session.js +178 -0
  31. package/dist/execution/plane.d.ts +5 -2
  32. package/dist/execution/plane.js +1 -1
  33. package/dist/execution/prepared/executor-body.d.ts +22 -0
  34. package/dist/execution/prepared/executor-body.js +73 -0
  35. package/dist/execution/prepared/executor-freeze.d.ts +17 -0
  36. package/dist/execution/prepared/executor-freeze.js +42 -0
  37. package/dist/execution/prepared/executor-pipeline.d.ts +11 -0
  38. package/dist/execution/prepared/executor-pipeline.js +26 -0
  39. package/dist/execution/prepared/executor-types.d.ts +131 -0
  40. package/dist/execution/prepared/executor-types.js +2 -0
  41. package/dist/execution/prepared/executor.d.ts +8 -0
  42. package/dist/execution/prepared/executor.js +261 -0
  43. package/dist/execution/prepared/memory-batch-store.d.ts +4 -0
  44. package/dist/execution/prepared/memory-batch-store.js +4 -0
  45. package/dist/execution/prepared/pipeline-prepared-batch.d.ts +27 -0
  46. package/dist/execution/prepared/pipeline-prepared-batch.js +175 -0
  47. package/dist/execution/prepared/pipeline-prepared.d.ts +10 -0
  48. package/dist/execution/prepared/pipeline-prepared.js +54 -0
  49. package/dist/execution/remote-device-files.js +33 -4
  50. package/dist/execution/remote-epoch-gate.d.ts +19 -0
  51. package/dist/execution/remote-epoch-gate.js +46 -0
  52. package/dist/execution/remote-epoch.d.ts +53 -0
  53. package/dist/execution/remote-epoch.js +74 -0
  54. package/dist/execution/remote-executor.d.ts +8 -1
  55. package/dist/execution/remote-executor.js +24 -6
  56. package/dist/execution/remote-file-call.js +1 -0
  57. package/dist/execution/remote-hand-ledger.d.ts +11 -3
  58. package/dist/execution/remote-hand-ledger.js +31 -15
  59. package/dist/execution/remote-link.d.ts +6 -1
  60. package/dist/execution/remote-link.js +50 -14
  61. package/dist/execution/remote-protocol.d.ts +30 -1
  62. package/dist/execution/remote-protocol.js +30 -0
  63. package/dist/execution/remote-tool-host.d.ts +12 -0
  64. package/dist/execution/remote-tool-host.js +3 -1
  65. package/dist/execution/testing/epoch-cases.d.ts +8 -0
  66. package/dist/execution/testing/epoch-cases.js +84 -0
  67. package/dist/execution/testing/epoch-harness.d.ts +47 -0
  68. package/dist/execution/testing/epoch-harness.js +172 -0
  69. package/dist/execution/testing/epoch-registry.d.ts +3 -0
  70. package/dist/execution/testing/epoch-registry.js +17 -0
  71. package/dist/execution/testing/hand-harness.d.ts +3 -0
  72. package/dist/execution/testing/hand-harness.js +27 -22
  73. package/dist/execution/testing/hand-registry.d.ts +3 -0
  74. package/dist/execution/testing/hand-registry.js +20 -0
  75. package/dist/execution/testing/kill-epoch.d.ts +9 -0
  76. package/dist/execution/testing/kill-epoch.js +71 -0
  77. package/dist/execution/testing/kill-hook.d.ts +14 -0
  78. package/dist/execution/testing/kill-hook.js +117 -0
  79. package/dist/execution/testing/multi-epoch-cases.d.ts +4 -0
  80. package/dist/execution/testing/multi-epoch-cases.js +29 -0
  81. package/dist/execution/tool-host.d.ts +13 -1
  82. package/dist/execution/tool-host.js +18 -1
  83. package/dist/harness/agent-harness.d.ts +6 -0
  84. package/dist/harness/execution/tool-host-call.d.ts +13 -0
  85. package/dist/harness/execution/tool-host-call.js +55 -0
  86. package/dist/harness/execution/tools.d.ts +2 -1
  87. package/dist/harness/execution/tools.js +32 -17
  88. package/dist/harness/runtime/drive/tools.js +1 -1
  89. package/dist/harness/runtime/harness.js +1 -0
  90. package/dist/harness/runtime/types.d.ts +1 -0
  91. package/dist/index.d.ts +16 -2
  92. package/dist/index.js +14 -1
  93. package/dist/public-entry.d.ts +10 -0
  94. package/dist/public-entry.js +23 -0
  95. package/dist/step-commit.d.ts +24 -0
  96. package/dist/step-commit.js +24 -0
  97. package/dist/tool-name-alias.d.ts +1 -7
  98. package/dist/tool-name-alias.js +0 -17
  99. package/dist/types.d.ts +37 -1
  100. package/package.json +3 -3
@@ -1,7 +1,8 @@
1
+ import { spawn } from "node:child_process";
1
2
  import { constants } from "node:fs";
2
3
  import { lstat, mkdir, open, readdir, rename, rm } from "node:fs/promises";
3
4
  import { dirname } from "node:path";
4
- import { DeviceFileError, FILE_CHANNEL_MAX_BYTES } from "./device-files.js";
5
+ import { DeviceFileError, FILE_CHANNEL_MAX_BYTES, } from "./device-files.js";
5
6
  function deviceError(error, path) {
6
7
  if (error instanceof DeviceFileError)
7
8
  return error;
@@ -73,6 +74,42 @@ async function readBounded(path, signal) {
73
74
  await handle.close();
74
75
  }
75
76
  }
77
+ /** A fused session's `run`: a direct spawn in `cwd`, no shell, no allowlist and no hop, as the caller spawns today. */
78
+ function runDirect(request, signal) {
79
+ return new Promise((done, fail) => {
80
+ const child = spawn(request.exe, [...request.argv], {
81
+ cwd: request.cwd,
82
+ env: request.env === undefined ? process.env : { ...process.env, ...request.env },
83
+ shell: false,
84
+ windowsHide: true,
85
+ ...(signal === undefined ? {} : { signal }),
86
+ });
87
+ const out = [];
88
+ const err = [];
89
+ child.stdout.on("data", (chunk) => out.push(chunk));
90
+ child.stderr.on("data", (chunk) => err.push(chunk));
91
+ let killTimer;
92
+ const timer = request.timeoutMs === undefined
93
+ ? undefined
94
+ : setTimeout(() => {
95
+ child.kill("SIGTERM");
96
+ killTimer = setTimeout(() => child.kill("SIGKILL"), 10_000);
97
+ }, request.timeoutMs);
98
+ child.on("error", (error) => fail(new DeviceFileError(signal?.aborted ? "aborted" : "io", error.message)));
99
+ child.on("close", (code, exitSignal) => {
100
+ clearTimeout(timer);
101
+ clearTimeout(killTimer);
102
+ done({
103
+ code,
104
+ signal: exitSignal,
105
+ stdout: new Uint8Array(Buffer.concat(out)),
106
+ stderr: Buffer.concat(err).toString("utf8"),
107
+ });
108
+ });
109
+ child.stdin.on("error", () => undefined);
110
+ child.stdin.end(request.stdin === undefined ? undefined : Buffer.from(request.stdin));
111
+ });
112
+ }
76
113
  function statOf(entry) {
77
114
  const kind = entry.isFile() ? "file" : entry.isDirectory() ? "directory" : "other";
78
115
  return { kind, size: entry.size, mtimeMs: entry.mtimeMs };
@@ -107,6 +144,7 @@ export function localDeviceFiles() {
107
144
  mkdir: (path, options) => guarded(path, options?.signal, async () => {
108
145
  await mkdir(path, { recursive: true });
109
146
  }),
147
+ run: (request, options) => runDirect(request, options?.signal),
110
148
  };
111
149
  }
112
150
  //# sourceMappingURL=device-files-node.js.map
@@ -18,6 +18,8 @@ export interface DeviceFiles {
18
18
  remove(path: string, options?: DeviceFileOptions): Promise<void>;
19
19
  /** Creates a directory and its parents; an existing directory is not an error. */
20
20
  mkdir(path: string, options?: DeviceFileOptions): Promise<void>;
21
+ /** Runs git or lsof on the device (split: only the calls the hand's allowlist admits; fused: a direct spawn). */
22
+ run(request: DeviceRunRequest, options?: DeviceFileOptions): Promise<DeviceRunResult>;
21
23
  }
22
24
  export interface DeviceFileOptions {
23
25
  readonly signal?: AbortSignal;
@@ -31,8 +33,26 @@ export interface DeviceFileStat {
31
33
  export declare const FILE_CHANNEL = "file/1";
32
34
  /** The most data one operation reads or writes, in raw bytes, in both directions. */
33
35
  export declare const FILE_CHANNEL_MAX_BYTES: number;
34
- export type DeviceFileOp = "read" | "write" | "list" | "stat" | "rename" | "remove" | "mkdir";
36
+ export type DeviceFileOp = "read" | "write" | "list" | "stat" | "rename" | "remove" | "mkdir" | "run";
35
37
  export declare const DEVICE_FILE_OPS: readonly DeviceFileOp[];
38
+ /** The `run` operation's name in a hand's `hello` (S40 PR 2): git and lsof as the memory component calls them. */
39
+ export declare const RUN_CHANNEL = "run/1";
40
+ export interface DeviceRunRequest {
41
+ readonly exe: string;
42
+ readonly argv: readonly string[];
43
+ readonly cwd: string;
44
+ readonly env?: Readonly<Record<string, string>>;
45
+ readonly stdin?: Uint8Array;
46
+ readonly timeoutMs?: number;
47
+ /** Hold the memory component's git-activity lock as fd 3 while git runs; the hand derives the lock from `cwd`. */
48
+ readonly activityLock?: boolean;
49
+ }
50
+ export interface DeviceRunResult {
51
+ readonly code: number | null;
52
+ readonly signal: string | null;
53
+ readonly stdout: Uint8Array;
54
+ readonly stderr: string;
55
+ }
36
56
  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
57
  /**
38
58
  * A device file operation that did not complete. `interrupted` carries the hand's terminal reason; `uncertain` says the
@@ -60,6 +80,15 @@ export type DeviceFileArgs = {
60
80
  readonly op: "rename";
61
81
  readonly path: string;
62
82
  readonly to: string;
83
+ } | {
84
+ readonly op: "run";
85
+ readonly path: string;
86
+ readonly exe: string;
87
+ readonly argv: readonly string[];
88
+ readonly env: Readonly<Record<string, string>>;
89
+ readonly stdin?: string;
90
+ readonly timeoutMs?: number;
91
+ readonly activityLock: boolean;
63
92
  };
64
93
  /** One operation's outcome, carried in a settled result's `details.file`. */
65
94
  export type DeviceFileOutcome = {
@@ -2,7 +2,18 @@
2
2
  export const FILE_CHANNEL = "file/1";
3
3
  /** The most data one operation reads or writes, in raw bytes, in both directions. */
4
4
  export const FILE_CHANNEL_MAX_BYTES = 8 * 1024 * 1024;
5
- export const DEVICE_FILE_OPS = ["read", "write", "list", "stat", "rename", "remove", "mkdir"];
5
+ export const DEVICE_FILE_OPS = [
6
+ "read",
7
+ "write",
8
+ "list",
9
+ "stat",
10
+ "rename",
11
+ "remove",
12
+ "mkdir",
13
+ "run",
14
+ ];
15
+ /** The `run` operation's name in a hand's `hello` (S40 PR 2): git and lsof as the memory component calls them. */
16
+ export const RUN_CHANNEL = "run/1";
6
17
  /**
7
18
  * A device file operation that did not complete. `interrupted` carries the hand's terminal reason; `uncertain` says the
8
19
  * operation may have taken effect (a write may or may not have landed). Nothing is ever retried.
@@ -52,10 +63,36 @@ export function decodeDeviceFileArgs(op, args) {
52
63
  : undefined;
53
64
  case "rename":
54
65
  return typeof args.to === "string" && args.to.length > 0 ? { op, path, to: args.to } : undefined;
66
+ case "run":
67
+ return decodeRunArgs(path, args);
55
68
  default:
56
69
  return undefined;
57
70
  }
58
71
  }
72
+ function decodeRunArgs(path, args) {
73
+ const { exe, argv, env, stdin, timeoutMs, activityLock } = args;
74
+ if (typeof exe !== "string" || !Array.isArray(argv) || !argv.every((arg) => typeof arg === "string"))
75
+ return undefined;
76
+ const environment = env ?? {};
77
+ if (!isRecord(environment) || !Object.values(environment).every((value) => typeof value === "string"))
78
+ return undefined;
79
+ if (stdin !== undefined && typeof stdin !== "string")
80
+ return undefined;
81
+ if (timeoutMs !== undefined && (typeof timeoutMs !== "number" || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0))
82
+ return undefined;
83
+ if (activityLock !== undefined && typeof activityLock !== "boolean")
84
+ return undefined;
85
+ return {
86
+ op: "run",
87
+ path,
88
+ exe,
89
+ argv: argv,
90
+ env: environment,
91
+ ...(stdin === undefined ? {} : { stdin }),
92
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
93
+ activityLock: activityLock === true,
94
+ };
95
+ }
59
96
  export function encodeBase64(bytes) {
60
97
  let binary = "";
61
98
  for (let start = 0; start < bytes.length; start += 0x8000)
@@ -85,7 +85,9 @@ export type ExecutionCommand = {
85
85
  readonly now: number;
86
86
  readonly event: ExecutionEvent;
87
87
  };
88
- export type LedgerRefusal = "not_found" | "identity_conflict" | "invalid_admission" | "stale_generation" | "unauthorized" | "invalid_transition" | "invalid_renewal" | "invalid_time" | "terminal";
88
+ export type LedgerRefusal = "not_found" | "identity_conflict" | "invalid_admission" | "stale_generation" | "unauthorized" | "invalid_transition" | "invalid_renewal" | "invalid_time" | "terminal"
89
+ /** A guard refused the step: the sender's epoch is below the hand's floor for the call's scope (S35). */
90
+ | "epoch_fenced";
89
91
  export type LedgerReply = {
90
92
  readonly status: "applied" | "replayed";
91
93
  readonly entry: ExecutionEntry;
@@ -1,9 +1,15 @@
1
1
  import type { AdmissionLine } from "../durable/store-admission.ts";
2
2
  import type { DurableStore } from "../durable/store.ts";
3
- import { type ExecutionAdmission, type ExecutionCommand, type ExecutionEntry, type ExecutionKey, type LedgerReply } from "./ledger-types.ts";
3
+ import { type ExecutionAdmission, type ExecutionCommand, type ExecutionEntry, type ExecutionKey, type LedgerRefusal, type LedgerReply } from "./ledger-types.ts";
4
+ /**
5
+ * A precondition checked inside a mutation's admission slot, before anything is read or written: a refusal it names is
6
+ * the reply and nothing changes. A hand's epoch floor (S35) uses it so a floor raised between two steps of a call's
7
+ * walk refuses the next step.
8
+ */
9
+ export type LedgerGuard = () => LedgerRefusal | undefined;
4
10
  export interface ExecutionLedger {
5
- admit(input: ExecutionAdmission): Promise<LedgerReply>;
6
- apply(command: ExecutionCommand): Promise<LedgerReply>;
11
+ admit(input: ExecutionAdmission, guard?: LedgerGuard): Promise<LedgerReply>;
12
+ apply(command: ExecutionCommand, guard?: LedgerGuard): Promise<LedgerReply>;
7
13
  read(key: ExecutionKey): Promise<ExecutionEntry | undefined>;
8
14
  /** Called once on endpoint restart; also expires overdue leases and reconciliation deadlines. */
9
15
  recover(now: number): Promise<void>;
@@ -29,7 +29,10 @@ export function createExecutionLedger(options) {
29
29
  writes.push({ op: "put", key: keyOf(entry), data: entry });
30
30
  await store.commit(epoch, writes, () => { });
31
31
  };
32
- const apply = (command) => admission.admit(async () => {
32
+ const apply = (command, guard) => admission.admit(async () => {
33
+ const refusal = guard?.();
34
+ if (refusal !== undefined)
35
+ return refused(refusal);
33
36
  const entry = await read(command.key);
34
37
  if (entry === undefined)
35
38
  return refused("not_found");
@@ -45,7 +48,10 @@ export function createExecutionLedger(options) {
45
48
  return {
46
49
  read,
47
50
  apply,
48
- admit: (input) => admission.admit(async () => {
51
+ admit: (input, guard) => admission.admit(async () => {
52
+ const refusal = guard?.();
53
+ if (refusal !== undefined)
54
+ return refused(refusal);
49
55
  const prior = await read(input);
50
56
  if (prior !== undefined) {
51
57
  const same = prior.executor === input.executor &&
@@ -0,0 +1,33 @@
1
+ import type { JsonValue } from "@earendil-works/pi-ai";
2
+ import type { Transport } from "../transport/transport.ts";
3
+ /** Runs the user's hooks for one loop event on this machine and returns what they produced. */
4
+ export type LoopHookRunner = (event: string, payload: JsonValue) => Promise<JsonValue>;
5
+ /** The points of one hook call on the hand, in order; a kill-point probe may stop the process at any of them. */
6
+ export type LoopHookPoint = "received" | "started" | "ran" | "replied";
7
+ export interface LoopHookHandOptions {
8
+ /**
9
+ * The user machine's end of the link to the loop host. It must outlive this process (the machine's long-lived link
10
+ * endpoint): a `started` still unacknowledged when the endpoint dies is lost, and the loop host then sends the call
11
+ * again to the replacement process, which runs the hooks a second time.
12
+ */
13
+ readonly transport: Transport;
14
+ readonly lane: string;
15
+ readonly run: LoopHookRunner;
16
+ /** This process's identity; a new one per process start. */
17
+ readonly instance?: string;
18
+ /** Test-only probe: throwing here stops this process at that point, as a kill does. */
19
+ readonly onPoint?: (point: LoopHookPoint, callId: string) => void;
20
+ readonly onFault?: (error: unknown) => void;
21
+ }
22
+ export interface LoopHookHand {
23
+ /** Resolves once this process announced itself to the loop host. */
24
+ readonly ready: Promise<void>;
25
+ close(): void;
26
+ }
27
+ /**
28
+ * The user machine's side of the loop-hook link (S33): runs each hook call once per process and answers a repeated call
29
+ * from its stored answer. It announces itself first, and says `started` before any hook runs, so the loop host can tell
30
+ * a call this process never began (safe to send again) from one it may have run (never sent again).
31
+ */
32
+ export declare function serveLoopHooks(options: LoopHookHandOptions): LoopHookHand;
33
+ //# sourceMappingURL=loop-hook-host-hand.d.ts.map
@@ -0,0 +1,71 @@
1
+ import { decodeLoopHookMessage, encodeLoopHookMessage, } from "./loop-hook-host-protocol.js";
2
+ /**
3
+ * The user machine's side of the loop-hook link (S33): runs each hook call once per process and answers a repeated call
4
+ * from its stored answer. It announces itself first, and says `started` before any hook runs, so the loop host can tell
5
+ * a call this process never began (safe to send again) from one it may have run (never sent again).
6
+ */
7
+ export function serveLoopHooks(options) {
8
+ const { transport, lane } = options;
9
+ const instance = options.instance ?? crypto.randomUUID();
10
+ const answers = new Map();
11
+ let dead = false;
12
+ const send = (message) => transport.send(lane, encodeLoopHookMessage(message));
13
+ const point = (at, callId) => {
14
+ if (dead)
15
+ throw new Error("this hand process was stopped");
16
+ try {
17
+ options.onPoint?.(at, callId);
18
+ }
19
+ catch (error) {
20
+ dead = true;
21
+ throw error;
22
+ }
23
+ };
24
+ const serve = async (call) => {
25
+ if (answers.has(call.callId)) {
26
+ const answer = answers.get(call.callId);
27
+ if (answer !== undefined)
28
+ await send(answer);
29
+ return;
30
+ }
31
+ point("received", call.callId);
32
+ answers.set(call.callId, undefined);
33
+ await send({ kind: "hook.started", callId: call.callId, instance });
34
+ point("started", call.callId);
35
+ let answer;
36
+ try {
37
+ answer = { kind: "hook.reply", callId: call.callId, result: await options.run(call.event, call.payload) };
38
+ }
39
+ catch (error) {
40
+ answer = {
41
+ kind: "hook.failed",
42
+ callId: call.callId,
43
+ error: error instanceof Error ? error.message : String(error),
44
+ };
45
+ }
46
+ point("ran", call.callId);
47
+ answers.set(call.callId, answer);
48
+ await send(answer);
49
+ point("replied", call.callId);
50
+ };
51
+ transport.onFrame(async (frame) => {
52
+ if (dead)
53
+ return;
54
+ const message = decodeLoopHookMessage(frame.payload);
55
+ if (message?.kind !== "hook.call")
56
+ return;
57
+ try {
58
+ await serve(message);
59
+ }
60
+ catch (error) {
61
+ options.onFault?.(error);
62
+ }
63
+ });
64
+ return {
65
+ ready: send({ kind: "hook.hello", instance }),
66
+ close() {
67
+ dead = true;
68
+ },
69
+ };
70
+ }
71
+ //# sourceMappingURL=loop-hook-host-hand.js.map
@@ -0,0 +1,46 @@
1
+ import type { JsonValue } from "@earendil-works/pi-ai";
2
+ /**
3
+ * The loop-hook link (brain/hand split S33, decisions C8, K5, K7): when the loop runs away from the user's machine, the
4
+ * loop host asks that machine to run the user's loop hooks (shell hooks and the hook halves of extensions) and waits for
5
+ * the result before it builds the provider request. Every message travels on one lane, so a hook's `started` reaches
6
+ * the loop host before the `hello` of a hand process that replaced the one that started it, PROVIDED the hand's
7
+ * transport endpoint outlives the hand process: `started` is in the endpoint's send window once `send` resolves, not yet
8
+ * acknowledged, and the transport delivers it only while both endpoints live. If the endpoint dies with the process and
9
+ * takes an unacknowledged `started` with it, the loop host never learns the call began and sends it again to the
10
+ * replacement, so a hook that had run runs a second time. At-most-once dispatch therefore holds only on a hand whose
11
+ * endpoint is the machine's long-lived link endpoint, not one owned by the hand process.
12
+ */
13
+ export type LoopHookMessage = LoopHookCall | LoopHookHello | LoopHookStarted | LoopHookReply | LoopHookFailed;
14
+ /** Loop host to hand: run the hooks for `event`. A re-send after a hand restart carries the same `callId`. */
15
+ export interface LoopHookCall {
16
+ readonly kind: "hook.call";
17
+ readonly callId: string;
18
+ readonly event: string;
19
+ readonly payload: JsonValue;
20
+ }
21
+ /** Hand to loop host, once per hand process, before it serves anything. */
22
+ export interface LoopHookHello {
23
+ readonly kind: "hook.hello";
24
+ readonly instance: string;
25
+ }
26
+ /** Hand to loop host, sent before the hooks run: from here on the call may have had effects. */
27
+ export interface LoopHookStarted {
28
+ readonly kind: "hook.started";
29
+ readonly callId: string;
30
+ readonly instance: string;
31
+ }
32
+ export interface LoopHookReply {
33
+ readonly kind: "hook.reply";
34
+ readonly callId: string;
35
+ readonly result: JsonValue;
36
+ }
37
+ /** The hooks ran and failed; the message is the hook's own. */
38
+ export interface LoopHookFailed {
39
+ readonly kind: "hook.failed";
40
+ readonly callId: string;
41
+ readonly error: string;
42
+ }
43
+ export declare function encodeLoopHookMessage(message: LoopHookMessage): Uint8Array;
44
+ /** Parses one frame payload as a loop-hook message; anything else is `undefined`. */
45
+ export declare function decodeLoopHookMessage(payload: Uint8Array): LoopHookMessage | undefined;
46
+ //# sourceMappingURL=loop-hook-host-protocol.d.ts.map
@@ -0,0 +1,47 @@
1
+ const KINDS = [
2
+ "hook.call",
3
+ "hook.hello",
4
+ "hook.started",
5
+ "hook.reply",
6
+ "hook.failed",
7
+ ];
8
+ const encoder = new TextEncoder();
9
+ const decoder = new TextDecoder();
10
+ export function encodeLoopHookMessage(message) {
11
+ return encoder.encode(JSON.stringify(message));
12
+ }
13
+ const isRecord = (value) => typeof value === "object" && value !== null;
14
+ const isId = (value) => typeof value === "string" && value.length > 0;
15
+ /** Parses one frame payload as a loop-hook message; anything else is `undefined`. */
16
+ export function decodeLoopHookMessage(payload) {
17
+ let value;
18
+ try {
19
+ value = JSON.parse(decoder.decode(payload));
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ if (!isRecord(value) || !KINDS.includes(value.kind))
25
+ return undefined;
26
+ switch (value.kind) {
27
+ case "hook.call":
28
+ return isId(value.callId) && isId(value.event) && "payload" in value
29
+ ? { kind: "hook.call", callId: value.callId, event: value.event, payload: value.payload }
30
+ : undefined;
31
+ case "hook.hello":
32
+ return isId(value.instance) ? { kind: "hook.hello", instance: value.instance } : undefined;
33
+ case "hook.started":
34
+ return isId(value.callId) && isId(value.instance)
35
+ ? { kind: "hook.started", callId: value.callId, instance: value.instance }
36
+ : undefined;
37
+ case "hook.reply":
38
+ return isId(value.callId) && "result" in value
39
+ ? { kind: "hook.reply", callId: value.callId, result: value.result }
40
+ : undefined;
41
+ default:
42
+ return isId(value.callId) && typeof value.error === "string"
43
+ ? { kind: "hook.failed", callId: value.callId, error: value.error }
44
+ : undefined;
45
+ }
46
+ }
47
+ //# sourceMappingURL=loop-hook-host-protocol.js.map
@@ -0,0 +1,40 @@
1
+ import type { JsonValue } from "@earendil-works/pi-ai";
2
+ import type { Transport } from "../transport/transport.ts";
3
+ /**
4
+ * The loop host's side of the loop-hook link (brain/hand split S33; decisions C8, K5, K7). When the loop runs on a
5
+ * machine that is not the user's (a hosted loop), the user's loop hooks run on the user's machine: `run` sends one hook
6
+ * call there and resolves with its result, and the caller builds the provider request only from that result, so no
7
+ * provider request leaves without it. While that machine is unreachable the call simply waits (the work is paused), and
8
+ * the transport delivers it once the machine is back, so it resumes exactly once. A fused or split-local session never
9
+ * builds this host: its hooks run in its own process, as today.
10
+ *
11
+ * Restarts: a call the previous hand process never started is sent again, with the same ID, to the new one. A call it
12
+ * had started (and so may have run) is never sent again: it ends with {@link LoopHookRestartedError}. "Started" is what
13
+ * this host received, so this holds only while the hand's transport endpoint outlives the hand process (see
14
+ * `loop-hook-host-protocol.ts`).
15
+ */
16
+ export interface LoopHookHost {
17
+ /** Runs the user's hooks for `event` on the user's machine. Rejects with the hook's failure, a restart or an abort. */
18
+ run(event: string, payload: JsonValue, signal?: AbortSignal): Promise<JsonValue>;
19
+ /** IDs of the calls still waiting for the user's machine. */
20
+ waiting(): readonly string[];
21
+ close(): void;
22
+ }
23
+ export interface LoopHookHostOptions {
24
+ /** The loop host's end of the link to the user's machine. */
25
+ readonly transport: Transport;
26
+ /** The lane the link uses; one per session. */
27
+ readonly lane: string;
28
+ readonly mintId?: () => string;
29
+ }
30
+ /** The hooks ran on the user's machine and failed there; the message is the hook's own. */
31
+ export declare class LoopHookFailedError extends Error {
32
+ constructor(message: string);
33
+ }
34
+ /** The hand process that started the hooks was replaced before it answered; they may have run. Never re-run. */
35
+ export declare class LoopHookRestartedError extends Error {
36
+ readonly uncertain = true;
37
+ constructor(event: string);
38
+ }
39
+ export declare function createLoopHookHost(options: LoopHookHostOptions): LoopHookHost;
40
+ //# sourceMappingURL=loop-hook-host.d.ts.map
@@ -0,0 +1,87 @@
1
+ import { decodeLoopHookMessage, encodeLoopHookMessage } from "./loop-hook-host-protocol.js";
2
+ /** The hooks ran on the user's machine and failed there; the message is the hook's own. */
3
+ export class LoopHookFailedError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = "LoopHookFailedError";
7
+ }
8
+ }
9
+ /** The hand process that started the hooks was replaced before it answered; they may have run. Never re-run. */
10
+ export class LoopHookRestartedError extends Error {
11
+ constructor(event) {
12
+ super(`The user's machine restarted while it ran the ${event} hooks; they were not run again and may have run.`);
13
+ this.uncertain = true;
14
+ this.name = "LoopHookRestartedError";
15
+ }
16
+ }
17
+ export function createLoopHookHost(options) {
18
+ const { transport, lane } = options;
19
+ const mintId = options.mintId ?? (() => crypto.randomUUID());
20
+ const pending = new Map();
21
+ let closed = false;
22
+ const send = (call) => {
23
+ transport.send(lane, encodeLoopHookMessage(call)).catch((error) => {
24
+ const reason = error instanceof Error ? error.message : String(error);
25
+ settle(call.callId, (waiter) => waiter.reject(new Error(`The link to the user's machine closed: ${reason}`)));
26
+ });
27
+ };
28
+ const settle = (callId, finish) => {
29
+ const waiter = pending.get(callId);
30
+ if (waiter === undefined)
31
+ return;
32
+ pending.delete(callId);
33
+ finish(waiter);
34
+ };
35
+ transport.onFrame((frame) => {
36
+ const message = decodeLoopHookMessage(frame.payload);
37
+ if (message === undefined)
38
+ return;
39
+ switch (message.kind) {
40
+ case "hook.started": {
41
+ const waiter = pending.get(message.callId);
42
+ if (waiter !== undefined)
43
+ waiter.startedBy = message.instance;
44
+ return;
45
+ }
46
+ case "hook.reply":
47
+ return settle(message.callId, (waiter) => waiter.resolve(message.result));
48
+ case "hook.failed":
49
+ return settle(message.callId, (waiter) => waiter.reject(new LoopHookFailedError(message.error)));
50
+ case "hook.hello":
51
+ for (const waiter of [...pending.values()]) {
52
+ if (waiter.startedBy === undefined)
53
+ send(waiter.call);
54
+ else if (waiter.startedBy !== message.instance)
55
+ settle(waiter.call.callId, (stale) => stale.reject(new LoopHookRestartedError(stale.call.event)));
56
+ }
57
+ return;
58
+ case "hook.call":
59
+ return;
60
+ }
61
+ });
62
+ return {
63
+ run(event, payload, signal) {
64
+ if (closed)
65
+ return Promise.reject(new Error("The loop-hook link is closed"));
66
+ if (signal?.aborted)
67
+ return Promise.reject(new Error("Operation aborted"));
68
+ const call = { kind: "hook.call", callId: mintId(), event, payload };
69
+ const result = new Promise((resolve, reject) => {
70
+ pending.set(call.callId, { call, resolve, reject });
71
+ });
72
+ const onAbort = () => settle(call.callId, (waiter) => waiter.reject(new Error("Operation aborted")));
73
+ signal?.addEventListener("abort", onAbort, { once: true });
74
+ void result.then(() => signal?.removeEventListener("abort", onAbort), () => signal?.removeEventListener("abort", onAbort));
75
+ send(call);
76
+ return result;
77
+ },
78
+ waiting: () => [...pending.keys()],
79
+ close() {
80
+ closed = true;
81
+ for (const callId of [...pending.keys()])
82
+ settle(callId, (waiter) => waiter.reject(new Error("The loop-hook link was closed before the hooks ran")));
83
+ transport.close();
84
+ },
85
+ };
86
+ }
87
+ //# sourceMappingURL=loop-hook-host.js.map
@@ -0,0 +1,56 @@
1
+ import type { AgentToolResult } from "../types.ts";
2
+ import type { AgentLoopConfig } from "../types.ts";
3
+ import { type NestedRequest, type PlaneHandler } from "./plane.ts";
4
+ import { type ToolHost } from "./tool-host.ts";
5
+ /**
6
+ * The session plane (brain/hand split, S32): tools that act on the session (todo, thread tools, task/subagent spawn,
7
+ * `ask_user`, and the other built-ins declared `runs: "brain"`) run where the loop runs. A model call to one of them
8
+ * never reaches the hand, and a hand-run tool that needs one asks the brain that owns its call on this plane.
9
+ */
10
+ export declare const SESSION_PLANE = "session";
11
+ /** One loop-side tool call a hand-run tool asks the brain for. */
12
+ export interface SessionPlaneRequest {
13
+ readonly tool: string;
14
+ readonly arguments: Readonly<Record<string, unknown>>;
15
+ }
16
+ /** Parses a request body, keeping only the fields of {@link SessionPlaneRequest}; refuses a malformed one. */
17
+ export declare function decodeSessionPlaneRequest(body: unknown): SessionPlaneRequest;
18
+ /** The registered tools a split session runs loop-side: exactly those declared `runs: "brain"`. */
19
+ export declare function loopSideToolNames(tools: Iterable<{
20
+ readonly name: string;
21
+ readonly runs?: "brain" | "hand";
22
+ }>): ReadonlySet<string>;
23
+ /**
24
+ * The brain's session plane: runs one loop-side tool call with the session's own tools and returns its result. A tool
25
+ * that is not loop-side is refused `not_loop_side`: a hand's tools never run on the brain through this plane.
26
+ */
27
+ export declare function serveSessionPlane(options: {
28
+ readonly loopSide: ReadonlySet<string>;
29
+ readonly run: (request: SessionPlaneRequest, signal: AbortSignal) => Promise<AgentToolResult<unknown>>;
30
+ }): PlaneHandler;
31
+ /** A hand's client for the session plane, over the running call's nested requests. */
32
+ export declare function createSessionPlaneClient(nested: NestedRequest): {
33
+ call(request: SessionPlaneRequest, signal?: AbortSignal): Promise<AgentToolResult<unknown>>;
34
+ };
35
+ type LoopToolSource = Pick<AgentLoopConfig, "resolveUnknownToolCall" | "beforeToolCall" | "afterToolCall" | "removedToolHints" | "afterToolFreeze" | "batchStoreFactory">;
36
+ /**
37
+ * The loop's own pipeline as a ToolHost (the prepared pipeline a fused session runs), for a split session's loop-side
38
+ * calls. It reads `agent`'s hooks and batch store at each batch, so hooks installed after it was made still apply.
39
+ */
40
+ export declare function createLoopToolHost(agent: LoopToolSource): ToolHost;
41
+ /**
42
+ * The ToolHost of a split session: each call to a loop-side tool runs on `loop` (the session's own pipeline, in its
43
+ * process) and every other call on `hand`. A batch of one side goes to that host whole. A mixed batch keeps the mode:
44
+ * `parallel` runs both sides at once and emits the result messages in source order once both finished, as the fused
45
+ * pipeline does; `sequential` runs each run of same-side calls in source order and starts none after an abort. Results come
46
+ * back in the model's source order and the batch terminates only when every call asked to.
47
+ */
48
+ export declare function createSplitToolHost(options: {
49
+ readonly loopSide: (toolName: string) => boolean;
50
+ /** The tools declared `executionMode: "sequential"`: in a parallel batch each waits for every earlier call. */
51
+ readonly isSequential: (toolName: string) => boolean;
52
+ readonly loop: ToolHost;
53
+ readonly hand: ToolHost;
54
+ }): ToolHost;
55
+ export {};
56
+ //# sourceMappingURL=plane-session.d.ts.map