@code-yeongyu/senpi-agent-core 2026.11.4-2 → 2026.11.6-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 (111) 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 +12 -1
  5. package/dist/conformance/index.js +6 -0
  6. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  7. package/dist/conformance/loop-core-manifest.js +18 -0
  8. package/dist/conformance/registry.js +11 -17
  9. package/dist/durable/session-store.d.ts +42 -0
  10. package/dist/durable/session-store.js +124 -0
  11. package/dist/durable/store-memory.d.ts +2 -2
  12. package/dist/durable/store-memory.js +36 -34
  13. package/dist/durable/store.d.ts +9 -0
  14. package/dist/durable/testing/store-harness.d.ts +1 -0
  15. package/dist/durable/testing/store-harness.js +1 -0
  16. package/dist/durable/testing/sync-commit-cases.d.ts +20 -0
  17. package/dist/durable/testing/sync-commit-cases.js +89 -0
  18. package/dist/egress/types.d.ts +102 -0
  19. package/dist/egress/types.js +7 -0
  20. package/dist/execution/canonical-digest.d.ts +10 -0
  21. package/dist/execution/canonical-digest.js +20 -0
  22. package/dist/execution/chain-count.d.ts +26 -0
  23. package/dist/execution/chain-count.js +45 -0
  24. package/dist/execution/coordinator-plan.d.ts +1 -2
  25. package/dist/execution/coordinator-plan.js +4 -17
  26. package/dist/execution/device-files-node.js +40 -1
  27. package/dist/execution/device-files.d.ts +39 -1
  28. package/dist/execution/device-files.js +48 -1
  29. package/dist/execution/ledger-types.d.ts +3 -1
  30. package/dist/execution/ledger.d.ts +9 -3
  31. package/dist/execution/ledger.js +8 -2
  32. package/dist/execution/loop-hook-host-hand.d.ts +33 -0
  33. package/dist/execution/loop-hook-host-hand.js +71 -0
  34. package/dist/execution/loop-hook-host-protocol.d.ts +46 -0
  35. package/dist/execution/loop-hook-host-protocol.js +47 -0
  36. package/dist/execution/loop-hook-host.d.ts +40 -0
  37. package/dist/execution/loop-hook-host.js +87 -0
  38. package/dist/execution/plane-session.d.ts +56 -0
  39. package/dist/execution/plane-session.js +178 -0
  40. package/dist/execution/plane.d.ts +5 -2
  41. package/dist/execution/plane.js +1 -1
  42. package/dist/execution/prepared/executor-body.d.ts +22 -0
  43. package/dist/execution/prepared/executor-body.js +73 -0
  44. package/dist/execution/prepared/executor-freeze.d.ts +22 -0
  45. package/dist/execution/prepared/executor-freeze.js +55 -0
  46. package/dist/execution/prepared/executor-pipeline.d.ts +11 -0
  47. package/dist/execution/prepared/executor-pipeline.js +26 -0
  48. package/dist/execution/prepared/executor-types.d.ts +131 -0
  49. package/dist/execution/prepared/executor-types.js +2 -0
  50. package/dist/execution/prepared/executor.d.ts +8 -0
  51. package/dist/execution/prepared/executor.js +260 -0
  52. package/dist/execution/prepared/memory-batch-store.d.ts +4 -0
  53. package/dist/execution/prepared/memory-batch-store.js +4 -0
  54. package/dist/execution/prepared/pipeline-prepared-batch.d.ts +27 -0
  55. package/dist/execution/prepared/pipeline-prepared-batch.js +175 -0
  56. package/dist/execution/prepared/pipeline-prepared.d.ts +10 -0
  57. package/dist/execution/prepared/pipeline-prepared.js +54 -0
  58. package/dist/execution/remote-device-files.js +33 -4
  59. package/dist/execution/remote-epoch-gate.d.ts +19 -0
  60. package/dist/execution/remote-epoch-gate.js +46 -0
  61. package/dist/execution/remote-epoch.d.ts +53 -0
  62. package/dist/execution/remote-epoch.js +74 -0
  63. package/dist/execution/remote-executor.d.ts +8 -1
  64. package/dist/execution/remote-executor.js +24 -6
  65. package/dist/execution/remote-file-call.js +1 -0
  66. package/dist/execution/remote-hand-ledger.d.ts +11 -3
  67. package/dist/execution/remote-hand-ledger.js +31 -15
  68. package/dist/execution/remote-link.d.ts +6 -1
  69. package/dist/execution/remote-link.js +50 -14
  70. package/dist/execution/remote-protocol.d.ts +30 -1
  71. package/dist/execution/remote-protocol.js +30 -0
  72. package/dist/execution/remote-tool-host.d.ts +12 -0
  73. package/dist/execution/remote-tool-host.js +3 -1
  74. package/dist/execution/testing/epoch-cases.d.ts +8 -0
  75. package/dist/execution/testing/epoch-cases.js +84 -0
  76. package/dist/execution/testing/epoch-harness.d.ts +47 -0
  77. package/dist/execution/testing/epoch-harness.js +172 -0
  78. package/dist/execution/testing/epoch-registry.d.ts +3 -0
  79. package/dist/execution/testing/epoch-registry.js +17 -0
  80. package/dist/execution/testing/hand-harness.d.ts +5 -0
  81. package/dist/execution/testing/hand-harness.js +57 -24
  82. package/dist/execution/testing/hand-registry.d.ts +3 -0
  83. package/dist/execution/testing/hand-registry.js +20 -0
  84. package/dist/execution/testing/kill-epoch.d.ts +9 -0
  85. package/dist/execution/testing/kill-epoch.js +71 -0
  86. package/dist/execution/testing/kill-hook.d.ts +14 -0
  87. package/dist/execution/testing/kill-hook.js +117 -0
  88. package/dist/execution/testing/multi-epoch-cases.d.ts +4 -0
  89. package/dist/execution/testing/multi-epoch-cases.js +29 -0
  90. package/dist/execution/testing/multi-hand-cases.js +1 -1
  91. package/dist/execution/tool-host.d.ts +16 -1
  92. package/dist/execution/tool-host.js +18 -1
  93. package/dist/harness/agent-harness.d.ts +6 -0
  94. package/dist/harness/execution/tool-host-call.d.ts +14 -0
  95. package/dist/harness/execution/tool-host-call.js +56 -0
  96. package/dist/harness/execution/tools.d.ts +2 -1
  97. package/dist/harness/execution/tools.js +45 -17
  98. package/dist/harness/runtime/drive/tools.js +1 -1
  99. package/dist/harness/runtime/harness.js +1 -0
  100. package/dist/harness/runtime/types.d.ts +1 -0
  101. package/dist/harness/tools/read.js +1 -1
  102. package/dist/index.d.ts +19 -2
  103. package/dist/index.js +15 -1
  104. package/dist/public-entry.d.ts +10 -0
  105. package/dist/public-entry.js +23 -0
  106. package/dist/step-commit.d.ts +24 -0
  107. package/dist/step-commit.js +24 -0
  108. package/dist/tool-name-alias.d.ts +1 -7
  109. package/dist/tool-name-alias.js +0 -17
  110. package/dist/types.d.ts +37 -1
  111. package/package.json +3 -3
