@code-yeongyu/senpi-agent-core 2026.11.5-1 → 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 (31) hide show
  1. package/dist/conformance/index.d.ts +5 -1
  2. package/dist/conformance/index.js +2 -0
  3. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  4. package/dist/conformance/loop-core-manifest.js +1 -0
  5. package/dist/durable/session-store.d.ts +42 -0
  6. package/dist/durable/session-store.js +124 -0
  7. package/dist/durable/store-memory.d.ts +2 -2
  8. package/dist/durable/store-memory.js +36 -34
  9. package/dist/durable/store.d.ts +9 -0
  10. package/dist/durable/testing/store-harness.d.ts +1 -0
  11. package/dist/durable/testing/store-harness.js +1 -0
  12. package/dist/durable/testing/sync-commit-cases.d.ts +20 -0
  13. package/dist/durable/testing/sync-commit-cases.js +89 -0
  14. package/dist/execution/device-files-node.js +2 -1
  15. package/dist/execution/device-files.d.ts +9 -0
  16. package/dist/execution/device-files.js +10 -0
  17. package/dist/execution/prepared/executor-freeze.d.ts +8 -3
  18. package/dist/execution/prepared/executor-freeze.js +15 -2
  19. package/dist/execution/prepared/executor.js +2 -3
  20. package/dist/execution/prepared/pipeline-prepared-batch.js +2 -2
  21. package/dist/execution/testing/hand-harness.d.ts +3 -1
  22. package/dist/execution/testing/hand-harness.js +32 -4
  23. package/dist/execution/testing/multi-hand-cases.js +1 -1
  24. package/dist/execution/tool-host.d.ts +3 -0
  25. package/dist/harness/execution/tool-host-call.d.ts +4 -3
  26. package/dist/harness/execution/tool-host-call.js +5 -4
  27. package/dist/harness/execution/tools.js +17 -4
  28. package/dist/harness/tools/read.js +1 -1
  29. package/dist/index.d.ts +4 -1
  30. package/dist/index.js +2 -1
  31. package/package.json +3 -3
@@ -6,13 +6,17 @@ export type { CaseImplementation, CaseResult, ConformanceHost, HostReport } from
6
6
  export { runSuite } from "./runner.ts";
7
7
  export type { SuiteHashEntry } from "./suite-hash.ts";
8
8
  export { computeSuiteHash, sha256Hex } from "./suite-hash.ts";
9
- export type { CommitResult, DurableStore, DurableStoreErrorCode, DurableStoreOptions, RecordScan, StoreDocument, StoreOperation, StoreRecord, StoreSnapshot, StoreValue, StoreWrite, StoreWritePoint, } from "../durable/store.ts";
9
+ export type { CommitResult, DurableStore, DurableStoreErrorCode, DurableStoreOptions, RecordScan, StoreDocument, StoreOperation, StoreRecord, StoreSnapshot, StoreValue, StoreWrite, StoreWritePoint, SyncCommit, SyncCommitStore, } from "../durable/store.ts";
10
10
  export { DurableStoreError } from "../durable/store.ts";
11
+ export type { SessionHandle, SessionHeader, SessionStoreErrorCode, StoredEntry, StoredSession, SyncSessionHandle, } from "../durable/session-store.ts";
12
+ export { openSessionStore, openSyncSessionStore, SessionStoreError } from "../durable/session-store.ts";
11
13
  export type { AdmissionLine } from "../durable/store-admission.ts";
12
14
  export type { KillDeclaration } from "../durable/testing/kill-store.ts";
13
15
  export { KILL_STORE_CASES, KILL_STORE_DECLARATIONS } from "../durable/testing/kill-store.ts";
14
16
  export { STORE_CASES } from "../durable/testing/store-cases.ts";
15
17
  export type { StoreCaseAdapters, StoreConformanceAdapter } from "../durable/testing/store-harness.ts";
18
+ export type { SyncCommitCaseAdapters, SyncCommitConformanceAdapter } from "../durable/testing/sync-commit-cases.ts";
19
+ export { SYNC_COMMIT_CASES, SYNC_COMMIT_REGISTRY } from "../durable/testing/sync-commit-cases.ts";
16
20
  export type { KillWakeDeclaration } from "../durable/testing/kill-wake.ts";
17
21
  export { KILL_WAKE_CASES, KILL_WAKE_DECLARATIONS } from "../durable/testing/kill-wake.ts";
18
22
  export type { ManualTimers } from "../durable/testing/manual-timers.ts";
@@ -3,8 +3,10 @@ export { ADAPTER_KINDS, CONFORMANCE_REGISTRY } from "./registry.js";
3
3
  export { runSuite } from "./runner.js";
4
4
  export { computeSuiteHash, sha256Hex } from "./suite-hash.js";
5
5
  export { DurableStoreError } from "../durable/store.js";
6
+ export { openSessionStore, openSyncSessionStore, SessionStoreError } from "../durable/session-store.js";
6
7
  export { KILL_STORE_CASES, KILL_STORE_DECLARATIONS } from "../durable/testing/kill-store.js";
7
8
  export { STORE_CASES } from "../durable/testing/store-cases.js";
9
+ export { SYNC_COMMIT_CASES, SYNC_COMMIT_REGISTRY } from "../durable/testing/sync-commit-cases.js";
8
10
  export { KILL_WAKE_CASES, KILL_WAKE_DECLARATIONS } from "../durable/testing/kill-wake.js";
9
11
  export { createManualTimers } from "../durable/testing/manual-timers.js";
10
12
  export { MULTI_HOST_CASES } from "../durable/testing/multi-host-cases.js";
@@ -4,7 +4,7 @@
4
4
  * Host adapters, carriers, persistence implementations and the Node harness stay outside.
5
5
  * Extend this closure when adding loop modules; never add a host implementation to it.
6
6
  */
