1
import { mkdtemp, rm } from "node:fs/promises";2
import { tmpdir } from "node:os";3
import { join } from "node:path";4
import type { JsonValue } from "@earendil-works/chord";5
import { withAbortSignal } from "@earendil-works/chord/context";6
import {7
type AssistantMessage,8
fauxAssistantMessage,9
fauxText,10
fauxToolCall,11
type ToolResultMessage,12
Type,13
type Usage,14
} from "@earendil-works/pi-ai";15
import {16
type AgentEvent,17
AssistantEntry,18
defineTool,19
type EntryRecord,20
type Harness,21
LiveDoc,22
MemoryStorage,23
NestedCallDoc,24
type NestedToolExecutionResult,25
type TaskId,26
type ToolHookCall,27
type ToolRegistration,28
ToolResultEntry,29
ToolTask,30
type ToolTaskInput,31
type ToolTaskResult,32
UsageDoc,33
watchEvents,34
} from "@earendil-works/pi-durable";35
import { afterEach, describe, expect, it } from "vitest";36
import { openNodeSqliteStorage } from "../src/storage/sqlite/node.ts";37
import { allEntries, type ChatSetup, chatSetup, openChat } from "./chat-support.ts";38
import { addHooks, addTool } from "./harness-support.ts";39
import { context } from "./session-support.ts";40
import { aborted, deferred, eventually } from "./task-support.ts";42
const Parameters = Type.Object({ text: Type.Optional(Type.String()) });43
type Tool = ToolRegistration<typeof Parameters>;45
function tool(name: string, execute: Tool["execute"], extra: Partial<Tool> = {}): Tool {46
return defineTool({ name, description: name, parameters: Parameters, execute, ...extra });47
}49
/** Returns `echo <text>` and counts its runs. */50
function echoTool(extra: Partial<Tool> = {}) {51
const state = { runs: 0 };52
const registration = tool(53
"echo",54
async (args) => {55
state.runs++;56
return { output: [{ type: "text", text: `echo ${args.text ?? ""}` }] };57
},58
extra,59
);60
return { registration, state };61
}63
function call(name: string, args: Record<string, string> = {}, id = "c1"): AssistantMessage {64
return fauxAssistantMessage([fauxToolCall(name, args, { id })], { stopReason: "toolUse" });65
}67
const DONE = fauxAssistantMessage([fauxText("done")]);69
function results(entries: readonly EntryRecord[]): ToolResultMessage[] {70
return entries.filter((entry) => ToolResultEntry.is(entry)).map((entry) => entry.model![0] as ToolResultMessage);71
}73
/** The text of a result message, or the value a schema-less nested call gives programs. */74
function text(result: NestedToolExecutionResult | ToolResultMessage | undefined): string {75
if (result === undefined) return "";76
if (!("role" in result)) return typeof result.structuredOutput === "string" ? result.structuredOutput : "";77
return result.content.map((item) => (item.type === "text" ? item.text : "")).join("|");78
}80
async function toolTasks(harness: Harness) {81
return (await harness.commit((tx) => tx.scanTasks({ kind: ToolTask.definition.name }, 100), context)).items;82
}84
async function runOnce(setup: ChatSetup, responses: AssistantMessage[]) {85
setup.faux.setResponses(responses);86
const { harness, root } = await openChat(new MemoryStorage(), setup);87
const settled = await (await root.submit({ type: "input", content: "go" }, context)).wait(context);88
return { harness, root, status: settled.status, entries: await allEntries(root) };89
}91
const directories = new Set<string>();93
afterEach(async () => {94
for (const directory of directories) await rm(directory, { recursive: true, force: true });95
directories.clear();96
});98
describe("nested tool calls", () => {99
it("stores one document per nested call, keyed by its key, written only by that call", async () => {100
const setup = chatSetup();101
const echo = echoTool();102
addTool(setup.registry, echo.registration);103
addTool(104
setup.registry,105
tool("batch", async (_args, api, callContext) => {106
await Promise.all([107
api.executeTool("echo", { text: "a" }, callContext),108
api.executeTool("echo", { text: "b" }, callContext, { key: "named" }),109
]);110
return {};111
}),112
);113
setup.faux.setResponses([call("batch"), DONE]);114
const storage = new MemoryStorage();115
// Per document written, the keys of the nested calls it holds.116
const written: { kind: string; key: string | undefined }[] = [];117
const commit = storage.commit.bind(storage);118
storage.commit = (writes, commitContext) => {119
for (const write of writes) {120
if (write.type === "document.create") written.push({ kind: write.record.kind, key: write.record.key });121
}122
return commit(writes, commitContext);123
};124
const { harness, root } = await openChat(storage, setup);125
await (await root.submit({ type: "input", content: "go" }, context)).wait(context);126
const nested = written.filter((write) => write.kind.startsWith("pi.tool."));127
expect(nested).toEqual([128
{ kind: NestedCallDoc.definition.kind, key: "1" },129
{ kind: NestedCallDoc.definition.kind, key: "named" },130
]);131
await harness.close(context);132
});134
it("rejects a nested call of an aborted caller and leaves no document for it", async () => {135
const setup = chatSetup();136
const echo = echoTool();137
addTool(setup.registry, echo.registration);138
const started = deferred();139
const marked = deferred();140
let rejected: unknown;141
let caller: TaskId | undefined;142
addTool(143
setup.registry,144
tool("late", async (_args, api) => {145
caller = api.taskId;146
started.resolve();147
await marked.promise;148
// Its context is aborted too, so pass one that is not: the admission itself must refuse.149
try {150
await api.executeTool("echo", { text: "a" }, context);151
} catch (error) {152
rejected = error;153
}154
return {};155
}),156
);157
setup.faux.setResponses([call("late"), DONE]);158
const { harness, root } = await openChat(new MemoryStorage(), setup);159
const submission = await root.submit({ type: "input", content: "go" }, context);160
await started.promise;161
await harness.commit(async (tx) => {162
const record = (await tx.task(caller!))!;163
(tx as unknown as { setTask(value: unknown): void }).setTask({ ...record, abortRequested: true });164
}, context);165
marked.resolve();166
await submission.wait(context);167
expect(String(rejected)).toMatch(/abort mark|aborted|has settled/);168
expect(await harness.snapshot(NestedCallDoc, caller!, "1", context)).toBeUndefined();169
await harness.close(context);170
});172
it("runs a nested call as its own tool task and returns its result to the caller, not the transcript", async () => {173
const setup = chatSetup();174
const echo = echoTool();175
addTool(setup.registry, echo.registration);176
let nested: NestedToolExecutionResult | undefined;177
addTool(178
setup.registry,179
tool("batch", async (_args, api, callContext) => {180
nested = await api.executeTool("echo", { text: "a" }, callContext);181
return { output: [{ type: "text", text: `got ${text(nested)}` }] };182
}),183
);184
const { harness, root, status, entries } = await runOnce(setup, [call("batch"), DONE]);185
expect(status).toBe("done");186
const [parent, child] = await toolTasks(harness);187
expect(nested).toEqual({188
taskId: child!.id,189
structuredOutput: "echo a",190
isError: false,191
diagnostics: [],192
durationMs: expect.any(Number),193
});194
// One result entry: the model-issued call's, which records nothing of its nested calls.195
expect(results(entries).map((result) => [result.toolCallId, text(result)])).toEqual([["c1", "got echo a"]]);196
expect(results(entries)[0]).not.toHaveProperty("nestedCalls");197
expect(parent!.input).toMatchObject({ kind: "model", callId: "c1" });198
expect(child!.owner).toBe(parent!.id);199
expect(child!.input as ToolTaskInput).toEqual({200
kind: "nested",201
parent: parent!.id,202
parentCallId: "c1",203
key: "1",204
call: { type: "toolCall", id: "c1/1", name: "echo", arguments: { text: "a" } },205
});206
// The receipt stays small: the result lived in the caller's documents, which retired with it.207
expect(child!.state).toEqual({208
status: "terminal",209
outcome: { status: "completed", result: { kind: "nested" } },210
});211
expect(await harness.snapshot(NestedCallDoc, parent!.id, "1", context)).toBeUndefined();212
expect(await harness.snapshot(LiveDoc, root.id, context)).toEqual({});213
await harness.close(context);214
});216
it("gives each nested call its own task and call ID", async () => {217
const setup = chatSetup();218
const seen: { taskId: TaskId; callId: string }[] = [];219
addTool(220
setup.registry,221
tool("who", async (_args, api) => {222
seen.push({ taskId: api.taskId, callId: api.callId });223
return {};224
}),225
);226
addTool(227
setup.registry,228
tool("batch", async (_args, api, callContext) => {229
await Promise.all([230
api.executeTool("who", {}, callContext, { key: "a" }),231
api.executeTool("who", {}, callContext, { key: "b" }),232
]);233
return {};234
}),235
);236
const { harness } = await runOnce(setup, [call("batch"), DONE]);237
expect(seen.map((each) => each.callId).sort()).toEqual(["c1/a", "c1/b"]);238
expect(new Set(seen.map((each) => each.taskId)).size).toBe(2);239
await harness.close(context);240
});242
it("runs the tool hooks on nested calls, which see their parent", async () => {243
const setup = chatSetup();244
const echo = echoTool();245
addTool(setup.registry, echo.registration);246
const parents: ToolHookCall["parent"][] = [];247
addHooks(setup.registry, ToolTask, {248
beforeTool: (hookCall) => {249
parents.push(hookCall.parent);250
return hookCall.parent !== undefined && hookCall.arguments.text === "secret"251
? { block: "no secrets" }252
: undefined;253
},254
afterTool: (hookCall, result) =>255
hookCall.parent === undefined ? undefined : { ...result, output: [{ type: "text", text: "rewritten" }] },256
});257
const nested: NestedToolExecutionResult[] = [];258
addTool(259
setup.registry,260
tool("batch", async (_args, api, callContext) => {261
nested.push(await api.executeTool("echo", { text: "secret" }, callContext));262
nested.push(await api.executeTool("echo", { text: "public" }, callContext));263
return {};264
}),265
);266
const { harness } = await runOnce(setup, [call("batch"), DONE]);267
const [parent] = await toolTasks(harness);268
expect(parents).toEqual([undefined, { taskId: parent!.id, callId: "c1" }, { taskId: parent!.id, callId: "c1" }]);269
expect(nested[0]).toMatchObject({270
isError: true,271
diagnostics: [{ severity: "error", code: "blocked", message: "Tool call blocked: no secrets" }],272
});273
expect(text(nested[1])).toBe("rewritten");274
expect(echo.state.runs).toBe(1);275
await harness.close(context);276
});278
it("returns an error result for an unavailable tool and invalid arguments", async () => {279
const setup = chatSetup();280
addTool(setup.registry, echoTool().registration);281
const nested: NestedToolExecutionResult[] = [];282
addTool(283
setup.registry,284
tool("batch", async (_args, api, callContext) => {285
nested.push(await api.executeTool("missing", {}, callContext));286
nested.push(await api.executeTool("echo", { text: { not: "a string" } }, callContext));287
return {};288
}),289
);290
const { harness } = await runOnce(setup, [call("batch"), DONE]);291
expect(nested.map((result) => [result.isError, result.diagnostics[0]?.code])).toEqual([292
[true, "tool_unavailable"],293
[true, "invalid_arguments"],294
]);295
await harness.close(context);296
});298
it("returns the call a key already names, and rejects reusing the key for another call", async () => {299
const setup = chatSetup();300
const echo = echoTool();301
addTool(setup.registry, echo.registration);302
let reused: NestedToolExecutionResult | undefined;303
addTool(304
setup.registry,305
tool("batch", async (_args, api, callContext) => {306
await api.executeTool("echo", { text: "a" }, callContext, { key: "k" });307
reused = await api.executeTool("echo", { text: "a" }, callContext, { key: "k" });308
await api.executeTool("echo", { text: "b" }, callContext, { key: "k" });309
return {};310
}),311
);312
const { harness, entries } = await runOnce(setup, [call("batch"), DONE]);313
expect(echo.state.runs).toBe(1);314
expect(text(reused)).toBe("echo a");315
expect(text(results(entries)[0])).toContain(316
"Nested call c1/k was already made with another tool or other arguments",317
);318
await harness.close(context);319
});321
it("matches a reused key's arguments regardless of key order", async () => {322
const setup = chatSetup();323
let runs = 0;324
addTool(325
setup.registry,326
defineTool({327
name: "pair",328
description: "pair",329
parameters: Type.Object({ a: Type.String(), b: Type.String() }),330
execute: async (args) => {331
runs++;332
return { output: [{ type: "text", text: `${args.a}${args.b}` }] };333
},334
}),335
);336
const nested: NestedToolExecutionResult[] = [];337
addTool(338
setup.registry,339
tool("batch", async (_args, api, callContext) => {340
nested.push(await api.executeTool("pair", { a: "x", b: "y" }, callContext, { key: "k" }));341
nested.push(await api.executeTool("pair", { b: "y", a: "x" }, callContext, { key: "k" }));342
return {};343
}),344
);345
const { harness } = await runOnce(setup, [call("batch"), DONE]);346
expect(runs).toBe(1);347
expect(nested.map((result) => text(result))).toEqual(["xy", "xy"]);348
await harness.close(context);349
});351
it("aborts the nested calls a caller left running when it returns, keeping their details", async () => {352
const setup = chatSetup();353
const running = deferred();354
addTool(355
setup.registry,356
tool("hang", async (_args, api, callContext) => {357
api.output("partial\n");358
await api.details({ step: 1 }, callContext);359
running.resolve();360
return aborted(callContext.abortSignal!);361
}),362
);363
let abandoned: Promise<NestedToolExecutionResult> | undefined;364
addTool(365
setup.registry,366
tool("batch", async (_args, api, callContext) => {367
abandoned = api.executeTool("hang", {}, callContext);368
abandoned.catch(() => {});369
await running.promise;370
return { output: [{ type: "text", text: "returned early" }] };371
}),372
);373
setup.faux.setResponses([call("batch"), DONE]);374
const { harness, root } = await openChat(new MemoryStorage(), setup);375
const stream = await watchEvents(harness, root.id, context);376
const ends: AgentEvent[] = [];377
stream.start(async (batch) => {378
ends.push(...batch.filter((event) => event.type === "tool_execution_end"));379
});380
const settled = await (await root.submit({ type: "input", content: "go" }, context)).wait(context);381
expect(settled.status).toBe("done");382
await harness.waitForIdle(context);383
await stream.stop();384
const [result] = results(await allEntries(root));385
expect(text(result)).toBe("returned early");386
const [, child] = await toolTasks(harness);387
expect(child!.state).toMatchObject({388
status: "terminal",389
outcome: { status: "aborted", result: { kind: "nested" } },390
});391
// The aborted call's result keeps its details; programs get no partial output, which only the model read.392
const childEnd = ends.find((event) => event.type === "tool_execution_end" && event.toolCallId === "c1/1");393
expect(childEnd).toMatchObject({ result: { isError: true, details: { step: 1 } } });394
expect((childEnd as { result?: NestedToolExecutionResult }).result).not.toHaveProperty("structuredOutput");395
// The nested call ends, with its result, before its caller.396
expect(ends.map((event) => [event.type === "tool_execution_end" && event.toolCallId, "result" in event])).toEqual(397
[398
["c1/1", true],399
["c1", false],400
],401
);402
expect(await harness.snapshot(LiveDoc, root.id, context)).toEqual({});403
await harness.close(context);404
});406
it("records a nested call's usage under its tool", async () => {407
const setup = chatSetup();408
const usage: Usage = {409
input: 1,410
output: 2,411
cacheRead: 0,412
cacheWrite: 0,413
totalTokens: 3,414
cost: { input: 0.1, output: 0.2, cacheRead: 0, cacheWrite: 0, total: 0.3 },415
};416
addTool(417
setup.registry,418
tool("paid", async () => ({ usage })),419
);420
addTool(421
setup.registry,422
tool("batch", async (_args, api, callContext) => {423
await api.executeTool("paid", {}, callContext);424
return {};425
}),426
);427
const { harness, root } = await runOnce(setup, [call("batch"), DONE]);428
expect((await harness.snapshot(UsageDoc, root.id, context))?.tools).toEqual({ paid: usage });429
await harness.close(context);430
});432
it("reports nested calls in pi.live.nestedTools and as tool events with their parent", async () => {433
const setup = chatSetup();434
const release = deferred();435
const running = deferred();436
addTool(437
setup.registry,438
tool("slow", async (_args, api, callContext) => {439
api.output("working\n");440
await api.details({ step: 1 }, callContext);441
running.resolve();442
await release.promise;443
return { output: [{ type: "text", text: "slow done" }] };444
}),445
);446
addTool(447
setup.registry,448
tool("batch", async (_args, api, callContext) => {449
const result = await api.executeTool("slow", {}, callContext);450
return { output: [{ type: "text", text: text(result) }] };451
}),452
);453
setup.faux.setResponses([call("batch"), DONE]);454
const { harness, root } = await openChat(new MemoryStorage(), setup);455
const stream = await watchEvents(harness, root.id, context);456
expect(stream.snapshot.nestedTools).toEqual([]);457
const events: AgentEvent[] = [];458
stream.start(async (batch) => {459
events.push(...batch);460
});461
const submission = await root.submit({ type: "input", content: "go" }, context);462
await running.promise;463
const live = await harness.snapshot(LiveDoc, root.id, context);464
expect(live?.nestedTools).toEqual([465
{466
callId: "c1/1",467
parentCallId: "c1",468
parentTaskId: expect.any(Number),469
name: "slow",470
taskId: expect.any(Number),471
arguments: {},472
status: "running",473
output: "working\n",474
details: { step: 1 },475
},476
]);477
release.resolve();478
await submission.wait(context);479
await harness.waitForIdle(context);480
await stream.stop();481
const tools = events.flatMap((event) =>482
event.type === "tool_execution_start" || event.type === "tool_execution_end"483
? [[event.type, event.toolCallId, event.parentToolCallId]]484
: [],485
);486
expect(tools).toEqual([487
["tool_execution_start", "c1", undefined],488
["tool_execution_start", "c1/1", "c1"],489
["tool_execution_end", "c1/1", "c1"],490
["tool_execution_end", "c1", undefined],491
]);492
const nestedEnd = events.find((event) => event.type === "tool_execution_end" && event.toolCallId === "c1/1");493
expect(nestedEnd).toMatchObject({ result: { structuredOutput: "slow done", isError: false } });494
// Events name the call's task and, for a nested call, the calling one.495
const [parent, child] = await toolTasks(harness);496
const parentEnd = events.find((event) => event.type === "tool_execution_end" && event.toolCallId === "c1");497
expect(nestedEnd).toMatchObject({ taskId: child!.id, parentTaskId: parent!.id });498
expect(parentEnd).toMatchObject({ taskId: parent!.id });499
expect(parentEnd).not.toHaveProperty("parentTaskId");500
expect(501
events.some(502
(event) =>503
event.type === "tool_execution_update" && event.toolCallId === "c1/1" && event.parentToolCallId === "c1",504
),505
).toBe(true);506
expect(await harness.snapshot(LiveDoc, root.id, context)).toEqual({});507
await harness.close(context);508
});510
it("aborts nested calls with their caller", async () => {511
const setup = chatSetup();512
const running = deferred();513
addTool(514
setup.registry,515
tool("hang", async (_args, _api, callContext) => {516
running.resolve();517
return aborted(callContext.abortSignal!);518
}),519
);520
addTool(521
setup.registry,522
tool("batch", async (_args, api, callContext) => {523
await api.executeTool("hang", {}, callContext);524
return {};525
}),526
);527
setup.faux.setResponses([call("batch"), DONE]);528
const { harness, root } = await openChat(new MemoryStorage(), setup);529
const submission = await root.submit({ type: "input", content: "go" }, context);530
await running.promise;531
await root.abort(context);532
expect((await submission.wait(context)).status).toBe("unanswered");533
const [parent, child] = await toolTasks(harness);534
const outcome = (record: typeof parent) =>535
record!.state.status === "terminal" ? record!.state.outcome : undefined;536
expect(outcome(child)).toMatchObject({ status: "aborted", result: { kind: "nested" } });537
expect(outcome(parent)).toMatchObject({ status: "aborted", result: { kind: "model" } });538
expect(await harness.snapshot(LiveDoc, root.id, context)).toEqual({});539
await harness.close(context);540
});542
it("aborts a running nested call when its caller throws", async () => {543
const setup = chatSetup();544
const running = deferred();545
addTool(546
setup.registry,547
tool("hang", async (_args, _api, callContext) => {548
running.resolve();549
return aborted(callContext.abortSignal!);550
}),551
);552
addTool(553
setup.registry,554
tool("batch", async (_args, api, callContext) => {555
void api.executeTool("hang", {}, callContext).catch(() => {});556
await running.promise;557
throw new Error("caller failed");558
}),559
);560
const { harness, status, entries } = await runOnce(setup, [call("batch"), DONE]);561
expect(status).toBe("done");562
expect(text(results(entries)[0])).toContain("caller failed");563
const [, child] = await toolTasks(harness);564
expect(child!.state).toMatchObject({ status: "terminal", outcome: { status: "aborted" } });565
await harness.close(context);566
});568
it("reattaches a replay-safe caller to the nested calls it made before a restart", async () => {569
const directory = await mkdtemp(join(tmpdir(), "pi-durable-nested-"));570
directories.add(directory);571
const path = join(directory, "session.sqlite");572
const setup = chatSetup();573
const echo = echoTool();574
addTool(setup.registry, echo.registration);575
const blocked = deferred();576
let runs = 0;577
addTool(578
setup.registry,579
tool(580
"batch",581
async (_args, api, callContext) => {582
runs++;583
const first = await api.executeTool("echo", { text: "a" }, callContext);584
if (runs === 1) {585
blocked.resolve();586
await aborted(callContext.abortSignal!);587
}588
// A call new to the rerun: its slot, after the reattached one's, is found and finishes.589
const second = await api.executeTool("echo", { text: "b" }, callContext);590
return { output: [{ type: "text", text: `run ${runs}: ${text(first)}, ${text(second)}` }] };591
},592
{ replay: "safe" },593
),594
);595
setup.faux.setResponses([call("batch"), DONE]);596
let opened = await openChat(await openNodeSqliteStorage(path), setup);597
const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;598
await blocked.promise;599
await opened.harness.close(context);601
opened = await openChat(await openNodeSqliteStorage(path), setup);602
opened.harness.resume();603
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");604
expect(runs).toBe(2);605
expect(echo.state.runs).toBe(2);606
expect(text(results(await allEntries(opened.root))[0])).toBe("run 2: echo a, echo b");607
const tasks = await toolTasks(opened.harness);608
expect(tasks.filter((task) => (task.input as ToolTaskInput).kind === "nested")).toHaveLength(2);609
const outcome = tasks[1]!.state.status === "terminal" ? tasks[1]!.state.outcome : undefined;610
expect((outcome?.result as ToolTaskResult | undefined)?.kind).toBe("nested");611
await opened.harness.close(context);612
});614
it("stops only the wait when a caller cancels it; the call runs on and its key returns its result", async () => {615
const setup = chatSetup();616
const cancel = new AbortController();617
const release = deferred();618
const attempts: string[] = [];619
let retry: NestedToolExecutionResult | undefined;620
addTool(621
setup.registry,622
tool("slow", async () => {623
cancel.abort(new Error("cancelled"));624
await release.promise;625
return { output: [{ type: "text", text: "slow done" }] };626
}),627
);628
addTool(629
setup.registry,630
tool("batch", async (_args, api, callContext) => {631
const cancelled = withAbortSignal(cancel.signal, callContext);632
await api.executeTool("slow", {}, cancelled, { key: "same" }).then(633
() => attempts.push("first done"),634
() => attempts.push("first cancelled"),635
);636
release.resolve();637
retry = await api.executeTool("slow", {}, callContext, { key: "same" });638
return {};639
}),640
);641
const { harness } = await runOnce(setup, [call("batch"), DONE]);642
expect(attempts).toEqual(["first cancelled"]);643
expect(retry).toMatchObject({ isError: false, structuredOutput: "slow done" });644
expect(await toolTasks(harness)).toHaveLength(2);645
await harness.close(context);646
});648
it("admits one nested call for a key used by concurrent calls", async () => {649
const setup = chatSetup();650
const echo = echoTool();651
addTool(setup.registry, echo.registration);652
let both: NestedToolExecutionResult[] = [];653
addTool(654
setup.registry,655
tool("batch", async (_args, api, callContext) => {656
both = await Promise.all([657
api.executeTool("echo", { text: "a" }, callContext, { key: "k" }),658
api.executeTool("echo", { text: "a" }, callContext, { key: "k" }),659
]);660
return {};661
}),662
);663
const { harness } = await runOnce(setup, [call("batch"), DONE]);664
expect(echo.state.runs).toBe(1);665
expect(both.map((result) => text(result))).toEqual(["echo a", "echo a"]);666
expect(await toolTasks(harness)).toHaveLength(2);667
await harness.close(context);668
});670
it("aborts left-running nested calls of a caller interrupted while it cleaned them up", async () => {671
const directory = await mkdtemp(join(tmpdir(), "pi-durable-nested-"));672
directories.add(directory);673
const path = join(directory, "session.sqlite");674
const setup = chatSetup();675
const running = deferred();676
const cleaning = deferred();677
const release = deferred();678
let hangRuns = 0;679
addTool(680
setup.registry,681
tool("hang", async (_args, api, callContext) => {682
hangRuns++;683
api.output("partial\n");684
await api.details({ step: 1 }, callContext);685
running.resolve();686
await aborted(callContext.abortSignal!).catch(() => {});687
// The caller's cleanup waits for this abort; hold it there until the Harness closes.688
cleaning.resolve();689
await release.promise;690
throw new Error("aborted");691
}),692
);693
addTool(694
setup.registry,695
tool("batch", async (_args, api, callContext) => {696
void api.executeTool("hang", {}, callContext).catch(() => {});697
await running.promise;698
return { output: [{ type: "text", text: "returned early" }] };699
}),700
);701
setup.faux.setResponses([call("batch"), DONE]);702
let opened = await openChat(await openNodeSqliteStorage(path), setup);703
const id = (await opened.root.submit({ type: "input", content: "go" }, context)).id;704
await cleaning.promise;705
const closed = opened.harness.close(context);706
release.resolve();707
await closed;709
opened = await openChat(await openNodeSqliteStorage(path), setup);710
opened.harness.resume();711
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");712
await opened.harness.waitForIdle(context);713
// The caller is replay-unsafe: it reports the interruption, and its cleanup aborts the nested call.714
const [result] = results(await allEntries(opened.root));715
expect(result).toMatchObject({ toolCallId: "c1", isError: true });716
expect(text(result)).toContain("Tool batch was interrupted");717
const [, child] = await toolTasks(opened.harness);718
expect(child!.state).toMatchObject({ status: "terminal", outcome: { status: "aborted" } });719
expect(hangRuns).toBe(1);720
expect(await opened.harness.snapshot(LiveDoc, opened.root.id, context)).toEqual({});721
await opened.harness.close(context);722
});724
it("aborts a nested call whose admission was still committing when its caller returned", async () => {725
const setup = chatSetup();726
addTool(setup.registry, echoTool().registration);727
addTool(728
setup.registry,729
tool("hang", async (_args, _api, callContext) => aborted(callContext.abortSignal!)),730
);731
addTool(732
setup.registry,733
tool("batch", async (_args, api, callContext) => {734
await api.executeTool("echo", { text: "warm" }, callContext, { key: "warm" });735
void api.executeTool("hang", {}, callContext, { key: "late" }).catch(() => {});736
return {};737
}),738
);739
const { harness, root, status } = await runOnce(setup, [call("batch"), DONE]);740
expect(status).toBe("done");741
const late = (await toolTasks(harness)).find((task) => {742
const input = task.input as ToolTaskInput;743
return input.kind === "nested" && input.call.name === "hang";744
});745
expect(late!.state).toMatchObject({ status: "terminal", outcome: { status: "aborted" } });746
expect(await harness.snapshot(LiveDoc, root.id, context)).toEqual({});747
await harness.close(context);748
});750
it("aborts every left-running nested call before waiting for any", async () => {751
const setup = chatSetup();752
const bAborted = deferred();753
const started = { a: deferred(), b: deferred() };754
// A only stops once B was told to stop.755
addTool(756
setup.registry,757
tool("a", async () => {758
started.a.resolve();759
await bAborted.promise;760
return {};761
}),762
);763
addTool(764
setup.registry,765
tool("b", async (_args, _api, callContext) => {766
started.b.resolve();767
await aborted(callContext.abortSignal!).catch(() => {});768
bAborted.resolve();769
throw new Error("aborted");770
}),771
);772
addTool(773
setup.registry,774
tool("batch", async (_args, api, callContext) => {775
void api.executeTool("a", {}, callContext, { key: "a" }).catch(() => {});776
void api.executeTool("b", {}, callContext, { key: "b" }).catch(() => {});777
await Promise.all([started.a.promise, started.b.promise]);778
return {};779
}),780
);781
const { harness, status } = await runOnce(setup, [call("batch"), DONE]);782
expect(status).toBe("done");783
const nested = (await toolTasks(harness)).filter((task) => (task.input as ToolTaskInput).kind === "nested");784
expect(nested.map((task) => task.state.status)).toEqual(["terminal", "terminal"]);785
await harness.close(context);786
});788
it("rejects explicit keys that are empty, have a slash, are __proto__, or are positive integers", async () => {789
const setup = chatSetup();790
addTool(setup.registry, echoTool().registration);791
const errors: string[] = [];792
addTool(793
setup.registry,794
tool("batch", async (_args, api, callContext) => {795
for (const key of ["", "a/b", "__proto__", "7"]) {796
await api797
.executeTool("echo", {}, callContext, { key })798
.catch((error: Error) => errors.push(error.message));799
}800
return {};801
}),802
);803
const { harness } = await runOnce(setup, [call("batch"), DONE]);804
const rule = 'must be non-empty, without "/", not "__proto__", and not a positive integer';805
expect(errors).toEqual([806
`Nested call key "" ${rule}`,807
`Nested call key "a/b" ${rule}`,808
`Nested call key "__proto__" ${rule}`,809
`Nested call key "7" ${rule}`,810
]);811
await harness.close(context);812
});814
it("runs nested calls of nested calls, and ends them children first", async () => {815
const setup = chatSetup();816
const echo = echoTool();817
addTool(setup.registry, echo.registration);818
addTool(819
setup.registry,820
tool("inner", async (_args, api, callContext) => {821
const result = await api.executeTool("echo", { text: "deep" }, callContext, { key: "x" });822
return { output: [{ type: "text", text: text(result) }] };823
}),824
);825
addTool(826
setup.registry,827
tool("outer", async (_args, api, callContext) => {828
const result = await api.executeTool("inner", {}, callContext);829
return { output: [{ type: "text", text: text(result) }] };830
}),831
);832
setup.faux.setResponses([call("outer"), DONE]);833
const { harness, root } = await openChat(new MemoryStorage(), setup);834
const stream = await watchEvents(harness, root.id, context);835
const tools: (string | undefined)[][] = [];836
stream.start(async (batch) => {837
for (const event of batch) {838
if (event.type === "tool_execution_start" || event.type === "tool_execution_end") {839
tools.push([event.type, event.toolCallId, event.parentToolCallId]);840
}841
}842
});843
await (await root.submit({ type: "input", content: "go" }, context)).wait(context);844
await harness.waitForIdle(context);845
await stream.stop();846
expect(text(results(await allEntries(root))[0])).toBe("echo deep");847
const [outer, inner, deep] = await toolTasks(harness);848
expect([inner!.owner, deep!.owner]).toEqual([outer!.id, inner!.id]);849
expect(tools).toEqual([850
["tool_execution_start", "c1", undefined],851
["tool_execution_start", "c1/1", "c1"],852
["tool_execution_start", "c1/1/x", "c1/1"],853
["tool_execution_end", "c1/1/x", "c1/1"],854
["tool_execution_end", "c1/1", "c1"],855
["tool_execution_end", "c1", undefined],856
]);857
expect(await harness.snapshot(LiveDoc, root.id, context)).toEqual({});858
await harness.close(context);859
});861
it("reports the output of several running nested calls, and shows them to a late subscriber", async () => {862
const setup = chatSetup();863
const release = deferred();864
const running = { one: deferred(), two: deferred() };865
const wrote = { one: deferred(), two: deferred() };866
addTool(867
setup.registry,868
tool("slow", async (args, api, callContext) => {869
const name = args.text as "one" | "two";870
running[name].resolve();871
await wrote[name].promise;872
api.output(`${name}\n`);873
await api.details({ name }, callContext);874
await release.promise;875
return {};876
}),877
);878
addTool(879
setup.registry,880
tool("batch", async (_args, api, callContext) => {881
await Promise.all([882
api.executeTool("slow", { text: "one" }, callContext),883
api.executeTool("slow", { text: "two" }, callContext),884
]);885
return {};886
}),887
);888
setup.faux.setResponses([call("batch"), DONE]);889
const { harness, root } = await openChat(new MemoryStorage(), setup);890
const submission = await root.submit({ type: "input", content: "go" }, context);891
await Promise.all([running.one.promise, running.two.promise]);892
const stream = await watchEvents(harness, root.id, context);893
expect(stream.snapshot.nestedTools.map((slot) => [slot.callId, slot.status])).toEqual([894
["c1/1", "running"],895
["c1/2", "running"],896
]);897
const updates: [string, unknown][] = [];898
stream.start(async (batch) => {899
for (const event of batch) {900
if (event.type === "tool_execution_update" && event.output !== undefined) {901
updates.push([event.toolCallId, event.output]);902
}903
}904
});905
// The second slot writes first, so a wrong slot index in the update path would show.906
wrote.two.resolve();907
await eventually(() => updates.length === 1);908
wrote.one.resolve();909
await eventually(() => updates.length === 2);910
release.resolve();911
await submission.wait(context);912
await stream.stop();913
expect(updates).toEqual([914
["c1/2", { set: "two\n" }],915
["c1/1", { set: "one\n" }],916
]);917
await harness.close(context);918
});920
it("commits only the status of a nested call made with progress: false, and keeps its output in the result", async () => {921
const setup = chatSetup();922
const running = deferred();923
const release = deferred();924
addTool(925
setup.registry,926
tool("chatty", async (_args, api, callContext) => {927
api.output("line\n");928
api.diagnostic({ severity: "info", message: "note" });929
await api.details({ step: 1 }, callContext);930
running.resolve();931
await release.promise;932
return {};933
}),934
);935
let result: NestedToolExecutionResult | undefined;936
addTool(937
setup.registry,938
tool("batch", async (_args, api, callContext) => {939
result = await api.executeTool("chatty", {}, callContext, { progress: false });940
return {};941
}),942
);943
setup.faux.setResponses([call("batch"), DONE]);944
const { harness, root } = await openChat(new MemoryStorage(), setup);945
const submission = await root.submit({ type: "input", content: "go" }, context);946
// `details()` resolved before this, so a progress commit would have landed already.947
await running.promise;948
const [slot] = (await harness.snapshot(LiveDoc, root.id, context))!.nestedTools!;949
expect(slot).toEqual({950
callId: "c1/1",951
parentCallId: "c1",952
parentTaskId: expect.any(Number),953
name: "chatty",954
taskId: expect.any(Number),955
arguments: {},956
status: "running",957
});958
release.resolve();959
await submission.wait(context);960
expect(result).toMatchObject({961
structuredOutput: "line\n",962
details: { step: 1 },963
diagnostics: [{ severity: "info", message: "note" }],964
});965
await harness.close(context);966
});968
it("loses the running output of a nested call made with progress: false when it is aborted", async () => {969
const setup = chatSetup();970
const running = deferred();971
addTool(972
setup.registry,973
tool("chatty", async (_args, api, callContext) => {974
api.output("line\n");975
api.diagnostic({ severity: "info", message: "note" });976
await api.details({ step: 1 }, callContext);977
running.resolve();978
return aborted(callContext.abortSignal!);979
}),980
);981
addTool(982
setup.registry,983
tool("batch", async (_args, api, callContext) => {984
void api.executeTool("chatty", {}, callContext, { progress: false }).catch(() => {});985
await running.promise;986
return {};987
}),988
);989
setup.faux.setResponses([call("batch"), DONE]);990
const { harness, root } = await openChat(new MemoryStorage(), setup);991
const stream = await watchEvents(harness, root.id, context);992
const ends: AgentEvent[] = [];993
stream.start(async (batch) => {994
ends.push(...batch.filter((event) => event.type === "tool_execution_end"));995
});996
await (await root.submit({ type: "input", content: "go" }, context)).wait(context);997
await harness.waitForIdle(context);998
await stream.stop();999
// The abort's result is built from the slot, which never got the output.1000
const end = ends.find((event) => event.type === "tool_execution_end" && event.toolCallId === "c1/1");1001
const result = (end as { result?: NestedToolExecutionResult }).result!;1002
expect(result).toMatchObject({ isError: true });1003
expect(result).not.toHaveProperty("structuredOutput");1004
expect(result).not.toHaveProperty("details");1005
expect(result.diagnostics.map((diagnostic) => diagnostic.code)).toEqual(["aborted"]);1006
await harness.close(context);1007
});1009
it("shows a nested call's arguments in its slot: as made, then, unbounded, as it runs with them", async () => {1010
const setup = chatSetup();1011
const hookEntered = deferred();1012
const hookRelease = deferred();1013
const running = deferred();1014
const release = deferred();1015
const large = "x".repeat(64 * 1024);1016
addTool(1017
setup.registry,1018
tool("slow", async () => {1019
running.resolve();1020
await release.promise;1021
return {};1022
}),1023
);1024
addHooks(setup.registry, ToolTask, {1025
beforeTool: async (hookCall) => {1026
if (hookCall.parent === undefined) return undefined;1027
hookEntered.resolve();1028
await hookRelease.promise;1029
return { arguments: { text: large } };1030
},1031
});1032
addTool(1033
setup.registry,1034
tool("batch", async (_args, api, callContext) => {1035
await api.executeTool("slow", { text: "asked" }, callContext);1036
return {};1037
}),1038
);1039
setup.faux.setResponses([call("batch"), DONE]);1040
const { harness, root } = await openChat(new MemoryStorage(), setup);1041
const stream = await watchEvents(harness, root.id, context);1042
const starts: AgentEvent[] = [];1043
stream.start(async (batch) => {1044
starts.push(...batch.filter((event) => event.type === "tool_execution_start"));1045
});1046
const submission = await root.submit({ type: "input", content: "go" }, context);1047
const slot = async () => (await harness.snapshot(LiveDoc, root.id, context))!.nestedTools![0]!;1048
await hookEntered.promise;1049
expect(await slot()).toMatchObject({ status: "pending", arguments: { text: "asked" } });1050
hookRelease.resolve();1051
await running.promise;1052
expect(await slot()).toMatchObject({ status: "running", arguments: { text: large } });1053
release.resolve();1054
await submission.wait(context);1055
await harness.waitForIdle(context);1056
await stream.stop();1057
// The start event carries the arguments the call runs with; the task input keeps the ones it was made with.1058
const start = starts.find((event) => event.type === "tool_execution_start" && event.toolCallId === "c1/1");1059
expect(start).toMatchObject({ args: { text: large } });1060
const nested = (await toolTasks(harness)).find((task) => (task.input as ToolTaskInput).kind === "nested");1061
expect(nested!.input as ToolTaskInput).toMatchObject({ call: { arguments: { text: "asked" } } });1062
await harness.close(context);1063
});1065
it("runs a nested call whose repaired arguments set an optional property to undefined", async () => {1066
const setup = chatSetup();1067
const seen: unknown[] = [];1068
addTool(1069
setup.registry,1070
tool(1071
"repaired",1072
async (args) => {1073
seen.push(args);1074
return {};1075
},1076
{ prepareArguments: () => ({ text: undefined }) },1077
),1078
);1079
let result: NestedToolExecutionResult | undefined;1080
addTool(1081
setup.registry,1082
tool("batch", async (_args, api, callContext) => {1083
result = await api.executeTool("repaired", { text: "x" }, callContext);1084
return {};1085
}),1086
);1087
const { harness } = await runOnce(setup, [call("batch"), DONE]);1088
expect(result).toMatchObject({ isError: false });1089
expect(seen).toEqual([{}]);1090
await harness.close(context);1091
});1093
it("finds each nested call's slot after slots in the middle were removed", async () => {1094
const setup = chatSetup();1095
addTool(setup.registry, echoTool().registration);1096
addTool(1097
setup.registry,1098
tool("inner", async (_args, api, callContext) => {1099
await api.executeTool("echo", { text: "m1" }, callContext);1100
await api.executeTool("echo", { text: "m2" }, callContext);1101
return {};1102
}),1103
);1104
const before = deferred();1105
const checked = deferred();1106
let slots: { callId: string; status: string; summary?: unknown }[] = [];1107
addTool(1108
setup.registry,1109
tool("batch", async (_args, api, callContext) => {1110
await api.executeTool("echo", { text: "n1" }, callContext);1111
// n2 makes m1 and m2 and settles, which removes them from between n2 and n3.1112
await api.executeTool("inner", {}, callContext);1113
await api.executeTool("echo", { text: "n3" }, callContext);1114
await api.executeTool("echo", { text: "n4" }, callContext);1115
const live = await api.snapshot(LiveDoc, api.conversationId, callContext);1116
slots = (live?.nestedTools ?? []).map(({ callId, status, summary }) => ({ callId, status, summary }));1117
before.resolve();1118
await checked.promise;1119
return {};1120
}),1121
);1122
setup.faux.setResponses([call("batch"), DONE]);1123
const { harness, root } = await openChat(new MemoryStorage(), setup);1124
const submission = await root.submit({ type: "input", content: "go" }, context);1125
await before.promise;1126
const done = { status: "done", summary: { isError: false, durationMs: expect.any(Number) } };1127
expect(slots).toEqual(["c1/1", "c1/2", "c1/3", "c1/4"].map((callId) => ({ callId, ...done })));1128
checked.resolve();1129
await submission.wait(context);1130
await harness.close(context);1131
});1133
it("gives callers a result with its task ID and only diagnostics for a nested call the scheduler faulted", async () => {1134
const setup = chatSetup();1135
// Details that are not JSON make the result commit throw, so the task faults and stores no result.1136
addTool(1137
setup.registry,1138
tool("echo", async () => ({ details: { count: 1n } as unknown as JsonValue })),1139
);1140
let result: NestedToolExecutionResult | undefined;1141
addTool(1142
setup.registry,1143
tool("batch", async (_args, api, callContext) => {1144
result = await api.executeTool("echo", { text: "a" }, callContext);1145
return {};1146
}),1147
);1148
setup.faux.setResponses([call("batch"), DONE]);1149
const { harness, root } = await openChat(new MemoryStorage(), setup);1150
await (await root.submit({ type: "input", content: "go" }, context)).wait(context);1151
const [, child] = await toolTasks(harness);1152
expect(child!.state).toMatchObject({ status: "terminal", outcome: { status: "faulted" } });1153
expect(result).toEqual({1154
taskId: child!.id,1155
isError: true,1156
diagnostics: [{ severity: "error", code: "faulted", message: expect.stringContaining("Tool echo failed") }],1157
});1158
await harness.close(context);1159
});1161
it("gives callers what a schema-less tool streamed before it threw", async () => {1162
const setup = chatSetup();1163
addTool(1164
setup.registry,1165
tool("fails", async (_args, api) => {1166
api.output("half way\n");1167
throw new Error("broke");1168
}),1169
);1170
let result: NestedToolExecutionResult | undefined;1171
addTool(1172
setup.registry,1173
tool("batch", async (_args, api, callContext) => {1174
result = await api.executeTool("fails", {}, callContext);1175
return {};1176
}),1177
);1178
const { harness } = await runOnce(setup, [call("batch"), DONE]);1179
expect(result).toMatchObject({1180
isError: true,1181
structuredOutput: "half way\n",1182
diagnostics: [{ code: "tool_error", message: "broke" }],1183
});1184
await harness.close(context);1185
});1187
it("shows a finished nested call as a done slot with its summary until its caller settles", async () => {1188
const setup = chatSetup();1189
const release = deferred();1190
const checked = deferred();1191
// Diagnostics win over output for the error text, which is cut to 500 characters.1192
addTool(1193
setup.registry,1194
tool("verbose", async () => ({1195
output: [{ type: "text", text: "ignored" }],1196
isError: true,1197
diagnostics: [{ severity: "error", message: "e".repeat(600) }],1198
})),1199
);1200
const usage: Usage = {1201
input: 1,1202
output: 2,1203
cacheRead: 0,1204
cacheWrite: 0,1205
totalTokens: 3,1206
cost: { input: 0.1, output: 0.2, cacheRead: 0, cacheWrite: 0, total: 0.3 },1207
};1208
addTool(setup.registry, echoTool().registration);1209
addTool(1210
setup.registry,1211
tool("paid", async () => ({ usage })),1212
);1213
// An error with mixed content: programs get the list, the summary its text.1214
addTool(1215
setup.registry,1216
tool("broken", async () => ({1217
output: [1218
{ type: "text", text: "bad image" },1219
{ type: "image", data: "AAAA", mimeType: "image/png" },1220
],1221
isError: true,1222
})),1223
);1224
addTool(1225
setup.registry,1226
tool("batch", async (_args, api, callContext) => {1227
await api.executeTool("echo", { text: "a" }, callContext);1228
await api.executeTool("missing", {}, callContext);1229
await api.executeTool("paid", {}, callContext);1230
await api.executeTool("broken", {}, callContext);1231
await api.executeTool("verbose", {}, callContext);1232
checked.resolve();1233
await release.promise;1234
return {};1235
}),1236
);1237
setup.faux.setResponses([call("batch"), DONE]);1238
const { harness, root } = await openChat(new MemoryStorage(), setup);1239
const submission = await root.submit({ type: "input", content: "go" }, context);1240
await checked.promise;1241
const slots = (await harness.snapshot(LiveDoc, root.id, context))!.nestedTools!;1242
expect(slots.map(({ callId, status, summary }) => ({ callId, status, summary }))).toEqual([1243
{ callId: "c1/1", status: "done", summary: { isError: false, durationMs: expect.any(Number) } },1244
{1245
callId: "c1/2",1246
status: "done",1247
summary: { isError: true, error: "Tool missing is not available" },1248
},1249
{ callId: "c1/3", status: "done", summary: { isError: false, durationMs: expect.any(Number), usage } },1250
{1251
callId: "c1/4",1252
status: "done",1253
summary: { isError: true, durationMs: expect.any(Number), error: "bad image" },1254
},1255
{1256
callId: "c1/5",1257
status: "done",1258
summary: { isError: true, durationMs: expect.any(Number), error: "e".repeat(500) },1259
},1260
]);1261
release.resolve();1262
await submission.wait(context);1263
expect(await harness.snapshot(LiveDoc, root.id, context)).toEqual({});1264
await harness.close(context);1265
});1267
it("migrates version 1 tool task input to a model-issued call", () => {1268
const migrate = ToolTask.definition.migrate!;1269
expect(migrate({ assistant: 3, callId: "c1" }, { phase: "call" }, 1)).toEqual({1270
input: { kind: "model", assistant: 3, callId: "c1" },1271
checkpoint: { phase: "call" },1272
});1273
});1274
});1276
describe("tool task version 1 records", () => {1277
/**1278
* Store a live tool task for call `c1` of an assistant entry, close, and rewrite its record as version 1 stored it:1279
* `{ assistant, callId }` input at version 1, with `checkpoint`. Returns the storage path and the task ID.1280
*/1281
async function storeVersion1(setup: ChatSetup, checkpoint: JsonValue): Promise<{ path: string; id: TaskId }> {1282
const directory = await mkdtemp(join(tmpdir(), "pi-durable-tool-v1-"));1283
directories.add(directory);1284
const path = join(directory, "session.sqlite");1285
// No submission, so the Harness never starts scheduling and the task stays pending.1286
const { harness, root } = await openChat(await openNodeSqliteStorage(path), setup);1287
const id = await root.commit(async (tx) => {1288
const entry = await tx.appendEntry(AssistantEntry, root.id, { model: [call("echo", { text: "old" })] });1289
return tx.createTask(1290
ToolTask,1291
{ kind: "model", assistant: entry.id, callId: "c1" },1292
{ ownership: { kind: "conversation" } },1293
);1294
}, context);1295
await harness.close(context);1296
const storage = await openNodeSqliteStorage(path);1297
const record = (await storage.task(id, context))!;1298
const { kind: _kind, ...input } = record.input as Extract<ToolTaskInput, { kind: "model" }>;1299
const state = { ...record.state, checkpoint } as typeof record.state;1300
await storage.commit(1301
[{ type: "task", value: { ...record, version: 1, input, state } as typeof record }],1302
context,1303
);1304
await storage.close(context);1305
return { path, id };1306
}1308
it("migrates a pending version 1 task and runs it as a model-issued call", async () => {1309
const setup = chatSetup();1310
const echo = echoTool();1311
addTool(setup.registry, echo.registration);1312
const { path, id } = await storeVersion1(setup, { phase: "call" });1313
const { harness, root } = await openChat(await openNodeSqliteStorage(path), setup);1314
expect((await harness.getTask(id, context))?.version).toBe(1);1315
harness.resume();1316
const settled = await harness.waitForTask(id, context);1317
expect(settled.version).toBe(2);1318
expect(settled.input).toMatchObject({ kind: "model", callId: "c1" });1319
expect(settled.state.outcome).toMatchObject({ status: "completed", result: { kind: "model" } });1320
expect(echo.state.runs).toBe(1);1321
const [result] = results(await allEntries(root));1322
expect([result!.toolCallId, text(result)]).toEqual(["c1", "echo old"]);1323
await harness.close(context);1324
});1326
it("migrates a version 1 task interrupted after intent and settles it interrupted", async () => {1327
const setup = chatSetup();1328
const echo = echoTool();1329
addTool(setup.registry, echo.registration);1330
const intent = { phase: "execute", arguments: { text: "old" }, replay: "unsafe" };1331
const { path, id } = await storeVersion1(setup, intent);1332
const { harness, root } = await openChat(await openNodeSqliteStorage(path), setup);1333
harness.resume();1334
const settled = await harness.waitForTask(id, context);1335
expect(settled.version).toBe(2);1336
expect(settled.state.outcome).toMatchObject({ status: "failed", result: { kind: "model" } });1337
expect(echo.state.runs).toBe(0);1338
const [result] = results(await allEntries(root));1339
expect(result).toMatchObject({ toolCallId: "c1", isError: true });1340
expect(text(result)).toContain("Tool echo was interrupted");1341
await harness.close(context);1342
});1343
});