@@ -9,6 +9,7 @@ export interface StoreConformanceAdapter {
9
9
  export interface StoreCaseAdapters {
10
10
  readonly store: StoreConformanceAdapter;
11
11
  }
12
+ export declare const isCutSignal: (error: unknown) => boolean;
12
13
  export declare function cutOnceAt(target: StoreWritePoint): DurableStoreOptions;
13
14
  export declare function expectEqual(actual: unknown, expected: unknown, what: string): void;
14
15
  export declare function expectStoreError(operation: Promise<unknown>, code: DurableStoreErrorCode, what: string): Promise<void>;
@@ -5,6 +5,7 @@ class CutSignal extends Error {
5
5
  this.name = "CutSignal";
6
6
  }
7
7
  }
8
+ export const isCutSignal = (error) => error instanceof CutSignal;
8
9
  const samePoint = (a, b) => a.op === b.op && a.at === b.at && (a.at !== "write" || (b.at === "write" && a.index === b.index));
9
10
  export function cutOnceAt(target) {
10
11
  let armed = true;
@@ -0,0 +1,20 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import type { RegisteredCase } from "../../conformance/registry.ts";
3
+ import type { DurableStoreOptions, SyncCommitStore } from "../store.ts";
4
+ /** What a backend that offers `commitSync` provides to the SYNC-COMMIT cases. */
5
+ export interface SyncCommitConformanceAdapter {
6
+ createMedium(): Promise<string>;
7
+ open(medium: string, options?: DurableStoreOptions): Promise<SyncCommitStore>;
8
+ }
9
+ export interface SyncCommitCaseAdapters {
10
+ readonly store: SyncCommitConformanceAdapter;
11
+ }
12
+ type SyncCommitCase = CaseImplementation<SyncCommitCaseAdapters>;
13
+ export declare const SYNC_COMMIT_CASES: ReadonlyMap<string, SyncCommitCase>;
14
+ /**
15
+ * The SYNC-COMMIT cases, run only by backends that offer `commitSync` (memory, Bun SQLite). They are kept out of the
16
+ * cross-host CONFORMANCE_REGISTRY: a Durable Object store commits durably only asynchronously and offers no sync commit.
17
+ */
18
+ export declare const SYNC_COMMIT_REGISTRY: readonly RegisteredCase[];
19
+ export {};
20
+ //# sourceMappingURL=sync-commit-cases.d.ts.map
@@ -0,0 +1,89 @@
1
+ import { DurableStoreError } from "../store.js";
2
+ import { adoptLog, cutOnceAt, expectEqual, isCutSignal, reopenSnapshot } from "./store-harness.js";
3
+ import { append, put, stored } from "./store-cases.js";
4
+ async function claimed(adapter, options) {
5
+ const medium = await adapter.createMedium();
6
+ const setup = await adapter.open(medium);
7
+ await setup.claim(0, 1);
8
+ await setup.commit(1, [append("r1"), put("a", 1)], () => { });
9
+ return { medium, store: await adapter.open(medium, options) };
10
+ }
11
+ function sameCallOutcome(call) {
12
+ try {
13
+ return { returned: call() };
14
+ }
15
+ catch (error) {
16
+ return { threw: error };
17
+ }
18
+ }
19
+ const isThenable = (value) => typeof value === "object" && value !== null && typeof Reflect.get(value, "then") === "function";
20
+ const commitsWholeOnReturn = async ({ store: adapter }) => {
21
+ const { medium, store } = await claimed(adapter);
22
+ const log = adoptLog();
23
+ const outcome = sameCallOutcome(() => store.commitSync(1, [append("r2"), put("a", 2)], log.adopt));
24
+ if (!("returned" in outcome))
25
+ throw new Error(`a valid sync commit threw: ${String(outcome.threw)}`);
26
+ if (isThenable(outcome.returned))
27
+ throw new Error("commitSync returned a promise: it is not synchronous");
28
+ expectEqual(outcome.returned, { seqs: [2], head: 2 }, "the result is the batch's seqs and the new head");
29
+ expectEqual(log.calls, ["adopt:2"], "adopt ran once, before commitSync returned");
30
+ expectEqual(await reopenSnapshot(adapter, medium), { epoch: 1, head: 2, records: [stored(1, "r1"), stored(2, "r2")], documents: [{ key: "a", data: 2 }] }, "another instance on the medium sees the batch as soon as commitSync returns");
31
+ };
32
+ const BATCH = [append("r2"), put("a", 2), { op: "delete", key: "a" }, append("r3")];
33
+ const REFUSALS = [
34
+ { what: "stale epoch", epoch: 2, writes: BATCH, expected: "stale-epoch" },
35
+ { what: "duplicate record id", epoch: 1, writes: [append("r2"), append("r1")], expected: "duplicate-record-id" },
36
+ { what: "cut before", epoch: 1, writes: BATCH, options: cutOnceAt({ op: "commit", at: "before" }), expected: "cut" },
37
+ ...BATCH.map((_, index) => ({
38
+ what: `cut at write ${index}`,
39
+ epoch: 1,
40
+ writes: BATCH,
41
+ options: cutOnceAt({ op: "commit", at: "write", index }),
42
+ expected: "cut",
43
+ })),
44
+ ];
45
+ const refusedThrowsOnTheSameCall = async ({ store: adapter }) => {
46
+ for (const refusal of REFUSALS) {
47
+ const { medium, store } = await claimed(adapter, refusal.options);
48
+ const before = await reopenSnapshot(adapter, medium);
49
+ const log = adoptLog();
50
+ const outcome = sameCallOutcome(() => store.commitSync(refusal.epoch, refusal.writes, log.adopt));
51
+ if (!("threw" in outcome)) {
52
+ throw new Error(`${refusal.what}: the refused sync commit did not throw on the same call`);
53
+ }
54
+ const code = outcome.threw instanceof DurableStoreError
55
+ ? outcome.threw.code
56
+ : isCutSignal(outcome.threw)
57
+ ? "cut"
58
+ : `unexpected ${String(outcome.threw)}`;
59
+ expectEqual(code, refusal.expected, `${refusal.what}: the refusal`);
60
+ expectEqual(log.calls, [], `${refusal.what}: no adopt`);
61
+ expectEqual(await reopenSnapshot(adapter, medium), before, `${refusal.what}: the store is unchanged`);
62
+ }
63
+ };
64
+ export const SYNC_COMMIT_CASES = new Map([
65
+ ["SYNC-COMMIT-01", commitsWholeOnReturn],
66
+ ["SYNC-COMMIT-02", refusedThrowsOnTheSameCall],
67
+ ]);
68
+ const SYNC_COMMIT_IMPL = "packages/agent/src/durable/testing/sync-commit-cases.ts";
69
+ /**
70
+ * The SYNC-COMMIT cases, run only by backends that offer `commitSync` (memory, Bun SQLite). They are kept out of the
71
+ * cross-host CONFORMANCE_REGISTRY: a Durable Object store commits durably only asynchronously and offers no sync commit.
72
+ */
73
+ export const SYNC_COMMIT_REGISTRY = [
74
+ {
75
+ id: "SYNC-COMMIT-01",
76
+ impl: SYNC_COMMIT_IMPL,
77
+ intro: "#5827",
78
+ adapters: ["store"],
79
+ expected: "a sync commit is durable, adopted once and visible to another instance when it returns",
80
+ },
81
+ {
82
+ id: "SYNC-COMMIT-02",
83
+ impl: SYNC_COMMIT_IMPL,
84
+ intro: "#5827",
85
+ adapters: ["store"],
86
+ expected: "a refused sync commit (stale epoch, duplicate id, cut) throws on the same call and changes nothing",
87
+ },
88
+ ];
89
+ //# sourceMappingURL=sync-commit-cases.js.map
@@ -0,0 +1,102 @@
1
+ /**
2
+ * `ModelEgress`: one provider-pipeline layer that decides, per provider and per request, whether a model call
3
+ * is dialed directly (today's stream function, unchanged), with secrets released from sealed custody, or
4
+ * through a device the user owns. Only types and constants live here; implementations live with the
5
+ * provider pipeline, and the fused path passes today's stream function through untouched.
6
+ */
7
+ import type { StreamFn } from "../types.ts";
8
+ export type ProviderId = string;
9
+ export type DeviceId = string;
10
+ export type Epoch = number;
11
+ export type EgressRoute = "direct" | "sealed" | "device";
12
+ export type RouteReason = "fused" | "custody:sealed" | "custody:device" | "roster:unknown" | "custody:cwd-scoped" | "custody:unavailable" | "owner:revoked" | "definition:variant" | "address:private" | "address:self" | "address:unknown" | "capability:local-only" | "capability:ambient" | "capability:callback-stream" | "capability:callback-stream-undefined" | "api:no-fetch-injection" | "network:device-bound" | "provider:extension" | "provider:hand-local" | "provider:unknown" | "hook:stream" | "hook:stream-undefined" | "hook:unknown" | "hook:request-offline" | "redirect:cross-origin";
13
+ export type WaitCondition = {
14
+ readonly kind: "device-online";
15
+ readonly deviceId: DeviceId;
16
+ } | {
17
+ readonly kind: "custody-available";
18
+ } | {
19
+ readonly kind: "refresh-ack";
20
+ readonly providerId: ProviderId;
21
+ } | {
22
+ readonly kind: "roster-sync";
23
+ } | {
24
+ readonly kind: "hand-selected";
25
+ } | {
26
+ readonly kind: "hand-advertised";
27
+ readonly deviceId: DeviceId;
28
+ } | {
29
+ readonly kind: "config-head-change";
30
+ } | {
31
+ readonly kind: "live-digest-change";
32
+ readonly deviceId: DeviceId;
33
+ readonly providerId: ProviderId;
34
+ } | {
35
+ readonly kind: "storage-available";
36
+ } | {
37
+ readonly kind: "epoch-fresh";
38
+ } | {
39
+ readonly kind: "claim-renewed";
40
+ } | {
41
+ readonly kind: "user-choice";
42
+ readonly choiceId: string;
43
+ };
44
+ export interface EgressRouteDecision {
45
+ readonly route: EgressRoute;
46
+ readonly reason: RouteReason;
47
+ readonly deviceId?: DeviceId;
48
+ /** False: the call waits in the stream (never fails) until `waitFor` holds, showing `steer`. */
49
+ readonly servedNow: boolean;
50
+ readonly steer?: string;
51
+ readonly waitFor?: readonly WaitCondition[];
52
+ readonly requestHooksOn?: DeviceId;
53
+ readonly executorHooks?: "enabled" | "disabled";
54
+ readonly serveOwnDefinition?: true;
55
+ }
56
+ /** The durable admission fence; `generation` is the agent instance generation, and older generations are refused for good. */
57
+ export interface AdmissionFence {
58
+ readonly epoch: Epoch;
59
+ readonly admissionSeq: number;
60
+ readonly generation: number;
61
+ }
62
+ export interface StepRef {
63
+ readonly kind: "step";
64
+ readonly sessionId: string;
65
+ readonly stepId: string;
66
+ readonly attempt: number;
67
+ readonly fence: AdmissionFence;
68
+ }
69
+ export interface AuxRef {
70
+ readonly kind: "aux";
71
+ readonly sessionId: string;
72
+ readonly auxId: string;
73
+ readonly auxKey: string;
74
+ readonly streamKind: string;
75
+ readonly fence: AdmissionFence;
76
+ }
77
+ export type CallRef = StepRef | AuxRef;
78
+ export interface EgressWait {
79
+ readonly call: CallRef;
80
+ readonly reason: RouteReason | "device-offline" | "result-pending" | "refresh-pending" | "config-churn" | "epoch-stale" | "claim-expired";
81
+ readonly steer: string;
82
+ readonly waitFor: readonly WaitCondition[];
83
+ }
84
+ export interface EgressHostHooks {
85
+ currentStep(): StepRef;
86
+ admitAux(streamKind: string, auxKey: string): Promise<AuxRef>;
87
+ onWait(wait: EgressWait): Promise<void>;
88
+ onWaitEnd(callId: string): Promise<void>;
89
+ historyHasStep(stepId: string): Promise<boolean>;
90
+ }
91
+ /** Bound from a hosted session latching on a failed step commit to its rebuilt instance accepting work. */
92
+ export declare const HOSTED_REBUILD_DEADLINE_MS = 5000;
93
+ /** Maximum age of a registry epoch check accepted for a secret release, a step commit or a tool dispatch. */
94
+ export declare const EPOCH_FRESHNESS_MS = 5000;
95
+ /** Margin a new placement owner waits beyond `EPOCH_FRESHNESS_MS` before cutting over a moved session. */
96
+ export declare const MOVE_SKEW_MS = 2000;
97
+ export interface ModelEgress {
98
+ /** Pure and cheap: no I/O, safe to call from UI code. */
99
+ routeFor(providerId: ProviderId): EgressRouteDecision;
100
+ readonly stream: StreamFn;
101
+ }
102
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,7 @@
1
+ /** Bound from a hosted session latching on a failed step commit to its rebuilt instance accepting work. */
2
+ export const HOSTED_REBUILD_DEADLINE_MS = 5_000;
3
+ /** Maximum age of a registry epoch check accepted for a secret release, a step commit or a tool dispatch. */
4
+ export const EPOCH_FRESHNESS_MS = 5_000;
5
+ /** Margin a new placement owner waits beyond `EPOCH_FRESHNESS_MS` before cutting over a moved session. */
6
+ export const MOVE_SKEW_MS = 2_000;
7
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,10 @@
1
+ import type { StoreValue } from "../durable/store.ts";
2
+ /**
3
+ * The canonical JSON of a store value: object keys sorted by UTF-16 code unit, no whitespace. Every execution digest
4
+ * (a batch manifest, a call's request, a frozen call, a tool schema) hashes this form, so two sides that build the same
5
+ * value agree on its digest.
6
+ */
7
+ export declare function canonicalJson(value: StoreValue): string;
8
+ /** Lower-case hex SHA-256 of {@link canonicalJson}, through Web Crypto so the agent loop stays browser-safe. */
9
+ export declare function canonicalDigest(value: StoreValue): Promise<string>;
10
+ //# sourceMappingURL=canonical-digest.d.ts.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The canonical JSON of a store value: object keys sorted by UTF-16 code unit, no whitespace. Every execution digest
3
+ * (a batch manifest, a call's request, a frozen call, a tool schema) hashes this form, so two sides that build the same
4
+ * value agree on its digest.
5
+ */
6
+ export function canonicalJson(value) {
7
+ if (Array.isArray(value))
8
+ return `[${value.map(canonicalJson).join(",")}]`;
9
+ if (value !== null && typeof value === "object") {
10
+ const entries = Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
11
+ return `{${entries.map(([key, inner]) => `${JSON.stringify(key)}:${canonicalJson(inner)}`).join(",")}}`;
12
+ }
13
+ return JSON.stringify(value);
14
+ }
15
+ /** Lower-case hex SHA-256 of {@link canonicalJson}, through Web Crypto so the agent loop stays browser-safe. */
16
+ export async function canonicalDigest(value) {
17
+ const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonicalJson(value)));
18
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
19
+ }
20
+ //# sourceMappingURL=canonical-digest.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The hop count of a thread chain (brain/hand split, decision K8): session A's thread tool prompts session B, B's
3
+ * prompts A again, and so on. A→B→A is allowed. Each call carries the count of the hop it makes; a session started by
4
+ * a thread call is at that call's count, and its own thread calls carry one more. The only limit is a count the user
5
+ * sets; unset means unlimited. There is no cost limit, no hidden default and no refusal for coming back to an origin.
6
+ */
7
+ /** The refusal reason of a thread call past the user's count limit. */
8
+ export declare const CHAIN_COUNT_LIMIT = "chain_count_limit";
9
+ /** A user-started session is at count 0; its first thread call is hop 1. */
10
+ export declare const CHAIN_ORIGIN = 0;
11
+ export declare class ChainCountLimitError extends Error {
12
+ readonly reason = "chain_count_limit";
13
+ readonly count: number;
14
+ readonly limit: number;
15
+ constructor(count: number, limit: number);
16
+ }
17
+ /** The count a thread call sent from a session at `sessionCount` carries. */
18
+ export declare function nextChainCount(sessionCount: number): number;
19
+ /** Parses the count a thread call carries; absent means the call starts a chain (hop 1 from a user-started session). */
20
+ export declare function decodeChainCount(value: unknown): number;
21
+ /**
22
+ * Admits a thread call that makes its chain `count` hops long. `readLimit` is read at each admission, never cached
23
+ * (on the CLI: the user's `threads.chainCountLimit` setting); `undefined` admits every call at any length.
24
+ */
25
+ export declare function admitChainCall(count: number, readLimit: () => number | undefined): number;
26
+ //# sourceMappingURL=chain-count.d.ts.map
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The hop count of a thread chain (brain/hand split, decision K8): session A's thread tool prompts session B, B's
3
+ * prompts A again, and so on. A→B→A is allowed. Each call carries the count of the hop it makes; a session started by
4
+ * a thread call is at that call's count, and its own thread calls carry one more. The only limit is a count the user
5
+ * sets; unset means unlimited. There is no cost limit, no hidden default and no refusal for coming back to an origin.
6
+ */
7
+ /** The refusal reason of a thread call past the user's count limit. */
8
+ export const CHAIN_COUNT_LIMIT = "chain_count_limit";
9
+ /** A user-started session is at count 0; its first thread call is hop 1. */
10
+ export const CHAIN_ORIGIN = 0;
11
+ export class ChainCountLimitError extends Error {
12
+ constructor(count, limit) {
13
+ super(`This thread call would be hop ${count} of its chain; your thread chain count limit is ${limit}.`);
14
+ this.reason = CHAIN_COUNT_LIMIT;
15
+ this.name = "ChainCountLimitError";
16
+ this.count = count;
17
+ this.limit = limit;
18
+ }
19
+ }
20
+ const isCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
21
+ /** The count a thread call sent from a session at `sessionCount` carries. */
22
+ export function nextChainCount(sessionCount) {
23
+ if (!isCount(sessionCount))
24
+ throw new TypeError(`not a chain count: ${String(sessionCount)}`);
25
+ return sessionCount + 1;
26
+ }
27
+ /** Parses the count a thread call carries; absent means the call starts a chain (hop 1 from a user-started session). */
28
+ export function decodeChainCount(value) {
29
+ if (value === undefined)
30
+ return nextChainCount(CHAIN_ORIGIN);
31
+ if (!isCount(value) || value === CHAIN_ORIGIN)
32
+ throw new TypeError(`malformed chain count: ${JSON.stringify(value)}`);
33
+ return value;
34
+ }
35
+ /**
36
+ * Admits a thread call that makes its chain `count` hops long. `readLimit` is read at each admission, never cached
37
+ * (on the CLI: the user's `threads.chainCountLimit` setting); `undefined` admits every call at any length.
38
+ */
39
+ export function admitChainCall(count, readLimit) {
40
+ const limit = readLimit();
41
+ if (limit !== undefined && count > limit)
42
+ throw new ChainCountLimitError(count, limit);
43
+ return count;
44
+ }
45
+ //# sourceMappingURL=chain-count.js.map
@@ -1,7 +1,6 @@
1
1
  import type { BatchManifest, BatchPlan, CallOutcome, PrepareReply, SettleReply } from "./coordinator-types.ts";
2
2
  /**
3
- * Release dependencies exactly as today's scheduler assigns them (agent-loop.ts, executeToolCallsParallel): a
4
- * sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
3
+ * Release dependencies exactly as the agent loop has always ordered a batch: a sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
5
4
  * previous sequential call only.
6
5
  */
7
6
  export declare function batchDependencies(calls: readonly {
@@ -1,7 +1,7 @@
1
1
  import { TOOL_RESULT_PLACEHOLDER } from "@earendil-works/pi-ai";
2
+ import { canonicalDigest } from "./canonical-digest.js";
2
3
  /**
3
- * Release dependencies exactly as today's scheduler assigns them (agent-loop.ts, executeToolCallsParallel): a
4
- * sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
4
+ * Release dependencies exactly as the agent loop has always ordered a batch: a sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
5
5
  * previous sequential call only.
6
6
  */
7
7
  export function batchDependencies(calls) {
@@ -22,19 +22,6 @@ export function batchDependencies(calls) {
22
22
  }
23
23
  return result;
24
24
  }
25
- function canonical(value) {
26
- if (Array.isArray(value))
27
- return `[${value.map(canonical).join(",")}]`;
28
- if (value !== null && typeof value === "object") {
29
- const entries = Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
30
- return `{${entries.map(([key, inner]) => `${JSON.stringify(key)}:${canonical(inner)}`).join(",")}}`;
31
- }
32
- return JSON.stringify(value);
33
- }
34
- async function digest(value) {
35
- const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(value)));
36
- return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
37
- }
38
25
  export async function buildBatchManifest(issuer, plan) {
39
26
  const dependencies = batchDependencies(plan.calls);
40
27
  const calls = [];
@@ -45,11 +32,11 @@ export async function buildBatchManifest(issuer, plan) {
45
32
  sourceIndex,
46
33
  dependsOn: placement.dependsOn,
47
34
  wave: placement.wave,
48
- requestDigest: await digest({ name: call.name, args: call.args }),
35
+ requestDigest: await canonicalDigest({ name: call.name, args: call.args }),
49
36
  });
