diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 58e55ffcafdfb..056235ddb630c 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3230,6 +3230,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { readonly forkSession?: ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerShape["forkSession"]; readonly allocateSessionId?: Effect.Effect; readonly promptSuggestions?: boolean; + /** Opens with an adoptRunId return a CLI left running by an earlier server. */ + readonly adopted?: boolean; }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -3283,6 +3285,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { Extract >(); let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined; + const adoptRunIds: Array = []; + const activeRuns: Array = []; const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, settings: options?.settings ?? DEFAULT_CLAUDE_SETTINGS, @@ -3309,6 +3313,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { open: (input) => Effect.gen(function* () { openedOptions = input.options; + adoptRunIds.push(input.adoptRunId); const processMessages = options?.freshQueueOnReopen === true && processQueues.length > 0 ? yield* Queue.unbounded() @@ -3357,6 +3362,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { } processQueues.push(sdkMessages); return { + ...(options?.adopted === true && input.adoptRunId !== undefined + ? { adopted: true } + : {}), + setActiveRun: (runId) => void activeRuns.push(runId), messages, offer: (message) => Effect.sync(() => { @@ -3472,6 +3481,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { planReceipts, providerThreadReceipts, getOpenedOptions: () => openedOptions, + adoptRunIds, + activeRuns, terminalEvents, hasPendingBackgroundWork, until: changes.until, @@ -3482,6 +3493,102 @@ describe("ClaudeAdapterV2 background wake turns", () => { }); const makeWakeHarness = makeWakeHarnessWithOptions(); + // After a restart the CLI is still mid-tool-call; its output, read back from + // its file, is the turn, and it cannot take the continuation's prompt. + it.effect("finishes a restart continuation from the CLI the previous server left running", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ adopted: true }); + const sourceRunId = RunId.make("run-before-restart"); + const input = { + ...makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("adopted-continuation"), + text: "T3 Code restarted while this turn was running.", + attachments: [], + messageCreatedBy: "agent", + messageCreationSource: "server", + providerTurnOrdinal: 2, + }), + restartContinuationOfRunId: sourceRunId, + }; + yield* harness.runtime.startTurn(input); + assert.deepEqual(harness.adoptRunIds, [sourceRunId]); + assert.deepEqual(harness.activeRuns, [input.runId]); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_adopted_tool", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: "toolu_adopted", + name: "Bash", + input: { command: "sleep 45; echo done" }, + }, + ], + stop_reason: null, + stop_sequence: null, + usage: { + input_tokens: 1, + output_tokens: 1, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + }, + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000901", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [{ type: "tool_result", tool_use_id: "toolu_adopted", content: "done" }], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000902", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000903", text: "FINISHED" }), + ); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000904", result: "FINISHED" }), + ); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "completed"); + assert.lengthOf(harness.offeredMessages, 0); + assert.deepEqual(harness.activeRuns, [input.runId, null]); + const toolCall = harness.events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "toolu_adopted", + ); + assert.equal( + toolCall?.type === "turn_item.updated" ? toolCall.turnItem.status : undefined, + "completed", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect.each(["release-after", "cancel-after", "release-before", "resume-pending"] as const)( "keeps attachment reservations across compaction: %s boundary", (outcome) => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 3e04ba1e421b5..f30491d1ae0ae 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -6,6 +6,12 @@ import { } from "@t3tools/shared/toolOutput"; import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts"; import { claudeTaskOutputRoot, tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts"; +import { followClaudeDetachedOutput } from "./ClaudeDetachedOutput.ts"; +import { + DETACHED_STDOUT_FILE, + DetachedAgentTurns, + type DetachedAgentTurn, +} from "../../process/detachedAgentTurns.ts"; import { dynamicToolTitle, formatReadToolLabel, @@ -402,6 +408,108 @@ export function spawnClaudeProcessGroup( return child as ClaudeSpawnedProcess; } +// Twelve hours of 2 s polls bounds a detached CLI that never ends its turn. +const CLAUDE_DETACHED_MAX_POLLS = 21_600; + +/** + * Like CLAUDE_GROUP_WATCH_SCRIPT, but stdout also goes to `$out/stdout.jsonl` + * through tee, which keeps writing the file after the server's pipe closes. + * A guard that reads "detach" waits for the CLI to finish its turn instead of + * stopping it; the CLI ends the turn and exits on its own once stdin closes. + */ +const CLAUDE_DETACHABLE_GROUP_WATCH_SCRIPT = [ + "out=$1", + "shift", + `{ trap '' TERM; read -r cmd <&3; if [ "$cmd" = detach ]; then n=0; while kill -0 $$ && [ "$n" -lt ${CLAUDE_DETACHED_MAX_POLLS} ]; do sleep 2; n=$((n + 1)); done; fi; kill -TERM 0; sleep 5; kill -KILL 0; } /dev/null 2>&1 &`, + "trap '' PIPE", + 'mkfifo "$out/stdout.fifo" || exit 1', + `( exec <"$out/stdout.fifo" 3<&-; rm -f "$out/stdout.fifo"; exec tee -a "$out/${DETACHED_STDOUT_FILE}" ) &`, + 'exec "$@" 3<&- >"$out/stdout.fifo"', +].join("\n"); +// tee can still be passing the CLI's last lines to the SDK when the CLI exits. +const CLAUDE_STDOUT_DRAIN_TIMEOUT_MS = 2_000; + +/** + * The command that runs the CLI under the detachable guard. It goes inside the + * agent's scope launcher so the guard and tee share the CLI's systemd scope and + * outlive the server's own unit. + */ +export function detachableClaudeLaunch(outputDir: string, command: string) { + return { + command: "/bin/sh", + args: ["-c", CLAUDE_DETACHABLE_GROUP_WATCH_SCRIPT, "t3-claude", outputDir, command], + } as const; +} + +export interface DetachableClaudeProcess { + readonly process: ClaudeSpawnedProcess; + readonly pid: number | undefined; + /** Leaves the CLI running after this server exits; nothing here stops it afterwards. */ + readonly detach: () => void; +} + +/** Spawns a command that ends in `detachableClaudeLaunch`, in its own process group. */ +export function spawnDetachableClaudeProcessGroup( + options: ClaudeSpawnOptions, + onExit?: () => void, + onStderr: (text: string) => void = () => {}, + onStderrClose: () => void = () => {}, +): DetachableClaudeProcess { + let detached = false; + const child = NodeChildProcess.spawn(options.command, options.args, { + cwd: options.cwd, + env: options.env, + stdio: ["pipe", "pipe", "pipe", "pipe"], + detached: true, + }); + // Node's own abort handling would kill a detached CLI when the SDK aborts during shutdown. + options.signal?.addEventListener( + "abort", + () => { + if (!detached) child.kill("SIGTERM"); + }, + { once: true }, + ); + child.stderr?.setEncoding("utf8").on("data", onStderr).once("close", onStderrClose); + child.once("exit", () => { + if (detached) return; + const stopGroup = () => { + try { + signalProcessGroup(child.pid ?? 0, "SIGKILL"); + } catch {} + onExit?.(); + }; + const stdout = child.stdout; + if (stdout === null || stdout.closed) return stopGroup(); + // @effect-diagnostics-next-line globalTimers:off - Runs in a ChildProcess callback outside any fiber. + const timer = setTimeout(stopGroup, CLAUDE_STDOUT_DRAIN_TIMEOUT_MS); + stdout.once("close", () => { + clearTimeout(timer); + stopGroup(); + }); + }); + // The SDK kills its CLI on close and on process exit; a detached CLI must outlive both. + const spawned = new Proxy(child, { + get(target, key) { + if (key === "kill") { + return (signal?: NodeJS.Signals) => (detached ? false : target.kill(signal)); + } + const value: unknown = Reflect.get(target, key, target); + return typeof value === "function" ? value.bind(target) : value; + }, + }) as ClaudeSpawnedProcess; + return { + process: spawned, + pid: child.pid, + detach: () => { + if (detached || child.exitCode !== null || child.signalCode !== null) return; + detached = true; + const guard = child.stdio[3]; + if (guard !== null && guard !== undefined && "write" in guard) guard.write("detach\n"); + }, + }; +} + export const ClaudeProviderCapabilitiesV2 = { sessions: { supportsMultipleProviderThreadsPerSession: false, @@ -549,6 +657,8 @@ export interface ClaudeAgentSdkQueryOpenInput { readonly options: ClaudeAgentSdkQueryOptions; readonly threadId: ThreadId; readonly providerSessionId: OrchestrationV2ProviderSession["id"]; + /** The run a restart continuation resumes; its CLI may still be running from before the restart. */ + readonly adoptRunId?: string; } export interface ClaudeAgentSdkQuerySession { @@ -590,6 +700,12 @@ export interface ClaudeAgentSdkQuerySession { >; readonly interrupt: Effect.Effect; readonly close: Effect.Effect; + /** Replays a CLI that kept running through a server restart; it takes no input. */ + readonly adopted?: boolean; + /** The run whose turn the CLI is working on, so shutdown can leave that turn running. */ + readonly setActiveRun?: (runId: string | null) => void; + /** The last message the adapter handled, where a later server resumes reading. */ + readonly markHandled?: (message: SDKMessage) => void; } type ClaudeQueryStreamExit = Exit.Exit; @@ -1160,10 +1276,13 @@ export const layerQueryRunner: Layer.Layer< | Path.Path | PortScanner.PortDiscovery | ProviderEventLoggers.ProviderEventLoggers + | FileSystem.FileSystem > = Layer.effect( ClaudeAgentSdkQueryRunner, Effect.gen(function* () { const random = yield* SecureRandom.SecureRandom; + const fileSystem = yield* FileSystem.FileSystem; + const detachedTurns = yield* DetachedAgentTurns; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers; @@ -1173,6 +1292,87 @@ export const layerQueryRunner: Layer.Layer< const hostEnvironment = yield* HostProcess.Environment; const portDiscovery = yield* PortScanner.PortDiscovery; + const adoptedUnavailable = (method: string) => + Effect.fail( + queryRunnerError( + new Error("This Claude turn kept running through a server restart and takes no input."), + method, + ), + ); + + /** A CLI left running by the previous server, replayed from its output file. */ + const adoptDetachedTurn = Effect.fn("ClaudeAgentSdkQueryRunner.adoptDetachedTurn")(function* ( + input: ClaudeAgentSdkQueryOpenInput, + turn: DetachedAgentTurn, + ) { + // Messages wait for the adapter to attach the turn, so none land before it. + const attached = yield* Deferred.make(); + let detached = false; + let ended = false; + let activeRunId: string | null = null; + let lastHandledUuid = turn.resumeAfterUuid; + yield* detachedTurns.track({ + outputDir: turn.outputDir, + threadId: input.threadId, + nativeThreadId: turn.nativeThreadId, + pid: turn.pid, + unit: turn.unit, + activeRunId: () => activeRunId, + resumeAfterUuid: () => lastHandledUuid, + detach: () => { + detached = true; + }, + }); + const end = (outcome: "finished" | "stopped") => + Effect.suspend(() => { + if (detached || ended) return Effect.void; + ended = true; + return outcome === "finished" ? detachedTurns.finish(turn) : detachedTurns.kill(turn); + }); + const stop = end("stopped"); + const messages = Stream.fromEffect(Deferred.await(attached)).pipe( + Stream.flatMap(() => + followClaudeDetachedOutput({ + filePath: turn.stdoutPath, + resumeAfterUuid: turn.resumeAfterUuid, + alive: detachedTurns.alive(turn), + }), + ), + Stream.mapEffect((message) => (detached ? Effect.never : Effect.succeed(message))), + // The file holds the CLI's own stream-json lines, the messages the SDK would have yielded. + Stream.map((message) => message as unknown as SDKMessage), + Stream.concat(Stream.fromEffect(end("finished")).pipe(Stream.drain)), + Stream.provideService(FileSystem.FileSystem, fileSystem), + ); + yield* Effect.logInfo("orchestration-v2.claude-adopted-detached-turn", { + threadId: input.threadId, + runId: turn.runId, + }); + return { + adopted: true, + messages, + offer: () => adoptedUnavailable("offer"), + setModel: () => adoptedUnavailable("setModel"), + applyFlagSettings: () => adoptedUnavailable("applyFlagSettings"), + setPermissionMode: () => adoptedUnavailable("setPermissionMode"), + stopTask: () => adoptedUnavailable("stopTask"), + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => adoptedUnavailable("readMcpResource"), + callMcpTool: () => adoptedUnavailable("callMcpTool"), + listPermissionRules: adoptedUnavailable("listPermissionRules"), + interrupt: stop, + close: stop, + setActiveRun: (runId) => { + activeRunId = runId; + if (runId !== null) Deferred.doneUnsafe(attached, Exit.void); + }, + markHandled: (message) => { + lastHandledUuid = message.uuid ?? lastHandledUuid; + }, + } satisfies ClaudeAgentSdkQuerySession; + }); + return ClaudeAgentSdkQueryRunner.of({ allocateSessionId: random.uuidV4(), open: Effect.fn("ClaudeAgentSdkQueryRunner.open")( @@ -1204,13 +1404,34 @@ export const layerQueryRunner: Layer.Layer< }; // The SDK can prepend a scope wrapper to native binaries; script entries run through node. const binaryPath = queryOptions.pathToClaudeCodeExecutable; - const launch = + const nativeBinary = binaryPath === undefined || CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext)) + ? undefined + : binaryPath; + const nativeThreadId = input.options.resume ?? input.options.sessionId; + if (nativeThreadId !== undefined && platform !== "win32") { + // Any other turn first stops a CLI the previous server left running in this session. + const detachedTurn = yield* detachedTurns.claim({ + nativeThreadId, + runId: input.adoptRunId, + }); + if (detachedTurn !== undefined) return yield* adoptDetachedTurn(input, detachedTurn); + } + const outputDir = + nativeBinary === undefined || + nativeThreadId === undefined || + platform === "win32" || + queryOptions.spawnClaudeCodeProcess !== undefined + ? undefined + : yield* detachedTurns.allocate; + const launch = + nativeBinary === undefined ? undefined : yield* agentScope.wrap({ - command: binaryPath, - args: [], + ...(outputDir === undefined + ? { command: nativeBinary, args: [] } + : detachableClaudeLaunch(outputDir, nativeBinary)), name: "claude", threadId: input.threadId, env: queryOptions.env, @@ -1236,6 +1457,39 @@ export const layerQueryRunner: Layer.Layer< if (answered) return; stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH); }; + let activeRunId: string | null = null; + let lastHandledUuid: string | undefined; + let detached = false; + const spawnDetachable = (spawnOptions: ClaudeSpawnOptions, onStderrClose: () => void) => { + const spawned = spawnDetachableClaudeProcessGroup( + spawnOptions, + stopScope, + appendStderr, + onStderrClose, + ); + if (outputDir === undefined || nativeThreadId === undefined) return spawned.process; + if (spawned.pid !== undefined) { + runFork( + detachedTurns.track({ + outputDir, + threadId: input.threadId, + nativeThreadId, + pid: spawned.pid, + unit, + activeRunId: () => activeRunId, + resumeAfterUuid: () => lastHandledUuid, + detach: () => { + detached = true; + spawned.detach(); + }, + }), + ); + } + spawned.process.once("exit", () => { + if (!detached) runFork(detachedTurns.release(outputDir)); + }); + return spawned.process; + }; const spawnProcess = options.spawnClaudeCodeProcess ?? ((spawnOptions: ClaudeSpawnOptions) => { @@ -1243,7 +1497,9 @@ export const layerQueryRunner: Layer.Layer< // Node can report "exit" before it has read the stderr the CLI wrote. let stderrDone = () => {}; stderrClosed = new Promise((resolve) => (stderrDone = resolve)); - return spawnClaudeProcessGroup(spawnOptions, stopScope, appendStderr, stderrDone); + return outputDir === undefined + ? spawnClaudeProcessGroup(spawnOptions, stopScope, appendStderr, stderrDone) + : spawnDetachable(spawnOptions, stderrDone); } const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, { cwd: spawnOptions.cwd, @@ -1369,6 +1625,8 @@ export const layerQueryRunner: Layer.Layer< claudeQueryMessages(queryRuntime), (cause) => cause, ).pipe( + // The next server handles the rest of a detached turn from its resume point. + Stream.mapEffect((message) => (detached ? Effect.never : Effect.succeed(message))), Stream.catch((cause) => Stream.fromEffect( Effect.gen(function* () { @@ -1400,7 +1658,14 @@ export const layerQueryRunner: Layer.Layer< ), offer: (message, onQueued) => Effect.uninterruptibleMask((restore) => - restore(Queue.offer(promptQueue, message)).pipe( + // The output file only has to hold the turn this prompt starts. + (outputDir === undefined + ? Effect.void + : fileSystem + .truncate(path.join(outputDir, DETACHED_STDOUT_FILE)) + .pipe(Effect.ignore) + ).pipe( + Effect.andThen(restore(Queue.offer(promptQueue, message))), Effect.tap(() => Effect.sync(() => onQueued?.())), ), ).pipe( @@ -1550,6 +1815,12 @@ export const layerQueryRunner: Layer.Layer< }), ), ), + setActiveRun: (runId) => { + activeRunId = runId; + }, + markHandled: (message) => { + lastHandledUuid = message.uuid ?? lastHandledUuid; + }, } satisfies ClaudeAgentSdkQuerySession; }, // Fresh IDs may already have a metadata-only transcript; only resumed opens can reuse their ID. @@ -8352,9 +8623,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ], { concurrency: 1 }, ); - yield* Ref.update(activeTurn, (current) => - current?.providerTurnId === input.context.providerTurnId ? null : current, + const cleared = yield* Ref.modify(activeTurn, (current) => + current?.providerTurnId === input.context.providerTurnId + ? [true, null] + : [false, current], ); + if (cleared) (yield* Ref.get(queryContext))?.query.setActiveRun?.(null); if (input.status === "completed") { settledTurnByNativeThread.set(input.context.nativeThreadId, input.context); } else { @@ -11008,7 +11282,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( modelCatalog, ); const resumeSessionAt = yield* getNativeConversationHeadId(turnInput.providerThread); - const existing = yield* Ref.get(queryContext); + const live = yield* Ref.get(queryContext); + // An adopted CLI takes no input, so a later turn always replaces it. + const existing = live?.query.adopted === true ? null : live; + if (live !== null && existing === null) yield* live.query.close.pipe(Effect.ignore); // Continuations drain existing output without prompting; retain the live process regardless of selection. if ( existing !== null && @@ -11171,6 +11448,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( threadId: turnInput.threadId, providerSessionId: input.providerSessionId, options: queryOptions, + ...(turnInput.restartContinuationOfRunId === undefined + ? {} + : { adoptRunId: turnInput.restartContinuationOfRunId }), }) .pipe( Effect.onError(() => @@ -11278,7 +11558,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( resultsReportingNewContextWindow.add(message); } } - return handleSdkMessage({ query: querySession, message }); + return handleSdkMessage({ query: querySession, message }).pipe( + Effect.tap(() => Effect.sync(() => querySession.markHandled?.(message))), + ); }), ), ), @@ -11439,7 +11721,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( subagentsByTaskId: new Map(), subagentsByToolUseId: new Map(), promptUuid, - promptEcho: isClaudeProviderContinuationTurn(turnInput) ? "confirmed" : "pending", + promptEcho: + isClaudeProviderContinuationTurn(turnInput) || querySession.query.adopted === true + ? "confirmed" + : "pending", promptStarted: false, nativeWakeStarted: false, gatedFramesBeforeEcho: 0, @@ -11456,6 +11741,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( querySession.lastTurn = context; return [true, current]; }); + if (attached) querySession.query.setActiveRun?.(turnInput.runId); if (!attached) { yield* Ref.update(activeTurn, (current) => (current === context ? null : current)); return yield* new ProviderAdapter.ProviderAdapterProtocolError({ @@ -11518,6 +11804,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), }); }); + // The adopted CLI is already working on this turn; its output is the turn. + if (querySession.query.adopted === true) { + yield* attachTurn; + return; + } if (userMessage !== null) { yield* attachTurn; yield* startUserTurnForWakeReports(nativeThreadId); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 1ea0a62e168ce..dc17eac32602d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -32,6 +32,8 @@ import { type ClaudeAgentSdkQueryOpenInput, layerQueryRunner, spawnClaudeProcessGroup, + detachableClaudeLaunch, + spawnDetachableClaudeProcessGroup, } from "./ClaudeAdapterV2.ts"; vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); @@ -655,6 +657,74 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro }), ); + // A detached CLI's stdout keeps reaching its file after the server's pipes close. + const fileContains = (file: string, text: string) => + new Promise((resolve) => { + const watcher = NodeFS.watch(file, () => check()); + const check = () => { + if (!NodeFS.readFileSync(file, "utf8").includes(text)) return; + watcher.close(); + resolve(); + }; + check(); + }); + + const spawnDetachableFakeCli = (script: string) => + Effect.gen(function* () { + const cli = fakeClaudeCli(script); + const dir = NodePath.dirname(cli); + NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "go")]); + const outputDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-out-")); + const launch = detachableClaudeLaunch(outputDir, cli); + const spawned = spawnDetachableClaudeProcessGroup({ + command: launch.command, + args: [...launch.args], + cwd: dir, + env: process.env, + // @effect-diagnostics-next-line abortControllerInEffect:off - These fixtures close pipes themselves. + signal: new AbortController().signal, + }); + const child = spawned.process as unknown as NodeChildProcess.ChildProcess; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + try { + signalProcessGroup(child.pid ?? 0, "SIGKILL"); + } catch {} + NodeFS.rmSync(dir, { recursive: true, force: true }); + NodeFS.rmSync(outputDir, { recursive: true, force: true }); + }), + ); + const exited = new Promise((resolve) => child.once("exit", () => resolve())); + const firstLine = new Promise((resolve) => child.stdout?.once("data", () => resolve())); + yield* Effect.promise(() => firstLine); + return { spawned, child, dir, exited, stdoutFile: NodePath.join(outputDir, "stdout.jsonl") }; + }); + + it.effect("leaves a detached CLI to finish its turn after the server goes away", () => + Effect.gen(function* () { + const { spawned, child, dir, exited, stdoutFile } = yield* spawnDetachableFakeCli( + ['dir=$(dirname "$0")', "echo first", 'read -r _ < "$dir/go"', "echo second"].join("\n"), + ); + spawned.detach(); + for (const pipe of child.stdio) pipe?.destroy(); + // The CLI blocks on the FIFO until the "server" is gone, then ends its turn. + NodeFS.writeFileSync(NodePath.join(dir, "go"), "go\n"); + yield* Effect.promise(() => exited); + yield* Effect.promise(() => fileContains(stdoutFile, "second")); + assert.equal(NodeFS.readFileSync(stdoutFile, "utf8"), "first\nsecond\n"); + }), + ); + + it.effect("stops a CLI it did not detach when the server goes away", () => + Effect.gen(function* () { + const { child, exited } = yield* spawnDetachableFakeCli( + ['dir=$(dirname "$0")', "echo first", 'read -r _ < "$dir/go"'].join("\n"), + ); + for (const pipe of child.stdio) pipe?.destroy(); + yield* Effect.promise(() => exited); + }), + ); + it.effect("marks the CLI's jobs with its thread and counts it as an agent until it exits", () => { let runningAgents = 0; let releaseAgent!: () => void; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeDetachedOutput.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeDetachedOutput.test.ts new file mode 100644 index 0000000000000..ac667190d7f79 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeDetachedOutput.test.ts @@ -0,0 +1,121 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Stream from "effect/Stream"; + +import { + ClaudeOutputFollower, + claudeOutputCompletesTurn, + followClaudeDetachedOutput, +} from "./ClaudeDetachedOutput.ts"; + +const toolUse = { + type: "assistant", + uuid: "u-tool", + parent_tool_use_id: null, + message: { + id: "msg_1", + content: [ + { type: "text", text: "Running it." }, + { type: "tool_use", id: "toolu_done", name: "Read", input: {} }, + { type: "tool_use", id: "toolu_open", name: "Bash", input: { command: "sleep 45" } }, + ], + }, +}; +const doneResult = { + type: "user", + uuid: "u-done", + parent_tool_use_id: null, + message: { content: [{ type: "tool_result", tool_use_id: "toolu_done", content: "x" }] }, +}; +const progress = { type: "tool_progress", uuid: "u-progress", tool_use_id: "toolu_open" }; +const openResult = { + type: "user", + uuid: "u-open", + parent_tool_use_id: null, + message: { content: [{ type: "tool_result", tool_use_id: "toolu_open", content: "done" }] }, +}; +const result = { type: "result", subtype: "success", uuid: "u-result", parent_tool_use_id: null }; +const lines = (...messages: ReadonlyArray) => + new TextEncoder().encode(messages.map((message) => `${JSON.stringify(message)}\n`).join("")); + +describe("ClaudeOutputFollower", () => { + it("resumes after the last handled message, first resending tool calls still waiting", () => { + const follower = new ClaudeOutputFollower("u-progress"); + const replayed = [ + ...follower.pushInitial( + lines(toolUse, doneResult, progress, { type: "control_request", request_id: "r" }), + ), + ...follower.push(lines(openResult, result)), + ]; + assert.deepEqual( + replayed.map((message) => message.uuid), + ["u-tool", "u-open", "u-result"], + ); + // Only the unanswered call is resent; the text and answered call were shown already. + assert.deepEqual( + (replayed[0]!.message as { content: Array<{ id?: string }> }).content.map( + (block) => block.id, + ), + ["toolu_open"], + ); + }); + + it("replays everything when the resume point is not in the file", () => { + const follower = new ClaudeOutputFollower("u-truncated-away"); + assert.deepEqual( + follower.pushInitial(lines(openResult, result)).map((message) => message.uuid), + ["u-open", "u-result"], + ); + }); + + it("drops partial stream events of a message whose start was handled before", () => { + const follower = new ClaudeOutputFollower("u-tool"); + const delta = (uuid: string, type: string) => ({ type: "stream_event", uuid, event: { type } }); + const text = `${JSON.stringify(toolUse)}\n${JSON.stringify(delta("d1", "content_block_delta"))}\n`; + const replayed = [ + ...follower.pushInitial(new TextEncoder().encode(text)), + // A line split across reads is held until it is complete. + ...follower.push(new TextEncoder().encode(JSON.stringify(delta("d2", "message_stop")))), + ...follower.push(lines({}).subarray(2)), + ...follower.push(lines(delta("d3", "message_start"), delta("d4", "content_block_delta"))), + ]; + assert.deepEqual( + replayed.map((message) => message.uuid), + ["u-tool", "d3", "d4"], + ); + }); + + it("knows whether the rest of the file finishes the turn", () => { + assert.isTrue(claudeOutputCompletesTurn(lines(toolUse, openResult, result), "u-tool")); + assert.isFalse(claudeOutputCompletesTurn(lines(toolUse, result, openResult), "u-result")); + }); +}); + +describe("followClaudeDetachedOutput", () => { + it.effect("reads an exited CLI's file to the end, including a last line without a newline", () => + Effect.scoped( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-detached-" }); + const file = path.join(dir, "stdout.jsonl"); + yield* fileSystem.writeFileString( + file, + `${JSON.stringify(toolUse)}\n${JSON.stringify(openResult)}\n${JSON.stringify(result)}`, + ); + const messages = yield* followClaudeDetachedOutput({ + filePath: file, + resumeAfterUuid: "u-tool", + alive: Effect.succeed(false), + }).pipe(Stream.runCollect); + assert.deepEqual( + messages.map((message) => message.uuid), + ["u-tool", "u-open", "u-result"], + ); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeDetachedOutput.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeDetachedOutput.ts new file mode 100644 index 0000000000000..01bb13565569a --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeDetachedOutput.ts @@ -0,0 +1,184 @@ +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; + +/** The SDK consumes these stdout lines itself; they never reach the adapter. */ +const SDK_INTERNAL_TYPES = new Set([ + "control_request", + "control_response", + "control_cancel_request", + "keep_alive", + "transcript_mirror", +]); + +const POLL_INTERVAL = "250 millis"; + +export type ClaudeOutputMessage = Record & { readonly type: string }; + +function parseClaudeOutputLine(line: string): ClaudeOutputMessage | undefined { + if (line.trim().length === 0) return undefined; + let value: unknown; + try { + value = JSON.parse(line); + } catch { + return undefined; + } + if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined; + const type = (value as { readonly type?: unknown }).type; + if (typeof type !== "string" || SDK_INTERNAL_TYPES.has(type)) return undefined; + return value as ClaudeOutputMessage; +} + +/** + * Yields the lines after `resumeAfterUuid` (all lines if it is gone), first + * resending tool calls still waiting for their result so their results have a + * call. Stream events of a message whose start came earlier are dropped; the + * complete assistant message that follows carries their text. + */ +export class ClaudeOutputFollower { + private remainder = ""; + private resumed: boolean; + private midMessage = true; + private readonly decoder = new TextDecoder("utf-8", { fatal: false }); + private readonly resumeAfterUuid: string | undefined; + private readonly openToolUses = new Map(); + + constructor(resumeAfterUuid: string | undefined) { + this.resumeAfterUuid = resumeAfterUuid; + this.resumed = resumeAfterUuid === undefined; + } + + /** The first chunk must be the whole file so the resume point can be found. */ + pushInitial(bytes: Uint8Array): ReadonlyArray { + const text = this.decoder.decode(bytes, { stream: true }); + if (!this.resumed && !text.includes(`"${this.resumeAfterUuid}"`)) this.resumed = true; + return this.pushText(text); + } + + push(bytes: Uint8Array): ReadonlyArray { + return this.pushText(this.decoder.decode(bytes, { stream: true })); + } + + /** A final line without its newline is still a whole message once the writer is gone. */ + flush(): ReadonlyArray { + return this.pushText(`${this.decoder.decode()}\n`); + } + + private pushText(text: string): ReadonlyArray { + const lines = (this.remainder + text).split("\n"); + this.remainder = lines.pop() ?? ""; + const messages: Array = []; + for (const line of lines) { + const message = parseClaudeOutputLine(line); + if (message === undefined) continue; + if (!this.resumed) { + this.trackOpenToolUses(message); + if (message.uuid === this.resumeAfterUuid) { + this.resumed = true; + messages.push(...this.takeOpenToolUses()); + } + continue; + } + if (message.type === "stream_event") { + const event = message.event as { readonly type?: unknown } | undefined; + if (event?.type === "message_start") this.midMessage = false; + if (this.midMessage) continue; + } else if (message.type === "assistant") { + this.midMessage = false; + } + messages.push(message); + } + return messages; + } + + private trackOpenToolUses(message: ClaudeOutputMessage) { + if (message.parent_tool_use_id != null) return; + for (const block of contentBlocks(message)) { + if (message.type === "assistant" && block.type === "tool_use" && typeof block.id === "string") + this.openToolUses.set(block.id, message); + if (message.type === "user" && block.type === "tool_result") + this.openToolUses.delete(String(block.tool_use_id)); + } + } + + /** Each message once, with only its unanswered tool calls. */ + private takeOpenToolUses(): ReadonlyArray { + const byMessage = new Map>(); + for (const [id, message] of this.openToolUses) { + byMessage.set(message, (byMessage.get(message) ?? new Set()).add(id)); + } + this.openToolUses.clear(); + return [...byMessage].map(([message, ids]) => ({ + ...message, + message: { + ...(message.message as Record), + content: contentBlocks(message).filter( + (block) => block.type === "tool_use" && ids.has(String(block.id)), + ), + }, + })); + } +} + +function contentBlocks(message: ClaudeOutputMessage): ReadonlyArray> { + const content = (message.message as { readonly content?: unknown } | undefined)?.content; + return Array.isArray(content) + ? content.filter( + (block): block is Record => typeof block === "object" && block !== null, + ) + : []; +} + +/** Whether replaying the file would finish the turn the CLI was running. */ +export function claudeOutputCompletesTurn(bytes: Uint8Array, resumeAfterUuid: string | undefined) { + const follower = new ClaudeOutputFollower(resumeAfterUuid); + return [...follower.pushInitial(bytes), ...follower.flush()].some( + (message) => message.type === "result" && message.parent_tool_use_id == null, + ); +} + +/** + * Follows a detached CLI's stdout file from the resume point until the CLI has + * exited and every line it wrote has been read. + */ +export const followClaudeDetachedOutput = (input: { + readonly filePath: string; + readonly resumeAfterUuid: string | undefined; + readonly alive: Effect.Effect; +}): Stream.Stream => + Stream.unwrap( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const follower = new ClaudeOutputFollower(input.resumeAfterUuid); + const readFrom = (offset: number) => + Effect.scoped( + Effect.gen(function* () { + const size = Number((yield* fileSystem.stat(input.filePath)).size); + if (size <= offset) return new Uint8Array(); + const handle = yield* fileSystem.open(input.filePath, { flag: "r" }); + yield* handle.seek(BigInt(offset), "start"); + return Option.getOrElse(yield* handle.readAlloc(size - offset), () => new Uint8Array()); + }), + ).pipe(Effect.orElseSucceed(() => new Uint8Array())); + const initial = yield* readFrom(0); + const first = follower.pushInitial(initial); + return Stream.concat( + Stream.fromIterable(first), + Stream.paginate(initial.byteLength, (previous) => + Effect.gen(function* () { + // Read after checking liveness so the last lines of an exited CLI are not missed. + const alive = yield* input.alive; + const bytes = yield* readFrom(previous); + const offset = previous + bytes.byteLength; + if (bytes.byteLength > 0) { + return [follower.push(bytes), Option.some(offset)] as const; + } + if (!alive) return [follower.flush(), Option.none()] as const; + yield* Effect.sleep(POLL_INTERVAL); + return [[], Option.some(offset)] as const; + }), + ), + ); + }), + ); diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index 89e43e5b1ede4..49d57177b1d7f 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -5,6 +5,7 @@ import { isProviderNativeSubagentThread, type OrchestrationV2DomainEvent, type ProviderThreadId, + type RunId, type OrchestrationV2RestartCancelledBackgroundWork, type OrchestrationV2Subagent, type OrchestrationV2ThreadProjection, @@ -75,7 +76,8 @@ export class ProviderRuntimeRecoveryService extends Context.Service< readonly reconcile: ( trigger: "startup" | "shutdown", ) => Effect.Effect; - readonly prepareForShutdown: Effect.Effect; + /** Records restart continuations and returns the runs they will continue. */ + readonly prepareForShutdown: Effect.Effect, ProviderRuntimeRecoveryError>; readonly recover: Effect.Effect; } >()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {} @@ -954,12 +956,13 @@ export const make = Effect.gen(function* () { }); const prepareForShutdown = Effect.gen(function* () { + const continued = new Set(); const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null)); - if (!enabled) return; + if (!enabled) return continued; const enabledProjects = Object.entries(enabled.projectSettingsOverrides) .filter(([, overrides]) => overrides.continueThreadsAfterServerUpdate === true) .map(([id]) => id); - if (!enabled.continueThreadsAfterServerUpdate && enabledProjects.length === 0) return; + if (!enabled.continueThreadsAfterServerUpdate && enabledProjects.length === 0) return continued; const disabledProjects = Object.entries(enabled.projectSettingsOverrides) .filter(([, overrides]) => overrides.continueThreadsAfterServerUpdate === false) .map(([id]) => id); @@ -994,6 +997,7 @@ export const make = Effect.gen(function* () { }, ], }); + continued.add(run.id); }).pipe( Effect.catchCauseIf( (cause) => !Cause.hasInterruptsOnly(cause), @@ -1004,6 +1008,7 @@ export const make = Effect.gen(function* () { // Leave room in the four-reader pool for other shutdown reads. { concurrency: 2, discard: true }, ); + return continued; }).pipe( Effect.withSpan("ProviderRuntimeRecoveryService.prepareForShutdown"), Effect.mapError((cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause })), diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts index 299e3e43b5b3f..71c69e123e82a 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts @@ -30,6 +30,7 @@ import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as EffectWorker from "./EffectWorker.ts"; import * as EffectOutbox from "./EffectOutbox.ts"; +import { DetachedAgentTurns } from "../process/detachedAgentTurns.ts"; const threadId = ThreadId.make("thread:restart"); const runId = RunId.make("run:restart"); @@ -531,7 +532,7 @@ it.effect("prepares no continuation for background work another provider thread ), ), ); - yield* recovery.prepareForShutdown; + assert.deepEqual([...(yield* recovery.prepareForShutdown)], []); assert.lengthOf(writes, 0); const ownWork = { ...projection, @@ -558,7 +559,8 @@ it.effect("prepares no continuation for background work another provider thread ), ), ); - yield* ownRecovery.prepareForShutdown; + // Shutdown leaves running the CLIs of exactly the runs it will continue. + assert.deepEqual([...(yield* ownRecovery.prepareForShutdown)], [runId]); assert.lengthOf(writes, 1); assert.deepEqual(writes[0]!.effects[0]?.request, { type: "provider-runtime.continue", @@ -923,6 +925,27 @@ it.effect("continues a cut run past queued follow-ups, which stay held", () => }), ); +// The CLI kept working through the restart, so the run only needs its output shown. +it.effect("notes instead of prompting when the cut turn kept running", () => + Effect.gen(function* () { + const dispatches = yield* continuationDispatches(cutMidTurn()).pipe( + Effect.provideService(DetachedAgentTurns, { + ...DetachedAgentTurns.defaultValue(), + adoptable: (sourceRunId) => Effect.succeed(sourceRunId === runId), + }), + ); + assert.deepEqual( + dispatches.map((command) => [command.text, command.notification?.summary]), + [ + [ + "T3 Code restarted while this turn was running. The agent kept working, and the rest of its turn follows.", + "T3 Code restarted; this turn kept running", + ], + ], + ); + }), +); + it.effect("continues a resumed queued run that ran after an earlier continuation", () => Effect.gen(function* () { const finishedContinuation = { diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index f8724d0fbf025..9cfa587151800 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -13,6 +13,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import type { ProjectionRuntimeRecoveryState } from "./ProjectionStore.ts"; +import { DetachedAgentTurns } from "../process/detachedAgentTurns.ts"; import * as ServerSettings from "../serverSettings.ts"; import { isNativeMaintenanceCommand } from "./CommandPolicy.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; @@ -33,6 +34,10 @@ import { const CONTINUE_PROMPT = "Continue where you left off. Your last turn was cut short, so a command or other action it started may have finished or may still be running. Before you repeat one that changes state, confirm it did not take effect and is not still running; if you cannot tell, say so instead of repeating it."; +// Shown, not sent: the adopted CLI takes no input. +const ADOPTED_TURN_NOTE = + "T3 Code restarted while this turn was running. The agent kept working, and the rest of its turn follows."; + const MAX_CONTINUATION_CHAIN = 3; const CONTINUATION_LOOP_WINDOW_MS = 5 * 60 * 1_000; @@ -184,6 +189,7 @@ export function restartContinuationRun( export const continueRestartedRun = Effect.fn("RestartContinuation.continueRestartedRun")( function* (input: { readonly threadId: ThreadId; readonly sourceRunId: RunId }) { const settings = yield* ServerSettings.ServerSettingsService; + const detachedTurns = yield* DetachedAgentTurns; const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null)); if (!enabled) return; const threads = yield* ThreadManagementService.ThreadManagementService; @@ -290,6 +296,7 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta (message) => message.id === source.userMessageId, ); if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return; + const adopting = yield* detachedTurns.adoptable(input.sourceRunId); const note = restartContinuationNote( source, projection.runs, @@ -298,8 +305,9 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta ); const noteText = note.work.length === 0 ? undefined : restartCancelledBackgroundWorkNote(note.work); - const text = - noteText === undefined + const text = adopting + ? ADOPTED_TURN_NOTE + : noteText === undefined ? CONTINUE_PROMPT : note.settled ? noteText @@ -314,9 +322,11 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta notification: { source: { kind: "system" }, outcome: "updated", - summary: note.settled - ? "T3 Code restarted and stopped background work" - : "T3 Code restarted and resumed this turn", + summary: adopting + ? "T3 Code restarted; this turn kept running" + : note.settled + ? "T3 Code restarted and stopped background work" + : "T3 Code restarted and resumed this turn", detail: text, }, attachments: [], diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 0095146a3021f..d5aed3a32f4e2 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -112,6 +112,8 @@ const withFakeSystemd = ( fileSystem.readFileString(path.replace("/sys/fs/cgroup", cgroupRoot), encoding), writeFileString: (path, data, options) => fileSystem.writeFileString(path.replace("/sys/fs/cgroup", cgroupRoot), data, options), + readDirectory: (path, options) => + fileSystem.readDirectory(path.replace("/sys/fs/cgroup", cgroupRoot), options), }), ); const { stateDir } = yield* ServerConfig.ServerConfig; @@ -329,6 +331,38 @@ describe("AgentScope service", () => { ), ); + it.effect("keeps the scopes of turns a restarted server left running", () => + withFakeSystemd(({ scope, units, calls, stateDir, cgroupRoot }) => + Effect.gen(function* () { + const slice = ownedAgentSlice(stateDir); + units.set(slice, { activeState: "active", result: "success", controlGroup: `/${slice}` }); + NodeFS.mkdirSync(NodePath.join(cgroupRoot, slice, "t3code-claude-kept.scope"), { + recursive: true, + }); + NodeFS.mkdirSync(NodePath.join(cgroupRoot, slice, "t3code-claude-old.scope")); + NodeFS.writeFileSync(NodePath.join(cgroupRoot, slice, "cgroup.events"), "populated 1\n"); + const turnDir = NodePath.join(stateDir, "agent-turns", "turn-1"); + NodeFS.mkdirSync(turnDir, { recursive: true }); + NodeFS.writeFileSync( + NodePath.join(turnDir, "record.json"), + JSON.stringify({ + version: 1, + driver: "claude", + threadId: "thread-1", + runId: "run-1", + nativeThreadId: "native-1", + pid: 1, + startTime: "1", + unit: "t3code-claude-kept.scope", + detachedAt: "2026-01-01T00:00:00.000Z", + }), + ); + yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); + expect(stopsOf(calls)).toEqual([["--user", "stop", "t3code-claude-old.scope"]]); + }), + ), + ); + it.effect("stops leftover processes only in an active agent scope", () => withFakeSystemd(({ scope, units, calls, cgroupRoot }) => Effect.gen(function* () { diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index b9b6b56acb140..0bcb2e407f20f 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -17,6 +17,7 @@ import * as Path from "effect/Path"; import * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; +import { readDetachedAgentUnits } from "./detachedAgentTurns.ts"; const AGENT_SLICE = "app-t3code-agents.slice"; // Owns every agent slice and competes with the server's unit or scope under app.slice. @@ -142,9 +143,26 @@ export const make = Effect.gen(function* () { const controlGroup = values.get("ControlGroup") ?? ""; const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : ""; if (parseCgroupCounter(events, "populated") === 0) return; - yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice }); + // Turns the previous server left running for this one to adopt keep their scopes. + const kept = yield* readDetachedAgentUnits(stateDir).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ); + const leftover = + kept.size === 0 + ? [ownedSlice] + : (yield* fileSystem + .readDirectory(path.join("/sys/fs/cgroup", controlGroup)) + .pipe(Effect.orElseSucceed(() => []))).filter( + (unit) => unit.endsWith(".scope") && !kept.has(unit), + ); + if (leftover.length === 0) return; + yield* Effect.logWarning("Stopping agents left by a previous server", { + slice: ownedSlice, + kept: kept.size, + }); const stopped = yield* runner - .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" }) + .run({ command: systemctl, args: ["--user", "stop", ...leftover], timeout: "30 seconds" }) .pipe(Effect.option); if (stopped._tag === "None" || stopped.value.code !== 0) { yield* Effect.logWarning("Could not stop agents left by a previous server", { diff --git a/apps/server/src/process/detachedAgentTurns.test.ts b/apps/server/src/process/detachedAgentTurns.test.ts new file mode 100644 index 0000000000000..7b63526d909f2 --- /dev/null +++ b/apps/server/src/process/detachedAgentTurns.test.ts @@ -0,0 +1,150 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the stand-in CLIs are real processes the registry signals. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ServerConfig from "../config.ts"; +import { make, type DetachableAgentProcess } from "./detachedAgentTurns.ts"; + +const makeLinux = make.pipe(Effect.provideService(HostProcess.Platform, "linux")); + +/** A process standing in for a CLI, in its own group as the real ones are. */ +const spawnStandIn = Effect.acquireRelease( + Effect.sync(() => { + const child = NodeChildProcess.spawn("sleep", ["600"], { detached: true, stdio: "ignore" }); + const exited = new Promise((resolve) => child.once("exit", () => resolve())); + return { pid: child.pid!, exited, child }; + }), + ({ child }) => Effect.sync(() => child.kill("SIGKILL")), +); + +const tracked = (input: { + readonly outputDir: string; + readonly pid: number; + readonly runId: string; + readonly onDetach: () => void; +}): DetachableAgentProcess => ({ + outputDir: input.outputDir, + threadId: "thread-1", + nativeThreadId: `native-${input.runId}`, + pid: input.pid, + unit: undefined, + activeRunId: () => input.runId, + resumeAfterUuid: () => "u-handled", + detach: input.onDetach, +}); + +const writeRecord = (dir: string, fields: { readonly pid: number; readonly runId: string }) => { + NodeFS.mkdirSync(dir, { recursive: true }); + NodeFS.writeFileSync( + NodePath.join(dir, "record.json"), + JSON.stringify({ + version: 1, + driver: "claude", + threadId: "thread-1", + runId: fields.runId, + nativeThreadId: `native-${fields.runId}`, + pid: fields.pid, + startTime: "0", + resumeAfterUuid: "u-handled", + detachedAt: "2026-01-01T00:00:00.000Z", + }), + ); +}; + +const testLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-detached-turns-" }).pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), +); + +describe("DetachedAgentTurns", () => { + it.effect("leaves running only CLIs on a continued run, for the next server to adopt", () => + Effect.gen(function* () { + const first = yield* makeLinux; + const continued = yield* spawnStandIn; + const other = yield* spawnStandIn; + const detached: Array = []; + const continuedDir = (yield* first.allocate)!; + const otherDir = (yield* first.allocate)!; + yield* first.track( + tracked({ + outputDir: continuedDir, + pid: continued.pid, + runId: "run-1", + onDetach: () => detached.push("run-1"), + }), + ); + yield* first.track( + tracked({ + outputDir: otherDir, + pid: other.pid, + runId: "run-2", + onDetach: () => detached.push("run-2"), + }), + ); + assert.equal(yield* first.detach(new Set(["run-1"])), 1); + assert.deepEqual(detached, ["run-1"]); + assert.isFalse(NodeFS.existsSync(NodePath.join(otherDir, "record.json"))); + + // The next server finds only the detached turn; the other CLI's output is left over. + const next = yield* makeLinux; + assert.isFalse(NodeFS.existsSync(otherDir)); + assert.isTrue(yield* next.adoptable("run-1")); + const turn = yield* next.claim({ nativeThreadId: "native-run-1", runId: "run-1" }); + assert.equal(turn?.pid, continued.pid); + assert.equal(turn?.resumeAfterUuid, "u-handled"); + assert.isFalse(NodeFS.existsSync(NodePath.join(continuedDir, "record.json"))); + assert.isUndefined(yield* next.claim({ nativeThreadId: "native-run-1", runId: "run-1" })); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + + it.effect("stops a detached CLI when another turn of its session starts first", () => + Effect.gen(function* () { + const first = yield* makeLinux; + const cli = yield* spawnStandIn; + const outputDir = (yield* first.allocate)!; + yield* first.track(tracked({ outputDir, pid: cli.pid, runId: "run-1", onDetach: () => {} })); + yield* first.detach(new Set(["run-1"])); + + const next = yield* makeLinux; + assert.isUndefined(yield* next.claim({ nativeThreadId: "native-run-1", runId: undefined })); + yield* Effect.promise(() => cli.exited); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + + it.effect("adopts a turn that ended while no server ran only if its output finishes it", () => + Effect.gen(function* () { + const { stateDir } = yield* ServerConfig.ServerConfig; + const root = NodePath.join(stateDir, "agent-turns"); + const finished = NodePath.join(root, "finished"); + const cut = NodePath.join(root, "cut"); + // A dead PID: this test's own stand-in, already reaped. + const gone = yield* Effect.scoped( + Effect.gen(function* () { + const standIn = yield* spawnStandIn; + return standIn; + }), + ); + yield* Effect.promise(() => gone.exited); + writeRecord(finished, { pid: gone.pid, runId: "run-finished" }); + NodeFS.writeFileSync( + NodePath.join(finished, "stdout.jsonl"), + `${JSON.stringify({ type: "assistant", uuid: "u-handled", message: { content: [] } })}\n` + + `${JSON.stringify({ type: "result", subtype: "success", uuid: "u-result" })}\n`, + ); + writeRecord(cut, { pid: gone.pid, runId: "run-cut" }); + NodeFS.writeFileSync(NodePath.join(cut, "stdout.jsonl"), ""); + + const registry = yield* makeLinux; + assert.isTrue(yield* registry.adoptable("run-finished")); + assert.isFalse(yield* registry.adoptable("run-cut")); + assert.isFalse(NodeFS.existsSync(cut)); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); +}); diff --git a/apps/server/src/process/detachedAgentTurns.ts b/apps/server/src/process/detachedAgentTurns.ts new file mode 100644 index 0000000000000..2422fb75405df --- /dev/null +++ b/apps/server/src/process/detachedAgentTurns.ts @@ -0,0 +1,309 @@ +import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; +import { AgentScope } from "@t3tools/shared/AgentScope"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import * as ServerConfig from "../config.ts"; +import { claudeOutputCompletesTurn } from "../orchestration-v2/Adapters/ClaudeDetachedOutput.ts"; + +/** + * Agent CLIs that were mid-turn when the server shut down keep running, write + * their output to a file, and are adopted by the next server. See + * `spawnClaudeProcessGroup` for the process side. + */ + +const OUTPUT_ROOT = "agent-turns"; +const RECORD_FILE = "record.json"; +export const DETACHED_STDOUT_FILE = "stdout.jsonl"; +// Restart continuations wait for activation; a turn nobody adopts by then is stopped. +const UNCLAIMED_DEADLINE = "10 minutes"; +const KILL_GRACE = "5 seconds"; + +const DetachedAgentTurnRecord = Schema.Struct({ + version: Schema.Literal(1), + driver: Schema.Literal("claude"), + threadId: Schema.String, + runId: Schema.String, + nativeThreadId: Schema.String, + pid: Schema.Number, + startTime: Schema.String, + unit: Schema.optional(Schema.String), + resumeAfterUuid: Schema.optional(Schema.String), + detachedAt: Schema.String, +}); +type DetachedAgentTurnRecord = typeof DetachedAgentTurnRecord.Type; +const decodeRecord = Schema.decodeUnknownEffect(Schema.fromJsonString(DetachedAgentTurnRecord)); +const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(DetachedAgentTurnRecord)); + +export interface DetachedAgentTurn extends DetachedAgentTurnRecord { + readonly outputDir: string; + readonly stdoutPath: string; +} + +/** A CLI this server started, registered so shutdown can leave it running. */ +export interface DetachableAgentProcess { + readonly outputDir: string; + readonly threadId: string; + readonly nativeThreadId: string; + readonly pid: number; + readonly unit: string | undefined; + readonly activeRunId: () => string | null; + readonly resumeAfterUuid: () => string | undefined; + /** Tells the process guard not to stop the CLI when this server goes away. */ + readonly detach: () => void; +} + +export interface DetachedAgentTurnsShape { + /** A fresh output directory for one CLI, or undefined where turns cannot survive restarts. */ + readonly allocate: Effect.Effect; + readonly track: (process: DetachableAgentProcess) => Effect.Effect; + /** Forgets a CLI that exited while this server still owned it, and deletes its output. */ + readonly release: (outputDir: string) => Effect.Effect; + /** Leaves running the CLIs whose active run is in `runIds`. Returns how many. */ + readonly detach: (runIds: ReadonlySet) => Effect.Effect; + readonly adoptable: (runId: string) => Effect.Effect; + /** + * Takes the detached turn of a native session. A turn for another run, or + * one with nothing left to show, is stopped instead and yields undefined. + */ + readonly claim: (input: { + readonly nativeThreadId: string; + readonly runId: string | undefined; + }) => Effect.Effect; + readonly alive: (turn: DetachedAgentTurn) => Effect.Effect; + /** Stops an adopted CLI, its scope, and deletes its output. */ + readonly kill: (turn: DetachedAgentTurn) => Effect.Effect; + /** Reaps what an adopted CLI left after it exited, and deletes its output. */ + readonly finish: (turn: DetachedAgentTurn) => Effect.Effect; +} + +export const DetachedAgentTurns = Context.Reference( + "t3/process/DetachedAgentTurns", + { + defaultValue: () => ({ + allocate: Effect.undefined, + track: () => Effect.void, + release: () => Effect.void, + detach: () => Effect.succeed(0), + adoptable: () => Effect.succeed(false), + claim: () => Effect.undefined, + alive: () => Effect.succeed(false), + kill: () => Effect.void, + finish: () => Effect.void, + }), + }, +); + +/** Field 22 of /proc//stat: start time in clock ticks since boot, which tells a reused PID apart. */ +function procStartTime(stat: string): string | undefined { + const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" "); + return fields[19]; +} + +/** Scopes of detached turns that the startup sweep of leftover agents must keep. */ +export const readDetachedAgentUnits = Effect.fn("DetachedAgentTurns.readUnits")(function* ( + stateDir: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = path.join(stateDir, OUTPUT_ROOT); + const units = new Set(); + for (const entry of yield* fileSystem.readDirectory(root).pipe(Effect.orElseSucceed(() => []))) { + const record = yield* fileSystem + .readFileString(path.join(root, entry, RECORD_FILE)) + .pipe(Effect.flatMap(decodeRecord), Effect.option); + if (record._tag === "Some" && record.value.unit !== undefined) units.add(record.value.unit); + } + return units; +}); + +export const make = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + // Liveness checks read /proc; other platforms keep stopping agents on shutdown. + if (platform !== "linux") return DetachedAgentTurns.defaultValue(); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const random = yield* SecureRandom.SecureRandom; + const agentScope = yield* AgentScope; + const { stateDir } = yield* ServerConfig.ServerConfig; + const layerScope = yield* Effect.scope; + const root = path.join(stateDir, OUTPUT_ROOT); + + const tracked = new Map(); + const pending = new Map(); + + const removeDir = (dir: string) => + fileSystem.remove(dir, { recursive: true }).pipe(Effect.ignore); + + const startTimeOf = (pid: number) => + fileSystem.readFileString(`/proc/${pid}/stat`).pipe( + Effect.map(procStartTime), + Effect.orElseSucceed(() => undefined), + ); + + const alive = (turn: DetachedAgentTurn) => + startTimeOf(turn.pid).pipe(Effect.map((startTime) => startTime === turn.startTime)); + + const completesTurn = (turn: DetachedAgentTurn) => + fileSystem.readFile(turn.stdoutPath).pipe( + Effect.map((bytes) => claudeOutputCompletesTurn(bytes, turn.resumeAfterUuid)), + Effect.orElseSucceed(() => false), + ); + + const isAdoptable = (turn: DetachedAgentTurn) => + alive(turn).pipe(Effect.flatMap((live) => (live ? Effect.succeed(true) : completesTurn(turn)))); + + const signal = (turn: DetachedAgentTurn, name: NodeJS.Signals) => + Effect.sync(() => { + try { + signalProcessGroup(turn.pid, name); + } catch {} + }); + + const finish = Effect.fn("DetachedAgentTurns.finish")(function* (turn: DetachedAgentTurn) { + tracked.delete(turn.outputDir); + if (turn.unit !== undefined) yield* agentScope.stop(turn.unit); + yield* removeDir(turn.outputDir); + }); + + const kill = Effect.fn("DetachedAgentTurns.kill")(function* (turn: DetachedAgentTurn) { + tracked.delete(turn.outputDir); + if (yield* alive(turn)) { + yield* signal(turn, "SIGTERM"); + yield* Effect.sleep(KILL_GRACE).pipe( + Effect.andThen(alive(turn)), + Effect.flatMap((live) => (live ? signal(turn, "SIGKILL") : Effect.void)), + Effect.andThen(finish(turn)), + Effect.forkIn(layerScope), + ); + return; + } + yield* finish(turn); + }); + + // Adopt only what the previous server detached; anything else here is output of a CLI it stopped. + for (const entry of yield* fileSystem.readDirectory(root).pipe(Effect.orElseSucceed(() => []))) { + const outputDir = path.join(root, entry); + const record = yield* fileSystem + .readFileString(path.join(outputDir, RECORD_FILE)) + .pipe(Effect.flatMap(decodeRecord), Effect.option); + if (record._tag === "None") { + yield* removeDir(outputDir); + continue; + } + const turn: DetachedAgentTurn = { + ...record.value, + outputDir, + stdoutPath: path.join(outputDir, DETACHED_STDOUT_FILE), + }; + const previous = pending.get(turn.nativeThreadId); + if ((yield* isAdoptable(turn)) && previous === undefined) { + pending.set(turn.nativeThreadId, turn); + yield* Effect.logInfo("Found an agent turn that kept running through a restart", { + threadId: turn.threadId, + runId: turn.runId, + }); + } else { + yield* kill(turn); + } + } + + if (pending.size > 0) { + yield* Effect.sleep(UNCLAIMED_DEADLINE).pipe( + Effect.andThen( + Effect.suspend(() => { + const unclaimed = [...pending.values()]; + pending.clear(); + return Effect.forEach( + unclaimed, + (turn) => + Effect.logWarning("Stopping an agent turn no thread adopted after a restart", { + threadId: turn.threadId, + runId: turn.runId, + }).pipe(Effect.andThen(kill(turn))), + { discard: true }, + ); + }), + ), + Effect.forkIn(layerScope), + ); + } + + return DetachedAgentTurns.of({ + allocate: Effect.gen(function* () { + const dir = path.join(root, yield* random.uuidV4()); + return yield* fileSystem.makeDirectory(dir, { recursive: true }).pipe( + Effect.as(dir), + Effect.orElseSucceed(() => undefined), + ); + }), + track: Effect.fn("DetachedAgentTurns.track")((process: DetachableAgentProcess) => + Effect.sync(() => void tracked.set(process.outputDir, process)), + ), + release: Effect.fn("DetachedAgentTurns.release")(function* (outputDir) { + tracked.delete(outputDir); + yield* removeDir(outputDir); + }), + detach: Effect.fn("DetachedAgentTurns.detach")(function* (runIds) { + let detached = 0; + const detachedAt = DateTime.formatIso(yield* DateTime.now); + for (const process of tracked.values()) { + const runId = process.activeRunId(); + if (runId === null || !runIds.has(runId)) continue; + const startTime = yield* startTimeOf(process.pid); + if (startTime === undefined) continue; + const resumeAfterUuid = process.resumeAfterUuid(); + const written = yield* encodeRecord({ + version: 1, + driver: "claude", + threadId: process.threadId, + runId, + nativeThreadId: process.nativeThreadId, + pid: process.pid, + startTime, + ...(process.unit === undefined ? {} : { unit: process.unit }), + ...(resumeAfterUuid === undefined ? {} : { resumeAfterUuid }), + detachedAt, + }).pipe( + Effect.flatMap((json) => + fileSystem.writeFileString(path.join(process.outputDir, RECORD_FILE), json), + ), + Effect.option, + ); + if (written._tag === "None") continue; + process.detach(); + tracked.delete(process.outputDir); + detached += 1; + } + return detached; + }), + adoptable: Effect.fn("DetachedAgentTurns.adoptable")(function* (runId) { + const turn = [...pending.values()].find((candidate) => candidate.runId === runId); + return turn === undefined ? false : yield* isAdoptable(turn); + }), + claim: Effect.fn("DetachedAgentTurns.claim")(function* ({ nativeThreadId, runId }) { + const turn = pending.get(nativeThreadId); + if (turn === undefined) return undefined; + pending.delete(nativeThreadId); + if (turn.runId === runId && (yield* isAdoptable(turn))) { + // A crash during adoption must not adopt the same output twice. + yield* fileSystem.remove(path.join(turn.outputDir, RECORD_FILE)).pipe(Effect.ignore); + return turn; + } + yield* kill(turn); + return undefined; + }), + alive, + kill, + finish, + }); +}); + +export const layer = Layer.effect(DetachedAgentTurns, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 47190f60dcf51..9bf85c88b7dae 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -38,6 +38,7 @@ import { import { fixPath } from "./os-jank.ts"; import * as Ws from "./ws.ts"; import * as AgentScopeLive from "./process/agentScope.ts"; +import * as DetachedAgentTurns from "./process/detachedAgentTurns.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; import * as NodePtyAdapter from "./terminal/NodePtyAdapter.ts"; import * as PullRequestHttp from "./pullRequest/http.ts"; @@ -1221,6 +1222,7 @@ const layerMakeServer = Layer.unwrap( Layer.provide(layerApplicationObservability), Layer.provideMerge(FetchHttpClient.layer), Layer.provide(VcsProcess.layer), + Layer.provideMerge(DetachedAgentTurns.layer), Layer.provideMerge(AgentScopeLive.layer), Layer.provideMerge(layerPlatformServices), ); diff --git a/apps/server/src/serverRuntimeStartup.autoPull.test.ts b/apps/server/src/serverRuntimeStartup.autoPull.test.ts index 549aae79e8be5..041fda8ae16bf 100644 --- a/apps/server/src/serverRuntimeStartup.autoPull.test.ts +++ b/apps/server/src/serverRuntimeStartup.autoPull.test.ts @@ -113,7 +113,7 @@ it.effect("parks automatic pull until activation without delaying command readin }), Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({ recover: Effect.succeed(recovery), - prepareForShutdown: Effect.void, + prepareForShutdown: Effect.succeed(new Set()), reconcile: () => Effect.succeed(recovery), }), Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }), diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index e91a0ac1ac65e..a17e68b56542d 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -112,7 +112,7 @@ it.effect.each([ }), Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({ recover: Effect.succeed(recovery), - prepareForShutdown: Effect.void, + prepareForShutdown: Effect.succeed(new Set()), reconcile: () => Effect.succeed(recovery), }), Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }), diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 26f91f59affc9..9980fb0336877 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -36,6 +36,7 @@ import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1Threa import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts"; import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; +import * as DetachedAgentTurns from "./process/detachedAgentTurns.ts"; import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts"; import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "./project/ProjectService.ts"; @@ -447,6 +448,7 @@ const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: Startup const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; const orchestrator = yield* Orchestrator.OrchestratorV2; const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + const detachedTurns = yield* DetachedAgentTurns.DetachedAgentTurns; const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; const serverSettings = yield* ServerSettings.ServerSettingsService; @@ -473,6 +475,18 @@ const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: Startup yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore); } yield* providerRuntimeRecovery.prepareForShutdown.pipe( + // Turns the next server continues keep running; it adopts their output. + Effect.tap((continued) => + detachedTurns + .detach(continued) + .pipe( + Effect.tap((detached) => + detached === 0 + ? Effect.void + : Effect.logInfo("Left agent turns running through the restart", { detached }), + ), + ), + ), Effect.ensuring(providerSessions.shutdown), ); const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");