1
import { mkdtemp, rm } from "node:fs/promises";2
import { tmpdir } from "node:os";3
import { dirname, join } from "node:path";4
import type { JsonValue } from "@earendil-works/chord";5
import {6
type AssistantMessage,7
fauxAssistantMessage,8
fauxText,9
fauxToolCall,10
type ToolResultMessage,11
Type,12
} from "@earendil-works/pi-ai";13
import {14
defineTool,15
type EntryRecord,16
GenerationTask,17
type Harness,18
LiveDoc,19
type TaskId,20
type ToolRegistration,21
ToolResultEntry,22
ToolTask,23
} from "@earendil-works/pi-durable";24
import { afterEach, describe, expect, it } from "vitest";25
import type { ExecutionEnv } from "../src/env/index.ts";26
import { NodeExecutionEnv } from "../src/env/node.ts";27
import { openNodeSqliteStorage } from "../src/storage/sqlite/node.ts";28
import { createBashTool } from "../src/tools/index.ts";29
import { allEntries, type ChatSetup, chatSetup, openChat, waitFor } from "./chat-support.ts";30
import { addHooks, addTool, type Installed } from "./harness-support.ts";31
import { context } from "./session-support.ts";32
import { aborted, deferred } from "./task-support.ts";34
const directories = new Set<string>();36
afterEach(async () => {37
for (const directory of directories) await rm(directory, { recursive: true, force: true });38
directories.clear();39
});41
async function sqlitePath(): Promise<string> {42
const directory = await mkdtemp(join(tmpdir(), "pi-durable-tools-"));43
directories.add(directory);44
return join(directory, "session.sqlite");45
}47
async function open(path: string, setup: ChatSetup, env?: ExecutionEnv) {48
const opened = await openChat(await openNodeSqliteStorage(path), setup, env === undefined ? {} : { env });49
opened.harness.resume();50
return opened;51
}53
function tool(54
name: string,55
execute: ToolRegistration["execute"],56
extra: Partial<ToolRegistration> = {},57
): ToolRegistration {58
return defineTool({ name, description: name, parameters: Type.Object({}), execute, ...extra });59
}61
function call(name: string, id = "c1"): AssistantMessage {62
return fauxAssistantMessage([fauxToolCall(name, {}, { id })], { stopReason: "toolUse" });63
}65
const DONE = fauxAssistantMessage([fauxText("done")]);67
function results(entries: readonly EntryRecord[]): ToolResultMessage[] {68
return entries.filter((entry) => ToolResultEntry.is(entry)).map((entry) => entry.model![0] as ToolResultMessage);69
}71
function text(message: ToolResultMessage | undefined): string {72
return (message?.content ?? []).map((item) => (item.type === "text" ? item.text : "")).join("|");73
}75
async function toolTaskId(harness: Harness): Promise<TaskId> {76
let id: TaskId | undefined;77
await waitFor(async () => {78
id = (await harness.snapshot(LiveDoc, 1 as never, context))?.tools?.[0]?.taskId;79
return id !== undefined;80
});81
return id!;82
}84
/**85
* A tool that writes output, then blocks until its invocation is cancelled the first `blocking` times it runs.86
* `started` resolves once the output is durable.87
*/88
function blockingTool(name: string, extra: Partial<ToolRegistration> = {}) {89
const started = deferred();90
const state = { runs: 0, blocking: 1 };91
const registration = tool(92
name,93
async (_args, api, callContext) => {94
state.runs++;95
api.output(`run ${state.runs}\n`);96
await api.details({ run: state.runs }, callContext);97
if (state.runs <= state.blocking) {98
started.resolve();99
await aborted(callContext.abortSignal!);100
}101
return {};102
},103
extra,104
);105
return { registration, started, state };106
}108
describe("tool recovery", () => {109
it("answers an unsafe tool interrupted after intent with its durable partial output", async () => {110
const path = await sqlitePath();111
const setup = chatSetup();112
const { registration, started, state } = blockingTool("work");113
addTool(setup.registry, registration);114
setup.faux.setResponses([call("work"), DONE]);115
let opened = await open(path, setup);116
const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;117
await started.promise;118
const taskId = await toolTaskId(opened.harness);119
await opened.harness.close(context);121
opened = await open(path, setup);122
expect((await opened.harness.getTask(taskId, context))?.state).toMatchObject({123
checkpoint: { phase: "execute", arguments: {}, replay: "unsafe" },124
});125
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");126
expect(state.runs).toBe(1);127
const [result] = results(await allEntries(opened.root));128
expect(result).toMatchObject({ isError: true, details: { run: 1 } });129
expect(text(result)).toBe(130
"run 1\n|<harness>\n[error] Tool work was interrupted and may have partially run\n</harness>",131
);132
expect(await opened.harness.snapshot(LiveDoc, opened.root.id, context)).toEqual({});133
await opened.harness.close(context);134
});136
it("reruns a tool only when both the stored and the current replay policy are safe", async () => {137
const cases: [stored: "safe" | "unsafe", current: "safe" | "unsafe", reruns: boolean][] = [138
["safe", "safe", true],139
["safe", "unsafe", false],140
["unsafe", "safe", false],141
];142
for (const [stored, current, reruns] of cases) {143
const path = await sqlitePath();144
const setup = chatSetup();145
const blocking = blockingTool("work", { replay: stored });146
const registration: Installed = addTool(setup.registry, blocking.registration);147
setup.faux.setResponses([call("work"), DONE]);148
let opened = await open(path, setup);149
const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;150
await blocking.started.promise;151
await opened.harness.close(context);153
registration.dispose();154
addTool(setup.registry, { ...blocking.registration, replay: current });155
opened = await open(path, setup);156
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");157
const [result] = results(await allEntries(opened.root));158
expect(blocking.state.runs).toBe(reruns ? 2 : 1);159
expect(result!.isError).toBe(!reruns);160
if (reruns) expect(text(result)).toBe("run 2\n");161
await opened.harness.close(context);162
}163
});165
it("reruns a safe tool with the environment of the conversation's cwd at rerun, and not once it is deselected", async () => {166
for (const change of ["cwd", "deselect"] as const) {167
const path = await sqlitePath();168
const setup = chatSetup();169
const cwds: (string | undefined)[] = [];170
const started = deferred();171
const work = tool(172
"work",173
async (_args, api, callContext) => {174
cwds.push(api.env?.cwd);175
if (cwds.length === 1) {176
started.resolve();177
await aborted(callContext.abortSignal!);178
}179
return {};180
},181
{ replay: "safe" },182
);183
addTool(setup.registry, work);184
setup.faux.setResponses([call("work"), DONE]);185
const env = ({ cwd = "/" }: { readonly cwd?: string }) => new NodeExecutionEnv({ cwd });186
const reopen = async () => {187
const opened = await openChat(await openNodeSqliteStorage(path), setup, { env });188
opened.harness.resume();189
return opened;190
};191
let opened = await reopen();192
await opened.root.configure({ cwd: "/one" }, context);193
const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;194
await started.promise;195
await opened.root.configure(change === "cwd" ? { cwd: "/two" } : { extensions: [] }, context);196
await opened.harness.close(context);198
opened = await reopen();199
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");200
const [result] = results(await allEntries(opened.root));201
if (change === "cwd") {202
expect(cwds).toEqual(["/one", "/two"]);203
expect(result!.isError).toBe(false);204
} else {205
// A tool that no longer resolves is treated as unsafe: interrupted, not rerun.206
expect(cwds).toEqual(["/one"]);207
expect(text(result)).toContain("was interrupted");208
}209
await opened.harness.close(context);210
}211
});213
it("reruns beforeTool when interrupted before intent, and executes once", async () => {214
const path = await sqlitePath();215
const setup = chatSetup();216
let runs = 0;217
addTool(218
setup.registry,219
tool("work", async () => {220
runs++;221
return { output: [] };222
}),223
);224
const reached = deferred();225
let asked = 0;226
const decisions: string[] = [];227
addHooks(setup.registry, ToolTask, {228
beforeTool: async (_call, api, callContext) => {229
asked++;230
// A durable first-writer-wins decision survives the rerun.231
decisions.push(await api.memo("test:decision", `attempt ${asked}`, callContext));232
if (asked === 1) {233
reached.resolve();234
await aborted(callContext.abortSignal!);235
}236
return undefined;237
},238
});239
setup.faux.setResponses([call("work"), DONE]);240
let opened = await open(path, setup);241
const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;242
await reached.promise;243
await opened.harness.close(context);245
opened = await open(path, setup);246
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");247
expect([asked, runs]).toEqual([2, 1]);248
expect(decisions).toEqual(["attempt 1", "attempt 1"]);249
await opened.harness.close(context);250
});252
it("reruns the generation tools phase interrupted before its commit", async () => {253
const path = await sqlitePath();254
const setup = chatSetup();255
addTool(256
setup.registry,257
tool("work", async () => ({ output: [] })),258
);259
const reached = deferred();260
let observed = 0;261
addHooks(setup.registry, GenerationTask, {262
afterTools: async (_assistant, _results, _api, callContext) => {263
observed++;264
if (observed === 1) {265
reached.resolve();266
await aborted(callContext.abortSignal!);267
}268
},269
});270
setup.faux.setResponses([call("work"), DONE]);271
let opened = await open(path, setup);272
const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;273
await reached.promise;274
await opened.harness.close(context);276
opened = await open(path, setup);277
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");278
expect(observed).toBe(2);279
expect((await allEntries(opened.root)).map((entry) => entry.kind)).toEqual([280
"pi.user",281
"pi.system",282
"pi.assistant",283
"pi.tool-result",284
"pi.assistant",285
]);286
await opened.harness.close(context);287
});289
it("answers an aborted tool with its partial output and continues the run", async () => {290
const path = await sqlitePath();291
const setup = chatSetup();292
const { registration, started } = blockingTool("work");293
addTool(setup.registry, registration);294
setup.faux.setResponses([call("work"), DONE]);295
const opened = await open(path, setup);296
const submission = await opened.root.submit({ type: "input", content: "go" }, context);297
await started.promise;298
const taskId = await toolTaskId(opened.harness);299
expect(await opened.harness.abortTask(taskId, context)).toBe("marked");300
expect((await opened.harness.waitForTask(taskId, context)).state.outcome).toMatchObject({301
status: "aborted",302
result: { entryId: expect.any(Number) },303
});304
expect((await submission.wait(context)).status).toBe("done");305
const [result] = results(await allEntries(opened.root));306
expect(text(result)).toBe("run 1\n|<harness>\n[error] Tool work was aborted\n</harness>");307
await opened.harness.close(context);308
});310
it("lets context derivation answer a faulted tool and continues the run", async () => {311
const path = await sqlitePath();312
const setup = chatSetup();313
// A result that is not strict JSON makes the result commit throw, so the scheduler faults the task.314
addTool(315
setup.registry,316
tool("bad", async () => ({ output: [], details: { fn: (() => 1) as unknown as JsonValue } })),317
);318
const requests: string[] = [];319
setup.faux.setResponses([320
call("bad"),321
(request) => {322
const result = request.messages.find((message) => message.role === "toolResult");323
requests.push(result?.role === "toolResult" ? text(result) : "none");324
return DONE;325
},326
]);327
const opened = await open(path, setup);328
const settled = await (await opened.root.submit({ type: "input", content: "go" }, context)).wait(context);329
expect(settled.status).toBe("done");330
expect(results(await allEntries(opened.root))).toEqual([]);331
expect(requests).toEqual(["Tool result unavailable: history ends before this call completed."]);332
const tasks = await opened.harness.commit((tx) => tx.scanTasks({ conversationId: opened.root.id }, 20), context);333
const faulted = tasks.items.find((task) => task.kind === "pi.tool")!;334
expect(faulted.state).toMatchObject({ status: "terminal", outcome: { status: "faulted" } });335
await opened.harness.close(context);336
});338
it("answers a real bash command interrupted by close and reopen, then finishes the run", async () => {339
const path = await sqlitePath();340
const env = new NodeExecutionEnv({ cwd: dirname(path) });341
const setup = chatSetup();342
addTool(setup.registry, createBashTool());343
setup.faux.setResponses([344
fauxAssistantMessage([fauxToolCall("bash", { command: "echo started; sleep 30" }, { id: "b" })], {345
stopReason: "toolUse",346
}),347
DONE,348
]);349
let opened = await open(path, setup, env);350
const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;351
await waitFor(async () => {352
const slot = (await opened.harness.snapshot(LiveDoc, opened.root.id, context))?.tools?.[0];353
return slot?.output === "started\n";354
});355
await opened.harness.close(context);357
opened = await open(path, setup, env);358
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");359
const [result] = results(await allEntries(opened.root));360
expect(text(result)).toBe(361
"started\n|<harness>\n[error] Tool bash was interrupted and may have partially run\n</harness>",362
);363
await opened.harness.close(context);364
});366
it("clears the interrupted attempt's progress before a safe rerun", async () => {367
const path = await sqlitePath();368
const setup = chatSetup();369
const started = [deferred(), deferred()];370
let runs = 0;371
addTool(372
setup.registry,373
tool(374
"work",375
async (_args, api, callContext) => {376
const run = runs++;377
if (run === 0) {378
api.diagnostic({ severity: "info", message: "first a" });379
api.diagnostic({ severity: "info", message: "first b" });380
await api.details({ run: 1, extra: true }, callContext);381
} else {382
api.diagnostic({ severity: "info", message: "second" });383
await api.details({ run: 2 }, callContext);384
}385
started[run]!.resolve();386
await aborted(callContext.abortSignal!);387
return {};388
},389
{ replay: "safe" },390
),391
);392
setup.faux.setResponses([call("work"), DONE]);393
let opened = await open(path, setup);394
await opened.root.submit({ type: "input", content: "go" }, context);395
await started[0]!.promise;396
await opened.harness.close(context);398
opened = await open(path, setup);399
await started[1]!.promise;400
const slot = (await opened.harness.snapshot(LiveDoc, opened.root.id, context))?.tools?.[0];401
expect(slot?.diagnostics).toEqual([{ severity: "info", message: "second" }]);402
expect(slot?.details).toEqual({ run: 2 });403
await opened.harness.close(context);404
});405
});