50
37
  }
51
38
  const { calls: _calls, ...header } = plan;
52
- return { ...header, issuer, calls, manifestDigest: await digest({ ...header, issuer, calls }) };
39
+ return { ...header, issuer, calls, manifestDigest: await canonicalDigest({ ...header, issuer, calls }) };
53
40
  }
54
41
  /**
55
42
  * A reply after which no later call is prepared and the decision is ABORT. A raw `settled` outcome other than a result
@@ -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, LOCAL_DEVICE_FILES, } 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,8 @@ 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),
148
+ [LOCAL_DEVICE_FILES]: true,
110
149
  };
111
150
  }
112
151
  //# sourceMappingURL=device-files-node.js.map
@@ -18,7 +18,18 @@ 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>;
23
+ readonly [LOCAL_DEVICE_FILES]?: true;
21
24
  }
25
+ /**
26
+ * Marks the local filesystem's {@link DeviceFiles} (a fused session, or a hand's own runtime), so extension code that
27
+ * keeps its own local file path can tell it from a split session's file channel. A registry symbol, so a second copy
28
+ * of this package marks the same objects.
29
+ */
30
+ export declare const LOCAL_DEVICE_FILES: unique symbol;
31
+ /** Whether `files` is the local filesystem rather than a split session's file channel to the hand. */
32
+ export declare function isLocalDeviceFiles(files: DeviceFiles): boolean;
22
33
  export interface DeviceFileOptions {
23
34
  readonly signal?: AbortSignal;
24
35
  }
@@ -31,8 +42,26 @@ export interface DeviceFileStat {
31
42
  export declare const FILE_CHANNEL = "file/1";
32
43
  /** The most data one operation reads or writes, in raw bytes, in both directions. */
33
44
  export declare const FILE_CHANNEL_MAX_BYTES: number;
34
- export type DeviceFileOp = "read" | "write" | "list" | "stat" | "rename" | "remove" | "mkdir";
45
+ export type DeviceFileOp = "read" | "write" | "list" | "stat" | "rename" | "remove" | "mkdir" | "run";
35
46
  export declare const DEVICE_FILE_OPS: readonly DeviceFileOp[];
47
+ /** The `run` operation's name in a hand's `hello` (S40 PR 2): git and lsof as the memory component calls them. */
48
+ export declare const RUN_CHANNEL = "run/1";
49
+ export interface DeviceRunRequest {
50
+ readonly exe: string;
51
+ readonly argv: readonly string[];
52
+ readonly cwd: string;
53
+ readonly env?: Readonly<Record<string, string>>;
54
+ readonly stdin?: Uint8Array;
55
+ readonly timeoutMs?: number;
56
+ /** Hold the memory component's git-activity lock as fd 3 while git runs; the hand derives the lock from `cwd`. */
57
+ readonly activityLock?: boolean;
58
+ }
59
+ export interface DeviceRunResult {
60
+ readonly code: number | null;
61
+ readonly signal: string | null;
62
+ readonly stdout: Uint8Array;
63
+ readonly stderr: string;
64
+ }
36
65
  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
66
  /**
38
67
  * A device file operation that did not complete. `interrupted` carries the hand's terminal reason; `uncertain` says the
@@ -60,6 +89,15 @@ export type DeviceFileArgs = {
60
89
  readonly op: "rename";
61
90
  readonly path: string;
62
91
  readonly to: string;
92
+ } | {
93
+ readonly op: "run";
94
+ readonly path: string;
95
+ readonly exe: string;
96
+ readonly argv: readonly string[];
97
+ readonly env: Readonly<Record<string, string>>;
98
+ readonly stdin?: string;
99
+ readonly timeoutMs?: number;
100
+ readonly activityLock: boolean;
63
101
  };
64
102
  /** One operation's outcome, carried in a settled result's `details.file`. */
65
103
  export type DeviceFileOutcome = {
@@ -1,8 +1,29 @@
1
+ /**
2
+ * Marks the local filesystem's {@link DeviceFiles} (a fused session, or a hand's own runtime), so extension code that
3
+ * keeps its own local file path can tell it from a split session's file channel. A registry symbol, so a second copy
4
+ * of this package marks the same objects.
5
+ */
6
+ export const LOCAL_DEVICE_FILES = Symbol.for("senpi.device-files.local");
7
+ /** Whether `files` is the local filesystem rather than a split session's file channel to the hand. */
8
+ export function isLocalDeviceFiles(files) {
9
+ return files[LOCAL_DEVICE_FILES] === true;
10
+ }
1
11
  /** The channel's name in a hand's `hello`. */
2
12
  export const FILE_CHANNEL = "file/1";
3
13
  /** The most data one operation reads or writes, in raw bytes, in both directions. */
4
14
  export const FILE_CHANNEL_MAX_BYTES = 8 * 1024 * 1024;
5
- export const DEVICE_FILE_OPS = ["read", "write", "list", "stat", "rename", "remove", "mkdir"];
15
+ export const DEVICE_FILE_OPS = [
16
+ "read",
17
+ "write",
18
+ "list",
19
+ "stat",
20
+ "rename",
21
+ "remove",
22
+ "mkdir",
23
+ "run",
24
+ ];
25
+ /** The `run` operation's name in a hand's `hello` (S40 PR 2): git and lsof as the memory component calls them. */
26
+ export const RUN_CHANNEL = "run/1";
6
27
  /**
7
28
  * A device file operation that did not complete. `interrupted` carries the hand's terminal reason; `uncertain` says the
8
29
  * operation may have taken effect (a write may or may not have landed). Nothing is ever retried.
@@ -52,10 +73,36 @@ export function decodeDeviceFileArgs(op, args) {
52
73
  : undefined;
53
74
  case "rename":
54
75
  return typeof args.to === "string" && args.to.length > 0 ? { op, path, to: args.to } : undefined;
76
+ case "run":
77
+ return decodeRunArgs(path, args);
55
78
  default:
56
79
  return undefined;
57
80
  }
58
81
  }
82
+ function decodeRunArgs(path, args) {
83
+ const { exe, argv, env, stdin, timeoutMs, activityLock } = args;
84
+ if (typeof exe !== "string" || !Array.isArray(argv) || !argv.every((arg) => typeof arg === "string"))
85
+ return undefined;
86
+ const environment = env ?? {};
87
+ if (!isRecord(environment) || !Object.values(environment).every((value) => typeof value === "string"))
88
+ return undefined;
89
+ if (stdin !== undefined && typeof stdin !== "string")
90
+ return undefined;
91
+ if (timeoutMs !== undefined && (typeof timeoutMs !== "number" || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0))
92
+ return undefined;
93
+ if (activityLock !== undefined && typeof activityLock !== "boolean")
94
+ return undefined;
95
+ return {
96
+ op: "run",
97
+ path,
98
+ exe,
99
+ argv: argv,
100
+ env: environment,
101
+ ...(stdin === undefined ? {} : { stdin }),
102
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
103
+ activityLock: activityLock === true,
104
+ };
105
+ }
59
106
  export function encodeBase64(bytes) {
60
107
  let binary = "";
61
108
  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 &&