[orchestrator-v2] fix(orchestrator): Restore Claude session continuity for resume, wake, and idle release (#3860)

Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
authored and Julius Marminge committed 2026-07-20 16:08:10 +02:00
1 parent 90c6401268
commit 0aebed2ca6
16 files changed
+2159 -88

No files matched your search

+1 -1
View File
@@ -25,7 +25,7 @@
"test": "vp test run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
"@anthropic-ai/claude-agent-sdk": "^0.3.205",
"@connectrpc/connect": "1.7.0",
"@connectrpc/connect-node": "1.7.0",
"@cursor/sdk": "1.0.22",
File diff suppressed because it is too large. Load diff
@@ -346,6 +346,9 @@ function permissionRequestOptionsFromFrame(
...(options.description === undefined ? {} : { description: options.description }),
toolUseID: options.toolUseID,
...(options.agentID === undefined ? {} : { agentID: options.agentID }),
// Replay transcripts predate the SDK requiring requestId on canUseTool
// options; the adapter only reads toolUseID, so a derived id is safe.
requestId: options.toolUseID,
};
}
@@ -463,6 +466,16 @@ function makeReplayQueryRunner(transcript: ClaudeAgentSdkReplayTranscript): Clau
request.input,
permissionRequestOptionsFromFrame(request),
);
if (result === null) {
const error = new ClaudeReplayUnexpectedOutboundError({
scenario: transcript.scenario,
cursor,
expectedType: "permission.response",
actual: null,
});
failure = error;
throw error;
}
assertNextOutboundFrame(makeClaudePermissionResponseFrame(result));
continue;
}
@@ -38,6 +38,7 @@ import {
ProviderDriverKind,
type ProviderInstanceId,
type ProviderRequestKind,
type ProviderThreadId,
type ThreadId,
} from "@t3tools/contracts";
@@ -100,6 +101,10 @@ import {
type ProviderAdapterDriver,
type ProviderAdapterDriverCreateInput,
} from "../ProviderAdapterDriver.ts";
import {
type ProviderContinuationRequest,
ProviderContinuationRequests,
} from "../ProviderContinuationRequests.ts";
import {
makeSubagentChildThread,
makeSubagentConversationArtifacts,
@@ -315,6 +320,16 @@ function closeClaudeQuery(queryRuntime: ClaudeQuery) {
});
}
// Iterate the Query itself, not query[Symbol.asyncIterator]() (the raw
// sdkMessages generator). The raw generator's return() queues behind the
// in-flight read of the next CLI message and never settles while the CLI is
// idle, deadlocking stream interruption (and with it, session scope close).
// Query.return() runs cleanup() first, which closes the transport and
// unblocks that read.
export function claudeQueryMessages(queryRuntime: ClaudeQuery): AsyncIterable<SDKMessage, void> {
return { [Symbol.asyncIterator]: () => queryRuntime };
}
export interface ClaudeAgentSdkLoggedQueryOptions {
readonly model: ClaudeAgentSdkQueryOptions["model"];
readonly tools: ClaudeAgentSdkQueryOptions["tools"];
@@ -508,7 +523,7 @@ export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer<
});
return {
messages: Stream.fromAsyncIterable(queryRuntime, (cause) =>
messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) =>
queryRunnerError(cause, "fromAsyncIterable"),
).pipe(
Stream.tap((message) =>
@@ -1406,6 +1421,19 @@ function claudeSubagentResultText(output: ClaudeNativeToolOutput): string {
return claudeNativeToolOutputText(output);
}
function isClaudeSubagentAsyncLaunchAck(output: ClaudeNativeToolOutput): boolean {
const value = claudeNativeToolOutputValue(output);
if (typeof value === "object" && value !== null) {
if ("isAsync" in value && value.isAsync === true) {
return true;
}
if ("status" in value && value.status === "async_launched") {
return true;
}
}
return claudeSubagentResultText(output).startsWith("Async agent launched successfully.");
}
function webSearchPatternsFromClaudeTool(input: {
readonly toolInput: ClaudeNativeToolInput;
readonly output: ClaudeNativeToolOutput;
@@ -1654,7 +1682,9 @@ function terminalStatusFromResult(
"completed" | "interrupted" | "failed" | "cancelled"
> {
if (message.subtype === "success") {
return "completed";
// The SDK reports API-level failures (401 auth, 529 overloaded, …) as
// subtype "success" with is_error set; the turn produced no real work.
return message.is_error ? "failed" : "completed";
}
const errorText = message.errors.join("\n").toLowerCase();
if (errorText.includes("interrupt")) {
@@ -1670,6 +1700,28 @@ function isClaudeActiveSteeringAbortResult(message: SDKResultMessage): boolean {
return message.terminal_reason === "aborted_streaming";
}
function providerFailureFromResult(
message: SDKResultMessage,
): OrchestrationV2ProviderFailure | null {
if (message.subtype !== "success") {
return makeProviderFailure({
message: message.errors.join("\n"),
code: message.subtype,
class: "provider_error",
});
}
if (!message.is_error) {
return null;
}
const apiErrorStatus = message.api_error_status ?? null;
return makeProviderFailure({
message: message.result,
code: apiErrorStatus === null ? "sdk_result_error" : `api_error_${apiErrorStatus}`,
class: "provider_error",
retryable: apiErrorStatus === 429 || apiErrorStatus === 529 ? true : null,
});
}
function buildAssistantArtifacts(input: {
readonly idAllocator: IdAllocatorV2Shape;
readonly turnInput: ProviderAdapterV2TurnInput;
@@ -1823,12 +1875,19 @@ export interface ClaudeAdapterV2Options {
readonly fileSystem: FileSystem.FileSystem;
readonly idAllocator: IdAllocatorV2Shape;
readonly queryRunner: ClaudeAgentSdkQueryRunnerShape;
/** Sink for wake-turn continuation requests; defaults to dropping them. */
readonly continuationRequests?: {
readonly offer: (request: ProviderContinuationRequest) => Effect.Effect<void>;
};
}
export function makeClaudeAdapterV2(
adapterOptions: ClaudeAdapterV2Options,
): ProviderAdapterV2Shape {
const { attachmentsDir, fileSystem, idAllocator, queryRunner } = adapterOptions;
const continuationRequests = adapterOptions.continuationRequests ?? {
offer: () => Effect.void,
};
return ProviderAdapterV2.of({
instanceId: adapterOptions.instanceId,
@@ -1857,6 +1916,31 @@ export function makeClaudeAdapterV2(
const pendingRuntimeRequests = yield* Ref.make(
new Map<string, PendingClaudeRuntimeRequest>(),
);
// Background-task wake support. Claude can settle a turn while a
// local_bash background task keeps running; the CLI later re-invokes
// the model (a "wake turn") on the same query stream with no active
// provider turn. These refs track pending background tasks, buffer
// wake messages until a continuation run attaches, and remember where
// to dispatch that run.
const lastTurnRouteByNativeThread = yield* Ref.make(
new Map<
string,
{ readonly threadId: ThreadId; readonly providerThreadId: ProviderThreadId }
>(),
);
const pendingBackgroundTaskIds = yield* Ref.make(new Set<string>());
// Subagent registry that survives turn settle: a background subagent
// (Agent with run_in_background) can complete after the root turn
// ended, and its task_notification must both count as wake evidence
// and hydrate the original subagent node instead of being dropped.
const sessionSubagentsByTaskId = yield* Ref.make(new Map<string, ActiveClaudeSubagent>());
const wakeBuffers = yield* Ref.make(
new Map<
string,
{ readonly messages: ReadonlyArray<SDKMessage>; readonly detail: string | null }
>(),
);
const requestedContinuations = yield* Ref.make(new Set<string>());
const runtimeContext = yield* Effect.context<never>();
const runFork = Effect.runForkWith(runtimeContext);
const runPromise = Effect.runPromiseWith(runtimeContext);
@@ -2060,17 +2144,45 @@ export function makeClaudeAdapterV2(
OrchestrationV2ExecutionNode["status"],
"running" | "completed" | "failed" | "cancelled"
>;
readonly reopen?: boolean;
}) {
// The session registry lets a wake-replay turn (fresh context maps)
// hydrate a subagent that was created by an earlier, settled turn.
const existingSubagent =
input.context.subagentsByTaskId.get(input.taskId) ??
(input.toolUseId === undefined
? undefined
: input.context.subagentsByToolUseId.get(input.toolUseId));
: input.context.subagentsByToolUseId.get(input.toolUseId)) ??
(yield* Ref.get(sessionSubagentsByTaskId)).get(input.taskId);
if (existingSubagent === undefined && input.status !== "running") {
return;
}
// Status is monotone with one exception: task_started for a known
// task id is an authoritative CLI lifecycle event (SendMessage to a
// completed subagent resumes it and re-emits task_started with the
// same id), so it may re-open a terminal entry. A late or
// out-of-order task_progress must not.
const isReopen =
input.reopen === true &&
existingSubagent !== undefined &&
existingSubagent.task.status !== "running" &&
input.status === "running";
if (
existingSubagent !== undefined &&
existingSubagent.task.status !== "running" &&
input.status === "running" &&
!isReopen
) {
return;
}
const lifecycleChanged =
existingSubagent === undefined || existingSubagent.task.status !== input.status;
existingSubagent === undefined ||
existingSubagent.task.status !== input.status ||
// A drain-replayed resume task_started finds the registry entry
// already pre-opened to running by bufferWakeMessage while the
// projection node still holds the old terminal status; re-emit
// the node lifecycle for authoritative task_started updates.
(input.reopen === true && input.status === "running");
const now = yield* DateTime.now;
const nativeItemId = `task:${input.taskId}`;
@@ -2098,8 +2210,19 @@ export function makeClaudeAdapterV2(
const turnItemOrdinal =
existingSubagent?.turnItemOrdinal ??
(yield* resolveItemOrdinal(input.context, `${nativeItemId}:subagent`));
// A resumed subagent's previous final answer and progress no longer
// represent its outcome; the next task_progress/task_notification
// carry the new ones.
const priorTask =
existingSubagent === undefined
? undefined
: isReopen
? (({ progress: _staleProgress, ...rest }) => ({ ...rest, result: null }))(
existingSubagent.task,
)
: existingSubagent.task;
const task = {
...(existingSubagent?.task ?? {
...(priorTask ?? {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
@@ -2122,6 +2245,18 @@ export function makeClaudeAdapterV2(
startedAt: now,
}),
status: input.status,
// A reopen replayed under a continuation run re-attributes the
// subagent to that run. RunExecutionService routes parent-thread
// events by runId, and only the resuming run's ingestion fiber is
// guaranteed alive (the launch run's fiber stops once its child
// subagents terminalize); attribution also enrolls the subagent
// in the resuming run's active-child tracking so its fiber
// outlives settle until the resumed task completes.
...(input.reopen === true &&
input.status === "running" &&
existingSubagent !== undefined
? { runId: input.context.input.runId }
: {}),
...(input.prompt === undefined ? {} : { prompt: input.prompt }),
...(input.title === undefined ? {} : { title: input.title }),
...(input.progress === undefined ? {} : { progress: input.progress }),
@@ -2149,6 +2284,25 @@ export function makeClaudeAdapterV2(
if (input.toolUseId !== undefined) {
input.context.subagentsByToolUseId.set(input.toolUseId, subagent);
}
// The same terminal protection, applied atomically: a concurrent
// fiber (live stream vs continuation drain) may have terminalized
// the registry entry after this update's lookup read it. A resume
// re-open (task_started) bypasses it only when the registered entry
// is still the terminal generation the lookup resolved; if a
// concurrent fiber installed a newer terminal entry meanwhile, the
// re-open must not clobber its result.
yield* Ref.update(sessionSubagentsByTaskId, (current) => {
const registered = current.get(input.taskId);
if (
registered !== undefined &&
registered.task.status !== "running" &&
input.status === "running" &&
!(isReopen && registered === existingSubagent)
) {
return current;
}
return new Map(current).set(input.taskId, subagent);
});
if (existingSubagent === undefined) {
const childThread = makeSubagentChildThread({
@@ -2181,10 +2335,13 @@ export function makeClaudeAdapterV2(
driver: CLAUDE_PROVIDER,
node: {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
parentNodeId: input.context.input.rootNodeId,
rootNodeId: input.context.input.rootNodeId,
// Parenting stays with the launch run's root node even on
// wake-replay; runId follows task.runId, which a reopen
// re-attributes to the resuming run (see task construction).
threadId: task.threadId,
runId: task.runId,
parentNodeId: task.parentNodeId,
rootNodeId: task.parentNodeId,
kind: "subagent",
status: input.status,
countsForRun: false,
@@ -2755,6 +2912,138 @@ export function makeClaudeAdapterV2(
}
});
const clearPendingBackgroundTask = (taskId: string) =>
Ref.modify(pendingBackgroundTaskIds, (current) => {
if (!current.has(taskId)) {
return [false, current] as const;
}
const updated = new Set(current);
updated.delete(taskId);
return [true, updated] as const;
});
const bufferWakeMessage = Effect.fnUntraced(function* (wakeInput: {
readonly nativeThreadId: string;
readonly message: SDKMessage;
}) {
const message = wakeInput.message;
const isNotification =
message.type === "system" && message.subtype === "task_notification";
// Only notifications for tracked tasks count as wake evidence: a
// pending local_bash background task, or a session-registered
// subagent that is still running (Agent with run_in_background
// settling after the root turn). A stray notification for an
// unknown task is dropped as before instead of triggering a
// spurious continuation.
const isPendingTaskNotification =
isNotification && (yield* Ref.get(pendingBackgroundTaskIds)).has(message.task_id);
const isPendingSubagentNotification =
isNotification &&
!isPendingTaskNotification &&
(yield* Ref.get(sessionSubagentsByTaskId)).get(message.task_id)?.task.status ===
"running";
// A task_started for a session-registered subagent that races past
// settle is a resume (SendMessage to a completed subagent re-emits
// task_started with the same task id). Re-open the registry entry
// so the resumed run pins idle and its eventual notification counts
// as wake evidence again, and buffer the frame so the continuation
// drain re-opens the projection row; it does not itself offer a
// continuation.
const isKnownSubagentTaskStarted =
message.type === "system" &&
message.subtype === "task_started" &&
(yield* Ref.get(sessionSubagentsByTaskId)).has(message.task_id);
if (
isKnownSubagentTaskStarted &&
message.type === "system" &&
message.subtype === "task_started"
) {
const now = yield* DateTime.now;
yield* Ref.update(sessionSubagentsByTaskId, (current) => {
const registered = current.get(message.task_id);
if (registered === undefined || registered.task.status === "running") {
return current;
}
const { progress: _staleProgress, ...priorTask } = registered.task;
return new Map(current).set(message.task_id, {
...registered,
task: {
...priorTask,
status: "running",
result: null,
completedAt: null,
updatedAt: now,
},
});
});
}
const isWakeEvidence =
isPendingTaskNotification ||
isPendingSubagentNotification ||
isKnownSubagentTaskStarted ||
message.type === "assistant" ||
message.type === "user" ||
message.type === "result";
if (!isWakeEvidence) {
return;
}
const notificationSummary =
isNotification && typeof message.summary === "string" && message.summary.length > 0
? message.summary
: null;
yield* Ref.update(wakeBuffers, (current) => {
const existing = current.get(wakeInput.nativeThreadId);
const updated = new Map(current);
updated.set(wakeInput.nativeThreadId, {
messages: [...(existing?.messages ?? []), message],
detail: notificationSummary ?? existing?.detail ?? null,
});
return updated;
});
// Request a continuation run once per wake, when the wake turn has
// either announced the finished task or fully settled. Earlier
// messages only buffer; the continuation turn drains them.
if (
!isPendingTaskNotification &&
!isPendingSubagentNotification &&
message.type !== "result"
) {
return;
}
const route = (yield* Ref.get(lastTurnRouteByNativeThread)).get(wakeInput.nativeThreadId);
if (route === undefined) {
yield* Effect.logWarning("orchestration-v2.claude-wake-turn-unroutable", {
providerSessionId: input.providerSessionId,
nativeThreadId: wakeInput.nativeThreadId,
});
return;
}
const shouldOffer = yield* Ref.modify(requestedContinuations, (current) => {
if (current.has(wakeInput.nativeThreadId)) {
return [false, current] as const;
}
const updated = new Set(current);
updated.add(wakeInput.nativeThreadId);
return [true, updated] as const;
});
if (!shouldOffer) {
return;
}
const detail =
(yield* Ref.get(wakeBuffers)).get(wakeInput.nativeThreadId)?.detail ?? null;
yield* Effect.logInfo("orchestration-v2.claude-wake-turn-detected", {
providerSessionId: input.providerSessionId,
threadId: route.threadId,
providerThreadId: route.providerThreadId,
});
yield* continuationRequests.offer({
threadId: route.threadId,
providerThreadId: route.providerThreadId,
driver: CLAUDE_PROVIDER,
detail,
});
});
const handleSdkMessage = Effect.fnUntraced(function* (input: {
readonly query: ClaudeAgentSdkQuerySession;
readonly message: SDKMessage;
@@ -2767,6 +3056,7 @@ export function makeClaudeAdapterV2(
const message = input.message;
const context = yield* Ref.get(activeTurn);
if (context === null) {
yield* bufferWakeMessage({ nativeThreadId: liveQuery.nativeThreadId, message });
return;
}
@@ -2777,6 +3067,9 @@ export function makeClaudeAdapterV2(
if (message.type === "system" && message.subtype === "task_started") {
if (isClaudeNonSubagentTask(message)) {
context.ignoredTaskIds.add(message.task_id);
yield* Ref.update(pendingBackgroundTaskIds, (current) =>
new Set(current).add(message.task_id),
);
} else {
yield* updateClaudeSubagentNode({
context,
@@ -2785,13 +3078,21 @@ export function makeClaudeAdapterV2(
...(message.prompt === undefined ? {} : { prompt: message.prompt }),
title: message.description,
status: "running",
reopen: true,
});
}
}
if (message.type === "system" && message.subtype === "task_progress") {
const progress = message.description.trim();
if (progress.length > 0 && !context.ignoredTaskIds.has(message.task_id)) {
const isBackgroundTask = (yield* Ref.get(pendingBackgroundTaskIds)).has(
message.task_id,
);
if (
progress.length > 0 &&
!context.ignoredTaskIds.has(message.task_id) &&
!isBackgroundTask
) {
yield* updateClaudeSubagentNode({
context,
taskId: message.task_id,
@@ -2803,7 +3104,10 @@ export function makeClaudeAdapterV2(
}
if (message.type === "system" && message.subtype === "task_notification") {
if (!context.ignoredTaskIds.has(message.task_id)) {
// A wake-replay turn has empty ignoredTaskIds, so the session-level
// background registry is the durable ignore signal across turns.
const wasBackgroundTask = yield* clearPendingBackgroundTask(message.task_id);
if (!wasBackgroundTask && !context.ignoredTaskIds.has(message.task_id)) {
yield* updateClaudeSubagentNode({
context,
taskId: message.task_id,
@@ -2834,7 +3138,18 @@ export function makeClaudeAdapterV2(
for (const { toolResult, output } of claudeToolResultEntriesFromMessage(message)) {
const subagent = context.subagentsByToolUseId.get(toolResult.tool_use_id);
if (subagent !== undefined) {
// A resume task_started reuses the resuming tool call's
// tool_use_id (e.g. SendMessage), whose tool_result only
// acknowledges delivery. Only the Agent launch's tool_result may
// terminalize the subagent, and Agent tool_uses never enter
// toolCalls (they project as subagent rows instead).
if (subagent !== undefined && !context.toolCalls.has(toolResult.tool_use_id)) {
// A background Agent launch resolves its tool_use immediately
// with an async-launch ACK while the task keeps running; only
// the eventual task_notification terminalizes the subagent.
if (isClaudeSubagentAsyncLaunchAck(output)) {
continue;
}
const result = claudeSubagentResultText(output);
yield* updateClaudeSubagentNode({
context,
@@ -2886,7 +3201,12 @@ export function makeClaudeAdapterV2(
return;
}
const resultText = resultTextFromSdkMessage(message);
// An is_error result's text is the error message; it belongs on the
// terminal-failure item, not on a synthetic assistant message.
const resultText =
message.type === "result" && message.subtype === "success" && message.is_error
? null
: resultTextFromSdkMessage(message);
if (
context.assistant.emittedNativeItemIds.size === 0 &&
context.assistant.fallbackText.length === 0 &&
@@ -2909,19 +3229,12 @@ export function makeClaudeAdapterV2(
next.delete(context.providerTurnId);
return next;
});
const resultFailure = interrupted ? null : providerFailureFromResult(message);
yield* finalizeActiveTurn({
context,
status: interrupted ? "interrupted" : terminalStatusFromResult(message),
completedAt,
...(message.subtype === "success" || interrupted
? {}
: {
failure: makeProviderFailure({
message: message.errors.join("\n"),
code: message.subtype,
class: "provider_error",
}),
}),
...(resultFailure === null ? {} : { failure: resultFailure }),
});
}
});
@@ -3052,16 +3365,15 @@ export function makeClaudeAdapterV2(
yield* existing.query.close.pipe(Effect.ignore);
}
const openedWithResume = yield* Ref.modify(openedNativeThreads, (current) => {
const hasOpenedThread = current.has(nativeThreadId);
if (hasOpenedThread) {
return [true, current];
}
const updated = new Set(current);
updated.add(nativeThreadId);
return [false, updated];
});
const shouldResume = resumeSessionAt !== undefined || openedWithResume;
const openedWithResume = (yield* Ref.get(openedNativeThreads)).has(nativeThreadId);
// openedNativeThreads is per session instance and is lost when the
// provider session is idle-released. A prior persisted provider turn
// proves the native session already exists, so the query must resume
// it; reopening with a fixed session id makes the CLI fail fast with
// "Session ID ... is already in use".
const hasPersistedProviderTurn = turnInput.providerTurnOrdinal > 1;
const shouldResume =
resumeSessionAt !== undefined || openedWithResume || hasPersistedProviderTurn;
const querySession = yield* queryRunner.open({
threadId: turnInput.threadId,
providerSessionId: input.providerSessionId,
@@ -3082,6 +3394,17 @@ export function makeClaudeAdapterV2(
...(shouldInstallClaudePermissionCallback(queryPolicy) ? { canUseTool } : {}),
}),
});
// Marked only after a successful open: a failed create must not
// leave the runtime believing the native session exists, or the
// retry would resume a session that was never created.
yield* Ref.update(openedNativeThreads, (current) => {
if (current.has(nativeThreadId)) {
return current;
}
const updated = new Set(current);
updated.add(nativeThreadId);
return updated;
});
const closed = yield* Deferred.make<void, never>();
const context: ClaudeLiveQueryContext = {
nativeThreadId,
@@ -3129,6 +3452,14 @@ export function makeClaudeAdapterV2(
detail: `Claude provider turn ${currentTurn.providerTurnId} is still active.`,
});
}
yield* Ref.update(lastTurnRouteByNativeThread, (current) => {
const updated = new Map(current);
updated.set(nativeThreadId, {
threadId: turnInput.threadId,
providerThreadId: turnInput.providerThread.id,
});
return updated;
});
const context: ActiveClaudeTurnContext = {
input: turnInput,
nativeTurnId,
@@ -3147,15 +3478,24 @@ export function makeClaudeAdapterV2(
subagentsByToolUseId: new Map(),
subagentNodesByTaskId: new Map(),
};
const userMessage = yield* makeClaudeUserMessageWithAttachments({
text: applyClaudePromptEffortPrefix(
turnInput.message.text,
compileClaudeModelSelection(turnInput.modelSelection).promptEffort,
),
attachments: turnInput.message.attachments,
attachmentsDir,
fileSystem,
});
// Continuation turns attach to the wake output the CLI already
// produced instead of prompting it again: drain the buffered wake
// messages into this turn and let any still-streaming messages
// follow live. The continuation prompt text never reaches the CLI.
const isContinuationTurn =
turnInput.message.createdBy === "agent" &&
turnInput.message.creationSource === "provider";
const userMessage = isContinuationTurn
? null
: yield* makeClaudeUserMessageWithAttachments({
text: applyClaudePromptEffortPrefix(
turnInput.message.text,
compileClaudeModelSelection(turnInput.modelSelection).promptEffort,
),
attachments: turnInput.message.attachments,
attachmentsDir,
fileSystem,
});
const querySession = yield* openQuery(turnInput, nativeThreadId);
yield* Ref.set(activeTurn, context);
yield* emitProviderEvent({
@@ -3167,7 +3507,48 @@ export function makeClaudeAdapterV2(
completedAt: null,
}),
});
yield* querySession.query.offer(userMessage);
if (userMessage !== null) {
// A user turn that races a wake leaves the buffer alone: the
// continuation run the worker queued behind this run drains it
// afterwards with correct attribution.
yield* querySession.query.offer(userMessage);
return;
}
const drained = yield* Ref.modify(wakeBuffers, (current) => {
const entry = current.get(nativeThreadId);
if (entry === undefined) {
return [[] as ReadonlyArray<SDKMessage>, current] as const;
}
const updated = new Map(current);
updated.delete(nativeThreadId);
return [entry.messages, updated] as const;
});
yield* Ref.update(requestedContinuations, (current) => {
const updated = new Set(current);
updated.delete(nativeThreadId);
return updated;
});
if (drained.length === 0) {
// Spurious continuation (buffer already lost with a recycled
// session, or a duplicate request): settle immediately instead
// of leaving a run waiting on a prompt that was never sent.
const completedAt = yield* DateTime.now;
yield* finalizeActiveTurn({ context, status: "completed", completedAt });
return;
}
// Replay any result message last: a result finalizes the turn, and
// replaying it before the rest would drop them back into the wake
// buffer and request another continuation.
const resultMessages = drained.filter((entry) => entry.type === "result");
for (const entry of drained) {
if (entry.type !== "result") {
yield* handleSdkMessage({ query: querySession.query, message: entry });
}
}
const lastResult = resultMessages.at(-1);
if (lastResult !== undefined) {
yield* handleSdkMessage({ query: querySession.query, message: lastResult });
}
},
(effect, turnInput) =>
effect.pipe(
@@ -3338,6 +3719,23 @@ export function makeClaudeAdapterV2(
providerSessionId: input.providerSessionId,
providerSession: session,
events: Stream.fromEffectRepeat(Queue.take(events)),
hasPendingBackgroundWork: Effect.gen(function* () {
if ((yield* Ref.get(pendingBackgroundTaskIds)).size > 0) {
return true;
}
for (const subagent of (yield* Ref.get(sessionSubagentsByTaskId)).values()) {
if (subagent.task.status === "running") {
return true;
}
}
const buffers = yield* Ref.get(wakeBuffers);
for (const entry of buffers.values()) {
if (entry.messages.length > 0) {
return true;
}
}
return false;
}),
ensureThread: Effect.fn("ClaudeAdapterV2.ensureThread")(
function* (threadInput: ProviderAdapterV2EnsureThreadInput) {
const createdAt = yield* DateTime.now;
@@ -3610,6 +4008,7 @@ export const ClaudeAdapterV2Driver: ProviderAdapterDriver<
const idAllocator = yield* IdAllocatorV2;
const queryRunner = yield* ClaudeAgentSdkQueryRunner;
const serverConfig = yield* ServerConfig;
const continuationRequests = yield* ProviderContinuationRequests;
const baseEnvironment = mergeProviderInstanceEnvironment(environment, hostEnvironment);
const claudeEnvironment = yield* makeClaudeEnvironment(config, baseEnvironment);
return makeClaudeAdapterV2({
@@ -3620,6 +4019,7 @@ export const ClaudeAdapterV2Driver: ProviderAdapterDriver<
fileSystem,
idAllocator,
queryRunner,
continuationRequests,
});
},
(effect, input) =>
@@ -3643,6 +4043,7 @@ const makeDefaultClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2.layer")(function*
const idAllocator = yield* IdAllocatorV2;
const queryRunner = yield* ClaudeAgentSdkQueryRunner;
const serverConfig = yield* ServerConfig;
const continuationRequests = yield* ProviderContinuationRequests;
return makeClaudeAdapterV2({
instanceId: CLAUDE_DEFAULT_INSTANCE_ID,
@@ -3652,6 +4053,7 @@ const makeDefaultClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2.layer")(function*
fileSystem,
idAllocator,
queryRunner,
continuationRequests,
});
});
@@ -233,6 +233,7 @@ function makeProviderAdapter(
readonly providerSessionId: ProviderSessionId;
}) => Effect.Effect<void>;
readonly hasPendingBackgroundWork?: Effect.Effect<boolean>;
readonly hangSessionScopeClose?: boolean;
} = {},
): ProviderAdapterV2Shape {
return {
@@ -273,6 +274,12 @@ function makeProviderAdapter(
closeCount: current.closeCount + 1,
})),
);
if (options.hangSessionScopeClose === true) {
// Registered last so it runs first on scope close, wedging the
// close before the closeCount finalizer, like a provider process
// that never yields its message stream.
yield* Effect.addFinalizer(() => Effect.never);
}
return {
instanceId: ProviderInstanceId.make("codex"),
@@ -327,6 +334,7 @@ function makeTestLayer(input: {
}) => Effect.Effect<void>;
readonly failReleaseEventWrites?: boolean;
readonly hasPendingBackgroundWork?: Effect.Effect<boolean>;
readonly hangSessionScopeClose?: boolean;
}) {
const configuredEventSinkLayer = input.failReleaseEventWrites
? FailingReleaseEventSinkLayer
@@ -340,6 +348,9 @@ function makeTestLayer(input: {
...(input.hasPendingBackgroundWork === undefined
? {}
: { hasPendingBackgroundWork: input.hasPendingBackgroundWork }),
...(input.hangSessionScopeClose === undefined
? {}
: { hangSessionScopeClose: input.hangSessionScopeClose }),
}),
);
return Layer.mergeAll(
@@ -940,6 +951,53 @@ it.effect("ProviderSessionManagerV2 releases idle sessions without sweeping all
}),
);
it.effect("ProviderSessionManagerV2 persists release when session scope close hangs", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
const effect = Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const idAllocator = yield* IdAllocatorV2;
const manager = yield* ProviderSessionManagerV2;
const projectionStore = yield* ProjectionStoreV2;
const now = yield* DateTime.now;
const threadId = yield* idAllocator.allocate.thread({
fixtureName: "provider-session-manager-hung-close",
projectId: yield* idAllocator.allocate.project({
fixtureName: "provider-session-manager-hung-close",
}),
});
const providerSessionId = yield* idAllocator.allocate.providerSession({
providerInstanceId: modelSelection.instanceId,
threadId,
});
yield* eventSink.write({
events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
});
yield* manager.open({
threadId,
providerSessionId,
modelSelection,
runtimePolicy,
});
yield* TestClock.adjust("1 second");
yield* Effect.yieldNow;
assert.isTrue(Option.isNone(yield* manager.get(providerSessionId)));
yield* TestClock.adjust("30 seconds");
yield* Effect.yieldNow;
const projection = yield* projectionStore.getThreadProjection(threadId);
assert.equal(projection.providerSessions.at(-1)?.status, "stopped");
assert.equal((yield* Ref.get(state)).closeCount, 0);
});
yield* effect.pipe(
Effect.provide(makeTestLayer({ state, idleTimeoutMs: 1000, hangSessionScopeClose: true })),
);
}),
);
it.effect("ProviderSessionManagerV2 defers idle release while background work is pending", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
@@ -41,6 +41,7 @@ import { ProjectionStoreV2 } from "./ProjectionStore.ts";
const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
const DEFAULT_MAX_IDLE_PIN_MS = 4 * 60 * 60 * 1000;
const RELEASE_SCOPE_CLOSE_TIMEOUT_MS = 30 * 1000;
export const ProviderSessionReleaseReason = Schema.Literals([
"idle_timeout",
@@ -512,7 +513,49 @@ export const layerWithOptions = (
input.detail ?? `Provider session released: ${input.reason}.`,
);
}
const closeExit = yield* Effect.exit(Scope.close(entry.scope, Exit.void));
// Scope close can wedge on a misbehaving adapter finalizer
// (e.g. a provider process that never yields its message
// stream). Time-box it so release still persists released
// events and leaves a diagnosable trail instead of silently
// parking the session as "ready" forever.
const closeFiber = yield* Scope.close(entry.scope, Exit.void).pipe(
Effect.exit,
Effect.forkDetach({ startImmediately: true }),
);
const closeExit = yield* Fiber.join(closeFiber).pipe(
Effect.timeoutOption(RELEASE_SCOPE_CLOSE_TIMEOUT_MS),
);
if (Option.isNone(closeExit)) {
yield* Effect.logWarning(
"orchestration-v2.provider-session-scope-close-timeout",
{
providerSessionId: input.providerSessionId,
reason: input.reason,
timeoutMs: RELEASE_SCOPE_CLOSE_TIMEOUT_MS,
},
);
yield* Fiber.join(closeFiber).pipe(
Effect.flatMap((exit) =>
Exit.isFailure(exit)
? Effect.logWarning(
"orchestration-v2.provider-session-scope-close-failed",
{
providerSessionId: input.providerSessionId,
reason: input.reason,
cause: exit.cause,
},
)
: Effect.logInfo(
"orchestration-v2.provider-session-scope-close-completed-late",
{
providerSessionId: input.providerSessionId,
reason: input.reason,
},
),
),
Effect.forkDetach,
);
}
yield* writeReleasedSessionEvents({
entry,
reason: input.reason,
@@ -522,8 +565,8 @@ export const layerWithOptions = (
entry,
reason: input.reason,
});
if (Exit.isFailure(closeExit)) {
return yield* Effect.failCause(closeExit.cause);
if (Option.isSome(closeExit) && Exit.isFailure(closeExit.value)) {
return yield* Effect.failCause(closeExit.value.cause);
}
}),
}),
@@ -69,7 +69,12 @@ describe("orchestrator replay fixture contract", () => {
throw new Error(`${fixture.name}/${provider.driver} must start with thread.create`);
}
assert.equal(firstCommand.threadId, materialized.projectionThreadIds[0]);
assert.equal(materialized.commands.length, fixture.buildInput().steps.length + 1);
// advance_clock only moves the test clock; every other input step
// dispatches a command.
const commandProducingSteps = fixture
.buildInput()
.steps.filter((step) => step.type !== "advance_clock");
assert.equal(materialized.commands.length, commandProducingSteps.length + 1);
assert.isAtLeast(materialized.steps.length, materialized.commands.length);
assert.equal(typeof provider.assertOutput, "function");
@@ -0,0 +1,19 @@
{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"claude_idle_resume","metadata":{"prompts":["Respond with exactly: idle resume first turn complete","Respond with exactly: idle resume second turn complete"],"model":"claude-sonnet-4-6","nativeSessionId":"1d1e5e55-1041-4e40-8e40-000000000001","queryMode":"restart","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"manual-replay-from-thread-d0fe9018 runs 6-8 (idle-released session must reopen with resume, 2026-07-02T20:46:05Z)"}}
{"type":"expect_outbound","label":"query.open:1","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"1d1e5e55-1041-4e40-8e40-000000000001"}}}
{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Respond with exactly: idle resume first turn complete"},"parent_tool_use_id":null}}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"96353a54-8984-4e77-8060-b1dc6b030cf6","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"ffbfcc28-dd82-4c2a-a99f-58e5af6e393e","session_id":"1d1e5e55-1041-4e40-8e40-000000000001"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"96353a54-8984-4e77-8060-b1dc6b030cf6","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"bbf29fb9-d4b3-4ab2-b0e3-9d2aa833099c","session_id":"1d1e5e55-1041-4e40-8e40-000000000001"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-claude_idle_resume","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"f468f37d-e0e6-43cf-bcd7-71e34045083e","session_id":"1d1e5e55-1041-4e40-8e40-000000000001"}}
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01DKpWHtEMhugcX5nJwxKfeM","type":"message","role":"assistant","content":[{"type":"text","text":"idle resume first turn complete"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11792,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"1d1e5e55-1041-4e40-8e40-000000000001","uuid":"7e96c9db-0543-4276-b97d-ced7f53b93c4"}}
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"28620e49-aa10-42fa-a7f9-768c9c79c093","session_id":"1d1e5e55-1041-4e40-8e40-000000000001"}}
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2809,"duration_api_ms":2523,"num_turns":1,"result":"idle resume first turn complete","stop_reason":"end_turn","session_id":"1d1e5e55-1041-4e40-8e40-000000000001","total_cost_usd":0.0036516,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11792,"output_tokens":7,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":7,"cache_read_input_tokens":11792,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":7,"cacheReadInputTokens":11792,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.0036516,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"d88c31ae-a8fd-4ed4-a168-96cfd3b0edd7"}}
{"type":"runtime_exit","status":"success"}
{"type":"expect_outbound","label":"query.open:2","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"1d1e5e55-1041-4e40-8e40-000000000001"}}}
{"type":"expect_outbound","label":"prompt.offer:2","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Respond with exactly: idle resume second turn complete"},"parent_tool_use_id":null}}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"4db1e61e-de28-49ee-b7ef-c375670d0aae","hook_name":"SessionStart:resume","hook_event":"SessionStart","uuid":"66e900fe-b02e-41a0-ac08-92260125b13d","session_id":"377e06a0-fe46-420e-bfaa-b4b9fcc8b871"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"4db1e61e-de28-49ee-b7ef-c375670d0aae","hook_name":"SessionStart:resume","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"03f2754d-daee-4128-b180-c1a39faa03f0","session_id":"377e06a0-fe46-420e-bfaa-b4b9fcc8b871"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-claude_idle_resume","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"5e1d64c9-a2ca-4ad1-ba2c-546ba18d1785","session_id":"1d1e5e55-1041-4e40-8e40-000000000001"}}
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01CiTVsN2HCfqr6Ge166z8hv","type":"message","role":"assistant","content":[{"type":"text","text":"idle resume second turn complete"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11811,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":7,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"1d1e5e55-1041-4e40-8e40-000000000001","uuid":"e821cdff-a217-4fb3-b1d0-f89387dbac41"}}
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"21e2dfd3-a7f5-48d1-a343-ddb1be3198c8","session_id":"1d1e5e55-1041-4e40-8e40-000000000001"}}
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2103,"duration_api_ms":1644,"num_turns":1,"result":"idle resume second turn complete","stop_reason":"end_turn","session_id":"1d1e5e55-1041-4e40-8e40-000000000001","total_cost_usd":0.0036573,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11811,"output_tokens":7,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":7,"cache_read_input_tokens":11811,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":7,"cacheReadInputTokens":11811,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.0036573,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"a876579c-a18c-4237-ba4e-6105b2162bbb"}}
{"type":"runtime_exit","status":"success"}
@@ -0,0 +1,25 @@
import type { OrchestratorFixtureInput } from "../shared.ts";
export const CLAUDE_IDLE_RESUME_PROMPT_1 = "Respond with exactly: idle resume first turn complete";
export const CLAUDE_IDLE_RESUME_PROMPT_2 = "Respond with exactly: idle resume second turn complete";
/**
* Regression for the stale-session first-message failure (threads 47763f5e
* run 10 and d0fe9018 runs 7/8, 2026-07-01/02): the provider session manager
* idle-releases the session runtime between turns, wiping the adapter's
* in-memory openedNativeThreads set. The next turn must reopen the SDK query
* with `resume` (the persisted provider thread proves the native session
* exists) — a create-style `sessionId` open fails against an existing
* session and burned the user's first message after every idle gap.
*/
export function claudeIdleResumeInput(): OrchestratorFixtureInput {
return {
steps: [
{ type: "message", text: CLAUDE_IDLE_RESUME_PROMPT_1 },
// Past ProviderSessionManager's 30-minute idle timeout: the reaper
// releases the live session entry and closes the SDK query.
{ type: "advance_clock", duration: "31 minutes" },
{ type: "message", text: CLAUDE_IDLE_RESUME_PROMPT_2 },
],
};
}
@@ -0,0 +1,39 @@
import { assert } from "@effect/vitest";
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
import {
assertBaseProjection,
assertSemanticProjectionIntegrity,
assertUserMessagesInclude,
projectionFor,
} from "../shared.ts";
import { CLAUDE_IDLE_RESUME_PROMPT_1, CLAUDE_IDLE_RESUME_PROMPT_2 } from "./input.ts";
export function assertClaudeIdleResumeOutput(
result: OrchestratorV2ScenarioResult,
transcript: ProviderReplayTranscript,
) {
// The transcript itself enforces the regression: query.open:2 expects a
// `resume`-style open. A create-style reopen (the bug) fails the replay at
// the boundary before these assertions run. Both runs must complete — the
// pre-fix behavior burned the first post-idle message as a failed run.
assertBaseProjection({
result,
transcript,
runCount: 2,
runStatuses: ["completed", "completed"],
});
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertUserMessagesInclude(projection, [CLAUDE_IDLE_RESUME_PROMPT_1, CLAUDE_IDLE_RESUME_PROMPT_2]);
const assistantTexts = projection.turnItems.flatMap((item) =>
item.type === "assistant_message" ? [item.text] : [],
);
assert.deepEqual(assistantTexts, [
"idle resume first turn complete",
"idle resume second turn complete",
]);
}
@@ -0,0 +1,10 @@
{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"claude_result_is_error","metadata":{"prompts":["Say hello before the credentials expire.","Try again now that auth is back."],"model":"claude-sonnet-4-6","nativeSessionId":"aa401aa4-e597-4e40-8e40-1e401e401e40","queryMode":"streaming","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"manual-replay-from-thread-47763f5e run 1 (subtype success + is_error 401 result, 2026-07-01T20:56:54Z)"}}
{"type":"expect_outbound","label":"query.open","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"aa401aa4-e597-4e40-8e40-1e401e401e40"}}}
{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Say hello before the credentials expire."},"parent_tool_use_id":null}}}
{"type":"emit_inbound","label":"system:init:1","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.183","cwd":"/tmp/claude-replay-claude_result_is_error","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"aa401aa4-0000-4000-8000-000000000001","session_id":"aa401aa4-e597-4e40-8e40-1e401e401e40"}}
{"type":"emit_inbound","label":"assistant:synthetic_auth_error","frame":{"type":"assistant","message":{"id":"7f28a402-6d4c-491e-abbb-2b3c231a06f0","container":null,"model":"<synthetic>","role":"assistant","stop_details":null,"stop_reason":"stop_sequence","stop_sequence":"","type":"message","usage":{"input_tokens":0,"output_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":null,"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":null,"iterations":null,"speed":null},"content":[{"type":"text","text":"Failed to authenticate. API Error: 401 Invalid authentication credentials"}],"context_management":null},"parent_tool_use_id":null,"session_id":"aa401aa4-e597-4e40-8e40-1e401e401e40","uuid":"aa401aa4-0000-4000-8000-000000000002","error":"authentication_failed"}}
{"type":"emit_inbound","label":"result:1_is_error","frame":{"type":"result","subtype":"success","is_error":true,"api_error_status":401,"duration_ms":2116,"duration_api_ms":0,"num_turns":1,"result":"Failed to authenticate. API Error: 401 Invalid authentication credentials","stop_reason":"stop_sequence","session_id":"aa401aa4-e597-4e40-8e40-1e401e401e40","total_cost_usd":0,"usage":{"input_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":0,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"modelUsage":{},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"aa401aa4-0000-4000-8000-000000000003"}}
{"type":"expect_outbound","label":"prompt.offer:2","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Try again now that auth is back."},"parent_tool_use_id":null}}}
{"type":"emit_inbound","label":"assistant:recovered","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01iserrorfixture1","type":"message","role":"assistant","content":[{"type":"text","text":"claude result is_error fixture recovered"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"aa401aa4-e597-4e40-8e40-1e401e401e40","uuid":"aa401aa4-0000-4000-8000-000000000004"}}
{"type":"emit_inbound","label":"result:2_success","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":4000,"duration_api_ms":3500,"num_turns":1,"result":"claude result is_error fixture recovered","stop_reason":"end_turn","session_id":"aa401aa4-e597-4e40-8e40-1e401e401e40","total_cost_usd":0.001,"usage":{"input_tokens":2,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":2,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":1,"output_tokens":1,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":2,"outputTokens":2,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.001,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"aa401aa4-0000-4000-8000-000000000005"}}
{"type":"runtime_exit","status":"success"}
@@ -0,0 +1,22 @@
import {
CLAUDE_RESULT_IS_ERROR_FOLLOW_UP,
CLAUDE_RESULT_IS_ERROR_PROMPT,
type OrchestratorFixtureInput,
} from "../shared.ts";
/**
* Recorded from thread 47763f5e run 1 (2026-07-01): the SDK reports API-level
* failures (401 auth, 529 overloaded, …) as a result with subtype "success"
* but is_error: true, alongside a synthetic-model assistant message carrying
* the error text. The run must finalize as failed with the API error on the
* failure item — not as a completed run — and the session must stay usable
* for the next turn.
*/
export function claudeResultIsErrorInput(): OrchestratorFixtureInput {
return {
steps: [
{ type: "message", text: CLAUDE_RESULT_IS_ERROR_PROMPT },
{ type: "message", text: CLAUDE_RESULT_IS_ERROR_FOLLOW_UP },
],
};
}
@@ -0,0 +1,71 @@
import { assert } from "@effect/vitest";
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
import {
assertBaseProjection,
assertSemanticProjectionIntegrity,
assertUserMessagesInclude,
CLAUDE_RESULT_IS_ERROR_FOLLOW_UP,
CLAUDE_RESULT_IS_ERROR_PROMPT,
projectionFor,
} from "../shared.ts";
const AUTH_ERROR_TEXT = "Failed to authenticate. API Error: 401 Invalid authentication credentials";
export function assertClaudeResultIsErrorOutput(
result: OrchestratorV2ScenarioResult,
transcript: ProviderReplayTranscript,
) {
assertBaseProjection({
result,
transcript,
runCount: 2,
runStatuses: ["failed", "completed"],
});
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertUserMessagesInclude(projection, [
CLAUDE_RESULT_IS_ERROR_PROMPT,
CLAUDE_RESULT_IS_ERROR_FOLLOW_UP,
]);
// Run 1 ended with subtype "success" + is_error: the run and its provider
// turn must be failed, and the failure must preserve the API error verbatim
// (message + status code), not a generic wrapper string.
const failedRun = projection.runs.find((run) => run.ordinal === 1);
assert.isDefined(failedRun);
assert.equal(failedRun?.status, "failed");
const failedTurn = projection.providerTurns.find(
(turn) => turn.status !== "completed" && turn.status !== "running",
);
assert.equal(failedTurn?.status, "failed");
const errorItem = projection.turnItems.find(
(item) => item.runId === failedRun?.id && item.type === "error",
);
assert.isDefined(errorItem);
if (errorItem?.type !== "error") throw new Error("expected error item");
assert.equal(errorItem.failure.message, AUTH_ERROR_TEXT);
assert.equal(errorItem.failure.code, "api_error_401");
assert.equal(errorItem.failure.class, "provider_error");
// The SDK's synthetic assistant message still surfaces as ordinary
// assistant text (that is what the stream contained), but the error text
// must not be duplicated a second time via the result-text fallback.
const run1AssistantTexts = projection.turnItems.flatMap((item) =>
item.runId === failedRun?.id && item.type === "assistant_message" ? [item.text] : [],
);
assert.deepEqual(run1AssistantTexts, [AUTH_ERROR_TEXT]);
// The failed turn must not poison the thread: the follow-up run reuses the
// same open query and completes.
const recoveredRun = projection.runs.find((run) => run.ordinal === 2);
assert.isDefined(recoveredRun);
assert.equal(recoveredRun?.status, "completed");
const recoveredTexts = projection.turnItems.flatMap((item) =>
item.runId === recoveredRun?.id && item.type === "assistant_message" ? [item.text] : [],
);
assert.deepEqual(recoveredTexts, ["claude result is_error fixture recovered"]);
}
@@ -1,7 +1,11 @@
import { ProviderDriverKind } from "@t3tools/contracts";
import { claudeIdleResumeInput } from "./claude_idle_resume/input.ts";
import { assertClaudeIdleResumeOutput } from "./claude_idle_resume/output.ts";
import { claudeLocalBashTaskInput } from "./claude_local_bash_task/input.ts";
import { assertClaudeLocalBashTaskOutput } from "./claude_local_bash_task/output.ts";
import { claudeResultIsErrorInput } from "./claude_result_is_error/input.ts";
import { assertClaudeResultIsErrorOutput } from "./claude_result_is_error/output.ts";
import { grokSubagentLineageInput } from "./grok_subagent_lineage/input.ts";
import { assertGrokSubagentLineageOutput } from "./grok_subagent_lineage/output.ts";
import { assertClaudeMessageSteeringOutput } from "./message_steering/claude_output.ts";
@@ -95,6 +99,33 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
},
],
},
{
name: "claude_idle_resume",
buildInput: claudeIdleResumeInput,
providers: [
{
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL("./claude_idle_resume/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
assertOutput: assertClaudeIdleResumeOutput,
},
],
},
{
name: "claude_result_is_error",
buildInput: claudeResultIsErrorInput,
providers: [
{
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL(
"./claude_result_is_error/claude_transcript.ndjson",
import.meta.url,
),
modelSelection: CLAUDE_MODEL_SELECTION,
assertOutput: assertClaudeResultIsErrorOutput,
},
],
},
{
name: "grok_subagent_lineage",
buildInput: grokSubagentLineageInput,
@@ -18,6 +18,7 @@ import {
type ProviderReplayTranscript,
type ProviderUserInputAnswers,
} from "@t3tools/contracts";
import type * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import type {
@@ -38,6 +39,8 @@ export const TOOL_CALL_READ_ONLY_WORKSPACE_ROOT = "/tmp/claude-replay-tool_call_
export const TOOL_CALL_READ_ONLY_PROMPT = `Read ${TOOL_CALL_READ_ONLY_WORKSPACE_ROOT}/package.json and ${TOOL_CALL_READ_ONLY_WORKSPACE_ROOT}/tsconfig.json, then answer exactly: read only tool fixture complete`;
export const CLAUDE_LOCAL_BASH_TASK_PROMPT =
"Run a local Bash typecheck command, then answer exactly: claude local bash task fixture complete";
export const CLAUDE_RESULT_IS_ERROR_PROMPT = "Say hello before the credentials expire.";
export const CLAUDE_RESULT_IS_ERROR_FOLLOW_UP = "Try again now that auth is back.";
export const TOOL_CALL_WRITE_PROMPT =
"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.";
export const MESSAGE_STEERING_INITIAL_PROMPT =
@@ -192,6 +195,14 @@ export type OrchestratorFixtureInputStep =
readonly type: "rollback";
readonly checkpointScopeSuffix: string;
readonly checkpointSuffix: string;
}
| {
/**
* Advance the deterministic test clock, e.g. past the provider session
* manager's idle timeout so the next message must reopen the session.
*/
readonly type: "advance_clock";
readonly duration: Duration.Input;
};
export interface OrchestratorFixtureInput {
@@ -630,6 +641,9 @@ export function materializeFixtureInput(input: {
steps.push({ type: "advance_clock", duration: "1 millis" });
steps.push({ type: "await_thread_idle", threadId: ids.threadId });
break;
case "advance_clock":
steps.push({ type: "advance_clock", duration: step.duration });
break;
case "rollback":
{
const scopeId = yield* idAllocator.allocate.checkpointScope({
+37 -37
View File
@@ -439,8 +439,8 @@ importers:
apps/server:
dependencies:
'@anthropic-ai/claude-agent-sdk':
specifier: ^0.3.170
version: 0.3.170(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])
specifier: ^0.3.205
version: 0.3.205(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])
'@connectrpc/connect':
specifier: 1.7.0
version: 1.7.0(@bufbuild/[email protected])
@@ -940,52 +940,52 @@ packages:
'@alchemy.run/[email protected]':
resolution: {integrity: sha512-TiIhPXCTCi3tk0zmdYJJ14CNSesSfsJxXdIOP0HTSItQ1mZWLocrF7qCuEWKyW/IEFzp6kaiOf19aIA/mbCp1g==}
'@anthropic-ai/[email protected].170':
resolution: {integrity: sha512-rwfgArIa5WI0QPNqFsRBgvtSI0mrtpynUm0oK6+l6/KX4hcgnYGEzciZR1bOeD9/7sSZlTdIgt+T9alKeZmXcg==}
'@anthropic-ai/[email protected].205':
resolution: {integrity: sha512-lrfJ4eVtzfPkCpbSkBOGSMQCBbvmW6nbPzgHE4IwMN3scZlpuFMUFqh2aaJa/X2SAcWD9H2S0t2WWvSRgM7BjA==}
cpu: [arm64]
os: [darwin]
'@anthropic-ai/[email protected].170':
resolution: {integrity: sha512-0e58h8UQMtsQxLGIv9r4foxfBFWKZ7NeDtoplLhuD7EwQonehomw1sBXCch77t/IfUS+q5vQ5zv+fOGmap5nLQ==}
'@anthropic-ai/[email protected].205':
resolution: {integrity: sha512-G6ETPmL5mNzJ2DFsWxG3jmsmrXgZX1N2ZCJvxaGUUpjTsKZJ4Tup1cWYvcd/m7o5fYZmx9REmgzTwsAIc1fdPQ==}
cpu: [x64]
os: [darwin]
'@anthropic-ai/[email protected].170':
resolution: {integrity: sha512-SRYfQcsXlOq+CD/FqkQBTSHbaD++w73GnnO+NUV9adLYrca3kfetRwWT1iguY1cNS0l34dCR3rlzCPq78vg1Jg==}
'@anthropic-ai/[email protected].205':
resolution: {integrity: sha512-91fgdG4aTnQ29sKOcUqgH4+tKCW2ut6PWGRSYmXNDbROasJm1rAlPdzC5brdu/e4c0CDSNV6TWyE5JCjaS/jlQ==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@anthropic-ai/[email protected].170':
resolution: {integrity: sha512-gLbaFqcGppFJQd4DLNV4IXoeahejT/p2/M8bSSvRDbla9GOsBr1AxV5XLRyBn1e7xFGozZIAIQr3+1chp7NJgQ==}
'@anthropic-ai/[email protected].205':
resolution: {integrity: sha512-CXzySK3PV3EizCRPXnxPqeaAtgrBFDnMFOVpMe36oC3U16yDb1b1tAJGqZi/7uFrVvAiaXvnSFxhUWnDDSaO+A==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@anthropic-ai/[email protected].170':
resolution: {integrity: sha512-m4+I0qBEk7cxRKS+pL+eoWXbXTFOAo83fQ0tQvap4z/mDMm06IWJtEPoYTaMBwsp32GJWLkHWKbZSBCHZnp2DQ==}
'@anthropic-ai/[email protected].205':
resolution: {integrity: sha512-vvsb7GlnA8CTSVvvTkrXjcSeRKqxSM7p/tU3Od9ICAZeWHglptekEyzLEApzLuLbI5ewfFF/F0q3NwOBbo18dg==}
cpu: [x64]
os: [linux]
libc: [musl]
'@anthropic-ai/[email protected].170':
resolution: {integrity: sha512-Xl/m7TaSC3T5IDBdHrZQ9fCQYyDmPELN34CL+MoyPIf7uSmuZnjE9fUOqDh2Rv26JxWssi1M6X+BBvVuKd6Cpg==}
'@anthropic-ai/[email protected].205':
resolution: {integrity: sha512-siS+1iNqBSlGFZZvJY6+mhzZ/6/ec/TbX9GMuwmTF0E6fxGhIIp797jJxR1q8r6FAq7d39mEoRNhC0Ffo60uNQ==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@anthropic-ai/[email protected].170':
resolution: {integrity: sha512-IG+8isJNNJKbnnhO7m+PGhfVCg+XoQ/MDxGde5eigFI0WsEfitjuWSWwx82bT9ghxI1aa6qNvI+UPgPcZuo5Fg==}
'@anthropic-ai/[email protected].205':
resolution: {integrity: sha512-SpP5zF68weFez/6pKrGzq/UVAJDMDNphWqmkLfOpWTDBL5xy6XlIZw5Bl4EXoVnfi2VLFkwuffNeFe+9SdX7kw==}
cpu: [arm64]
os: [win32]
'@anthropic-ai/[email protected].170':
resolution: {integrity: sha512-7cuqSKbHVItPGVwRbd3A0BEJwcNtc7Fhoh6qHN4C6yrmjSrvdYYx3MLvq/VI768/RoG7mAMDxb+j7WfEfoP9BA==}
'@anthropic-ai/[email protected].205':
resolution: {integrity: sha512-kg2kkXyeSoFLruO3Ic2IruLxzBR0xCUtmlJHdWi3SYW7JhAKNJg4fcrdJsWcardmEw23Y2UDGDJbRyxqSVx6wg==}
cpu: [x64]
os: [win32]
'@anthropic-ai/[email protected].170':
resolution: {integrity: sha512-pAvhfk+iTodXZ6RF18Kz7BEUWFjL7EcR3tKuhUNdPpE1NAYCR3mSHGbafi72JsrNwKEDIs7FU31z3fqhwy8QzA==}
'@anthropic-ai/[email protected].205':
resolution: {integrity: sha512-ft6iBw9kXudsusiXNpeybIPBJ07Z3tqp1ROSg5cEJqgA+9i+JJj2sRfQth+QD+lyenbbAU8yPieLxIimvfBhtw==}
engines: {node: '>=18.0.0'}
peerDependencies:
'@anthropic-ai/sdk': '>=0.93.0'
@@ -10497,44 +10497,44 @@ snapshots:
'@alchemy.run/[email protected]': {}
'@anthropic-ai/[email protected].170':
'@anthropic-ai/[email protected].205':
optional: true
'@anthropic-ai/[email protected].170':
'@anthropic-ai/[email protected].205':
optional: true
'@anthropic-ai/[email protected].170':
'@anthropic-ai/[email protected].205':
optional: true
'@anthropic-ai/[email protected].170':
'@anthropic-ai/[email protected].205':
optional: true
'@anthropic-ai/[email protected].170':
'@anthropic-ai/[email protected].205':
optional: true
'@anthropic-ai/[email protected].170':
'@anthropic-ai/[email protected].205':
optional: true
'@anthropic-ai/[email protected].170':
'@anthropic-ai/[email protected].205':
optional: true
'@anthropic-ai/[email protected].170':
'@anthropic-ai/[email protected].205':
optional: true
'@anthropic-ai/[email protected].170(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])':
'@anthropic-ai/[email protected].205(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])':
dependencies:
'@anthropic-ai/sdk': 0.93.0([email protected])
'@modelcontextprotocol/sdk': 1.29.0([email protected])
zod: 4.4.3
optionalDependencies:
'@anthropic-ai/claude-agent-sdk-darwin-arm64': 0.3.170
'@anthropic-ai/claude-agent-sdk-darwin-x64': 0.3.170
'@anthropic-ai/claude-agent-sdk-linux-arm64': 0.3.170
'@anthropic-ai/claude-agent-sdk-linux-arm64-musl': 0.3.170
'@anthropic-ai/claude-agent-sdk-linux-x64': 0.3.170
'@anthropic-ai/claude-agent-sdk-linux-x64-musl': 0.3.170
'@anthropic-ai/claude-agent-sdk-win32-arm64': 0.3.170
'@anthropic-ai/claude-agent-sdk-win32-x64': 0.3.170
'@anthropic-ai/claude-agent-sdk-darwin-arm64': 0.3.205
'@anthropic-ai/claude-agent-sdk-darwin-x64': 0.3.205
'@anthropic-ai/claude-agent-sdk-linux-arm64': 0.3.205
'@anthropic-ai/claude-agent-sdk-linux-arm64-musl': 0.3.205
'@anthropic-ai/claude-agent-sdk-linux-x64': 0.3.205
'@anthropic-ai/claude-agent-sdk-linux-x64-musl': 0.3.205
'@anthropic-ai/claude-agent-sdk-win32-arm64': 0.3.205
'@anthropic-ai/claude-agent-sdk-win32-x64': 0.3.205
'@anthropic-ai/[email protected]([email protected])':
dependencies: