Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Resume/stop fast follows: one cause table, flagged resume notes, stop folded into killed calls (#2371)

Regan Bellab7abffe561c
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index d203f7fa1..f2c60bbf1 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -2040,7 +2040,6 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):
let pending: ToolActivity[] = [];
let deliveryFiles: DeliveredFile[] = [];
let posted = false;
- // Whether this turn already rendered its stopped state (a stopped partial reply).
let stoppedShown = false;
const heldPosts = new Map<string, { text: string; activity: ToolActivity }>();
const spillHeldPosts = (): void => {
@@ -2250,7 +2249,6 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):
appendDeliveryFiles(deliveredFilesFromAttachments(payload?.files));
} else if (e.type === "system") {
if ((e.payload as { kind?: unknown } | null)?.kind === "turn_stopped") {
- // The stop record closes the turn: show the stopped state once, never as a message.
spillHeldPosts();
if (pending.length || !stoppedShown)
flushWork("", e.createdAt, !posted, undefined, true, e.seq === undefined ? [] : [e.seq]);
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index a19dcf8d1..76307a057 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -145,7 +145,7 @@ import {
resumeStrategy,
runtimeSwitchNote,
turnAtSeq,
- unrecordedToolResult,
+ unrecordedResultEntries,
} from "./turn-resume.ts";
import type { RecordedTurn } from "./turn-resume.ts";
import {
@@ -2836,22 +2836,9 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
const partial = isRetry ? (recordedTurn ?? findTrailingPartialTurn(visibleHistory, input.text)) : null;
let resumePlan = partial ? resumeStrategy(visibleHistory, partial) : null;
if (partial && resumePlan?.kind === "settle") {
- // A tool call's lost outcome is recorded as its result, so the model reads what happened to it there.
- const unrecorded = resumePlan.calls;
+ const settle = resumePlan;
const settled = await withManagedRosterVersion(() =>
- deps.sessions.appendMany(
- lease,
- unrecorded.map((call) => ({
- type: "tool_result" as const,
- payload: {
- tool: call.tool,
- callId: call.callId,
- isError: true,
- result: unrecordedToolResult(input.resumeCause),
- },
- scopeLabel: scopeId,
- })),
- ),
+ deps.sessions.appendMany(lease, unrecordedResultEntries(settle, input.resumeCause, scopeId)),
);
visibleHistory = filterHistory(forModelContext([...rawEntries, ...settled]));
resumePlan = resumeStrategy(visibleHistory, partial);
@@ -3267,6 +3254,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
if (input.displayText?.trim() && payload.text === input.text && typeof payload.display !== "string")
payload.display = input.displayText;
if ((syntheticPrompt || continuation) && payload.steered !== true) payload.hidden = true;
+ if ((partial || continuation) && !payload.steered && !payload.overheard) payload.resumeNote = true;
return { ...entry, payload };
})();
const appended = await withManagedRosterVersion(() => deps.sessions.append(lease, stored));
diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.ts
index 40da4842e..b7e946fb9 100644
--- a/src/core/orchestrator/types.ts
+++ b/src/core/orchestrator/types.ts
@@ -97,7 +97,6 @@ export interface OrchestratorInput extends Omit<
origin: TurnOrigin;
runId?: string;
attempt?: number;
- /** Why the previous attempt of this run stopped (recorded by the run store); absent on a first attempt. */
resumeCause?: RunStop;
runLeaseToken?: string;
diff --git a/src/core/turn-resume.ts b/src/core/turn-resume.ts
index 3bd878858..f5bd940dd 100644
--- a/src/core/turn-resume.ts
+++ b/src/core/turn-resume.ts
@@ -1,17 +1,9 @@
import { TURN_STOPPED_KIND } from "../harness/replay.ts";
import type { RuntimeChoice } from "../harness/harness.ts";
-import { unrecordedToolResult } from "../harness/context-compaction.ts";
-
-export { unrecordedToolResult };
+import { stopCause, unrecordedToolResult } from "../harness/context-compaction.ts";
import type { RunStop } from "../runs/run-store.ts";
import type { SessionEntry } from "../types.ts";
-import { entryDeliveryKey, isOverheardEntry } from "../sessions/session-store.ts";
-
-const RESUME_HEAD = "[system] Your previous attempt";
-const RUNTIME_HEAD = "[system] Runtime switched";
-const TRIMMED_HEAD = "[system] Context was trimmed";
-/** Resume notes written before the [system] wording; still present in stored history. */
-const LEGACY_NOTE_HEAD = "(system note:";
+import { entryDeliveryKey, isOverheardEntry, type NewEntry } from "../sessions/session-store.ts";
export interface PartialTurn {
userSeq: number;
@@ -22,12 +14,10 @@ function entryText(e: SessionEntry): string {
return String((e.payload as { text?: string } | null)?.text ?? "").trim();
}
-export function isResumeNote(text: string): boolean {
- const t = text.trimStart();
- return [RESUME_HEAD, RUNTIME_HEAD, TRIMMED_HEAD, LEGACY_NOTE_HEAD].some((head) => t.startsWith(head));
+function isResumeNote(e: SessionEntry): boolean {
+ return (e.payload as { resumeNote?: unknown } | null)?.resumeNote === true;
}
-/** A stop record closes its turn, like a final answer: a later attempt must not resume it. */
function isTurnStoppedEntry(e: SessionEntry): boolean {
return e.type === "system" && (e.payload as { kind?: unknown } | null)?.kind === TURN_STOPPED_KIND;
}
@@ -47,8 +37,8 @@ export function findTrailingPartialTurn(entries: readonly SessionEntry[], inputT
}
if (e.type !== "user") continue;
if (isOverheardEntry(e)) continue;
+ if (isResumeNote(e)) continue;
const t = entryText(e);
- if (isResumeNote(t)) continue;
return t.startsWith(text) ? { userSeq: e.seq, workEntries } : null;
}
return null;
@@ -82,7 +72,7 @@ export function turnAtSeq(entries: readonly SessionEntry[], userSeq: number): Re
workEntries += 1;
continue;
}
- if (isOverheardEntry(e) || isResumeNote(entryText(e))) continue;
+ if (isOverheardEntry(e) || isResumeNote(e)) continue;
break;
}
return { userSeq, workEntries, ...(answer ? { answer } : {}) };
@@ -99,7 +89,6 @@ export type ResumeStrategy =
| { kind: "note" }
| { kind: "continue" }
| { kind: "retry"; call: ResumableToolCall }
- /** Tool calls whose outcome was never recorded: record what happened as their results, then continue. */
| { kind: "settle"; calls: Array<{ callId: string; tool: string }> };
export function resumeStrategy(entries: readonly SessionEntry[], partial: PartialTurn): ResumeStrategy {
@@ -120,8 +109,6 @@ export function resumeStrategy(entries: readonly SessionEntry[], partial: Partia
const last = turn.findLast((e) => MODEL_TURN_ENTRY_TYPES.has(e.type) || isTurnStoppedEntry(e));
return last?.type === "tool_result" ? { kind: "continue" } : { kind: "note" };
}
- // Calls with no result at all get one recording what happened; a call whose re-run was itself cut off
- // already has a result, so it only gets the note.
const unrecorded = dangling.flatMap((e) => {
const p = e.payload as { callId?: unknown; tool?: unknown } | null;
return typeof p?.callId === "string" && !withResult.has(p.callId)
@@ -151,38 +138,14 @@ export function resumeStrategy(entries: readonly SessionEntry[], partial: Partia
};
}
-export type ResumeCause = RunStop;
-
-/** Why the previous attempt stopped, from the cause the run store recorded. Never guessed. */
-function causePhrase(cause: ResumeCause | undefined): string {
- switch (cause?.kind) {
- case "shutdown":
- return "a routine platform deploy";
- case "lease_expired":
- return "the worker crashed";
- case "error":
- return cause.code ? `a model-provider call failed (${providerDetail(cause)})` : "an internal error";
- default:
- return "cause not recorded";
- }
-}
-
-function providerDetail(cause: { code?: string; status?: number }): string {
- return `${cause.code}${cause.status !== undefined ? `, HTTP ${cause.status}` : ""}`;
-}
-
const QUIET = "Don't mention this.";
-export function resumeNote(opts?: {
- strategy?: ResumeStrategy;
- backgroundJobs?: boolean;
- cause?: ResumeCause;
-}): string {
- const why = causePhrase(opts?.cause);
+export function resumeNote(opts?: { strategy?: ResumeStrategy; backgroundJobs?: boolean; cause?: RunStop }): string {
+ const why = stopCause(opts?.cause)?.phrase ?? "cause not recorded";
if (opts?.strategy?.kind === "restart")
- return `${RESUME_HEAD} stopped before recording any work — ${why}. Start the request now. ${QUIET}`;
+ return `[system] Your previous attempt stopped before recording any work — ${why}. Start the request now. ${QUIET}`;
return [
- `${RESUME_HEAD} was interrupted mid-turn — ${why}. Continue from the recorded work; don't repeat completed steps. ${QUIET}`,
+ `[system] Your previous attempt was interrupted mid-turn — ${why}. Continue from the recorded work; don't repeat completed steps. ${QUIET}`,
opts?.backgroundJobs
? "Background jobs on your computer kept running — check them with `background` list/poll."
: "",
@@ -191,12 +154,23 @@ export function resumeNote(opts?: {
.join(" ");
}
-/** Told to the model when a task continues on a new runtime, or after its context was cut down. */
+export function unrecordedResultEntries(
+ strategy: Extract<ResumeStrategy, { kind: "settle" }>,
+ stop: RunStop | undefined,
+ scopeLabel: NewEntry["scopeLabel"],
+): NewEntry[] {
+ return strategy.calls.map((call) => ({
+ type: "tool_result",
+ payload: { tool: call.tool, callId: call.callId, isError: true, result: unrecordedToolResult(stop) },
+ scopeLabel,
+ }));
+}
+
export function runtimeSwitchNote(choice: RuntimeChoice | undefined): string {
const head = choice
- ? `${RUNTIME_HEAD} to ${choice.modelId}${choice.fastMode ? " fast" : ""}${
+ ? `[system] Runtime switched to ${choice.modelId}${choice.fastMode ? " fast" : ""}${
choice.effortLevel && choice.effortLevel !== "auto" ? `; effort ${choice.effortLevel}` : ""
}.`
- : `${TRIMMED_HEAD} without a new summary.`;
+ : "[system] Context was trimmed without a new summary.";
return `${head} Continue from the recorded work; don't repeat completed actions or ask the user to restate.`;
}
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index 1682a4cec..5807ab5d4 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -387,8 +387,10 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
orgScopeId: ref.orgScopeId ?? ref.scopeLabel,
sourceScopeId,
});
- if (type === "tool_result" && ref.shutdown?.aborted && isObj(payload))
- payload = { ...payload, interrupted: true, stop: { kind: "shutdown" } };
+ if (type === "tool_result" && isObj(payload)) {
+ if (ref.shutdown?.aborted) payload = { ...payload, interrupted: true, stop: { kind: "shutdown" } };
+ else if (ref.abortSignal?.aborted) payload = { ...payload, stopped: true };
+ }
await ref.emit({ type, payload, scopeLabel });
};
diff --git a/src/harness/claude-harness.ts b/src/harness/claude-harness.ts
index 18961c3d4..5216a4c75 100644
--- a/src/harness/claude-harness.ts
+++ b/src/harness/claude-harness.ts
@@ -721,8 +721,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
const terminal = ref.runtimeHandoff || ref.silentRequested || ref.pausedOnApproval;
const reply = terminal ? "" : streamedText.trim();
await flushThinking();
- if (!terminal && (reply || stopped))
- await recordStoppedTurn(turn, reply, stopped ? stopReason : "because the run was cancelled");
+ if (!terminal) await recordStoppedTurn(turn, reply, stopped ? stopReason : "because the run was cancelled");
return {
reply,
...(!ref.runtimeHandoff || stopped ? { stopped: true as const } : {}),
diff --git a/src/harness/context-compaction.ts b/src/harness/context-compaction.ts
index deb996bc1..5f901bd04 100644
--- a/src/harness/context-compaction.ts
+++ b/src/harness/context-compaction.ts
@@ -1,3 +1,4 @@
+import type { RunStop } from "../runs/run-store.ts";
import { memoryBoundedEntries } from "../memory/context-boundary.ts";
import type { SessionEntry } from "../types.ts";
import { contextSummaryPayload } from "../sessions/session-store.ts";
@@ -20,28 +21,21 @@ function headTailSlice(s: string, maxChars: number, tailChars: number): string {
export const INTERRUPTED_TOOL_RESULT =
"[system] This call was interrupted; its outcome wasn't recorded. Check what happened before retrying.";
-/** What stopped an attempt, as recorded by the run store (`RunStop`) or on an interrupted tool result. */
-export type ToolInterruption = { kind: string; code?: string; status?: number } | undefined;
-
-/** What interrupted a tool call, as the subject of "... interrupted this call". */
-function interruptedBy(cause: ToolInterruption): string | null {
- switch (cause?.kind) {
- case "shutdown":
- return "A routine platform deploy";
- case "lease_expired":
- return "A worker crash";
- case "error":
- return cause.code
- ? `A model-provider failure (${cause.code}${cause.status !== undefined ? `, HTTP ${cause.status}` : ""})`
- : "An internal error";
- default:
- return null;
- }
+const STOP_CAUSES = {
+ shutdown: { phrase: "a routine platform deploy", subject: "A routine platform deploy" },
+ lease_expired: { phrase: "the worker crashed", subject: "A worker crash" },
+ error: { phrase: "an internal error", subject: "An internal error" },
+ provider: { phrase: "a model-provider call failed", subject: "A model-provider failure" },
+};
+
+export function stopCause(stop: RunStop | undefined): { phrase: string; subject: string } | undefined {
+ if (stop?.kind !== "error" || !stop.code) return stop && STOP_CAUSES[stop.kind];
+ const detail = ` (${stop.code}${stop.status !== undefined ? `, HTTP ${stop.status}` : ""})`;
+ return { phrase: STOP_CAUSES.provider.phrase + detail, subject: STOP_CAUSES.provider.subject + detail };
}
-/** The result a tool call gets when the attempt running it stopped before its outcome was recorded. */
-export function unrecordedToolResult(cause: ToolInterruption): string {
- const by = interruptedBy(cause);
+export function unrecordedToolResult(stop: RunStop | undefined): string {
+ const by = stopCause(stop)?.subject;
return by
? `[system] ${by} interrupted this call; its outcome wasn't recorded. Check what happened before retrying. Don't mention this.`
: INTERRUPTED_TOOL_RESULT;
diff --git a/src/harness/harness-shared.ts b/src/harness/harness-shared.ts
index b65e789f1..1510d0389 100644
--- a/src/harness/harness-shared.ts
+++ b/src/harness/harness-shared.ts
@@ -75,11 +75,6 @@ export async function recordSteerIntake(turn: HarnessTurnInput, steer: SteerInta
const STOPPED_FALLBACK_REASON = "unexpectedly";
-/**
- * Records a stopped turn: whatever the model actually wrote before the stop (never a placeholder),
- * then a system entry naming who or what stopped it. Replay shows the model that entry as a
- * "[system] Turn stopped: …" message; it is never a user or assistant entry.
- */
export async function recordStoppedTurn(
turn: HarnessTurnInput,
partial: string,
diff --git a/src/harness/mock-harness.ts b/src/harness/mock-harness.ts
index a3c171501..04522a8e9 100644
--- a/src/harness/mock-harness.ts
+++ b/src/harness/mock-harness.ts
@@ -1,4 +1,3 @@
-import { isResumeNote } from "../core/turn-resume.ts";
import {
defineHarness,
type Harness,
@@ -182,7 +181,7 @@ export function createMockHarness(): Harness {
} else if (command0 === "!boom-always" || boomAlwaysSessions.has(turn.session.id)) {
boomAlwaysSessions.add(turn.session.id);
throw new Error("boom: simulated turn fault");
- } else if (isResumeNote(command0) && resumePostSessions.has(turn.session.id)) {
+ } else if (resumePostSessions.has(turn.session.id)) {
const msg = resumePostSessions.get(turn.session.id)!;
resumePostSessions.delete(turn.session.id);
await turn.emit({
@@ -198,7 +197,7 @@ export function createMockHarness(): Harness {
});
usedTool = true;
reply = r.ok ? "(posted after resume)" : `[not sent] ${r.message ?? "failed"}`;
- } else if (isResumeNote(command0) && shutdownResumeSessions.has(turn.session.id)) {
+ } else if (shutdownResumeSessions.has(turn.session.id)) {
shutdownResumeSessions.delete(turn.session.id);
reply = "finished after resume";
} else if (command0 === "!work-until-shutdown") {
diff --git a/src/harness/replay.ts b/src/harness/replay.ts
index c177ba01a..a9aa21355 100644
--- a/src/harness/replay.ts
+++ b/src/harness/replay.ts
@@ -1,3 +1,4 @@
+import type { RunStop } from "../runs/run-store.ts";
import type {
AssistantMessage,
ImageContent,
@@ -17,28 +18,25 @@ import { contextSummaryPayload } from "../sessions/session-store.ts";
import { isoFromTs, messageTag } from "../util/message-tag.ts";
import { isObj } from "../util/objects.ts";
-/** System entry kind recording that a turn was stopped and who or what stopped it. */
export const TURN_STOPPED_KIND = "turn_stopped";
-/** How a stopped turn reads to the model on replay. `reason` reads after "Turn stopped", e.g. "by user". */
function turnStoppedNote(reason: string): string {
return `[system] Turn stopped ${reason}.`;
}
-/** The result of a tool call that was still running when its turn was stopped. */
function stoppedToolResult(reason: string): string {
return `[system] Turn stopped ${reason} while this call was running; its outcome wasn't recorded. Check what happened before retrying.`;
}
-/**
- * For each stop record that cut off running tool calls, the stop explanation becomes those calls'
- * results, and the stop record itself adds nothing more.
- */
+function cutOffByStop(result: SessionEntry | undefined): boolean {
+ return !result || (result.payload as { stopped?: unknown } | null)?.stopped === true;
+}
+
function stoppedToolCalls(
history: readonly SessionEntry[],
resultByCallId: ReadonlyMap<string, SessionEntry>,
-): { results: Map<string, string>; folded: Set<SessionEntry> } {
- const results = new Map<string, string>();
+): { reasons: Map<string, string>; folded: Set<SessionEntry> } {
+ const reasons = new Map<string, string>();
const folded = new Set<SessionEntry>();
let open: string[] = [];
for (const e of history) {
@@ -49,17 +47,16 @@ function stoppedToolCalls(
steered?: unknown;
overheard?: unknown;
};
- // Steers and overheard channel traffic arrive mid-turn; only a new ask (or a hidden resume note) ends it.
if (e.type === "user" && p.steered !== true && p.overheard !== true) open = [];
- else if (e.type === "tool_call" && typeof p.callId === "string" && !resultByCallId.has(p.callId))
+ else if (e.type === "tool_call" && typeof p.callId === "string" && cutOffByStop(resultByCallId.get(p.callId)))
open.push(p.callId);
else if (e.type === "system" && p.kind === TURN_STOPPED_KIND && typeof p.reason === "string") {
if (open.length) folded.add(e);
- for (const callId of open) results.set(callId, stoppedToolResult(p.reason));
+ for (const callId of open) reasons.set(callId, p.reason);
open = [];
}
}
- return { results, folded };
+ return { reasons, folded };
}
export { INTERRUPTED_TOOL_RESULT };
@@ -280,7 +277,7 @@ function toolResultMessage(
if (!re) return { ...base, content: text(missing), isError: true, timestamp: at };
const p = (re.payload ?? {}) as {
interrupted?: unknown;
- stop?: { kind?: unknown };
+ stop?: RunStop;
isError?: unknown;
result?: unknown;
wire?: ToolResultWire;
@@ -288,9 +285,7 @@ function toolResultMessage(
if (p.interrupted === true)
return {
...base,
- content: text(
- typeof p.stop?.kind === "string" ? unrecordedToolResult({ kind: p.stop.kind }) : INTERRUPTED_TOOL_RESULT,
- ),
+ content: text(unrecordedToolResult(p.stop)),
isError: true,
timestamp: re.createdAt,
};
@@ -423,9 +418,17 @@ export function reconstructMessagesFromHistory(history: readonly SessionEntry[])
}
out.push(m);
if (m.role !== "assistant") continue;
- for (const c of m.content)
- if (c.type === "toolCall")
- out.push(toolResultMessage(c, resultByCallId.get(c.id), m.timestamp, stopped.results.get(c.id)));
+ for (const c of m.content) {
+ if (c.type !== "toolCall") continue;
+ const reason = stopped.reasons.get(c.id);
+ const re = resultByCallId.get(c.id);
+ if (reason === undefined) out.push(toolResultMessage(c, re, m.timestamp));
+ else if (!re) out.push(toolResultMessage(c, undefined, m.timestamp, stoppedToolResult(reason)));
+ else {
+ const result = toolResultMessage(c, re, m.timestamp);
+ out.push({ ...result, content: [...result.content, { type: "text", text: turnStoppedNote(reason) }] });
+ }
+ }
}
if (out[0] && out[0].role !== "user")
out.unshift({ role: "user", content: [{ type: "text", text: AGENT_OPENED_TEXT }], timestamp: out[0].timestamp });
diff --git a/src/runs/run-signal-store.ts b/src/runs/run-signal-store.ts
index 842a0c2c6..68ca902f3 100644
--- a/src/runs/run-signal-store.ts
+++ b/src/runs/run-signal-store.ts
@@ -15,7 +15,6 @@ export interface RunSignal {
queuedRunId?: string;
callId?: string;
result?: ClientToolResult;
- /** abort only: who or what stopped the run, in words, for the stopped session's record. */
reason?: string;
}
diff --git a/src/runs/run-store.ts b/src/runs/run-store.ts
index a9d5a2015..532d098bb 100644
--- a/src/runs/run-store.ts
+++ b/src/runs/run-store.ts
@@ -19,7 +19,6 @@ export interface RunDeliveryState {
editRef?: string;
}
-/** Why a run's previous attempt stopped, recorded when the run is handed back to the queue. */
export type RunStop =
{ kind: "shutdown" } | { kind: "lease_expired" } | { kind: "error"; code?: string; status?: number };
@@ -41,7 +40,6 @@ export interface Run {
createdAt: number;
startedAt: number | null;
finishedAt: number | null;
- /** Why the previous attempt stopped; null on a run's first attempt. */
lastStop?: RunStop | null;
}
@@ -78,7 +76,6 @@ export interface RunStore {
heartbeat(runId: string, leaseToken: string, ttlMs: number): Promise<boolean>;
- /** Hands a running run back to the queue. `stop` records why the attempt ended; omit it when no attempt started. */
releaseLease(runId: string, leaseToken: string, stop?: RunStop): Promise<boolean>;
complete(runId: string, leaseToken: string, result: TurnResult): Promise<boolean>;
diff --git a/src/runs/worker.ts b/src/runs/worker.ts
index 931f00c54..a451ee774 100644
--- a/src/runs/worker.ts
+++ b/src/runs/worker.ts
@@ -278,7 +278,6 @@ export function createWorker(deps: WorkerDeps): Worker {
};
}
-/** What a resumed attempt is told about why this one failed: the typed provider code and status, never raw error text. */
function runStopFor(err: unknown): RunStop {
if (err instanceof ProviderTurnError)
return { kind: "error", code: err.code, ...(err.status !== undefined ? { status: err.status } : {}) };
diff --git a/src/sessions/session-syscalls.ts b/src/sessions/session-syscalls.ts
index 81b69333b..4ba40951c 100644
--- a/src/sessions/session-syscalls.ts
+++ b/src/sessions/session-syscalls.ts
@@ -277,7 +277,6 @@ function lastAssistantText(entries: readonly SessionEntry[]): string | undefined
const e = entries[i]!;
const stop = e.type === "system" ? (e.payload as { kind?: unknown; reason?: unknown } | null) : null;
if (stop?.kind === TURN_STOPPED_KIND) {
- // A partial reply recorded just before the stop is still the last thing said.
const before = entries[i - 1];
const partial = before?.type === "assistant" ? entryText(before) : "";
return (
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index 471c282e1..5b97dd18e 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -4164,6 +4164,7 @@ test("a tool result recorded after shutdown fires is marked interrupted; user St
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.equal(payload.stopped === true, abort === "stop", `${abort}: only a Stop marks the result as cut off`);
assert.deepEqual(strategy(emitted), { kind: "continue" });
}
});
diff --git a/test/claude-harness-turn.test.ts b/test/claude-harness-turn.test.ts
index c1b4f0477..787546389 100644
--- a/test/claude-harness-turn.test.ts
+++ b/test/claude-harness-turn.test.ts
@@ -812,3 +812,25 @@ for (const shutdown of [false, true]) {
}
});
}
+
+test("Claude records the stop when the worker cancels a turn before any output", async () => {
+ const waiting = Promise.withResolvers<void>();
+ const cancel = new AbortController();
+ currentScript = async function* () {
+ waiting.resolve();
+ await new Promise((resolve) => cancel.signal.addEventListener("abort", resolve, { once: true }));
+ yield* [];
+ };
+ const harness = createClaudeHarness({});
+ const { turn, entries } = harnessTurn({ input: "go", cancel: cancel.signal });
+ const running = harness.turns.runTurn(turn);
+ await waiting.promise;
+ cancel.abort();
+ const result = await running;
+ assert.equal(result.stopped, true);
+ assert.equal(result.reply, "");
+ assert.deepEqual(
+ entries.filter((e) => e.type !== "user").map((e) => e.payload),
+ [{ kind: "turn_stopped", reason: "because the run was cancelled" }],
+ );
+});
diff --git a/test/replay.test.ts b/test/replay.test.ts
index 7d7f1c6bd..d6a247939 100644
--- a/test/replay.test.ts
+++ b/test/replay.test.ts
@@ -643,6 +643,38 @@ test("overheard traffic between a cut-off call and the stop does not split the s
assert.ok(!text.includes("[system] Turn stopped by user."), "no separate stop note");
});
+test("a call killed by a Stop keeps its output and carries the stop in its result, once", () => {
+ const history: SessionEntry[] = [
+ ent("user", { text: "deploy it" }, 1),
+ ent("tool_call", { tool: "execute", callId: "c1", command: "make deploy" }, 2),
+ ent("tool_result", { callId: "c1", result: "[stderr]\nKilled\n\n[exit 137]", stopped: true }, 3),
+ ent("system", { kind: "turn_stopped", reason: "by user" }, 4),
+ ent("user", { text: "what happened?" }, 5),
+ ];
+ const msgs = reconstructMessagesFromHistory(history);
+ assertValidWire(msgs);
+ assert.deepEqual(
+ msgs.map((m) => m.role),
+ ["user", "assistant", "toolResult", "user"],
+ );
+ const result = msgs[2] as { content: unknown[] };
+ assert.deepEqual(
+ result.content.map((c) => (c as { text: string }).text),
+ ["[stderr]\nKilled\n\n[exit 137]", "[system] Turn stopped by user."],
+ "the recorded output is kept and the stop is part of that call's result",
+ );
+ assert.equal(JSON.stringify(msgs).split("Turn stopped by user").length, 2, "the stop appears once");
+});
+
+test("a result recorded while a Stop fired keeps its text when no stop was recorded", () => {
+ const history: SessionEntry[] = [
+ ent("user", { text: "deploy it" }, 1),
+ ent("tool_call", { tool: "execute", callId: "c1", command: "make deploy" }, 2),
+ ent("tool_result", { callId: "c1", result: "[exit 137]", stopped: true }, 3),
+ ];
+ assert.match(JSON.stringify(reconstructMessagesFromHistory(history)), /\[exit 137\]/);
+});
+
test("a tool result cut off by a deploy says so in its replayed result", () => {
const history: SessionEntry[] = [
ent("user", { text: "deploy it" }, 1),
diff --git a/test/tool-call-resume.test.ts b/test/tool-call-resume.test.ts
index 04ab0ae5a..854140459 100644
--- a/test/tool-call-resume.test.ts
+++ b/test/tool-call-resume.test.ts
@@ -4,7 +4,7 @@ import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createOrchestrator, type OrchestratorInput } from "../src/core/orchestrator.ts";
-import { isResumeNote, type ResumableToolCall } from "../src/core/turn-resume.ts";
+import type { ResumableToolCall } from "../src/core/turn-resume.ts";
import { INTERRUPTED_TOOL_RESULT } from "../src/harness/context-compaction.ts";
import { createIdentityService } from "../src/identity/identity-service.ts";
import { createMemoryConfigStore } from "../src/resolution/config-store.ts";
@@ -321,7 +321,7 @@ test("a retry whose dangling call was marked retry-safe re-runs it silently inst
assert.equal(received.length, 1);
const turn = received[0]!;
assert.deepEqual(turn.resumeToolCall, { callId: "c-budget", tool: "history", input: { query: "budget" } });
- assert.ok(isResumeNote(turn.input));
+ assert.match(turn.input, /^\[system\] Your previous attempt/);
assert.match(turn.input, /interrupted mid-turn/);
const entries = await sessions.getEntries(sessionId);
@@ -344,7 +344,7 @@ for (const [label, payload] of [
assert.equal(received.length, 1);
const turn = received[0]!;
assert.equal(turn.resumeToolCall, undefined);
- assert.ok(isResumeNote(turn.input));
+ assert.match(turn.input, /^\[system\] Your previous attempt/);
const entries = await sessions.getEntries(sessionId);
assert.deepEqual(
entries.map((e) => e.type),
diff --git a/test/turn-resume.test.ts b/test/turn-resume.test.ts
index b240e921d..2d5a0e22c 100644
--- a/test/turn-resume.test.ts
+++ b/test/turn-resume.test.ts
@@ -2,13 +2,12 @@ import { test } from "node:test";
import assert from "node:assert/strict";
import {
findTrailingPartialTurn,
- isResumeNote,
resumeNote,
resumeStrategy,
runtimeSwitchNote,
turnAtSeq,
- unrecordedToolResult,
} from "../src/core/turn-resume.ts";
+import { unrecordedToolResult } from "../src/harness/context-compaction.ts";
import type { SessionEntry } from "../src/types.ts";
function ent(type: SessionEntry["type"], payload: unknown, seq: number): SessionEntry {
@@ -18,6 +17,7 @@ function ent(type: SessionEntry["type"], payload: unknown, seq: number): Session
const user = (text: string, seq: number) => ent("user", { text }, seq);
const overheard = (text: string, seq: number) =>
ent("user", { overheard: true, ts: String(seq), name: "Alice", text }, seq);
+const resumeEntry = (seq: number) => ent("user", { text: resumeNote(), hidden: true, resumeNote: true }, seq);
const assistant = (text: string, seq: number) => ent("assistant", { text }, seq);
const toolCall = (seq: number) => ent("tool_call", { tool: "execute", callId: `c${seq}`, command: "make build" }, seq);
const toolResult = (seq: number) => ent("tool_result", { callId: `c${seq - 1}`, result: "ok" }, seq);
@@ -53,7 +53,7 @@ test("findTrailingPartialTurn returns null for empty input text and empty ledger
});
test("a trailing resume note from a prior dead resume is skipped, reaching the real user entry", () => {
- const entries = [user("build and deploy the release", 1), toolCall(2), user(resumeNote(), 3), toolCall(4)];
+ const entries = [user("build and deploy the release", 1), toolCall(2), resumeEntry(3), toolCall(4)];
const found = findTrailingPartialTurn(entries, "build and deploy the release");
assert.deepEqual(found, { userSeq: 1, workEntries: 2 }, "the note itself is not work");
});
@@ -64,7 +64,7 @@ test("an attempt that died before recording ANY work reports workEntries 0", ()
});
test("prior resume notes alone are NOT work — repeated no-work deaths still report 0", () => {
- const entries = [user("build and deploy the release", 1), user(resumeNote(), 2)];
+ const entries = [user("build and deploy the release", 1), resumeEntry(2)];
const found = findTrailingPartialTurn(entries, "build and deploy the release");
assert.deepEqual(found, { userSeq: 1, workEntries: 0 });
});
@@ -82,7 +82,10 @@ test("platform rails and render-only rows are NOT work — only tool rows replay
});
test("a prior no-work retry's restart note is skipped — later retries anchor on the human's entry", () => {
- const entries = [user("build and deploy the release", 1), user(resumeNote({ strategy: { kind: "restart" } }), 2)];
+ const entries = [
+ user("build and deploy the release", 1),
+ ent("user", { text: resumeNote({ strategy: { kind: "restart" } }), resumeNote: true }, 2),
+ ];
const found = findTrailingPartialTurn(entries, "build and deploy the release");
assert.deepEqual(found, { userSeq: 1, workEntries: 0 }, "provenance stays on the original, not attempt 2's prompt");
});
@@ -112,30 +115,23 @@ test("an empty-reply completed turn still counts as completed (assistant entry w
assert.equal(findTrailingPartialTurn(entries, "do the thing"), null);
});
-test("resumeNote is recognized by isResumeNote and mentions background jobs only when offered", () => {
- assert.ok(isResumeNote(resumeNote()));
- assert.ok(isResumeNote(resumeNote({ backgroundJobs: true })));
+test("the resume note mentions background jobs only when offered", () => {
assert.doesNotMatch(resumeNote(), /background/i);
assert.match(resumeNote({ backgroundJobs: true }), /`background` list\/poll/);
- assert.ok(isResumeNote(runtimeSwitchNote(undefined)));
- assert.ok(isResumeNote(runtimeSwitchNote({ harnessId: "pi", modelId: "claude-opus-5-5" })));
- assert.ok(!isResumeNote("build and deploy the release"));
});
test("the no-work wording promises nothing recorded, and neither wording re-sends the input", () => {
const restart = resumeNote({ strategy: { kind: "restart" } });
- assert.ok(isResumeNote(restart));
assert.doesNotMatch(restart, /recorded work|Continue/);
assert.match(restart, /Start the request now/);
for (const note of [resumeNote(), restart]) assert.doesNotMatch(note, /build and deploy the release/);
});
-test("isResumeNote recognizes the pre-rename notes recorded in existing ledgers", () => {
- const legacy =
- "(system note: the platform restarted mid-turn and interrupted your previous attempt at the request above. Continue.)";
- assert.ok(isResumeNote(legacy));
- const entries = [user("build and deploy the release", 1), toolCall(2), user(legacy, 3)];
+test("a resume note in the ledger is skipped by its flag, not its text", () => {
+ const entries = [user("build and deploy the release", 1), toolCall(2), resumeEntry(3)];
assert.deepEqual(findTrailingPartialTurn(entries, "build and deploy the release"), { userSeq: 1, workEntries: 1 });
+ const typed = [user("build and deploy the release", 1), toolCall(2), user(resumeNote(), 3)];
+ assert.equal(findTrailingPartialTurn(typed, "build and deploy the release"), null, "typed text is a new request");
});
test("turnAtSeq carries the answer the attempt recorded, so a retry can replay it", () => {
@@ -163,7 +159,7 @@ test("turnAtSeq reads through the resume note and the overheard traffic of its o
user("mine", 1),
toolCall(2),
overheard("chatter", 3),
- user(resumeNote(), 4),
+ resumeEntry(4),
toolCall(5),
assistant("finished", 6),
];
@@ -258,14 +254,9 @@ test("resumeStrategy restarts when the dead attempt recorded no work", () => {
assert.deepEqual(resumeStrategy([user("x", 1)], { userSeq: 1, workEntries: 0 }), { kind: "restart" });
});
-test("the resume notes state the recorded cause and are recognized as resume notes", () => {
- const note = resumeNote();
- assert.ok(isResumeNote(note));
- assert.match(note, /cause not recorded/);
- assert.match(note, /Don't mention this/);
- assert.ok(
- isResumeNote(resumeNote({ strategy: { kind: "retry", call: { callId: "c1", tool: "history", input: {} } } })),
- );
+test("the resume note states the recorded cause", () => {
+ assert.match(resumeNote(), /cause not recorded/);
+ assert.match(resumeNote(), /Don't mention this/);
});
test("a tool call whose outcome was lost records the cause as its own result", () => {
@@ -312,7 +303,7 @@ test("resumeStrategy continues silently only when every call is answered and the
assert.deepEqual(resumeStrategy([user("go", 1), toolCall(2), toolResult(3), steer("also", 4)], partial), {
kind: "note",
});
- assert.deepEqual(resumeStrategy([user("go", 1), toolCall(2), toolResult(3), user(resumeNote(), 4)], partial), {
+ assert.deepEqual(resumeStrategy([user("go", 1), toolCall(2), toolResult(3), resumeEntry(4)], partial), {
kind: "note",
});
assert.deepEqual(resumeStrategy([user("go", 1), toolCall(2), killed(3)], partial), { kind: "note" });
diff --git a/test/turn-retry-replay.test.ts b/test/turn-retry-replay.test.ts
index 1191f16e9..72d953f97 100644
--- a/test/turn-retry-replay.test.ts
+++ b/test/turn-retry-replay.test.ts
@@ -1,4 +1,3 @@
-import { isResumeNote } from "../src/core/turn-resume.ts";
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
@@ -298,7 +297,7 @@ test("a resume whose recorded work ends at a tool result asks the harness to con
assert.equal(retry.status, "ok");
assert.deepEqual(continued, [undefined, true], "unchanged inventories preserve assistant continuation");
assert.doesNotMatch(environments[1]!, /## Where you are|Environment changes/);
- assert.ok(isResumeNote(turns[1]!), "the note still travels as the fallback input");
+ assert.match(turns[1]!, /^\[system\] Your previous attempt/, "the note still travels as the fallback input");
assert.equal((await asks()).length, 1);
});