Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Mark tool results recorded after shutdown as interrupted (#2060)

Regan Bell32046dc58094
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index c84feb4c0..f9f57d9ef 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -3752,6 +3752,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
...(input.runId ? { runId: input.runId } : {}),
cancel: turnAbort.signal,
...(continueTurn && !continuation ? { continueTurn: true } : {}),
+ ...(input.shutdown ? { shutdown: input.shutdown } : {}),
input: harnessInput,
...(!partial && messageTs ? { triggerTs: messageTs } : {}),
...(!partial && entryTs ? { entryTs } : {}),
diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.ts
index ed6deaa73..3f5aadd83 100644
--- a/src/core/orchestrator/types.ts
+++ b/src/core/orchestrator/types.ts
@@ -103,6 +103,7 @@ export interface OrchestratorInput extends Omit<
finalAttempt?: boolean;
background?: boolean;
cancel?: AbortSignal;
+ shutdown?: AbortSignal;
queueMs?: number;
sessionParticipantIds?: readonly string[];
scopeVersion?: string;
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index fb9468b1c..aee3c3c58 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -90,6 +90,7 @@ export interface ToolContextRef {
onGapWork?: (work: GapWork) => void;
fast?: boolean;
abortSignal?: AbortSignal;
+ shutdown?: AbortSignal;
pollFire?: boolean;
silentRequested?: boolean;
@@ -429,6 +430,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
const callId = (payload as { callId?: unknown } | null)?.callId;
if (typeof callId === "string" && callId) (ref.tapeResultScopes ??= new Map()).set(callId, scopeLabel);
}
+ if (type === "tool_result" && ref.shutdown?.aborted && isObj(payload)) payload = { ...payload, interrupted: true };
await ref.emit({ type, payload, scopeLabel });
};
diff --git a/src/harness/harness-shared.ts b/src/harness/harness-shared.ts
index 4f0a5cd13..e8937e52e 100644
--- a/src/harness/harness-shared.ts
+++ b/src/harness/harness-shared.ts
@@ -119,6 +119,7 @@ export function harnessToolContext(turn: HarnessTurnInput): ToolContextRef {
screenToolResult: turn.screenToolResult,
verifyGoal: turn.verifyGoal,
toolApprovalGate: turn.toolApprovalGate,
+ shutdown: turn.shutdown,
};
}
diff --git a/src/harness/harness.ts b/src/harness/harness.ts
index 31673bce4..941605f78 100644
--- a/src/harness/harness.ts
+++ b/src/harness/harness.ts
@@ -104,6 +104,7 @@ export interface HarnessTurnInput {
runId?: string;
cancel?: AbortSignal;
continueTurn?: boolean;
+ shutdown?: AbortSignal;
input: string;
triggerTs?: string;
entryTs?: string;
diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.ts
index c7a3b2268..27dd6e326 100644
--- a/src/harness/pi-harness.ts
+++ b/src/harness/pi-harness.ts
@@ -101,7 +101,7 @@ import {
type PiReplayMessage,
type SeededMessage,
} from "./replay.ts";
-import { assistantDroppedAtReplay, ELIDED_IMAGE_TEXT, planTapeSeed } from "./tape-fold.ts";
+import { assistantDroppedAtReplay, ELIDED_IMAGE_TEXT, planTapeSeed, withResumedToolResult } from "./tape-fold.ts";
import { estimateHistoryTokens, INTERRUPTED_TOOL_RESULT } from "./context-compaction.ts";
import { summarizeHistory } from "./history-summary.ts";
import { countTokens } from "../util/tokens.ts";
@@ -1868,10 +1868,17 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
scopeLabel: dispatched.scopeLabel,
orgScopeId: dispatched.orgScopeId,
toolApprovalGate: dispatched.toolApprovalGate,
+ shutdown: dispatched.shutdown,
};
const tools = createTurnTools(ref, dispatched);
const resumed = await resumeInterruptedToolCall(dispatched, ref, tools as unknown as BridgedTool[]);
- const turn = resumed ? { ...dispatched, history: resumed.history } : dispatched;
+ const turn = resumed
+ ? {
+ ...dispatched,
+ history: resumed.history,
+ ...(dispatched.tapeFold ? { tapeFold: withResumedToolResult(dispatched.tapeFold, resumed.message) } : {}),
+ }
+ : dispatched;
if (resumed) {
const callId = resumed.message.toolCallId;
const resultScope = ref.tapeResultScopes?.get(callId);
@@ -2000,10 +2007,14 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
const callId = role === "toolResult" ? (message as { toolCallId?: unknown }).toolCallId : undefined;
const resultScope = typeof callId === "string" ? entry.ref.tapeResultScopes?.get(callId) : undefined;
if (typeof callId === "string") entry.ref.tapeResultScopes?.delete(callId);
+ const taped = stripImageBytes(message, isTrigger ? turn.images : steer?.images);
const rec: NewTapeRecord = {
kind: "message",
harness: "pi",
- payload: stripImageBytes(message, isTrigger ? turn.images : steer?.images),
+ payload:
+ role === "toolResult" && turn.shutdown?.aborted
+ ? { ...(taped as Record<string, unknown>), interrupted: true }
+ : taped,
scopeLabel: resultScope ?? turn.scopeLabel,
...(isTrigger && userEntry
? {
diff --git a/src/harness/tape-fold.ts b/src/harness/tape-fold.ts
index 674b6bcd6..52aa7c4aa 100644
--- a/src/harness/tape-fold.ts
+++ b/src/harness/tape-fold.ts
@@ -20,7 +20,7 @@ export function filterTapeForAudience(
out.push(r);
continue;
}
- const msg = r.payload as { role?: string; toolCallId?: string; toolName?: string } | null;
+ const msg = r.payload as { role?: string; toolCallId?: string; toolName?: string; interrupted?: unknown } | null;
if (msg?.role === "toolResult" && typeof msg.toolCallId === "string") {
out.push({
...r,
@@ -31,6 +31,7 @@ export function filterTapeForAudience(
content: [{ type: "text", text: INTERRUPTED_TOOL_RESULT }],
isError: true,
timestamp: r.createdAt,
+ ...(msg.interrupted === true ? { interrupted: true } : {}),
},
});
}
@@ -220,8 +221,34 @@ function withoutThinking(messages: readonly unknown[]): unknown[] {
});
}
+function interruptedToolResult(message: unknown): string | undefined {
+ const msg = message as { role?: string; interrupted?: unknown; toolCallId?: unknown } | null;
+ return msg?.role === "toolResult" && msg.interrupted === true && typeof msg.toolCallId === "string"
+ ? msg.toolCallId
+ : undefined;
+}
+
+function realToolResults(rows: readonly TapeRecord[]): Map<string, unknown> {
+ const results = new Map<string, unknown>();
+ for (const row of rows) {
+ if (row.kind !== "message") continue;
+ const msg = row.payload as { role?: string; interrupted?: unknown; toolCallId?: unknown } | null;
+ if (msg?.role === "toolResult" && msg.interrupted !== true && typeof msg.toolCallId === "string")
+ results.set(msg.toolCallId, row.payload);
+ }
+ return results;
+}
+
+export function withResumedToolResult(fold: readonly unknown[], message: unknown): unknown[] {
+ const callId = (message as { toolCallId?: unknown }).toolCallId;
+ const at = fold.findIndex((m) => interruptedToolResult(m) === callId);
+ return at < 0 ? [...fold, message] : fold.with(at, message);
+}
+
export function foldTape(rows: readonly TapeRecord[]): unknown[] {
const f: Foldable = { out: [], boundaries: [] };
+ const realResults = realToolResults(rows);
+ const superseded = new Set<string>();
for (const row of rows) {
if (row.kind === "annotation") {
if ((row.payload as { turnEnd?: unknown } | null)?.turnEnd === true && row.entrySeq !== undefined) {
@@ -261,17 +288,26 @@ export function foldTape(rows: readonly TapeRecord[]): unknown[] {
}
continue;
}
- if (row.kind === "message" && row.payload != null) f.out.push(interruptedResultPlaceholder(row.payload));
+ if (row.kind !== "message" || row.payload == null) continue;
+ const msg = row.payload as { role?: string; toolCallId?: unknown };
+ const interruptedCall = interruptedToolResult(row.payload);
+ if (interruptedCall === undefined) {
+ if (msg.role === "toolResult" && typeof msg.toolCallId === "string" && superseded.has(msg.toolCallId)) continue;
+ f.out.push(row.payload);
+ } else if (realResults.has(interruptedCall)) {
+ superseded.add(interruptedCall);
+ f.out.push(realResults.get(interruptedCall));
+ } else {
+ f.out.push({
+ ...(row.payload as Record<string, unknown>),
+ content: [{ type: "text", text: INTERRUPTED_TOOL_RESULT }],
+ isError: true,
+ });
+ }
}
return f.out;
}
-function interruptedResultPlaceholder(message: unknown): unknown {
- const msg = message as { role?: string; interrupted?: unknown; content?: unknown };
- if (msg?.role !== "toolResult" || msg.interrupted !== true) return message;
- return { ...msg, content: [{ type: "text", text: INTERRUPTED_TOOL_RESULT }], isError: true };
-}
-
const LEGACY_CONTINUATION_LINE = "(continuing after the tool result above)";
function healLegacyAssistantVoice(messages: readonly unknown[]): unknown[] {
@@ -331,7 +367,8 @@ export function openTapeToolCalls(rows: readonly TapeRecord[]): { messages: numb
const calls: string[] = [];
for (const m of fold) {
const msg = m as { role?: string; toolCallId?: string; content?: unknown };
- if (msg?.role === "toolResult" && typeof msg.toolCallId === "string") answered.add(msg.toolCallId);
+ if (msg?.role === "toolResult" && typeof msg.toolCallId === "string" && interruptedToolResult(m) === undefined)
+ answered.add(msg.toolCallId);
if (msg?.role !== "assistant" || !Array.isArray(msg.content) || assistantDroppedAtReplay(m)) continue;
for (const block of msg.content) {
const b = block as { type?: string; id?: string };
diff --git a/src/runs/worker.ts b/src/runs/worker.ts
index fcad0299a..627167ff3 100644
--- a/src/runs/worker.ts
+++ b/src/runs/worker.ts
@@ -85,6 +85,7 @@ export async function processRun(
finalAttempt: errorParks(run, deps.runs.maxClaims),
background: opts?.background ?? false,
cancel: cancel.signal,
+ ...(opts?.shutdown ? { shutdown: opts.shutdown } : {}),
...(queueMs !== undefined ? { queueMs } : {}),
...(run.startedAt !== null ? { runStartedAt: run.startedAt } : {}),
});
diff --git a/src/sessions/session-syscalls.ts b/src/sessions/session-syscalls.ts
index 53e157305..bd1809743 100644
--- a/src/sessions/session-syscalls.ts
+++ b/src/sessions/session-syscalls.ts
@@ -1136,6 +1136,7 @@ export async function deliverSubagentMail(deps: SubagentMailDeps, run: Run): Pro
"finalAttempt",
"background",
"cancel",
+ "shutdown",
"queueMs",
"modelAccount",
"privateSessionMessage",
diff --git a/src/swarms/swarm-service.ts b/src/swarms/swarm-service.ts
index 0661b5b99..03745c71a 100644
--- a/src/swarms/swarm-service.ts
+++ b/src/swarms/swarm-service.ts
@@ -175,6 +175,7 @@ function matchesDispatch(input: OrchestratorInput, expected: OrchestratorInput):
finalAttempt: true,
background: true,
cancel: true,
+ shutdown: true,
queueMs: true,
runStartedAt: true,
};
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index 1f726fd63..719af5a98 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -4,6 +4,7 @@ import assert from "node:assert/strict";
import { Check } from "typebox/value";
import { fromJSONSchema, z, type ZodObject } from "zod";
import { createAgentTools, pauseStampAfterToolCall, type ToolContextRef } from "../src/harness/agent-tools.ts";
+import { resumeStrategy } from "../src/core/turn-resume.ts";
import { createMemoryRunSignalStore, waitForClientResult } from "../src/runs/run-signal-store.ts";
import { filterHistoryForAudience } from "../src/resolution/context-filter.ts";
import { CommandDenied, NeedsApproval, type ToolContext } from "../src/tools/primitives.ts";
@@ -4125,3 +4126,50 @@ test("every tool schema carries the optional retrySafe flag, which is stripped b
"the flag never reaches the tool body or its result",
);
});
+
+test("a tool result recorded after shutdown fires is marked interrupted; user Stop and plain completion are not", async () => {
+ const record = async (abort: "shutdown" | "stop" | "none", retrySafe = true) => {
+ const emitted: Emitted[] = [];
+ const shutdown = new AbortController();
+ const cancel = new AbortController();
+ const ref: ToolContextRef = {
+ current: fakeToolContext(),
+ emit: (e) => {
+ emitted.push(e as Emitted);
+ },
+ scopeLabel: "personal:U1",
+ shutdown: shutdown.signal,
+ abortSignal: cancel.signal,
+ };
+ const history = createAgentTools(ref).find((t) => t.name === "history")!;
+ if (abort === "shutdown") shutdown.abort();
+ if (abort !== "none") cancel.abort();
+ await callWith(history, `call-${abort}`, { query: "budget", retrySafe });
+ return emitted;
+ };
+ const strategy = (emitted: Emitted[]) => {
+ const entries = emitted.map((e, i) => ({ ...e, seq: i + 2 }) as unknown as SessionEntry);
+ return resumeStrategy(entries, { userSeq: 1, workEntries: entries.length });
+ };
+
+ const interrupted = await record("shutdown");
+ const result = interrupted.find((e) => e.type === "tool_result")!.payload;
+ assert.equal(result.interrupted, true);
+ assert.equal(typeof result.result, "string", "the recorded text is kept alongside the mark");
+ assert.deepEqual(strategy(interrupted), {
+ kind: "retry",
+ call: { callId: "call-shutdown", tool: "history", input: { query: "budget" } },
+ });
+ assert.deepEqual(
+ strategy(await record("shutdown", false)),
+ { kind: "note" },
+ "a killed call the model marked unsafe gets the unknown-outcome note, never a continue",
+ );
+
+ for (const abort of ["stop", "none"] as const) {
+ const emitted = await record(abort);
+ const payload = emitted.find((e) => e.type === "tool_result")!.payload;
+ assert.ok(!("interrupted" in payload), `${abort}: an ordinary result stays a real answer`);
+ assert.deepEqual(strategy(emitted), { kind: "continue" });
+ }
+});
diff --git a/test/pi-harness-resume.test.ts b/test/pi-harness-resume.test.ts
index 92bf06b79..635ddbd65 100644
--- a/test/pi-harness-resume.test.ts
+++ b/test/pi-harness-resume.test.ts
@@ -2,7 +2,9 @@ import { test } from "node:test";
import assert from "node:assert/strict";
import { createPiHarness } from "../src/harness/pi-harness.ts";
import type { HarnessTurnInput } from "../src/harness/harness.ts";
-import type { NewEntry, NewTapeRecord } from "../src/sessions/session-store.ts";
+import type { NewEntry, NewTapeRecord, TapeRecord } from "../src/sessions/session-store.ts";
+import { foldTape } from "../src/harness/tape-fold.ts";
+import { zeroUsage } from "../src/harness/replay.ts";
import type { ToolContext } from "../src/tools/primitives.ts";
import type { ScopeId, SessionEntry } from "../src/types.ts";
@@ -75,11 +77,51 @@ test("the pi harness re-runs a retry-safe interrupted call before the model sees
},
];
let seq = 3;
+ const tapeRow = (payload: unknown, i: number): TapeRecord =>
+ ({
+ sessionId: "s1",
+ seq: i,
+ kind: "message",
+ harness: "pi",
+ payload,
+ scopeLabel: scope,
+ createdAt: i,
+ }) as TapeRecord;
+ const servedRows = [
+ { role: "user", content: [{ type: "text", text: "what about the budget?" }], timestamp: 1 },
+ {
+ role: "assistant",
+ content: [{ type: "toolCall", id: "c-budget", name: "history", arguments: { query: "budget", retrySafe: true } }],
+ stopReason: "toolUse",
+ timestamp: 2,
+ usage: zeroUsage(),
+ },
+ {
+ role: "toolResult",
+ toolCallId: "c-budget",
+ toolName: "history",
+ content: [{ type: "text", text: "[exit 143]" }],
+ isError: false,
+ interrupted: true,
+ timestamp: 3,
+ },
+ { role: "assistant", content: [], stopReason: "aborted", timestamp: 4, usage: zeroUsage() },
+ {
+ role: "assistant",
+ content: [{ type: "text", text: "(stopped)" }],
+ stopReason: "stop",
+ timestamp: 5,
+ usage: zeroUsage(),
+ },
+ ].map(tapeRow);
const turn: HarnessTurnInput = {
session: { id: "s1" } as HarnessTurnInput["session"],
input: NOTE,
systemPrompt: "BASE",
history,
+ tapeRows: servedRows,
+ tapeMode: "serve",
+ tapeFold: foldTape(servedRows),
tools: {
async history(q: string) {
queries.push(q);
@@ -128,7 +170,14 @@ test("the pi harness re-runs a retry-safe interrupted call before the model sees
assert.equal(requests.length, 1);
const flattened = JSON.stringify(requests[0]);
assert.ok(!flattened.includes("[interrupted"), "the model never sees an interrupted placeholder");
+ assert.ok(!flattened.includes("[exit 143]"), "the killed attempt's text is gone from the served fold");
const resultAt = flattened.indexOf("shared/q2.md");
+ const stoppedAt = flattened.indexOf("(stopped)");
const noteAt = flattened.indexOf("paused mid-turn and has resumed");
- assert.ok(resultAt > 0 && noteAt > resultAt, "the real tool result precedes the resume note in the model's context");
+ assert.ok(resultAt > 0 && stoppedAt > resultAt, "the re-run result sits beside its call, before the stop message");
+ assert.ok(noteAt > resultAt, "the real tool result precedes the resume note in the model's context");
+ const toolResults = requests[0]!.flatMap((m) =>
+ Array.isArray(m.content) ? m.content.filter((block) => block.type === "tool_result") : [],
+ );
+ assert.equal(toolResults.length, 1, "exactly one tool_result reaches the provider for the retried call");
});
diff --git a/test/pi-harness-tape-sync.test.ts b/test/pi-harness-tape-sync.test.ts
index efffe52cd..4e8974a11 100644
--- a/test/pi-harness-tape-sync.test.ts
+++ b/test/pi-harness-tape-sync.test.ts
@@ -579,3 +579,91 @@ for (const failure of ["acknowledge", "tape"] as const) {
}
});
}
+
+for (const abort of ["shutdown", "stop"] as const) {
+ test(`a Pi tool result recorded after ${abort === "shutdown" ? "shutdown is marked interrupted on entries and tape and leaves its call open" : "a user Stop stays a real answer"}`, async () => {
+ const harness = createPiHarness({ apiKey: "sk-test" });
+ const store = createMemorySessionStore();
+ const session = await store.getOrCreateByThread(`web:${abort}-tool`, "dm", "personal:tester" as ScopeId);
+ const lease = (await store.acquireLease(session.id, "turn")).lease!;
+ const realFetch = globalThis.fetch;
+ let calls = 0;
+ globalThis.fetch = (async () => {
+ if (++calls > 1) return sse(textReplyEvents("done"));
+ const events = textReplyEvents("");
+ events[1] = {
+ type: "content_block_start",
+ index: 0,
+ content_block: { type: "tool_use", id: "read-memory", name: "memory", input: {} },
+ };
+ events[2] = {
+ type: "content_block_delta",
+ index: 0,
+ delta: { type: "input_json_delta", partial_json: JSON.stringify({ action: "read", retrySafe: true }) },
+ };
+ events[4] = { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 3 } };
+ return sse(events);
+ }) as typeof fetch;
+ const shutdown = new AbortController();
+ const cancel = new AbortController();
+ const entries: SessionEntry[] = [];
+ try {
+ await harness.turns.runTurn(
+ turnInput(
+ session.id,
+ { entries: [], tape: [] },
+ {
+ session,
+ runId: `${abort}-tool`,
+ cancel: cancel.signal,
+ shutdown: shutdown.signal,
+ tools: {
+ memoryRead: async () => {
+ if (abort === "shutdown") shutdown.abort();
+ cancel.abort();
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ return "[exit 143]";
+ },
+ } as HarnessTurnInput["tools"],
+ emit: async (entry) => {
+ const saved = await store.append(lease, entry);
+ entries.push(saved);
+ return saved;
+ },
+ tape: (row) => store.appendTape(lease, row),
+ },
+ ),
+ );
+ const result = entries.find((entry) => entry.type === "tool_result");
+ assert.ok(result);
+ assert.deepEqual(
+ (({ interrupted, result }) => ({ interrupted, result }))(result.payload as Record<string, unknown>),
+ abort === "shutdown"
+ ? { interrupted: true, result: "[exit 143]" }
+ : { interrupted: undefined, result: "[exit 143]" },
+ );
+ const tape = await store.getTape(session.id);
+ const tapedResult = tape.find(
+ (row) => row.kind === "message" && (row.payload as { role?: string }).role === "toolResult",
+ );
+ assert.ok(tapedResult);
+ assert.equal(
+ (tapedResult.payload as { interrupted?: unknown }).interrupted,
+ abort === "shutdown" ? true : undefined,
+ );
+ const { openTapeToolCalls, foldTape, lintFold } = await import("../src/harness/tape-fold.ts");
+ assert.deepEqual(openTapeToolCalls(tape).open, abort === "shutdown" ? ["read-memory"] : []);
+ assert.ok(lintFold(foldTape(tape)).ok, "the served fold keeps the result beside its call");
+ const { resumeStrategy } = await import("../src/core/turn-resume.ts");
+ const userSeq = entries.find((entry) => entry.type === "user")!.seq;
+ assert.equal(
+ resumeStrategy(entries, { userSeq, workEntries: entries.filter((e) => e.seq > userSeq).length }).kind,
+ abort === "shutdown" ? "retry" : "note",
+ );
+ } finally {
+ globalThis.fetch = realFetch;
+ await store.releaseLease(lease);
+ await harness.turns.close?.();
+ }
+ });
+}
diff --git a/test/tape-fold.test.ts b/test/tape-fold.test.ts
index a89eef271..4aa79a0df 100644
--- a/test/tape-fold.test.ts
+++ b/test/tape-fold.test.ts
@@ -4,6 +4,8 @@ import {
filterTapeForAudience,
foldTape,
lintFold,
+ openTapeToolCalls,
+ withResumedToolResult,
planTapeSeed,
rehydrateFoldImages,
tapeNeedsInterruptHeal,
@@ -390,6 +392,7 @@ test("audience filter withholds message rows the whole room isn't entitled to, n
content: [{ type: "text", text: "U1's private DM text" }],
isError: false,
timestamp: 4,
+ interrupted: true,
},
scopeLabel: "personal:U1" as ScopeId,
}),
@@ -409,6 +412,7 @@ test("audience filter withholds message rows the whole room isn't entitled to, n
assert.equal(substituted.toolCallId, "c1");
assert.equal(substituted.isError, true);
assert.equal(substituted.content[0].text, INTERRUPTED_TOOL_RESULT);
+ assert.equal((substituted as { interrupted?: unknown }).interrupted, true, "the mark survives redaction");
assert.ok(!JSON.stringify(room).includes("private DM text"), "withheld bytes never survive");
assert.equal(room.filter((r) => r.kind === "context_event").length, 1, "events always survive");
assert.equal(filterTapeForAudience(rows, [], scope, org).length, 0, "empty audience sees nothing");
@@ -775,4 +779,52 @@ test("a toolResult row marked interrupted folds as the interrupted placeholder,
assert.equal(result.content[0]!.text, INTERRUPTED_TOOL_RESULT);
assert.equal(result.isError, true);
assert.ok(lintFold(fold).ok);
+ assert.deepEqual(openTapeToolCalls(rows).open, ["c1"], "a marked result leaves its call open for resume");
+});
+
+test("a later real result for the same call supersedes the interrupted one in place, so a retried call pairs once", () => {
+ const rows = [
+ user("run it"),
+ assistant([{ type: "toolCall", id: "c1", name: "history", arguments: { query: "budget" } }]),
+ row({
+ kind: "message",
+ payload: {
+ role: "toolResult",
+ toolCallId: "c1",
+ toolName: "history",
+ content: [{ type: "text", text: "[exit 143]" }],
+ isError: false,
+ interrupted: true,
+ },
+ }),
+ row({ kind: "message", payload: { role: "assistant", content: [], stopReason: "aborted", timestamp: 4 } }),
+ assistant([{ type: "text", text: "(stopped)" }]),
+ row({
+ kind: "message",
+ payload: {
+ role: "toolResult",
+ toolCallId: "c1",
+ toolName: "history",
+ content: [{ type: "text", text: "flat" }],
+ isError: false,
+ },
+ }),
+ ];
+ const fold = foldTape(rows) as Array<{ role: string; content: Array<{ text: string }>; stopReason?: string }>;
+ assert.deepEqual(
+ fold.map((m) => (m.role === "toolResult" ? `result:${m.content[0]!.text}` : m.role)),
+ ["user", "assistant", "result:flat", "assistant", "assistant"],
+ "the re-run result sits beside its call, not after the stop messages",
+ );
+ assert.ok(lintFold(fold).ok);
+ assert.deepEqual(openTapeToolCalls(rows).open, []);
+ assert.deepEqual(
+ withResumedToolResult(foldTape(rows.slice(0, 5)), rows[5]!.payload).map((m) =>
+ (m as { role: string }).role === "toolResult"
+ ? `result:${(m as { content: Array<{ text: string }> }).content[0]!.text}`
+ : (m as { role: string }).role,
+ ),
+ ["user", "assistant", "result:flat", "assistant", "assistant"],
+ "patching a served fold with the re-run result lands it in the same place",
+ );
});
diff --git a/test/worker-reaper.test.ts b/test/worker-reaper.test.ts
index 98c34fa1e..1255f1ec2 100644
--- a/test/worker-reaper.test.ts
+++ b/test/worker-reaper.test.ts
@@ -245,10 +245,12 @@ test("shutdown cancels before handback and holds both leases until the turn unwi
unwind = resolve;
});
let signal!: AbortSignal;
+ let shutdownSignal: AbortSignal | undefined;
let leaseToken!: string;
const orchestrator = {
async handleTurn(input: OrchestratorInput) {
signal = input.cancel!;
+ shutdownSignal = input.shutdown;
leaseToken = input.runLeaseToken!;
const { lease } = await sessions.acquireLease(session.id);
assert.ok(lease);
@@ -273,6 +275,7 @@ test("shutdown cancels before handback and holds both leases until the turn unwi
});
await sleep(20);
assert.equal(signal.aborted, true, "shutdown reaches the existing cancellation signal immediately");
+ assert.equal(shutdownSignal?.aborted, true, "the turn can tell this cancellation apart from a user Stop");
assert.equal(released, false, "handback waits for the cancellation checkpoint and finally block");
assert.equal((await runs.get(enq.id))?.status, "running");
assert.equal(await runs.claim("replacement", 5_000), null);