7
- export declare const LOOP_CORE_MODULES: readonly ["agent.ts", "agent-loop.ts", "assistant-terminal-state.ts", "empty-assistant-recovery.ts", "internal-events.ts", "local-failure.ts", "response-timing.ts", "stream-fn.ts", "stream-keepalive.ts", "tool-arguments.ts", "tool-name-alias.ts", "types.ts", "durable/store.ts", "execution/tool-host.ts", "execution/tool-outcome-events.ts", "execution/canonical-digest.ts", "execution/coordinator.ts", "execution/coordinator-codec.ts", "execution/coordinator-consent.ts", "execution/coordinator-plan.ts", "execution/coordinator-types.ts", "execution/ledger.ts", "execution/ledger-codec.ts", "execution/ledger-transition.ts", "execution/ledger-types.ts", "execution/prepared/executor.ts", "execution/prepared/executor-body.ts", "execution/prepared/executor-freeze.ts", "execution/prepared/executor-pipeline.ts", "execution/prepared/executor-types.ts", "execution/prepared/pipeline-prepared.ts", "execution/prepared/pipeline-prepared-batch.ts", "durable/store-admission.ts", "durable/wake-host.ts", "transport/transport.ts"];
7
+ export declare const LOOP_CORE_MODULES: readonly ["agent.ts", "agent-loop.ts", "assistant-terminal-state.ts", "empty-assistant-recovery.ts", "internal-events.ts", "local-failure.ts", "response-timing.ts", "stream-fn.ts", "stream-keepalive.ts", "tool-arguments.ts", "tool-name-alias.ts", "types.ts", "durable/store.ts", "execution/tool-host.ts", "execution/device-files.ts", "execution/tool-outcome-events.ts", "execution/canonical-digest.ts", "execution/coordinator.ts", "execution/coordinator-codec.ts", "execution/coordinator-consent.ts", "execution/coordinator-plan.ts", "execution/coordinator-types.ts", "execution/ledger.ts", "execution/ledger-codec.ts", "execution/ledger-transition.ts", "execution/ledger-types.ts", "execution/prepared/executor.ts", "execution/prepared/executor-body.ts", "execution/prepared/executor-freeze.ts", "execution/prepared/executor-pipeline.ts", "execution/prepared/executor-types.ts", "execution/prepared/pipeline-prepared.ts", "execution/prepared/pipeline-prepared-batch.ts", "durable/store-admission.ts", "durable/wake-host.ts", "transport/transport.ts"];
8
8
  /**
9
9
  * Existing portable model/message utilities and schema types, not provider runtimes.
10
10
  * Exact specifiers deliberately exclude compat, OAuth, SDKs and host-specific subpaths.
@@ -19,6 +19,7 @@ export const LOOP_CORE_MODULES = [
19
19
  "types.ts",
20
20
  "durable/store.ts",
21
21
  "execution/tool-host.ts",
22
+ "execution/device-files.ts",
22
23
  "execution/tool-outcome-events.ts",
23
24
  "execution/canonical-digest.ts",
24
25
  "execution/coordinator.ts",
@@ -0,0 +1,42 @@
1
+ import type { DurableStore, StoreValue, SyncCommitStore } from "./store.ts";
2
+ export interface StoredEntry {
3
+ readonly key: string;
4
+ readonly line: string;
5
+ }
6
+ export type SessionHeader = {
7
+ readonly [key: string]: StoreValue;
8
+ };
9
+ export interface StoredSession {
10
+ readonly id: string;
11
+ readonly header: SessionHeader;
12
+ readonly entries: readonly StoredEntry[];
13
+ }
14
+ export type SessionStoreErrorCode = "duplicate-entry" | "corrupt-session";
15
+ export declare class SessionStoreError extends Error {
16
+ readonly code: SessionStoreErrorCode;
17
+ constructor(code: SessionStoreErrorCode, message: string);
18
+ }
19
+ export interface SessionHandle {
20
+ header(): SessionHeader;
21
+ entries(): readonly StoredEntry[];
22
+ append(entries: readonly StoredEntry[]): Promise<void>;
23
+ rewrite(header: SessionHeader, entries: readonly StoredEntry[]): Promise<void>;
24
+ }
25
+ /** A session on any DurableStore (Durable Object included): every write is one async atomic commit. */
26
+ export declare function openSessionStore(store: DurableStore, epoch: number): {
27
+ load: (id: string) => Promise<StoredSession | undefined>;
28
+ open: (id: string, header: SessionHeader) => Promise<SessionHandle>;
29
+ };
30
+ export interface SyncSessionHandle {
31
+ header(): SessionHeader;
32
+ entries(): readonly StoredEntry[];
33
+ /** Durable when it returns; a refusal throws on this call and leaves the session and the store unchanged. */
34
+ appendSync(entries: readonly StoredEntry[]): void;
35
+ rewriteSync(header: SessionHeader, entries: readonly StoredEntry[]): void;
36
+ }
37
+ /** A session whose writes commit synchronously: only a backend with `commitSync` (memory, Bun SQLite) can build one. */
38
+ export declare function openSyncSessionStore(store: SyncCommitStore, epoch: number): {
39
+ load: (id: string) => Promise<StoredSession | undefined>;
40
+ open: (id: string, header: SessionHeader) => Promise<SyncSessionHandle>;
41
+ };
42
+ //# sourceMappingURL=session-store.d.ts.map
@@ -0,0 +1,124 @@
1
+ export class SessionStoreError extends Error {
2
+ constructor(code, message) {
3
+ super(message);
4
+ this.name = "SessionStoreError";
5
+ this.code = code;
6
+ }
7
+ }
8
+ // The S07 JSONL importer's key schema (coding-agent session-import/jsonl-import.ts): one format for both writers.
9
+ const SESSION = "session-import/session/";
10
+ const ENTRY = "session-import/entry/";
11
+ const sessionKey = (id) => SESSION + encodeURIComponent(id);
12
+ const entryKey = (sessionId, key) => `${ENTRY}${encodeURIComponent(sessionId)}/${encodeURIComponent(key)}`;
13
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14
+ async function readState(store, id) {
15
+ const manifest = await store.getDocument(sessionKey(id));
16
+ if (manifest === undefined)
17
+ return undefined;
18
+ const entryIds = isRecord(manifest) ? manifest.entryIds : undefined;
19
+ if (!isRecord(manifest) || !isRecord(manifest.header) || !Array.isArray(entryIds)) {
20
+ throw new SessionStoreError("corrupt-session", `session ${id} has no readable manifest`);
21
+ }
22
+ const entries = [];
23
+ for (const key of entryIds) {
24
+ const line = typeof key === "string" ? await store.getDocument(entryKey(id, key)) : undefined;
25
+ if (typeof key !== "string" || typeof line !== "string") {
26
+ throw new SessionStoreError("corrupt-session", `session ${id} is missing entry ${String(key)}`);
27
+ }
28
+ entries.push({ key, line });
29
+ }
30
+ return { id, header: manifest.header, entries, divergence: manifest.divergence ?? null };
31
+ }
32
+ const manifestWrite = (state) => ({
33
+ op: "put",
34
+ key: sessionKey(state.id),
35
+ data: {
36
+ id: state.id,
37
+ header: state.header,
38
+ entryIds: state.entries.map((entry) => entry.key),
39
+ divergence: state.divergence,
40
+ },
41
+ });
42
+ function planAppend(state, added) {
43
+ const held = new Set(state.entries.map((entry) => entry.key));
44
+ for (const entry of added) {
45
+ if (held.has(entry.key))
46
+ throw new SessionStoreError("duplicate-entry", `session ${state.id} already holds ${entry.key}`);
47
+ held.add(entry.key);
48
+ }
49
+ const next = { ...state, entries: [...state.entries, ...added] };
50
+ const puts = added.map((entry) => ({ op: "put", key: entryKey(state.id, entry.key), data: entry.line }));
51
+ return { writes: [...puts, manifestWrite(next)], next };
52
+ }
53
+ function planRewrite(state, header, entries) {
54
+ const kept = new Set();
55
+ for (const entry of entries) {
56
+ if (kept.has(entry.key))
57
+ throw new SessionStoreError("duplicate-entry", `rewrite of ${state.id} repeats ${entry.key}`);
58
+ kept.add(entry.key);
59
+ }
60
+ const next = { ...state, header, entries: [...entries] };
61
+ const deletes = state.entries
62
+ .filter((entry) => !kept.has(entry.key))
63
+ .map((entry) => ({ op: "delete", key: entryKey(state.id, entry.key) }));
64
+ const puts = entries.map((entry) => ({
65
+ op: "put",
66
+ key: entryKey(state.id, entry.key),
67
+ data: entry.line,
68
+ }));
69
+ return { writes: [...deletes, ...puts, manifestWrite(next)], next };
70
+ }
71
+ const stored = ({ id, header, entries }) => ({ id, header, entries });
72
+ /** An existing session keeps its stored header; `header` only seeds a session the store does not hold yet. */
73
+ async function openState(store, id, header) {
74
+ return (await readState(store, id)) ?? { id, header, entries: [], divergence: null };
75
+ }
76
+ /** A session on any DurableStore (Durable Object included): every write is one async atomic commit. */
77
+ export function openSessionStore(store, epoch) {
78
+ return {
79
+ load: async (id) => {
80
+ const state = await readState(store, id);
81
+ return state === undefined ? undefined : stored(state);
82
+ },
83
+ open: async (id, header) => {
84
+ let state = await openState(store, id, header);
85
+ // One write at a time, each planned from the state the previous one committed.
86
+ let tail = Promise.resolve();
87
+ const enqueue = (plan) => {
88
+ const run = tail.then(async () => {
89
+ const next = plan();
90
+ await store.commit(epoch, next.writes, () => { });
91
+ state = next.next;
92
+ });
93
+ tail = run.catch(() => undefined);
94
+ return run;
95
+ };
96
+ return {
97
+ header: () => state.header,
98
+ entries: () => state.entries,
99
+ append: (entries) => enqueue(() => planAppend(state, entries)),
100
+ rewrite: (header2, entries) => enqueue(() => planRewrite(state, header2, entries)),
101
+ };
102
+ },
103
+ };
104
+ }
105
+ /** A session whose writes commit synchronously: only a backend with `commitSync` (memory, Bun SQLite) can build one. */
106
+ export function openSyncSessionStore(store, epoch) {
107
+ return {
108
+ load: openSessionStore(store, epoch).load,
109
+ open: async (id, header) => {
110
+ let state = await openState(store, id, header);
111
+ const commit = (plan) => {
112
+ store.commitSync(epoch, plan.writes, () => { });
113
+ state = plan.next;
114
+ };
115
+ return {
116
+ header: () => state.header,
117
+ entries: () => state.entries,
118
+ appendSync: (entries) => commit(planAppend(state, entries)),
119
+ rewriteSync: (header2, entries) => commit(planRewrite(state, header2, entries)),
120
+ };
121
+ },
122
+ };
123
+ }
124
+ //# sourceMappingURL=session-store.js.map
@@ -1,4 +1,4 @@
1
- import { type DurableStore, type DurableStoreOptions, type StoreRecord, type StoreValue } from "./store.ts";
1
+ import { type DurableStoreOptions, type StoreRecord, type StoreValue, type SyncCommitStore } from "./store.ts";
2
2
  interface MediumState {
3
3
  readonly epoch: number;
4
4
  readonly records: readonly StoreRecord[];
@@ -10,6 +10,6 @@ export interface MemoryStoreMedium {
10
10
  }
11
11
  export declare function createMemoryStoreMedium(): MemoryStoreMedium;
12
12
  /** A DurableStore over `medium`. Each operation stages its writes and publishes them in one assignment: atomic. */
13
- export declare function openMemoryStore(medium: MemoryStoreMedium, options?: DurableStoreOptions): DurableStore;
13
+ export declare function openMemoryStore(medium: MemoryStoreMedium, options?: DurableStoreOptions): SyncCommitStore;
14
14
  export {};
15
15
  //# sourceMappingURL=store-memory.d.ts.map
@@ -49,6 +49,40 @@ const documentsOf = (state, prefix) => [...state.documents]
49
49
  /** A DurableStore over `medium`. Each operation stages its writes and publishes them in one assignment: atomic. */
50
50
  export function openMemoryStore(medium, options = {}) {
51
51
  const point = (at) => options.onWritePoint?.(at);
52
+ const commitSync = (epoch, writes, adopt) => {
53
+ point({ op: "commit", at: "before" });
54
+ const state = medium.current;
55
+ requireOwner(state, epoch);
56
+ const records = [...state.records];
57
+ const ids = new Set(records.map((record) => record.id));
58
+ const documents = new Map(state.documents);
59
+ const seqs = [];
60
+ writes.forEach((write, index) => {
61
+ point({ op: "commit", at: "write", index });
62
+ switch (write.op) {
63
+ case "append": {
64
+ if (ids.has(write.id))
65
+ throw new DurableStoreError("duplicate-record-id", `record ${write.id} exists`);
66
+ ids.add(write.id);
67
+ const seq = records.length + 1;
68
+ records.push({ seq, id: write.id, kind: write.kind, data: copy(write.data) });
69
+ seqs.push(seq);
70
+ break;
71
+ }
72
+ case "put":
73
+ documents.set(write.key, copy(write.data));
74
+ break;
75
+ case "delete":
76
+ documents.delete(write.key);
77
+ break;
78
+ }
79
+ });
80
+ medium.current = { epoch: state.epoch, records, documents };
81
+ point({ op: "commit", at: "durable" });
82
+ const result = { seqs, head: records.length };
83
+ adopt(result);
84
+ return result;
85
+ };
52
86
  return {
53
87
  readEpoch: async () => medium.current.epoch,
54
88
  readHead: async () => medium.current.records.length,
@@ -64,40 +98,8 @@ export function openMemoryStore(medium, options = {}) {
64
98
  medium.current = { ...state, epoch: nextEpoch };
65
99
  point({ op: "claim", at: "durable" });
66
100
  },
67
- async commit(epoch, writes, adopt) {
68
- point({ op: "commit", at: "before" });
69
- const state = medium.current;
70
- requireOwner(state, epoch);
71
- const records = [...state.records];
72
- const ids = new Set(records.map((record) => record.id));
73
- const documents = new Map(state.documents);
74
- const seqs = [];
75
- writes.forEach((write, index) => {
76
- point({ op: "commit", at: "write", index });
77
- switch (write.op) {
78
- case "append": {
79
- if (ids.has(write.id))
80
- throw new DurableStoreError("duplicate-record-id", `record ${write.id} exists`);
81
- ids.add(write.id);
82
- const seq = records.length + 1;
83
- records.push({ seq, id: write.id, kind: write.kind, data: copy(write.data) });
84
- seqs.push(seq);
85
- break;
86
- }
87
- case "put":
88
- documents.set(write.key, copy(write.data));
89
- break;
90
- case "delete":
91
- documents.delete(write.key);
92
- break;
93
- }
94
- });
95
- medium.current = { epoch: state.epoch, records, documents };
96
- point({ op: "commit", at: "durable" });
97
- const result = { seqs, head: records.length };
98
- adopt(result);
99
- return result;
100
- },
101
+ commit: async (epoch, writes, adopt) => commitSync(epoch, writes, adopt),
102
+ commitSync,
101
103
  mintId: () => crypto.randomUUID(),
102
104
  scanRecords: async (query = {}) => scan(medium.current.records, query),
103
105
  getDocument: async (key) => {
@@ -113,4 +113,13 @@ export interface DurableStore {
113
113
  */
114
114
  importSnapshot(epoch: number, snapshot: StoreSnapshot): Promise<void>;
115
115
  }
116
+ /**
117
+ * A backend whose commit is durable when it returns (memory; Bun SQLite with `synchronous=FULL`). `commitSync` keeps the
118
+ * `commit` contract on the same call: a refusal throws before it returns and leaves the store unchanged. A Durable Object
119
+ * store confirms durability only asynchronously, so it does not offer this.
120
+ */
121
+ export interface SyncCommit {
122
+ commitSync(epoch: number, writes: readonly StoreWrite[], adopt: (result: CommitResult) => void): CommitResult;
123
+ }
124
+ export type SyncCommitStore = DurableStore & SyncCommit;
116
125
  //# sourceMappingURL=store.d.ts.map
@@ -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
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { constants } from "node:fs";
3
3
  import { lstat, mkdir, open, readdir, rename, rm } from "node:fs/promises";
4
4
  import { dirname } from "node:path";
5
- import { DeviceFileError, FILE_CHANNEL_MAX_BYTES, } from "./device-files.js";
5
+ import { DeviceFileError, FILE_CHANNEL_MAX_BYTES, LOCAL_DEVICE_FILES, } from "./device-files.js";
6
6
  function deviceError(error, path) {
7
7
  if (error instanceof DeviceFileError)
8
8
  return error;
@@ -145,6 +145,7 @@ export function localDeviceFiles() {
145
145
  await mkdir(path, { recursive: true });
146
146
  }),
147
147
  run: (request, options) => runDirect(request, options?.signal),
148
+ [LOCAL_DEVICE_FILES]: true,
148
149
  };
149
150
  }
150
151
  //# sourceMappingURL=device-files-node.js.map
@@ -20,7 +20,16 @@ export interface DeviceFiles {
20
20
  mkdir(path: string, options?: DeviceFileOptions): Promise<void>;
21
21
  /** Runs git or lsof on the device (split: only the calls the hand's allowlist admits; fused: a direct spawn). */
22
22
  run(request: DeviceRunRequest, options?: DeviceFileOptions): Promise<DeviceRunResult>;
23
+ readonly [LOCAL_DEVICE_FILES]?: true;
23
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;
24
33
  export interface DeviceFileOptions {
25
34
  readonly signal?: AbortSignal;
26
35
  }
@@ -1,3 +1,13 @@
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. */
@@ -1,13 +1,18 @@
1
1
  import type { StoreValue } from "../../durable/store.ts";
2
- import type { AgentToolResult } from "../../types.ts";
3
2
  import type { FrozenCall } from "../ledger-types.ts";
3
+ import { type BodyOutcome } from "./executor-body.ts";
4
4
  import type { PrepareReply } from "./executor-types.ts";
5
5
  /** Tool arguments and results are JSON on every model and wire path; a round trip drops what JSON cannot carry. */
6
6
  export declare function toStoreValue(value: unknown): StoreValue;
7
7
  /** The call after the whole `tool_call` chain, detached from every object a handler or caller still holds. */
8
8
  export declare function freezeCall(name: string, args: unknown): Promise<FrozenCall>;
9
- /** The durable record of a settled body: what the issuer commits before ACK. Details stay in the in-process reply. */
10
- export declare function resultValue(result: AgentToolResult<unknown>, isError: boolean, requestedName?: string): StoreValue;
9
+ /**
10
+ * A settled body and its durable record. Content JSON cannot carry (an untyped tool breaking the content contract) settles
11
+ * the call as a tool error naming the problem, never as a rejection of the whole release (senpi#5864).
12
+ */
13
+ export declare function recordedResult(outcome: BodyOutcome, requestedName: string | undefined): BodyOutcome & {
14
+ readonly value: StoreValue;
15
+ };
11
16
  export type StoppedReply = Extract<PrepareReply, {
12
17
  readonly kind: "blocked" | "batch_abort";
13
18
  }>;
@@ -1,5 +1,5 @@
1
1
  import { canonicalDigest } from "../canonical-digest.js";
2
- import { errorResult } from "./executor-body.js";
2
+ import { errorResult, messageOf } from "./executor-body.js";
3
3
  /** Tool arguments and results are JSON on every model and wire path; a round trip drops what JSON cannot carry. */
4
4
  export function toStoreValue(value) {
5
5
  const json = JSON.stringify(value);
@@ -11,9 +11,22 @@ export async function freezeCall(name, args) {
11
11
  return { name, args: frozenArgs, digest: await canonicalDigest({ name, args: frozenArgs }) };
12
12
  }
13
13
  /** The durable record of a settled body: what the issuer commits before ACK. Details stay in the in-process reply. */
14
- export function resultValue(result, isError, requestedName) {
14
+ function resultValue(result, isError, requestedName) {
15
15
  return toStoreValue({ content: result.content ?? [], isError, requestedName });
16
16
  }
17
+ /**
18
+ * A settled body and its durable record. Content JSON cannot carry (an untyped tool breaking the content contract) settles
19
+ * the call as a tool error naming the problem, never as a rejection of the whole release (senpi#5864).
20
+ */
21
+ export function recordedResult(outcome, requestedName) {
22
+ try {
23
+ return { ...outcome, value: resultValue(outcome.result, outcome.isError, requestedName) };
24
+ }
25
+ catch (error) {
26
+ const result = errorResult(`Tool result content is not JSON: ${messageOf(error)}`);
27
+ return { result, isError: true, value: resultValue(result, true, requestedName) };
28
+ }
29
+ }
17
30
  /** A preparation that ended without a frozen call, as the ledger's durable `blocked` outcome value. */
18
31
  export function stoppedValue(reply) {
19
32
  const text = (reply.result.content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("");
@@ -1,7 +1,7 @@
1
1
  import { prepareAgentToolCall } from "../../agent-loop.js";
2
2
  import { canonicalDigest } from "../canonical-digest.js";
3
3
  import { errorResult, finalizeBody, messageOf, runBody } from "./executor-body.js";
4
- import { freezeCall, resultValue, stoppedReply, stoppedValue, toStoreValue, } from "./executor-freeze.js";
4
+ import { freezeCall, recordedResult, stoppedReply, stoppedValue, toStoreValue, } from "./executor-freeze.js";
5
5
  const keyId = ({ issuer, commandId }) => JSON.stringify([issuer, commandId]);
6
6
  const keyOf = (request) => ({
7
7
  issuer: request.issuer,
@@ -155,8 +155,7 @@ export function createPreparedExecutor(options) {
155
155
  return refusal(dispatched);
156
156
  }
157
157
  const executed = await runBody(body, signal, request.onUpdateFor?.(body.toolCall) ?? request.onUpdate ?? (() => { }));
158
- const { result, isError } = await finalizeBody(body, executed, pipeline, signal);
159
- const value = resultValue(result, isError, body.requestedName);
158
+ const { result, isError, value } = recordedResult(await finalizeBody(body, executed, pipeline, signal), body.requestedName);
160
159
  const recorded = await step(key, generation, { kind: "result", value });
161
160
  for (const memo of [bodies, preparations, releases])
162
161
  memo.delete(keyId(key));
@@ -101,7 +101,7 @@ export async function runPreparedBatch(request) {
101
101
  if (reply.kind === "prepared_awaiting_consent")
102
102
  return { kind: "prepared_awaiting_consent", frozenDigest: reply.call.digest };
103
103
  if (reply.kind === "refused")
104
- throw new Error(`prepared pipeline refused ${call.id}: ${reply.reason}`);
104
+ throw new Error(`prepared pipeline refused call ${call.id} (execution ${id}): ${reply.reason}`);
105
105
  const result = reply.kind === "blocked" && reply.requestedName !== undefined && tool !== undefined
106
106
  ? withToolNameCorrection(reply.result, reply.requestedName, tool.name)
107
107
  : reply.result;
@@ -135,7 +135,7 @@ export async function runPreparedBatch(request) {
135
135
  };
136
136
  }
137
137
  if (reply.kind !== "aborted")
138
- throw new Error(`prepared pipeline: release ${reply.kind} for ${call.id}`);
138
+ throw new Error(`prepared pipeline: release ${reply.kind} for call ${call.id} (execution ${id})`);
139
139
  await finish(id, signal?.aborted
140
140
  ? aborted(named(id, call))
141
141
  : { toolCall: named(id, call), result: reply.result, isError: true });
@@ -34,13 +34,15 @@ export interface HandRig {
34
34
  /** Advances transport time until `promise` settles; fails past the budget. */
35
35
  settle<T>(promise: Promise<T>, what: string, budgetMs?: number): Promise<T>;
36
36
  runUntil(done: () => boolean, what: string, budgetMs?: number): Promise<void>;
37
+ /** As `runUntil`, for a condition that needs an asynchronous read (the hand's durable rows). */
38
+ waitFor(done: () => Promise<boolean>, what: string, budgetMs?: number): Promise<void>;
37
39
  /** Drops the carrier between session and hand (the hand becomes unreachable) and attaches it again. */
38
40
  disconnect(): void;
39
41
  reconnect(): void;
40
42
  rows(): Promise<ExecutionEntry[]>;
41
43
  }
42
44
  export declare function call(id: string): AgentToolCall;
43
- export type TransportPump = Pick<HandRig, "advance" | "settle" | "runUntil">;
45
+ export type TransportPump = Pick<HandRig, "advance" | "settle" | "runUntil" | "waitFor">;
44
46
  /** Steps transport time on `timers` the way every hand rig waits (see {@link HandRig.advance}). */
45
47
  export declare function transportPump(timers: ManualTimers): TransportPump;
46
48
  export declare function openHandRig(adapters: HandCaseAdapters, options: {
@@ -9,9 +9,26 @@ import { createHandLedger } from "../remote-hand-ledger.js";
9
9
  import { createRemoteToolHost } from "../remote-tool-host.js";
10
10
  const TICK_MS = 5;
11
11
  const LEASE_MS = 3_600_000;
12
+ // A store may confirm a write only after I/O (a Durable Object commit awaits `storage.sync()`; the async-store
13
+ // conformance run takes three `setTimeout(0)` hops per write), and microtasks alone never let that write land
14
+ // between two clock steps. One event-loop turn per step is not enough either: a write that needs several hops
15
+ // lands one hop per 5 ms tick while a fault profile's own timers keep re-arming ahead of it, and `settle` burns
16
+ // its whole transport budget (senpi#6114). A step therefore takes a fixed number of event-loop turns. The count
17
+ // is measured, not derived (an immediate turn and a timer hop are not one-to-one): on the FAULT-HAND cases over
18
+ // the async store, 2 turns per step still fails, 4 passes every run, and 8 is 4 with the same margin again.
19
+ // `setImmediate` is the turn: each one runs after the loop's timers and I/O phases, so a pending `setTimeout(0)`
20
+ // hop lands between two of them, and it costs microseconds where `setTimeout(0)` costs its 1 ms clamp, which over
21
+ // the 120,000 ticks of a 600 s transport budget is the difference between a 0.3 s and a 150 s case. Where the
22
+ // host has no `setImmediate`, each turn is a timer turn. An adapter whose write takes more hops than this must
23
+ // raise the count here; the rig cannot observe a quiet loop from inside it.
24
+ const IO_TURNS_PER_STEP = 8;
25
+ const ioTurn = () => new Promise((resolve) => typeof setImmediate === "function" ? void setImmediate(resolve) : void setTimeout(resolve, 0));
12
26
  const drain = async () => {
13
- for (let turn = 0; turn < 32; turn++)
14
- await Promise.resolve();
27
+ for (let io = 0; io < IO_TURNS_PER_STEP; io++) {
28
+ await ioTurn();
29
+ for (let turn = 0; turn < 32; turn++)
30
+ await Promise.resolve();
31
+ }
15
32
  };
16
33
  export function call(id) {
17
34
  return { type: "toolCall", id, name: "probe", arguments: { id } };
@@ -39,7 +56,17 @@ export function transportPump(timers) {
39
56
  throw outcome?.error;
40
57
  return outcome.value;
41
58
  };
42
- return { advance: (ms) => pump(() => false, ms), settle, runUntil };
59
+ const waitFor = async (done, what, budgetMs = 600_000) => {
60
+ const end = timers.now() + budgetMs;
61
+ await drain();
62
+ while (!(await done())) {
63
+ if (timers.now() >= end)
64
+ throw new Error(`${what}: not reached within ${budgetMs} ms of transport time`);
65
+ await timers.advanceTo(Math.min(end, timers.now() + TICK_MS));
66
+ await drain();
67
+ }
68
+ };
69
+ return { advance: (ms) => pump(() => false, ms), settle, runUntil, waitFor };
43
70
  }
44
71
  export async function openHandRig(adapters, options) {
45
72
  const timers = createManualTimers(1_000);
@@ -108,7 +135,7 @@ export async function openHandRig(adapters, options) {
108
135
  let current = await adapters.store.open(medium, { onWritePoint: killing });
109
136
  await startHand(current).ready;
110
137
  const host = createRemoteToolHost({ transport: sessionSide, placement: options.placement });
111
- const { advance, settle, runUntil } = transportPump(timers);
138
+ const { advance, settle, runUntil, waitFor } = transportPump(timers);
112
139
  return {
113
140
  advance,
114
141
  bodies,
@@ -129,6 +156,7 @@ export async function openHandRig(adapters, options) {
129
156
  },
130
157
  settle,
131
158
  runUntil,
159
+ waitFor,
132
160
  disconnect: () => link.drop(),
133
161
  reconnect: () => link.connect(),
134
162
  rows: async () => createExecutionLedger({
@@ -34,7 +34,7 @@ const killWithScopesInFlight = async (adapters) => {
34
34
  const results = await rig.settle(Promise.all(batches), "MULTI-KILL-01: every scope got its outcome");
35
35
  expectEqual(results.map(({ messages }) => messages.map((message) => message.details)), SCOPES.map(() => [{ outcome: "hand_restarted", uncertain: true, hooksRan: true }]), "MULTI-KILL-01: each scope's call ended hand_restarted, uncertain");
36
36
  expectEqual(rig.bodies, SCOPES.map((scope) => `${scope}:${scope}1`), "MULTI-KILL-01: no call ran twice");
37
- await rig.advance(200);
37
+ await rig.waitFor(async () => (await rig.rows()).every((row) => row.progress.state === "acked"), "MULTI-KILL-01: every call's record acknowledged");
38
38
  expectEqual((await rig.rows()).map((row) => row.progress.state), SCOPES.map(() => "acked"), "MULTI-KILL-01: one durable record per call, acknowledged");
39
39
  };
40
40
  export const MULTI_HAND_CASES = new Map([
@@ -1,5 +1,6 @@
1
1
  import type { AssistantMessage, ToolResultMessage } from "@earendil-works/pi-ai";
2
2
  import type { AgentContext, AgentEvent, AgentToolCall, ToolExecutionMode } from "../types.ts";
3
+ import type { DeviceFiles } from "./device-files.ts";
3
4
  /** Brain-minted identity and execution root; the executor treats the identity as opaque. */
4
5
  export interface ExecutionScope {
5
6
  readonly id: string;
@@ -48,5 +49,7 @@ export declare class PreflightCarryMissingError extends Error {
48
49
  export declare function noPreflightCarry(_prepared: unknown, _frozen: unknown): void;
49
50
  export interface ToolHost {
50
51
  execute(call: ToolHostCall, options: ToolHostOptions): Promise<ToolHostResult>;
52
+ /** The files of the device this host runs calls on, for `scope` (S40); absent: the loop's own machine. */
53
+ deviceFiles?(scope: ExecutionScope): DeviceFiles;
51
54
  }
52
55
  //# sourceMappingURL=tool-host.d.ts.map
@@ -3,10 +3,11 @@ import type { AgentToolCall, AgentToolResult } from "../../types.ts";
3
3
  export type WitnessSink = (witness: ExecutionPipelineWitness) => Promise<void> | void;
4
4
  /**
5
5
  * Runs one cleared harness call's body on the in-process prepared ToolHost (S19c), as a one-call batch on its own
6
- * in-memory ledger. The harness already prepared, validated and hooked the call, so the host passes its arguments
7
- * through unchanged; `run` owns the harness's own signal, updates and error semantics.
6
+ * in-memory ledger. The harness already prepared, validated and hooked the call, so the host's schema passes its
7
+ * arguments through. The host records a JSON copy of them, but `run` executes the body on the cleared arguments object
8
+ * itself, as before the host (senpi#5861); it owns the harness's own signal, updates and error semantics.
8
9
  */
9
- export declare function runOnPreparedToolHost<T>(toolCall: AgentToolCall, scopeId: string, recordWitness: WitnessSink | undefined, run: (args: unknown) => Promise<{
10
+ export declare function runOnPreparedToolHost<T>(toolCall: AgentToolCall, scopeId: string, recordWitness: WitnessSink | undefined, run: () => Promise<{
10
11
  readonly outcome: T;
11
12
  readonly result: AgentToolResult<unknown>;
12
13
  }>): Promise<T>;
@@ -24,8 +24,9 @@ function issuingMessage(toolCall) {
24
24
  }
25
25
  /**
26
26
  * Runs one cleared harness call's body on the in-process prepared ToolHost (S19c), as a one-call batch on its own
27
- * in-memory ledger. The harness already prepared, validated and hooked the call, so the host passes its arguments
28
- * through unchanged; `run` owns the harness's own signal, updates and error semantics.
27
+ * in-memory ledger. The harness already prepared, validated and hooked the call, so the host's schema passes its
28
+ * arguments through. The host records a JSON copy of them, but `run` executes the body on the cleared arguments object
29
+ * itself, as before the host (senpi#5861); it owns the harness's own signal, updates and error semantics.
29
30
  */
30
31
  export async function runOnPreparedToolHost(toolCall, scopeId, recordWitness, run) {
31
32
  let settled;
@@ -34,8 +35,8 @@ export async function runOnPreparedToolHost(toolCall, scopeId, recordWitness, ru
34
35
  label: toolCall.name,
35
36
  description: toolCall.name,
36
37
  parameters: CLEARED_ARGUMENTS,
37
- execute: async (_toolCallId, args) => {
38
- const { outcome, result } = await run(args);
38
+ execute: async () => {
39
+ const { outcome, result } = await run();
39
40
  settled = { outcome };
40
41
  return result;
41
42
  },
@@ -1,4 +1,5 @@
1
1
  import { validateToolArguments } from "@earendil-works/pi-ai";
2
+ import { toStoreValue } from "../../execution/prepared/executor-freeze.js";
2
3
  import { withAbortSignal } from "../context.js";
3
4
  import { runOnPreparedToolHost } from "./tool-host-call.js";
4
5
  function createErrorToolResult(message) {
@@ -7,6 +8,16 @@ function createErrorToolResult(message) {
7
8
  details: undefined,
8
9
  };
9
10
  }
11
+ // Arguments the host cannot record as JSON (a BigInt, a cycle) settle as a tool error before the body (senpi#5861).
12
+ function unrecordableArguments(args) {
13
+ try {
14
+ toStoreValue(args);
15
+ return undefined;
16
+ }
17
+ catch (error) {
18
+ return `Tool arguments are not JSON: ${error instanceof Error ? error.message : String(error)}`;
19
+ }
20
+ }
10
21
  function immediateError(toolCall, message, terminate = false) {
11
22
  return {
12
23
  kind: "immediate",
@@ -59,6 +70,9 @@ export function executeToolCall(call, gate, onUpdate, toolContext, invocation, c
59
70
  return gate.admit(async () => {
60
71
  const admittedContext = withAbortSignal(gate.signal, context);
61
72
  admittedContext.abortSignal?.throwIfAborted();
73
+ const unrecordable = unrecordableArguments(call.args);
74
+ if (unrecordable !== undefined)
75
+ return { result: createErrorToolResult(unrecordable), isError: true };
62
76
  // The harness already prepared, validated and hooked this call, so the host gets only its identity and cleared
63
77
  // arguments: a stream flag such as `incomplete` would make the host refuse it before the body runs.
64
78
  const toolCall = {
@@ -67,12 +81,11 @@ export function executeToolCall(call, gate, onUpdate, toolContext, invocation, c
67
81
  name: call.toolCall.name,
68
82
  arguments: call.args,
69
83
  };
70
- // The body receives the host's frozen copy of the arguments (a JSON-value round trip): identical for the JSON
71
- // arguments a tool takes; a non-JSON value (NaN, Infinity, -0, a Date) would not survive it.
72
- return runOnPreparedToolHost(toolCall, invocation.invocationId, recordWitness, async (args) => {
84
+ // The host records a JSON copy of the arguments; the body and after_tool share the cleared arguments object itself.
85
+ return runOnPreparedToolHost(toolCall, invocation.invocationId, recordWitness, async () => {
73
86
  let executed;
74
87
  try {
75
- const result = await call.tool.execute(call.toolCall.id, args, (partial, options) => {
88
+ const result = await call.tool.execute(call.toolCall.id, call.args, (partial, options) => {
76
89
  if (acceptingUpdates)
77
90
  onUpdate(partial, options);
78
91
  }, toolContext, invocation, admittedContext);
@@ -15,7 +15,7 @@ export function createReadTool(options = { folder: selectedReadFolder }) {
15
15
  return {
16
16
  name: "read",
17
17
  label: "read",
18
- description: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,
18
+ description: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp; bmp only when an imageProcessor is configured). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete. A .js or .json file of 100+ lines read without offset/limit may come back folded: bodies are replaced by markers and a footer lists the offset/limit ranges to reread; markers are not source, so reread those ranges before quoting or editing them.`,
19
19
  parameters: readSchema,
20
20
  async execute(_toolCallId, { path, offset, limit }, _onUpdate, { env }, _invocation, context) {
21
21
  const absolutePath = await resolveReadToolPath(env, path, context);
package/dist/index.d.ts CHANGED
@@ -13,13 +13,16 @@ export { createHandLedger, type HandAdmission, type HandLedger, type HandLedgerO
13
13
  export { decodeRemoteMessage, encodeRemoteMessage, HAND_CONTROL_LANE, type RemoteAbort, type EpochRefusal, type RemoteAck, type RemoteHandMessage, type RemoteFile, type RemoteHello, type RemoteInvoke, type RemoteFloor, type RemoteFloorAck, type RemoteFloorRefused, type RemoteRefused, type RemoteSettled, RemoteProtocolError, type RemoteTerminal, type RemoteTerminalReason, type RemoteToolResult, } from "./execution/remote-protocol.ts";
14
14
  export { createErrorToolResult, createToolResultMessage, emitToolExecutionEnd, emitToolExecutionUpdate, emitToolResultMessage, shouldTerminateToolBatch, } from "./execution/tool-outcome-events.ts";
15
15
  export { createAdmissionLine } from "./durable/store-admission.ts";
16
+ export type { SessionHandle, SessionHeader, StoredEntry, StoredSession, SyncSessionHandle, } from "./durable/session-store.ts";
17
+ export { openSessionStore, openSyncSessionStore, SessionStoreError } from "./durable/session-store.ts";
18
+ export type { SyncCommit, SyncCommitStore } from "./durable/store.ts";
16
19
  export { createMemoryStoreMedium, openMemoryStore } from "./durable/store-memory.ts";
17
20
  export { createBatchCoordinator } from "./execution/coordinator.ts";
18
21
  export type { BatchExecutor, BatchPlan } from "./execution/coordinator-types.ts";
19
22
  export { createExecutionLedger } from "./execution/ledger.ts";
20
23
  export { authorize, createGrantVerifier, DEFAULT_WORKSPACE, type GrantRefusal, type GrantRow, type GrantSnapshot, type GrantVerdict, type GrantVerifier, type GrantVerifierOptions, HAND_CAPABILITY, type HandAuthority, type WorkspaceRoot, } from "./execution/grant-verify.ts";
21
24
  export { createHandEpochFence, EPOCH_FLOOR_MAX_STEP, type FloorRaise, HAND_SELF_SENDER, type HandEpochFence, type HandEpochFenceOptions, } from "./execution/remote-epoch.ts";
22
- export { base64Length, DEVICE_FILE_OPS, type DeviceFileArgs, DeviceFileError, type DeviceFileErrorCode, type DeviceFileOp, type DeviceFileOptions, type DeviceRunRequest, type DeviceRunResult, type DeviceFileOutcome, type DeviceFiles, type DeviceFileStat, decodeBase64, decodeDeviceFileArgs, encodeBase64, FILE_CHANNEL, FILE_CHANNEL_MAX_BYTES, RUN_CHANNEL, fileOutcomeOf, } from "./execution/device-files.ts";
25
+ export { base64Length, DEVICE_FILE_OPS, type DeviceFileArgs, DeviceFileError, type DeviceFileErrorCode, type DeviceFileOp, type DeviceFileOptions, type DeviceRunRequest, type DeviceRunResult, type DeviceFileOutcome, type DeviceFiles, type DeviceFileStat, decodeBase64, decodeDeviceFileArgs, encodeBase64, FILE_CHANNEL, FILE_CHANNEL_MAX_BYTES, isLocalDeviceFiles, LOCAL_DEVICE_FILES, RUN_CHANNEL, fileOutcomeOf, } from "./execution/device-files.ts";
23
26
  export { HELLO_WAIT_MS } from "./execution/remote-device-files.ts";
24
27
  export { fileRefusal, fileResult } from "./execution/remote-file-call.ts";
25
28
  export { createModelPlaneClient, decodeModelPlaneRequest, MODEL_PLANE, type ModelPlaneRequest, serveModelPlane, } from "./execution/plane-model.ts";
package/dist/index.js CHANGED
@@ -12,12 +12,13 @@ export { createHandLedger, } from "./execution/remote-hand-ledger.js";
12
12
  export { decodeRemoteMessage, encodeRemoteMessage, HAND_CONTROL_LANE, RemoteProtocolError, } from "./execution/remote-protocol.js";
13
13
  export { createErrorToolResult, createToolResultMessage, emitToolExecutionEnd, emitToolExecutionUpdate, emitToolResultMessage, shouldTerminateToolBatch, } from "./execution/tool-outcome-events.js";
14
14
  export { createAdmissionLine } from "./durable/store-admission.js";
15
+ export { openSessionStore, openSyncSessionStore, SessionStoreError } from "./durable/session-store.js";
15
16
  export { createMemoryStoreMedium, openMemoryStore } from "./durable/store-memory.js";
16
17
  export { createBatchCoordinator } from "./execution/coordinator.js";
17
18
  export { createExecutionLedger } from "./execution/ledger.js";
18
19
  export { authorize, createGrantVerifier, DEFAULT_WORKSPACE, HAND_CAPABILITY, } from "./execution/grant-verify.js";
19
20
  export { createHandEpochFence, EPOCH_FLOOR_MAX_STEP, HAND_SELF_SENDER, } from "./execution/remote-epoch.js";
20
- export { base64Length, DEVICE_FILE_OPS, DeviceFileError, decodeBase64, decodeDeviceFileArgs, encodeBase64, FILE_CHANNEL, FILE_CHANNEL_MAX_BYTES, RUN_CHANNEL, fileOutcomeOf, } from "./execution/device-files.js";
21
+ export { base64Length, DEVICE_FILE_OPS, DeviceFileError, decodeBase64, decodeDeviceFileArgs, encodeBase64, FILE_CHANNEL, FILE_CHANNEL_MAX_BYTES, isLocalDeviceFiles, LOCAL_DEVICE_FILES, RUN_CHANNEL, fileOutcomeOf, } from "./execution/device-files.js";
21
22
  export { HELLO_WAIT_MS } from "./execution/remote-device-files.js";
22
23
  export { fileRefusal, fileResult } from "./execution/remote-file-call.js";
23
24
  export { createModelPlaneClient, decodeModelPlaneRequest, MODEL_PLANE, serveModelPlane, } from "./execution/plane-model.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi-agent-core",
3
- "version": "2026.11.5-1",
3
+ "version": "2026.11.6-1",
4
4
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -72,8 +72,8 @@
72
72
  },
73
73
  "dependencies": {
74
74
  "@earendil-works/chord": "0.99.1",
75
- "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.5-1",
76
- "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.11.5-1",
75
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.6-1",
76
+ "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.11.6-1",
77
77
  "diff": "9.0.0",
78
78
  "ignore": "7.0.9",
79
79
  "typebox": "1.3.34",