@devries-cameron20 / t3code Mirror · read-only / commits / 0072f66ec1
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 08:30 UTC

fix(server): retry a fresh Claude session once after a startup or MCP registration timeout (#37943)

Julius Marminge committed Nov 16, 2026 at 22:39 UTC 0072f66ec125bc54ced9d6ef2cedc818622934d8
2 files changed +504 -496
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+459 -463
@@ -1453,490 +1453,486 @@ export const layerQueryRunner: Layer.Layer<
1453 return { refresh: refresh(true).pipe(Effect.asVoid), stop };
1454 };
1455
1456 - return ClaudeAgentSdkQueryRunner.of({
1457 - allocateSessionId: random.uuidV4(),
1458 - open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(
1459 - function* (input: ClaudeAgentSdkQueryOpenInput) {
1460 - const protocolLogger = makeClaudeAgentSdkProtocolLogger({
1461 - nativeEventLogger,
1462 - threadId: input.threadId,
1463 - providerSessionId: input.providerSessionId,
1456 + // The open span below is the tracing boundary for both attempts.
1457 + const openQuery = Effect.fnUntraced(function* (input: ClaudeAgentSdkQueryOpenInput) {
1458 + const protocolLogger = makeClaudeAgentSdkProtocolLogger({
1459 + nativeEventLogger,
1460 + threadId: input.threadId,
1461 + providerSessionId: input.providerSessionId,
1462 + });
1463 + const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
1464 + protocolLogger === undefined ? Effect.void : protocolLogger(event);
1465 + // A failed open shuts down its queue before retrying, so the old CLI cannot take the prompt.
1466 + const promptQueue = yield* Queue.unbounded<SDKUserMessage>();
1467 + const prompt = Stream.fromQueue(promptQueue).pipe(
1468 + Stream.catchCause((cause) =>
1469 + Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
1470 + ),
1471 + Stream.toAsyncIterable,
1472 + );
1473 + // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
1474 + const { mcpServers, ...sdkOptions } = input.options;
1475 + // Jobs the agent starts inherit the thread, so port discovery can attribute their servers.
1476 + let resumeSessionAt = sdkOptions.resumeSessionAt;
1477 + if (input.resume && sdkOptions.resume !== undefined) {
1478 + const messages = yield* runClaudeWorker({
1479 + method: "getSessionMessages",
1480 + sessionId: sdkOptions.resume,
1481 + options: sdkOptions.cwd === undefined ? {} : { dir: sdkOptions.cwd },
1482 + environment: sdkOptions.env ?? hostEnvironment,
1483 + }).pipe(
1484 + Effect.flatMap(decodeClaudeHistoryMessages),
1485 + Effect.mapError((cause) => queryRunnerError(cause, "getSessionMessages")),
1486 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1487 + Effect.provideService(Path.Path, path),
1488 + );
1489 + const boundary =
1490 + resumeSessionAt === undefined
1491 + ? messages.length
1492 + : messages.findIndex((message) => message.uuid === resumeSessionAt) + 1;
1493 + resumeSessionAt = claudeResumeSessionAt(messages.slice(0, boundary)) ?? resumeSessionAt;
1494 + }
1495 + const queryOptions = {
1496 + ...sdkOptions,
1497 + ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }),
1498 + env: {
1499 + ...(sdkOptions.env ?? hostEnvironment),
1500 + ...(input.resume
1501 + ? {
1502 + CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1",
1503 + CLAUDE_CODE_RESUME_REASON: "user_resume",
1504 + }
1505 + : {}),
1506 + [PortScanner.AGENT_THREAD_ENV]: input.threadId,
1507 + },
1508 + };
1509 + // The SDK can prepend a scope wrapper to native binaries; script entries run through node.
1510 + const binaryPath = queryOptions.pathToClaudeCodeExecutable;
1511 + const launch =
1512 + binaryPath === undefined || CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext))
1513 + ? undefined
1514 + : yield* agentScope.wrap({
1515 + command: binaryPath,
1516 + args: [],
1517 + name: "claude",
1518 + threadId: input.threadId,
1519 + env: queryOptions.env,
1520 + });
1521 + const options =
1522 + launch === undefined || launch.args.length === 0
1523 + ? queryOptions
1524 + : {
1525 + ...queryOptions,
1526 + pathToClaudeCodeExecutable: launch.command,
1527 + executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])],
1528 + };
1529 + const unit = launch?.unit;
1530 + const stopScope = unit === undefined ? undefined : () => void runFork(agentScope.stop(unit));
1531 + // Only a CLI that fails before its first message explains itself on
1532 + // stderr. The known root refusal becomes a curated failure; any other
1533 + // stderr can hold private text, so it stays out of turn failures.
1534 + let stderrTail = "";
1535 + let stderrClosed: Promise<void> = Promise.resolve();
1536 + let answered = false;
1537 + let conversationMissing = false;
1538 + const appendStderr = (text: string) => {
1539 + if (answered) return;
1540 + stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
1541 + };
1542 + let refreshDescendants: Effect.Effect<void> = Effect.void;
1543 + const spawnProcess =
1544 + options.spawnClaudeCodeProcess ??
1545 + ((spawnOptions: ClaudeSpawnOptions) => {
1546 + if (platform !== "win32") {
1547 + // Node can report "exit" before it has read the stderr the CLI wrote.
1548 + let stderrDone = () => {};
1549 + stderrClosed = new Promise((resolve) => (stderrDone = resolve));
1550 + const child = spawnClaudeProcessGroup(
1551 + spawnOptions,
1552 + stopScope,
1553 + appendStderr,
1554 + stderrDone,
1555 + providerProcesses.register,
1556 + );
1557 + if (unit === undefined && child.pid !== undefined) {
1558 + const tracker = trackDescendants(child.pid);
1559 + const polling = runFork(
1560 + tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))),
1561 + );
1562 + child.once("exit", () =>
1563 + runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))),
1564 + );
1565 + refreshDescendants = tracker.refresh;
1566 + }
1567 + return child;
1568 + }
1569 + const child = SpawnWorker.spawnPiped(spawnOptions.command, spawnOptions.args, {
1570 + cwd: spawnOptions.cwd,
1571 + env: spawnOptions.env,
1572 + signal: spawnOptions.signal,
1573 + windowsHide: true,
1574 });
1465 - const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
1466 - protocolLogger === undefined ? Effect.void : protocolLogger(event);
1467 - // A failed open shuts down its queue before retrying, so the old CLI cannot take the prompt.
1468 - const promptQueue = yield* Queue.unbounded<SDKUserMessage>();
1469 - const prompt = Stream.fromQueue(promptQueue).pipe(
1470 - Stream.catchCause((cause) =>
1471 - Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
1575 + child.stderr.setEncoding("utf8").on("data", (chunk: string) => options.stderr?.(chunk));
1576 + return child;
1577 + });
1578 + let spawnedProcess: ClaudeSpawnedProcess | undefined;
1579 + let processExited = false;
1580 + let processExit: Promise<void> | undefined;
1581 + const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => {
1582 + const child = spawnProcess(spawnOptions);
1583 + spawnedProcess = child;
1584 + // A spawn that fails emits only "error".
1585 + const releaseAgent = portDiscovery.trackAgent();
1586 + child.once("exit", releaseAgent);
1587 + child.on("error", releaseAgent);
1588 + processExited = child.exitCode !== null || child.signalCode != null;
1589 + processExit = new Promise<void>((resolve) => {
1590 + if (processExited) resolve();
1591 + else
1592 + child.once("exit", () => {
1593 + processExited = true;
1594 + resolve();
1595 + });
1596 + });
1597 + return child;
1598 + };
1599 + const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
1600 + Effect.try({
1601 + try: () =>
1602 + withoutClaudeCanUseToolShadowedWarning(() =>
1603 + query({
1604 + prompt,
1605 + options: { ...options, spawnClaudeCodeProcess },
1606 + }),
1607 ),
1473 - Stream.toAsyncIterable,
1474 - );
1475 - // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
1476 - const { mcpServers, ...sdkOptions } = input.options;
1477 - // Jobs the agent starts inherit the thread, so port discovery can attribute their servers.
1478 - let resumeSessionAt = sdkOptions.resumeSessionAt;
1479 - if (input.resume && sdkOptions.resume !== undefined) {
1480 - const messages = yield* runClaudeWorker({
1481 - method: "getSessionMessages",
1482 - sessionId: sdkOptions.resume,
1483 - options: sdkOptions.cwd === undefined ? {} : { dir: sdkOptions.cwd },
1484 - environment: sdkOptions.env ?? hostEnvironment,
1485 - }).pipe(
1486 - Effect.flatMap(decodeClaudeHistoryMessages),
1487 - Effect.mapError((cause) => queryRunnerError(cause, "getSessionMessages")),
1488 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1489 - Effect.provideService(Path.Path, path),
1490 - );
1491 - const boundary =
1492 - resumeSessionAt === undefined
1493 - ? messages.length
1494 - : messages.findIndex((message) => message.uuid === resumeSessionAt) + 1;
1495 - resumeSessionAt = claudeResumeSessionAt(messages.slice(0, boundary)) ?? resumeSessionAt;
1496 - }
1497 - const queryOptions = {
1498 - ...sdkOptions,
1499 - ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }),
1500 - env: {
1501 - ...(sdkOptions.env ?? hostEnvironment),
1502 - ...(input.resume
1503 - ? {
1504 - CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1",
1505 - CLAUDE_CODE_RESUME_REASON: "user_resume",
1506 - }
1507 - : {}),
1508 - [PortScanner.AGENT_THREAD_ENV]: input.threadId,
1509 - },
1510 - };
1511 - // The SDK can prepend a scope wrapper to native binaries; script entries run through node.
1512 - const binaryPath = queryOptions.pathToClaudeCodeExecutable;
1513 - const launch =
1514 - binaryPath === undefined ||
1515 - CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext))
1516 - ? undefined
1517 - : yield* agentScope.wrap({
1518 - command: binaryPath,
1519 - args: [],
1520 - name: "claude",
1521 - threadId: input.threadId,
1522 - env: queryOptions.env,
1523 - });
1524 - const options =
1525 - launch === undefined || launch.args.length === 0
1526 - ? queryOptions
1527 - : {
1528 - ...queryOptions,
1529 - pathToClaudeCodeExecutable: launch.command,
1530 - executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])],
1531 - };
1532 - const unit = launch?.unit;
1533 - const stopScope =
1534 - unit === undefined ? undefined : () => void runFork(agentScope.stop(unit));
1535 - // Only a CLI that fails before its first message explains itself on
1536 - // stderr. The known root refusal becomes a curated failure; any other
1537 - // stderr can hold private text, so it stays out of turn failures.
1538 - let stderrTail = "";
1539 - let stderrClosed: Promise<void> = Promise.resolve();
1540 - let answered = false;
1541 - let conversationMissing = false;
1542 - const appendStderr = (text: string) => {
1543 - if (answered) return;
1544 - stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
1545 - };
1546 - let refreshDescendants: Effect.Effect<void> = Effect.void;
1547 - const spawnProcess =
1548 - options.spawnClaudeCodeProcess ??
1549 - ((spawnOptions: ClaudeSpawnOptions) => {
1550 - if (platform !== "win32") {
1551 - // Node can report "exit" before it has read the stderr the CLI wrote.
1552 - let stderrDone = () => {};
1553 - stderrClosed = new Promise((resolve) => (stderrDone = resolve));
1554 - const child = spawnClaudeProcessGroup(
1555 - spawnOptions,
1556 - stopScope,
1557 - appendStderr,
1558 - stderrDone,
1559 - providerProcesses.register,
1560 - );
1561 - if (unit === undefined && child.pid !== undefined) {
1562 - const tracker = trackDescendants(child.pid);
1563 - const polling = runFork(
1564 - tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))),
1608 + catch: (cause) => queryRunnerError(cause, "query"),
1609 + }).pipe(
1610 + Effect.tap((queryRuntime) =>
1611 + restore(
1612 + Effect.gen(function* () {
1613 + if (mcpServers !== undefined) {
1614 + const timedOut = (phase: ClaudeMcpRegistrationTimeoutError["phase"]) => () =>
1615 + Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", {
1616 + threadId: input.threadId,
1617 + providerSessionId: input.providerSessionId,
1618 + phase,
1619 + }).pipe(
1620 + Effect.andThen(
1621 + Effect.fail(
1622 + queryRunnerError(new ClaudeMcpRegistrationTimeoutError({ phase }), phase),
1623 + ),
1624 + ),
1625 + );
1626 + // The SDK leaves query() boot unbounded, and it takes about a minute on a host
1627 + // with CPUs 12x oversubscribed, so it gets its own, longer deadline.
1628 + yield* Effect.promise(() =>
1629 + queryRuntime.initializationResult().catch(() => undefined),
1630 + ).pipe(
1631 + Effect.timeoutOrElse({
1632 + duration: CLAUDE_BOOT_TIMEOUT,
1633 + orElse: timedOut("initialize"),
1634 + }),
1635 );
1566 - child.once("exit", () =>
1567 - runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))),
1636 + // Errors and mcp_status can echo headers; log only server names.
1637 + const failed = yield* Effect.tryPromise({
1638 + try: () => queryRuntime.setMcpServers(mcpServers),
1639 + catch: (cause) => queryRunnerError(cause, "setMcpServers"),
1640 + }).pipe(
1641 + Effect.map((result) => Object.keys(result.errors)),
1642 + Effect.orElseSucceed(() => Object.keys(mcpServers)),
1643 + Effect.timeoutOrElse({
1644 + duration: CLAUDE_MCP_REGISTRATION_TIMEOUT,
1645 + orElse: timedOut("setMcpServers"),
1646 + }),
1647 );
1569 - refreshDescendants = tracker.refresh;
1648 + if (failed.length > 0) {
1649 + yield* Effect.logWarning("orchestration-v2.claude-mcp-servers-unavailable", {
1650 + threadId: input.threadId,
1651 + servers: failed,
1652 + });
1653 + }
1654 }
1571 - return child;
1572 - }
1573 - const child = SpawnWorker.spawnPiped(spawnOptions.command, spawnOptions.args, {
1574 - cwd: spawnOptions.cwd,
1575 - env: spawnOptions.env,
1576 - signal: spawnOptions.signal,
1577 - windowsHide: true,
1578 - });
1579 - child.stderr
1580 - .setEncoding("utf8")
1581 - .on("data", (chunk: string) => options.stderr?.(chunk));
1582 - return child;
1583 - });
1584 - let spawnedProcess: ClaudeSpawnedProcess | undefined;
1585 - let processExited = false;
1586 - let processExit: Promise<void> | undefined;
1587 - const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => {
1588 - const child = spawnProcess(spawnOptions);
1589 - spawnedProcess = child;
1590 - // A spawn that fails emits only "error".
1591 - const releaseAgent = portDiscovery.trackAgent();
1592 - child.once("exit", releaseAgent);
1593 - child.on("error", releaseAgent);
1594 - processExited = child.exitCode !== null || child.signalCode != null;
1595 - processExit = new Promise<void>((resolve) => {
1596 - if (processExited) resolve();
1597 - else
1598 - child.once("exit", () => {
1599 - processExited = true;
1600 - resolve();
1655 + yield* logProtocolEvent({
1656 + direction: "outgoing",
1657 + stage: "decoded",
1658 + payload: {
1659 + type: "query.open",
1660 + options: loggedClaudeQueryOptions(input.options),
1661 + },
1662 });
1602 - });
1603 - return child;
1604 - };
1605 - const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
1606 - Effect.try({
1607 - try: () =>
1608 - withoutClaudeCanUseToolShadowedWarning(() =>
1609 - query({
1610 - prompt,
1611 - options: { ...options, spawnClaudeCodeProcess },
1612 - }),
1613 - ),
1614 - catch: (cause) => queryRunnerError(cause, "query"),
1615 - }).pipe(
1616 - Effect.tap((queryRuntime) =>
1617 - restore(
1618 - Effect.gen(function* () {
1619 - if (mcpServers !== undefined) {
1620 - const timedOut = (phase: ClaudeMcpRegistrationTimeoutError["phase"]) => () =>
1621 - Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", {
1622 - threadId: input.threadId,
1623 - providerSessionId: input.providerSessionId,
1624 - phase,
1625 - }).pipe(
1626 - Effect.andThen(
1627 - Effect.fail(
1628 - queryRunnerError(
1629 - new ClaudeMcpRegistrationTimeoutError({ phase }),
1630 - phase,
1631 - ),
1632 - ),
1633 - ),
1634 - );
1635 - // The SDK leaves query() boot unbounded, and it takes about a minute on a host
1636 - // with CPUs 12x oversubscribed, so it gets its own, longer deadline.
1637 - yield* Effect.promise(() =>
1638 - queryRuntime.initializationResult().catch(() => undefined),
1639 - ).pipe(
1640 - Effect.timeoutOrElse({
1641 - duration: CLAUDE_BOOT_TIMEOUT,
1642 - orElse: timedOut("initialize"),
1643 - }),
1644 - );
1645 - // Errors and mcp_status can echo headers; log only server names.
1646 - const failed = yield* Effect.tryPromise({
1647 - try: () => queryRuntime.setMcpServers(mcpServers),
1648 - catch: (cause) => queryRunnerError(cause, "setMcpServers"),
1649 - }).pipe(
1650 - Effect.map((result) => Object.keys(result.errors)),
1651 - Effect.orElseSucceed(() => Object.keys(mcpServers)),
1652 - Effect.timeoutOrElse({
1653 - duration: CLAUDE_MCP_REGISTRATION_TIMEOUT,
1654 - orElse: timedOut("setMcpServers"),
1655 - }),
1656 - );
1657 - if (failed.length > 0) {
1658 - yield* Effect.logWarning(
1659 - "orchestration-v2.claude-mcp-servers-unavailable",
1660 - {
1661 - threadId: input.threadId,
1662 - servers: failed,
1663 - },
1664 - );
1665 - }
1666 - }
1667 - yield* logProtocolEvent({
1668 - direction: "outgoing",
1669 - stage: "decoded",
1670 - payload: {
1671 - type: "query.open",
1672 - options: loggedClaudeQueryOptions(input.options),
1663 + }),
1664 + ).pipe(
1665 + Effect.onError(() =>
1666 + Queue.shutdown(promptQueue).pipe(
1667 + // SDK disposal can return before process exit; await the owned child's exit before retrying.
1668 + Effect.andThen(
1669 + Effect.tryPromise({
1670 + try: async () => {
1671 + if (spawnedProcess !== undefined && !processExited) {
1672 + spawnedProcess.kill("SIGKILL");
1673 + }
1674 + await processExit;
1675 },
1674 - });
1675 - }),
1676 - ).pipe(
1677 - Effect.onError(() =>
1678 - Queue.shutdown(promptQueue).pipe(
1679 - // SDK disposal can return before process exit; await the owned child's exit before retrying.
1680 - Effect.andThen(
1681 - Effect.tryPromise({
1682 - try: async () => {
1683 - if (spawnedProcess !== undefined && !processExited) {
1684 - spawnedProcess.kill("SIGKILL");
1685 - }
1686 - await processExit;
1687 - },
1688 - catch: (cause) => queryRunnerError(cause, "close"),
1689 - }).pipe(Effect.timeout("10 seconds")),
1690 - ),
1691 - Effect.ensuring(
1692 - Effect.tryPromise({
1693 - try: () => queryRuntime[Symbol.asyncDispose](),
1694 - catch: (cause) => queryRunnerError(cause, "close"),
1695 - }).pipe(Effect.orDie),
1696 - ),
1697 - Effect.orDie,
1698 - ),
1676 + catch: (cause) => queryRunnerError(cause, "close"),
1677 + }).pipe(Effect.timeout("10 seconds")),
1678 ),
1679 + Effect.ensuring(
1680 + Effect.tryPromise({
1681 + try: () => queryRuntime[Symbol.asyncDispose](),
1682 + catch: (cause) => queryRunnerError(cause, "close"),
1683 + }).pipe(Effect.orDie),
1684 + ),
1685 + Effect.orDie,
1686 ),
1687 ),
1688 ),
1703 - );
1689 + ),
1690 + ),
1691 + );
1692
1705 - return {
1706 - messages: Stream.fromAsyncIterable(
1707 - claudeQueryMessages(queryRuntime),
1708 - (cause) => cause,
1709 - ).pipe(
1710 - Stream.catch((cause) =>
1711 - Stream.fromEffect(
1712 - Effect.gen(function* () {
1713 - if (!answered) {
1714 - yield* Effect.promise(() => stderrClosed).pipe(
1715 - Effect.timeoutOption(CLAUDE_STDERR_DRAIN_TIMEOUT),
1716 - );
1717 - }
1718 - const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL);
1719 - return yield* queryRunnerError(
1720 - refusedRoot
1721 - ? new ClaudeCodeRootRefusalError({ cause })
1722 - : conversationMissing ||
1723 - (!answered && stderrTail.includes(CLAUDE_CONVERSATION_NOT_FOUND))
1724 - ? new ClaudeConversationNotFoundError({ cause })
1725 - : cause,
1726 - "fromAsyncIterable",
1727 - );
1728 - }),
1729 - ),
1730 - ),
1731 - Stream.tap((message) =>
1732 - Effect.sync(() => {
1733 - answered = true;
1734 - if (
1735 - message.type === "result" &&
1736 - message.subtype !== "success" &&
1737 - message.errors.some((error) => error.startsWith(CLAUDE_CONVERSATION_NOT_FOUND))
1738 - ) {
1739 - conversationMissing = true;
1740 - }
1741 - }),
1742 - ),
1743 - Stream.tap((message) =>
1744 - logProtocolEvent({
1745 - direction: "incoming",
1746 - stage: "decoded",
1747 - payload: message,
1748 - }),
1749 - ),
1693 + return {
1694 + messages: Stream.fromAsyncIterable(
1695 + claudeQueryMessages(queryRuntime),
1696 + (cause) => cause,
1697 + ).pipe(
1698 + Stream.catch((cause) =>
1699 + Stream.fromEffect(
1700 + Effect.gen(function* () {
1701 + if (!answered) {
1702 + yield* Effect.promise(() => stderrClosed).pipe(
1703 + Effect.timeoutOption(CLAUDE_STDERR_DRAIN_TIMEOUT),
1704 + );
1705 + }
1706 + const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL);
1707 + return yield* queryRunnerError(
1708 + refusedRoot
1709 + ? new ClaudeCodeRootRefusalError({ cause })
1710 + : conversationMissing ||
1711 + (!answered && stderrTail.includes(CLAUDE_CONVERSATION_NOT_FOUND))
1712 + ? new ClaudeConversationNotFoundError({ cause })
1713 + : cause,
1714 + "fromAsyncIterable",
1715 + );
1716 + }),
1717 ),
1751 - offer: (message, onQueued) =>
1752 - Effect.uninterruptibleMask((restore) =>
1753 - restore(Queue.offer(promptQueue, message)).pipe(
1754 - Effect.tap(() => Effect.sync(() => onQueued?.())),
1755 - ),
1756 - ).pipe(
1757 - Effect.asVoid,
1758 - Effect.tap(() =>
1759 - logProtocolEvent({
1760 - direction: "outgoing",
1761 - stage: "decoded",
1762 - payload: {
1763 - type: "prompt.offer",
1764 - message,
1765 - },
1766 - }),
1767 - ),
1768 - ),
1769 - setModel: (model) =>
1770 - Effect.tryPromise({
1771 - try: () => queryRuntime.setModel(model),
1772 - catch: (cause) => queryRunnerError(cause, "setModel"),
1773 - }).pipe(
1774 - Effect.tap(() =>
1775 - logProtocolEvent({
1776 - direction: "outgoing",
1777 - stage: "decoded",
1778 - payload: {
1779 - type: "query.set_model",
1780 - model,
1781 - },
1782 - }),
1783 - ),
1784 - ),
1785 - applyFlagSettings: (settings) =>
1786 - Effect.tryPromise({
1787 - try: () => queryRuntime.applyFlagSettings(settings),
1788 - catch: (cause) => queryRunnerError(cause, "applyFlagSettings"),
1789 - }).pipe(
1790 - Effect.tap(() =>
1791 - logProtocolEvent({
1792 - direction: "outgoing",
1793 - stage: "decoded",
1794 - payload: {
1795 - type: "query.apply_flag_settings",
1796 - settings,
1797 - },
1798 - }),
1799 - ),
1800 - ),
1801 - setPermissionMode: (mode) =>
1802 - Effect.tryPromise({
1803 - try: () => queryRuntime.setPermissionMode(mode),
1804 - catch: (cause) => queryRunnerError(cause, "setPermissionMode"),
1805 - }).pipe(
1806 - Effect.tap(() =>
1807 - logProtocolEvent({
1808 - direction: "outgoing",
1809 - stage: "decoded",
1810 - payload: {
1811 - type: "query.set_permission_mode",
1812 - mode,
1813 - },
1814 - }),
1815 - ),
1816 - ),
1817 - renameSession: (title) =>
1818 - Effect.tryPromise({
1819 - try: () =>
1820 - sendClaudeControlRequest(queryRuntime, {
1821 - subtype: "rename_session",
1822 - title,
1823 - source: "host",
1824 - }),
1825 - catch: (cause) => queryRunnerError(cause, "renameSession"),
1826 - }).pipe(
1827 - Effect.asVoid,
1828 - Effect.tap(() =>
1829 - logProtocolEvent({
1830 - direction: "outgoing",
1831 - stage: "decoded",
1832 - payload: {
1833 - type: "query.rename_session",
1834 - title,
1835 - },
1836 - }),
1837 - ),
1838 - ),
1839 - stopTask: (taskId) =>
1840 - Effect.tryPromise({
1841 - try: () => queryRuntime.stopTask(taskId),
1842 - catch: (cause) => queryRunnerError(cause, "stopTask"),
1843 - }).pipe(
1844 - Effect.tap(() =>
1845 - logProtocolEvent({
1846 - direction: "outgoing",
1847 - stage: "decoded",
1848 - payload: { type: "query.stop_task", taskId },
1849 - }),
1850 - ),
1851 - ),
1852 - backgroundTasks: (toolUseId) =>
1853 - Effect.tryPromise({
1854 - try: () => queryRuntime.backgroundTasks(toolUseId),
1855 - catch: (cause) => queryRunnerError(cause, "backgroundTasks"),
1856 - }).pipe(
1857 - Effect.tap(() =>
1858 - logProtocolEvent({
1859 - direction: "outgoing",
1860 - stage: "decoded",
1861 - payload: { type: "query.background_tasks", toolUseId },
1862 - }),
1863 - ),
1864 - ),
1865 - mcpServerStatus: Effect.tryPromise({
1866 - try: () => queryRuntime.mcpServerStatus(),
1867 - catch: (cause) => queryRunnerError(cause, "mcpServerStatus"),
1718 + ),
1719 + Stream.tap((message) =>
1720 + Effect.sync(() => {
1721 + answered = true;
1722 + if (
1723 + message.type === "result" &&
1724 + message.subtype !== "success" &&
1725 + message.errors.some((error) => error.startsWith(CLAUDE_CONVERSATION_NOT_FOUND))
1726 + ) {
1727 + conversationMissing = true;
1728 + }
1729 + }),
1730 + ),
1731 + Stream.tap((message) =>
1732 + logProtocolEvent({
1733 + direction: "incoming",
1734 + stage: "decoded",
1735 + payload: message,
1736 }),
1869 - readMcpResource: ({ server, uri }) =>
1870 - Effect.tryPromise({
1871 - try: () => queryRuntime.readMcpResource(server, uri),
1872 - catch: (cause) => queryRunnerError(cause, "readMcpResource"),
1737 + ),
1738 + ),
1739 + offer: (message, onQueued) =>
1740 + Effect.uninterruptibleMask((restore) =>
1741 + restore(Queue.offer(promptQueue, message)).pipe(
1742 + Effect.tap(() => Effect.sync(() => onQueued?.())),
1743 + ),
1744 + ).pipe(
1745 + Effect.asVoid,
1746 + Effect.tap(() =>
1747 + logProtocolEvent({
1748 + direction: "outgoing",
1749 + stage: "decoded",
1750 + payload: {
1751 + type: "prompt.offer",
1752 + message,
1753 + },
1754 }),
1874 - callMcpTool: (call) =>
1875 - Effect.tryPromise({
1876 - try: () =>
1877 - sendClaudeControlRequest(queryRuntime, {
1878 - subtype: "mcp_call",
1879 - tool: call.tool,
1880 - arguments: call.arguments,
1881 - result_not_for_model: true,
1882 - }),
1883 - catch: (cause) => queryRunnerError(cause, "callMcpTool"),
1755 + ),
1756 + ),
1757 + setModel: (model) =>
1758 + Effect.tryPromise({
1759 + try: () => queryRuntime.setModel(model),
1760 + catch: (cause) => queryRunnerError(cause, "setModel"),
1761 + }).pipe(
1762 + Effect.tap(() =>
1763 + logProtocolEvent({
1764 + direction: "outgoing",
1765 + stage: "decoded",
1766 + payload: {
1767 + type: "query.set_model",
1768 + model,
1769 + },
1770 }),
1885 - listPermissionRules: Effect.tryPromise({
1886 - try: () =>
1887 - sendClaudeControlRequest(queryRuntime, { subtype: "list_permission_rules" }),
1888 - catch: (cause) => queryRunnerError(cause, "listPermissionRules"),
1889 - }).pipe(
1890 - Effect.flatMap(decodeClaudePermissionRules),
1891 - // A settings file Claude couldn't parse was skipped, so its rules are missing from the list.
1892 - Effect.filterOrFail(
1893 - ({ state }) => (state.errors ?? []).length === 0,
1894 - ({ state }) => new Error(`Claude skipped ${state.errors?.length} settings file(s)`),
1895 - ),
1896 - Effect.map(({ state }) => state.rules),
1897 - Effect.mapError((cause) => queryRunnerError(cause, "listPermissionRules")),
1771 ),
1899 - interrupt: Effect.tryPromise({
1900 - try: () => queryRuntime.interrupt(),
1901 - catch: (cause) => queryRunnerError(cause, "interrupt"),
1902 - }).pipe(
1903 - Effect.tap(() =>
1904 - logProtocolEvent({
1905 - direction: "outgoing",
1906 - stage: "decoded",
1907 - payload: {
1908 - type: "query.interrupt",
1909 - },
1910 - }),
1911 - ),
1772 + ),
1773 + applyFlagSettings: (settings) =>
1774 + Effect.tryPromise({
1775 + try: () => queryRuntime.applyFlagSettings(settings),
1776 + catch: (cause) => queryRunnerError(cause, "applyFlagSettings"),
1777 + }).pipe(
1778 + Effect.tap(() =>
1779 + logProtocolEvent({
1780 + direction: "outgoing",
1781 + stage: "decoded",
1782 + payload: {
1783 + type: "query.apply_flag_settings",
1784 + settings,
1785 + },
1786 + }),
1787 ),
1913 - // A job started since the last poll is recorded before the CLI is told to exit.
1914 - close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe(
1915 - Effect.andThen(Queue.shutdown(promptQueue)),
1916 - Effect.andThen(closeClaudeQuery(queryRuntime)),
1917 - Effect.tap(() =>
1918 - logProtocolEvent({
1919 - direction: "outgoing",
1920 - stage: "decoded",
1921 - payload: {
1922 - type: "query.close",
1923 - },
1924 - }),
1925 - ),
1788 + ),
1789 + setPermissionMode: (mode) =>
1790 + Effect.tryPromise({
1791 + try: () => queryRuntime.setPermissionMode(mode),
1792 + catch: (cause) => queryRunnerError(cause, "setPermissionMode"),
1793 + }).pipe(
1794 + Effect.tap(() =>
1795 + logProtocolEvent({
1796 + direction: "outgoing",
1797 + stage: "decoded",
1798 + payload: {
1799 + type: "query.set_permission_mode",
1800 + mode,
1801 + },
1802 + }),
1803 ),
1927 - } satisfies ClaudeAgentSdkQuerySession;
1928 - },
1929 - // Fresh IDs may already have a metadata-only transcript; only resumed opens can reuse their ID.
1930 - (effect, input) =>
1931 - effect.pipe(
1932 - Effect.retry({
1933 - times: 1,
1934 - while: (error) =>
1935 - input.options.resume !== undefined &&
1936 - isClaudeMcpRegistrationTimeoutError(error.cause),
1804 + ),
1805 + renameSession: (title) =>
1806 + Effect.tryPromise({
1807 + try: () =>
1808 + sendClaudeControlRequest(queryRuntime, {
1809 + subtype: "rename_session",
1810 + title,
1811 + source: "host",
1812 + }),
1813 + catch: (cause) => queryRunnerError(cause, "renameSession"),
1814 + }).pipe(
1815 + Effect.asVoid,
1816 + Effect.tap(() =>
1817 + logProtocolEvent({
1818 + direction: "outgoing",
1819 + stage: "decoded",
1820 + payload: {
1821 + type: "query.rename_session",
1822 + title,
1823 + },
1824 + }),
1825 + ),
1826 + ),
1827 + stopTask: (taskId) =>
1828 + Effect.tryPromise({
1829 + try: () => queryRuntime.stopTask(taskId),
1830 + catch: (cause) => queryRunnerError(cause, "stopTask"),
1831 + }).pipe(
1832 + Effect.tap(() =>
1833 + logProtocolEvent({
1834 + direction: "outgoing",
1835 + stage: "decoded",
1836 + payload: { type: "query.stop_task", taskId },
1837 + }),
1838 + ),
1839 + ),
1840 + backgroundTasks: (toolUseId) =>
1841 + Effect.tryPromise({
1842 + try: () => queryRuntime.backgroundTasks(toolUseId),
1843 + catch: (cause) => queryRunnerError(cause, "backgroundTasks"),
1844 + }).pipe(
1845 + Effect.tap(() =>
1846 + logProtocolEvent({
1847 + direction: "outgoing",
1848 + stage: "decoded",
1849 + payload: { type: "query.background_tasks", toolUseId },
1850 + }),
1851 + ),
1852 + ),
1853 + mcpServerStatus: Effect.tryPromise({
1854 + try: () => queryRuntime.mcpServerStatus(),
1855 + catch: (cause) => queryRunnerError(cause, "mcpServerStatus"),
1856 + }),
1857 + readMcpResource: ({ server, uri }) =>
1858 + Effect.tryPromise({
1859 + try: () => queryRuntime.readMcpResource(server, uri),
1860 + catch: (cause) => queryRunnerError(cause, "readMcpResource"),
1861 + }),
1862 + callMcpTool: (call) =>
1863 + Effect.tryPromise({
1864 + try: () =>
1865 + sendClaudeControlRequest(queryRuntime, {
1866 + subtype: "mcp_call",
1867 + tool: call.tool,
1868 + arguments: call.arguments,
1869 + result_not_for_model: true,
1870 + }),
1871 + catch: (cause) => queryRunnerError(cause, "callMcpTool"),
1872 + }),
1873 + listPermissionRules: Effect.tryPromise({
1874 + try: () => sendClaudeControlRequest(queryRuntime, { subtype: "list_permission_rules" }),
1875 + catch: (cause) => queryRunnerError(cause, "listPermissionRules"),
1876 + }).pipe(
1877 + Effect.flatMap(decodeClaudePermissionRules),
1878 + // A settings file Claude couldn't parse was skipped, so its rules are missing from the list.
1879 + Effect.filterOrFail(
1880 + ({ state }) => (state.errors ?? []).length === 0,
1881 + ({ state }) => new Error(`Claude skipped ${state.errors?.length} settings file(s)`),
1882 + ),
1883 + Effect.map(({ state }) => state.rules),
1884 + Effect.mapError((cause) => queryRunnerError(cause, "listPermissionRules")),
1885 + ),
1886 + interrupt: Effect.tryPromise({
1887 + try: () => queryRuntime.interrupt(),
1888 + catch: (cause) => queryRunnerError(cause, "interrupt"),
1889 + }).pipe(
1890 + Effect.tap(() =>
1891 + logProtocolEvent({
1892 + direction: "outgoing",
1893 + stage: "decoded",
1894 + payload: {
1895 + type: "query.interrupt",
1896 + },
1897 }),
1898 ),
1939 - ),
1899 + ),
1900 + // A job started since the last poll is recorded before the CLI is told to exit.
1901 + close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe(
1902 + Effect.andThen(Queue.shutdown(promptQueue)),
1903 + Effect.andThen(closeClaudeQuery(queryRuntime)),
1904 + Effect.tap(() =>
1905 + logProtocolEvent({
1906 + direction: "outgoing",
1907 + stage: "decoded",
1908 + payload: {
1909 + type: "query.close",
1910 + },
1911 + }),
1912 + ),
1913 + ),
1914 + } satisfies ClaudeAgentSdkQuerySession;
1915 + });
1916 +
1917 + return ClaudeAgentSdkQueryRunner.of({
1918 + allocateSessionId: random.uuidV4(),
1919 + open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(function* (
1920 + input: ClaudeAgentSdkQueryOpenInput,
1921 + ) {
1922 + // A fresh ID may already have a transcript, so a fresh session retries under a new ID;
1923 + // the adapter adopts it from the init message, as it does after /clear.
1924 + return yield* openQuery(input).pipe(
1925 + Effect.catchIf(
1926 + (error) => isClaudeMcpRegistrationTimeoutError(error.cause),
1927 + Effect.fnUntraced(function* () {
1928 + const { resume, ...options } = input.options;
1929 + if (resume !== undefined) return yield* openQuery(input);
1930 + const sessionId = yield* random.uuidV4();
1931 + return yield* openQuery({ ...input, options: { ...options, sessionId } });
1932 + }),
1933 + ),
1934 + );
1935 + }),
1936 forkSession: Effect.fn("ClaudeAgentSdkQueryRunner.forkSession")(function* (
1937 input: ClaudeAgentSdkSessionForkInput,
1938 ) {
apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+45 -33
@@ -464,21 +464,24 @@ it.effect("cancels a stalled registration without retrying or retaining its prom
464 }).pipe(Effect.provide(realQueryRunner)),
465 );
466
467 -it.effect("does not reuse a fresh session ID after MCP registration times out", () =>
467 +it.effect("retries a fresh session once after MCP registration times out", () =>
468 Effect.gen(function* () {
469 const registrationStarted = Promise.withResolvers<void>();
470 const disposed = vi.fn(async () => {});
471 - const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
472 - () =>
473 - ({
474 - initializationResult: async () => ({}),
475 - setMcpServers: () => {
476 - registrationStarted.resolve();
477 - return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
478 - },
479 - [Symbol.asyncDispose]: disposed,
480 - }) as unknown as ClaudeSdk.Query,
481 - );
471 + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
472 + const first = querySpy.mock.calls.length === 1;
473 + return {
474 + initializationResult: async () => ({}),
475 + setMcpServers: () => {
476 + registrationStarted.resolve();
477 + return first
478 + ? new Promise<ClaudeSdk.McpSetServersResult>(() => {})
479 + : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} });
480 + },
481 + close: vi.fn(),
482 + [Symbol.asyncDispose]: disposed,
483 + } as unknown as ClaudeSdk.Query;
484 + });
485 yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
486 const runner = yield* ClaudeAgentSdkQueryRunner;
487 const { resume, ...options } = resumedMcpQueryInput.options;
@@ -492,9 +495,13 @@ it.effect("does not reuse a fresh session ID after MCP registration times out",
495 yield* TestClock.adjust("90 seconds");
496 const result = yield* Fiber.join(opening);
497
495 - assert.equal(result._tag, "Failure");
496 - assert.equal(querySpy.mock.calls.length, 1);
498 + assert.equal(result._tag, "Success");
499 + if (result._tag === "Success") yield* result.success.close;
500 + assert.equal(querySpy.mock.calls.length, 2);
501 assert.equal(disposed.mock.calls.length, 1);
502 + // A fresh ID may already have a transcript, so the retry must not open it as fresh again.
503 + const retry = querySpy.mock.calls[1]![0].options;
504 + assert.isFalse(retry?.sessionId === resume && retry?.resume === undefined);
505 }).pipe(Effect.provide(realQueryRunner)),
506 );
507
@@ -503,37 +510,42 @@ it.effect.each([
510 ["times out a CLI that never boots", "5 minutes", false],
511 ] as const)("%s", ([, bootWait, boots]) =>
512 Effect.gen(function* () {
506 - const waiting = Promise.withResolvers<void>();
513 + const attempts = [Promise.withResolvers<void>(), Promise.withResolvers<void>()];
514 const booted = Promise.withResolvers<void>();
508 - const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
509 - () =>
510 - ({
511 - initializationResult: () => {
512 - waiting.resolve();
513 - return booted.promise;
514 - },
515 - // The CLI answers control requests only after it has booted.
516 - setMcpServers: async () => {
517 - waiting.resolve();
518 - await booted.promise;
519 - return { added: ["t3-code"], removed: [], errors: {} };
520 - },
521 - close: vi.fn(),
522 - [Symbol.asyncDispose]: async () => {},
523 - }) as unknown as ClaudeSdk.Query,
524 - );
515 + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
516 + const waiting = attempts[querySpy.mock.calls.length - 1]!;
517 + return {
518 + initializationResult: () => {
519 + waiting.resolve();
520 + return booted.promise;
521 + },
522 + // The CLI answers control requests only after it has booted.
523 + setMcpServers: async () => {
524 + waiting.resolve();
525 + await booted.promise;
526 + return { added: ["t3-code"], removed: [], errors: {} };
527 + },
528 + close: vi.fn(),
529 + [Symbol.asyncDispose]: async () => {},
530 + } as unknown as ClaudeSdk.Query;
531 + });
532 yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
533 const runner = yield* ClaudeAgentSdkQueryRunner;
534 const { resume, ...options } = resumedMcpQueryInput.options;
535 const opening = yield* runner
536 .open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume } })
537 .pipe(Effect.result, Effect.forkChild);
531 - yield* Effect.promise(() => waiting.promise);
538 + yield* Effect.promise(() => attempts[0]!.promise);
539 yield* TestClock.adjust(bootWait);
540 if (boots) booted.resolve();
541 + else {
542 + yield* Effect.promise(() => attempts[1]!.promise);
543 + yield* TestClock.adjust(bootWait);
544 + }
545 const result = yield* Fiber.join(opening);
546
547 assert.equal(result._tag, boots ? "Success" : "Failure");
548 + assert.equal(querySpy.mock.calls.length, boots ? 1 : 2);
549 if (result._tag === "Success") yield* result.success.close;
550 else
551 assert.equal(