@integrity-labs/agt-cli 0.28.1264 → 0.28.1266

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/{api-client-Q2FXLBH5.js → api-client-5CNPCJKS.js} +3 -3
  2. package/dist/bin/agt.js +8 -8
  3. package/dist/{chunk-GSMGU2QA.js → chunk-7Z3N4G2Y.js} +6 -6
  4. package/dist/{chunk-5BXIXSSH.js → chunk-BMO6GCK2.js} +2 -2
  5. package/dist/{chunk-C3PSUSJ2.js → chunk-SGYCPC5K.js} +3 -3
  6. package/dist/{chunk-KJ5OCCSJ.js → chunk-W2GHPRPZ.js} +2 -2
  7. package/dist/{chunk-KJ5OCCSJ.js.map → chunk-W2GHPRPZ.js.map} +1 -1
  8. package/dist/{chunk-GZMUGH6X.js → chunk-WJUGK4R5.js} +48 -32
  9. package/dist/chunk-WJUGK4R5.js.map +1 -0
  10. package/dist/{chunk-HJWOXFJM.js → chunk-X2FBQPNR.js} +2 -2
  11. package/dist/{chunk-HYQ7VOC3.js → chunk-XL2HPM67.js} +19 -3
  12. package/dist/chunk-XL2HPM67.js.map +1 -0
  13. package/dist/{claude-code-updater-JQLNRK25.js → claude-code-updater-XISTQTZX.js} +3 -3
  14. package/dist/{claude-pair-runtime-M6VJ3KZ3.js → claude-pair-runtime-2XKML4U6.js} +16 -14
  15. package/dist/claude-pair-runtime-2XKML4U6.js.map +1 -0
  16. package/dist/lib/manager-worker.js +42 -40
  17. package/dist/lib/manager-worker.js.map +1 -1
  18. package/dist/mcp/direct-chat-channel.js +8 -2
  19. package/dist/mcp/index.js +1 -1
  20. package/dist/mcp/origami.js +1 -1
  21. package/dist/mcp/slack-channel.js +8 -2
  22. package/dist/mcp/telegram-channel.js +8 -2
  23. package/dist/mcp/xero.js +727 -169
  24. package/dist/{persistent-session-3OES5QXZ.js → persistent-session-YBCMFF7T.js} +7 -5
  25. package/dist/{responsiveness-probe-BSSNRCPM.js → responsiveness-probe-ZOCD6UYO.js} +5 -5
  26. package/dist/{session-auth-dead-A3TO2N63.js → session-auth-dead-U62KZ342.js} +3 -3
  27. package/package.json +1 -1
  28. package/dist/chunk-GZMUGH6X.js.map +0 -1
  29. package/dist/chunk-HYQ7VOC3.js.map +0 -1
  30. package/dist/claude-pair-runtime-M6VJ3KZ3.js.map +0 -1
  31. /package/dist/{api-client-Q2FXLBH5.js.map → api-client-5CNPCJKS.js.map} +0 -0
  32. /package/dist/{chunk-GSMGU2QA.js.map → chunk-7Z3N4G2Y.js.map} +0 -0
  33. /package/dist/{chunk-5BXIXSSH.js.map → chunk-BMO6GCK2.js.map} +0 -0
  34. /package/dist/{chunk-C3PSUSJ2.js.map → chunk-SGYCPC5K.js.map} +0 -0
  35. /package/dist/{chunk-HJWOXFJM.js.map → chunk-X2FBQPNR.js.map} +0 -0
  36. /package/dist/{claude-code-updater-JQLNRK25.js.map → claude-code-updater-XISTQTZX.js.map} +0 -0
  37. /package/dist/{persistent-session-3OES5QXZ.js.map → persistent-session-YBCMFF7T.js.map} +0 -0
  38. /package/dist/{responsiveness-probe-BSSNRCPM.js.map → responsiveness-probe-ZOCD6UYO.js.map} +0 -0
  39. /package/dist/{session-auth-dead-A3TO2N63.js.map → session-auth-dead-U62KZ342.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/claude-dialogs.ts"],"sourcesContent":["/**\n * ENG-6017: shared Claude Code TUI dialog detection + dismissal.\n *\n * Extracted from persistent-session.ts's acceptDialogs() cascade so the\n * dialog knowledge has exactly one home, consumable from:\n *\n * - `acceptDialogs()` in persistent-session.ts — the spawn-time loop that\n * walks an agent through the first-run dialog cascade (theme → trust →\n * MCP → bypass …).\n * - `channel-input-watchdog.ts` — the per-poll-cycle watchdog that fires\n * Enter at stuck channel input. Before ENG-6017 the watchdog was\n * dialog-blind: when Claude Code's session-feedback dialog (\"How is\n * Claude doing this session?\") overlaid the pane, the watchdog's\n * single-shot Enter went into the dialog instead of the input box and\n * the inbound message sat unsubmitted for 40+ minutes (koda,\n * 2026-06-04) while every health metric stayed green.\n * - `injectMessageWithStatus()` — pre-send pane hygiene on the tmux\n * send-keys fallback path.\n *\n * Living in its own module (rather than persistent-session.ts) breaks the\n * import cycle persistent-session → channel-input-watchdog →\n * persistent-session that a shared export would otherwise create.\n *\n * DEFAULT-DENY: `sweepDialogs()` only ever returns an action for an\n * explicitly recognised dialog. An unknown dialog gets `null` — never a\n * blind Enter — because a future dialog's default option could be\n * destructive. Callers that want visibility into unknown overlays should\n * log the pane themselves.\n */\n\nimport { execFileSync } from 'node:child_process';\n\n/**\n * A recognised dialog plus the keystrokes that dismiss it.\n *\n * `keys` are tmux key names sent as individual `tmux send-keys` calls —\n * never batched into one call, so a multi-byte sequence can't get wrapped\n * into a single bracketed paste (the CSI-u trap documented on\n * defaultArmSender in persistent-session.ts).\n */\nexport interface DialogAction {\n kind:\n | 'theme-picker'\n | 'folder-trust'\n | 'resume-mode'\n | 'dev-channels'\n | 'mcp-servers'\n | 'bypass-permissions'\n | 'session-feedback'\n /** ENG-11865: the first-run acknowledgement after the theme picker. */\n | 'security-notes'\n | 'usage-limit-choice'\n | 'consumer-terms'\n /** ENG-11513: the manager's answer to a dangerous-rm permission prompt. */\n | 'dangerous-rm-backstop'\n /** ENG-11793: approving the key the manager itself injected. */\n | 'custom-api-key';\n /** tmux key names, one send-keys invocation each. */\n keys: readonly string[];\n /** Delay between consecutive key sends (selector dialogs need a beat\n * between picking an option and confirming it). */\n interKeyDelayMs: number;\n /** Past-tense log fragment, e.g. \"Auto-accepted theme picker\". Callers\n * append their own context (`for '<codeName>'` etc.). */\n logMessage: string;\n}\n\n/**\n * Detect whether Claude Code is showing the **login picker** dialog.\n *\n * ENG-4634: this dialog appears when ~/.claude.json is missing or\n * Claude Code can't validate the saved session. Pressing Enter on\n * the default (1. Claude account with subscription) kicks off a\n * browser-based OAuth flow that an unattended agent can't complete —\n * the helper used to fall through to the generic `❯ no Enter to\n * confirm` exit branch and declare the session \"ready\" while the\n * actual claude REPL was still on the picker. Without explicit\n * detection, every manager respawn would silently flip the agent\n * back to the picker and never recover.\n *\n * Pattern matches the literal option strings claude renders. Both\n * 'Claude account with subscription' and 'Anthropic Console account'\n * are present on the picker (and not in the post-login UI), so the\n * conjunction is unambiguous.\n *\n * NOT part of sweepDialogs() — the picker must never be keyed past\n * (it needs an operator OAuth); acceptDialogs() handles it specially.\n */\nexport function isLoginPickerVisible(screen: string): boolean {\n return (\n screen.includes('Select login method') ||\n (screen.includes('Claude account with subscription') &&\n screen.includes('Anthropic Console account'))\n );\n}\n\n/**\n * ENG-10619: the row we ALWAYS pick on Claude Code's consumer-terms dialog.\n *\n * Updates to Consumer Terms and Policies\n * …\n * ❯ 1. Accept terms · Help improve our AI models: ON\n * 2. Accept terms · Help improve our AI models: OFF\n *\n * Enter to confirm · Esc to cancel\n *\n * The cursor defaults to ON, which opts the account's chats and coding\n * sessions into model training and extends retention from 30 days to 5\n * years. A bare Enter would therefore consent on the customer's behalf, so\n * this row is selected by NAME (selectRowKeys) and never by position or\n * default. The `·` is U+00B7, the same separator Claude Code uses in its\n * confirm footer.\n */\nexport const CONSUMER_TERMS_OFF_OPTION =\n 'Accept terms \\u00b7 Help improve our AI models: OFF';\n\n/**\n * ENG-10619: the consumer-terms dialog is on screen. Keyed on the\n * conjunction of the heading and the OFF row's own text so prose that\n * mentions either alone does not match; selectRowKeys still requires a\n * focused modal and a complete option row before anything is keyed.\n */\nexport function isConsumerTermsDialogVisible(screen: string): boolean {\n return (\n screen.includes('Updates to Consumer Terms') &&\n screen.includes(CONSUMER_TERMS_OFF_OPTION)\n );\n}\n\n/**\n * ENG-10619: keys that pick \"Help improve our AI models: OFF\" on a focused\n * consumer-terms dialog, or null (answer nothing) when that row cannot be\n * resolved. Shared by sweepDialogs() and the Claude pair/re-login flow,\n * which drives its own dialog loop.\n */\nexport function consumerTermsOffKeys(screen: string): readonly string[] | null {\n if (!isConsumerTermsDialogVisible(screen)) return null;\n return selectRowKeys(screen, CONSUMER_TERMS_OFF_OPTION);\n}\n\n/**\n * ENG-10972: the operator-facing remedy for a session a human has to unstick at the\n * pane. EVERY \"needs a human\" line goes through this, and that is the point.\n *\n * On 2026-09-24 three Primo Cards agents sat blocked on the rate-limit prompt with\n * the consumer-terms dialog ALSO on the pane. The remedy text said only \"tmux\n * attach\". That dialog's cursor defaults to \"Help improve our AI models: ON\", which\n * opts the CUSTOMER's account into model training and stretches retention from 30\n * days to 5 years. The operator who cleared them by hand was one Enter away from\n * consenting on a customer's behalf, three times, and nothing he was shown said so.\n *\n * The blocking KIND never says \"consumer-terms\": on those panes the blocker was the\n * rate-limit prompt, and the consent dialog sat beside it. So the caller passes\n * whether a consent dialog is VISIBLE on the pane. That is a boolean, which is not\n * pane content, so it may leave the host in an alert row. The pane text itself may\n * not (see summarizeUnanswerablePane).\n *\n * Three states, because one site speaks before the pane has been read:\n * true -> name the safe row, and say not to press Enter\n * false -> the bare attach command; no warning on every hold, or it becomes noise\n * null -> we did not look, so a CONDITIONAL caution rather than silence\n *\n * The named row is `CONSUMER_TERMS_OFF_OPTION`, the same constant the automated\n * sweeper selects by name, so the human and the machine give the same answer.\n */\nexport function paneRemedy(codeName: string, consentDialogVisible: boolean | null): string {\n const attach = `tmux attach -t agt-${codeName}`;\n if (consentDialogVisible === true) {\n return (\n // Never glue punctuation to the command: `${attach}.` is copied as a session\n // named \"agt-<name>.\" that does not exist. Same \" (...)\" shape as the null\n // branch, and single-line because every caller embeds this mid-sentence.\n `${attach} (A CONSENT DIALOG IS ON THIS PANE: do NOT press Enter - the cursor defaults ` +\n `to opting this account into model training. Select \"${CONSUMER_TERMS_OFF_OPTION}\" by name, or Esc)`\n );\n }\n if (consentDialogVisible === null) {\n return (\n `${attach} (if the Consumer Terms dialog is showing, do NOT press Enter on the default - ` +\n `select \"${CONSUMER_TERMS_OFF_OPTION}\" by name)`\n );\n }\n return attach;\n}\n\nconst CUSTOM_API_KEY_DIALOG_TEXT = 'Detected a custom API key';\n\n/**\n * ENG-11793: Claude Code's \"Do you want to use this API key?\" prompt, measured on\n * 2.1.308. Its cursor defaults to \"No (recommended)\". Enter there saves the key as\n * rejected and lands on the login picker, so a bare Enter is the wrong answer.\n */\nexport function isCustomApiKeyDialogVisible(screen: string): boolean {\n const block = focusedModalBlock(screen, CONSENT_BLOCK_LINES);\n return !!block && block.some((line) => line.includes(CUSTOM_API_KEY_DIALOG_TEXT));\n}\n\n/**\n * ENG-11793: does the prompt's own key row show the injected key? The focused block also\n * holds lines of transcript above the prompt, so only the lines between the prompt's own\n * heading and its question count. No recognisable row there means no match.\n */\nfunction promptShowsInjectedKey(screen: string, injectedApiKey: string): boolean {\n // Must match CLAUDE_API_KEY_TAIL_CHARS in claude-config-location.ts: Claude Code stores 20.\n const tail = injectedApiKey.slice(-20);\n const block = focusedModalBlock(screen, CONSENT_BLOCK_LINES) ?? [];\n const heading = lastIndexWhere(block, (line) => line.includes(CUSTOM_API_KEY_DIALOG_TEXT));\n if (heading < 0) return false;\n const after = block.slice(heading + 1);\n const question = after.findIndex((line) => line.includes('Do you want to use this API key'));\n if (question < 0) return false;\n return after\n .slice(0, question)\n .some((line) => line.includes('ANTHROPIC_API_KEY') && line.trimEnd().endsWith(`...${tail}`));\n}\n\n/**\n * ENG-11793: the keys that approve the prompt, or null if we won't answer it.\n *\n * Only ever approves the key the manager injected, matched by the tail on screen.\n * This is the backstop for the config write in `approveApiKeyInClaudeConfig`, for a\n * Claude Code version that changes how approval is stored.\n */\nexport function customApiKeyDialogKeys(\n screen: string,\n injectedApiKey: string | null,\n): readonly string[] | null {\n if (!injectedApiKey || !isCustomApiKeyDialogVisible(screen)) return null;\n if (!promptShowsInjectedKey(screen, injectedApiKey)) return null;\n return selectRowKeys(screen, 'Yes');\n}\n\n/**\n * ENG-11793: why `customApiKeyDialogKeys` declined, in words for the log. These point\n * triage in different directions, so they must not share one message.\n */\nexport function customApiKeyDialogRefusal(screen: string, injectedApiKey: string | null): string {\n if (!injectedApiKey) return 'the manager did not inject a key for this session, so the key on screen came from elsewhere';\n if (!promptShowsInjectedKey(screen, injectedApiKey)) {\n return 'the key on screen does not match the injected key, or Claude Code rendered it differently';\n }\n return 'the key matched, but the Yes row or the cursor could not be read';\n}\n\n/**\n * ENG-11793: what to do about the login picker. An API-key host has no account to\n * pair, so \"pair\" or \"/login\" is the wrong advice there.\n */\nexport function loginPickerAdvice(apiKeyHost: boolean): string {\n return apiKeyHost\n ? 'this is an API-key host, so do not re-pair or run /login. Claude Code did not accept the key: ' +\n 'check that the host has a key set and that it is in the session'\n : \"agent cannot start until ~/.claude.json is provisioned. Pair via the Hosts page or run 'claude /login' on the host\";\n}\n\n/**\n * Detect Claude Code's resume-mode dialog (ENG-5364).\n *\n * On `claude --resume <uuid>` against a transcript large enough to\n * trigger Claude Code 2.1.x's context-management heuristic, the agent\n * lands on an interactive picker offering:\n *\n * ❯ 1. Resume from summary (recommended)\n * 2. Resume full session as-is\n * 3. Don't ask me again\n *\n * Without auto-dismissal the agent sits silently waiting for keyboard\n * input on every manager respawn — channel inbounds stack up while\n * health metrics stay green. Surfaced fleet-wide on 2026-05-20\n * (don/stirling/maven hit it on a single manager restart).\n *\n * Match on the conjunction of two distinct option strings so a\n * passing mention of \"Resume\" in a transcript doesn't false-positive.\n */\nexport function isResumeModeDialogVisible(screen: string): boolean {\n return (\n screen.includes('Resume from summary') &&\n screen.includes(\"Don't ask me again\")\n );\n}\n\n/**\n * Detect Claude Code's session-feedback dialog (ENG-6017).\n *\n * After some turns Claude Code renders an optional rating prompt:\n *\n * ● How is Claude doing this session? (optional)\n * 1: Bad 2: Fine 3: Good 0: Dismiss\n *\n * It waits for a digit — Enter does nothing — so any injected message\n * sits in the input box unsubmitted, and the channel-input-watchdog's\n * Enter is swallowed too. Observed live on koda (agt-aws-1) 2026-06-04:\n * an operator Slack DM sat typed-but-unsubmitted for 40+ minutes behind\n * this dialog while pane-activity / synthetic-probe / heartbeat all\n * stayed green.\n *\n * Match the question text together with the literal `0: Dismiss` option\n * so a transcript merely *quoting* the question doesn't false-positive.\n */\nexport function isSessionFeedbackDialogVisible(screen: string): boolean {\n return (\n screen.includes('How is Claude doing this session') &&\n screen.includes('0: Dismiss')\n );\n}\n\n/**\n * The stop-the-session safe option (ENG-8213). Exported so tests and callers\n * assert against the same literal the matcher uses, rather than a copy that\n * could drift.\n *\n * Kept as the name it has always had because callers and tests reference it,\n * but it is no longer the ONLY option this module selects — see\n * `USAGE_LIMIT_SAFE_OPTIONS` for the full preference order.\n */\nexport const USAGE_LIMIT_SAFE_OPTION = 'Stop and wait for limit to reset';\n\n/**\n * The auto-continue option, added by Claude Code on the Team seat spend-limit\n * variant of this modal:\n *\n * 2. Wait here, then continue automatically at Aug 21, 10am\n *\n * A PREFIX, deliberately: the row carries a reset date that changes every\n * time, so the literal can only ever be the stable leading text.\n */\nexport const USAGE_LIMIT_CONTINUE_OPTION = 'Wait here, then continue automatically';\n\n/**\n * Options this module is willing to press, MOST PREFERRED FIRST.\n *\n * `Wait here, then continue automatically` outranks `Stop and wait for limit to\n * reset` because the two differ in exactly the way that matters to an\n * unattended agent: both idle until the cap lifts, but only the first RESUMES\n * by itself afterwards. \"Stop and wait\" leaves the session parked until a human\n * touches it, which is the state this whole handler exists to avoid — we would\n * have answered the modal and still needed the human.\n *\n * Neither spends money, which is the invariant that governs this list. Every\n * other row on either variant of this modal is excluded on purpose:\n *\n * - `Switch to usage credits` — starts pay-as-you-go spend.\n * - `Switch to Team plan` — a plan change.\n * - `Ask your admin for more usage` — spends nothing, but it pages a human\n * and asks them to raise a budget. That is a decision with a cost attached\n * and it is not ours to make automatically; a human choosing to raise the\n * cap is a different act from a fleet of agents asking them to.\n */\nexport const USAGE_LIMIT_SAFE_OPTIONS: readonly string[] = [\n USAGE_LIMIT_CONTINUE_OPTION,\n USAGE_LIMIT_SAFE_OPTION,\n];\n\n/**\n * Every option label known to appear on this modal, including the ones we would\n * never press. This is the RECOGNITION vocabulary, and it is deliberately wider\n * than the selection vocabulary above.\n *\n * ENG-8213 anchored recognition on the BILLING rows alone, which tied \"is this\n * the usage-limit modal?\" to options that only exist on the subscription\n * variant. Claude Code's Team seat spend-limit variant renders\n *\n * ❯ 1. Stop and wait for limit to reset\n * 2. Wait here, then continue automatically at Aug 21, 10am\n * 3. Ask your admin for more usage\n *\n * with no billing row at all, so the modal was not recognised — and the failure\n * was not a no-op. This pane renders \"Enter to confirm\", and the `mcp-servers`\n * branch below fires on `'Enter to confirm' && 'MCP'` with \"MCP\" trivially\n * present in any agent's scrollback. So the unrecognised variant fell through to\n * a BARE ENTER, confirming whichever row the cursor sat on — row 1, \"Stop and\n * wait\", the one option that guarantees a human is needed. Observed on\n * acquire-intelligence, 2026-08-19.\n *\n * Recognising by \"an option row this modal is known to render\" rather than by\n * billing vocabulary keeps the structural guard (it must still be a numbered\n * ROW inside the block adjacent to the nearest footer) while covering both\n * variants and any future one whose rows we add here.\n */\nconst USAGE_LIMIT_KNOWN_OPTIONS: readonly string[] = [\n ...USAGE_LIMIT_SAFE_OPTIONS,\n 'Switch to usage credits',\n 'Switch to Team plan',\n // ENG-9006: the two-option variant Claude Code shipped ~2026-08-17. Filed\n // with a wedged pane and four unanswered customer Telegram messages queued\n // behind it.\n 'Upgrade your plan',\n 'Ask your admin for more usage',\n];\n\n/**\n * Detect Claude Code's usage-limit choice dialog (ENG-8213).\n *\n * On hitting the plan limit, Claude Code blocks the TUI on:\n *\n * What do you want to do?\n *\n * ❯ 1. Stop and wait for limit to reset\n * 2. Switch to usage credits\n * 3. Switch to Team plan\n *\n * Enter to confirm · Esc to cancel\n *\n * Nothing answered it, so the session sat on the modal and the agent was\n * unavailable until a human attached to the pane.\n *\n * Matched STRUCTURALLY: a KNOWN option (USAGE_LIMIT_KNOWN_OPTIONS) must appear\n * as a numbered option ROW (`<indent>[❯ ]<digit>. <text>`), not merely\n * somewhere in the capture, and the modal's confirm affordance must be present.\n *\n * The anchor was originally the BILLING rows specifically, which silently made\n * recognition subscription-only and let the Team seat spend-limit variant fall\n * through to a bare Enter. See USAGE_LIMIT_KNOWN_OPTIONS. The structural\n * requirement below is unchanged and is what actually does the safety work; only\n * the vocabulary widened.\n *\n * The looser \"billing phrase anywhere && 'Enter to confirm'\" version was\n * actively dangerous, and in the opposite direction to the bug this fixes.\n * \"Enter to confirm\" is rendered by OTHER dialogs (the MCP confirm among\n * them), and an agent that merely writes the words \"Switch to usage credits\"\n * - discussing a capped teammate, quoting this very file - leaves them in the\n * scrollback. Both true at once and this predicate fires on a pane that is\n * not this dialog. Because sweepDialogs() checks it FIRST and then finds no\n * safe option row, it would return null AND isUnanswerableUsageLimitDialog()\n * would tell every caller to hold the pane: the real dialog never gets\n * answered and the agent wedges. That is the ENG-8194 self-gating shape with\n * a worse blast radius, so the match has to key on layout, not vocabulary.\n */\n/**\n * How far above the \"Enter to confirm\" footer an option row may sit and still\n * count as part of the SAME modal.\n *\n * The real dialog puts its furthest option 4 lines above the footer, so 6\n * carries the whole block with room for a wrap. Deliberately tight: every line\n * of slack here is scrollback that a numbered write-up could occupy, and the\n * cost of being too generous (wedging the pane on a false positive) is worse\n * than the cost of being too tight (failing to answer, which is the status quo\n * this handler improves on).\n */\nconst USAGE_LIMIT_BLOCK_LINES = 6;\n\nfunction optionRowDigit(line: string, label: string): string | null {\n const m = line.match(\n new RegExp(\n String.raw`^[^\\S\\n]*(?:❯[^\\S\\n]*)?(\\d)\\.[^\\S\\n]*` +\n label.replace(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`),\n ),\n );\n return m?.[1] ?? null;\n}\n\n/**\n * Return the modal's own lines, or null when this dialog is not on screen.\n *\n * The match is bound to a REGION, not to the capture as a whole: a known\n * option row and the confirm footer must belong to the same block. Two earlier\n * versions of this predicate were too loose, in the same direction each time:\n *\n * 1. \"billing phrase anywhere && 'Enter to confirm' anywhere\" - satisfied by\n * prose about a capped teammate sitting behind an unrelated dialog.\n * 2. \"billing option ROW anywhere && 'Enter to confirm' anywhere\" - still\n * satisfied by a numbered list in prose (`1. Switch to Team plan`, which\n * is exactly how an agent writes up this very ticket) plus a confirm\n * footer from a different dialog.\n *\n * Both misfire the same way, and it is the dangerous way: sweepDialogs() checks\n * this branch FIRST (so the mcp-servers branch cannot bare-Enter the real\n * modal), so a false positive with no safe option row returns null AND makes\n * isUnanswerableUsageLimitDialog() tell every caller to hold the pane. The\n * dialog actually on screen never gets answered and the agent wedges.\n */\n/**\n * The lines of the FOCUSED modal — the block immediately above the nearest\n * \"Enter to confirm\" footer — or null when no modal is focused.\n *\n * Extracted from usageLimitModalBlock so every structural predicate reads the\n * same region by the same rule. \"Nearest footer\" is load-bearing and was\n * arrived at the hard way: with a newer dialog on screen and an older one still\n * in the scrollback, a backwards search skips the live dialog's footer and\n * matches the STALE one, so we would classify the pane as a dialog that is not\n * focused and key whatever actually is.\n */\nfunction focusedModalBlock(screen: string, blockLines: number): string[] | null {\n const lines = screen.split('\\n');\n let footer = -1;\n for (let i = lines.length - 1; i >= 0; i--) {\n if (lines[i]!.includes('Enter to confirm')) {\n footer = i;\n break;\n }\n }\n if (footer < 0) return null;\n return lines.slice(Math.max(0, footer - blockLines), footer);\n}\n\n/**\n * The MCP-servers dialog's own option rows.\n *\n * New MCP servers found in .mcp.json\n * ❯ 1. Use this and all future MCP servers in this project\n * 2. Continue without using these MCP servers\n *\n * Enter to confirm · Esc to cancel\n */\nconst MCP_DIALOG_OPTIONS: readonly string[] = [\n 'Use this and all future MCP servers in this project',\n 'Continue without using these MCP servers',\n];\n\n/**\n * Detect the MCP-servers dialog STRUCTURALLY.\n *\n * This branch used to read `screen.includes('Enter to confirm') &&\n * screen.includes('MCP')`, which is not a detector — it is a catch-all. Every\n * agent pane carries the string \"MCP\" somewhere (`Connected to MCP server:\n * slack` is printed at startup and never scrolls out of a quiet pane), so the\n * condition reduced to \"any focused confirm dialog at all\", and the action is a\n * BARE ENTER on whatever row the cursor sits on.\n *\n * That is not a hypothetical. It is the mechanism behind the acquire-intelligence\n * wedge on 2026-08-19: the spend-limit modal was not recognised by the\n * usage-limit branch, fell to this one, and got an Enter on the pre-selected\n * \"Stop and wait for limit to reset\". ENG-8213's fix for the SAME hazard was to\n * order the usage-limit branch first — correct, and only a fix for the one\n * dialog anybody had thought of.\n *\n * It also silently defeats the ENG-9006 backstop: an unclaimed modal cannot be\n * reported as unclaimed if this branch claims everything. Tightening here is\n * what lets an unrecognised dialog reach `isUnclaimedConfirmDialog` and become\n * visible instead of being blindly confirmed.\n */\nexport function isMcpServersDialogVisible(screen: string): boolean {\n const block = focusedModalBlock(screen, USAGE_LIMIT_BLOCK_LINES);\n if (!block) return false;\n return block.some((l) => MCP_DIALOG_OPTIONS.some((label) => optionRowDigit(l, label) !== null));\n}\n\n/**\n * ENG-9224 — the SAME dialog after Claude Code 2.1.237 replaced the widget.\n *\n * `isMcpServersDialogVisible` above matches a numbered option list. 2.1.237\n * ships a checkbox multi-select instead, with neither the digits nor either of\n * the `MCP_DIALOG_OPTIONS` labels:\n *\n * 3 new MCP servers found in this project\n * Select any you wish to enable.\n *\n * MCP servers may execute code or access system resources. All tool calls\n * require approval. Learn more in the MCP documentation.\n *\n * ❯ [✓] augmented\n * [✓] direct-chat\n * [✓] composio_googlesheets\n * Space to select · Enter to confirm · Esc to reject all\n *\n * So the branch stopped firing, agents froze on it, and the presence reaper\n * restarted them into the identical prompt until the breaker paused them. Both\n * customer orgs onboarded on 2026-08-20 died this way.\n *\n * This is the second rewrite of this dialog we have chased: ENG-5375 moved the\n * match onto the option TEXT when 2.1.146 reworded the prompt. Matching on text\n * is what left us exposed when the widget itself changed, so this one keys on\n * STRUCTURE — a header, a checked row, a confirm footer — which survives\n * renaming the servers or reordering the list.\n *\n * ## Why a checked row and not just any row\n *\n * `Enter` accepts the CURRENT selection. If Claude Code ever renders this with\n * nothing pre-selected, confirming it enables nothing: the servers stay unbound,\n * the reaper loop continues, and the log says `Auto-accepted MCP servers` while\n * no progress was made. That is strictly worse than today, because it is\n * invisible.\n *\n * So an all-unchecked dialog is deliberately NOT claimed. It falls through to\n * `isUnclaimedConfirmDialog` and becomes a human's problem — the correct outcome\n * for a state we cannot safely resolve by pressing one key.\n */\nconst MCP_CHECKBOX_HEADER = /new MCP servers? found in this project/i;\n\n/**\n * A CHECKED checkbox row: `❯ [✓] augmented`, ` [x] direct-chat`.\n *\n * `[ ]` is excluded on purpose — see the \"why a checked row\" note above. The\n * optional `❯` mirrors `optionRowDigit`'s handling of the focus caret.\n */\nconst MCP_CHECKED_ROW = /^[^\\S\\n]*(?:❯[^\\S\\n]*)?\\[[✓x]\\][^\\S\\n]*\\S/iu;\n\n/**\n * Wider than `USAGE_LIMIT_BLOCK_LINES` because this dialog puts its header\n * above two lines of prose, a blank line, and one row PER SERVER. Six lines\n * reaches the checkboxes but not the header. Twenty covers a comfortable\n * server count while still binding the match to a region rather than the whole\n * capture — the discipline that keeps this file's detectors from becoming the\n * catch-all described above.\n */\nconst MCP_CHECKBOX_BLOCK_LINES = 20;\n\nexport function isMcpCheckboxDialogVisible(screen: string): boolean {\n const block = focusedModalBlock(screen, MCP_CHECKBOX_BLOCK_LINES);\n if (!block) return false;\n if (!block.some((l) => MCP_CHECKBOX_HEADER.test(l))) return false;\n return block.some((l) => MCP_CHECKED_ROW.test(l));\n}\n\nfunction usageLimitModalBlock(screen: string): string[] | null {\n const lines = screen.split('\\n');\n // ONLY the nearest footer. Scanning further back was the fourth version of\n // this bug: with a newer dialog on screen and an older usage-limit block\n // still in the scrollback, a backwards search skips the live dialog's footer\n // (no billing row) and matches the STALE one - so we would classify the pane\n // as the usage-limit modal and send a digit + Enter into whatever dialog is\n // actually focused. The live dialog is always the last footer; treating this\n // as \"search the capture\" rather than \"read the focused dialog\" is what kept\n // producing near-misses.\n let footer = -1;\n for (let i = lines.length - 1; i >= 0; i--) {\n if (lines[i]!.includes('Enter to confirm')) {\n footer = i;\n break;\n }\n }\n if (footer < 0) return null;\n const block = lines.slice(Math.max(0, footer - USAGE_LIMIT_BLOCK_LINES), footer);\n const hasKnownOptionRow = block.some((l) =>\n USAGE_LIMIT_KNOWN_OPTIONS.some((label) => optionRowDigit(l, label) !== null),\n );\n return hasKnownOptionRow ? block : null;\n}\n\n/**\n * Detect Claude Code's usage-limit choice dialog (ENG-8213).\n *\n * On hitting the plan limit, Claude Code blocks the TUI on:\n *\n * What do you want to do?\n *\n * ❯ 1. Stop and wait for limit to reset\n * 2. Switch to usage credits\n * 3. Switch to Team plan\n *\n * Enter to confirm · Esc to cancel\n *\n * ...or, on a Claude Team seat that has hit its individual spend limit:\n *\n * What do you want to do?\n *\n * ❯ 1. Stop and wait for limit to reset\n * 2. Wait here, then continue automatically at Aug 21, 10am\n * 3. Ask your admin for more usage\n *\n * Enter to confirm · Esc to cancel\n *\n * Nothing answered it, so the session sat on the modal and the agent was\n * unavailable until a human attached to the pane.\n */\nexport function isUsageLimitChoiceDialogVisible(screen: string): boolean {\n return usageLimitModalBlock(screen) !== null;\n}\n\n/**\n * Locate the option to press by READING ITS NUMBER off the line that carries\n * the option's text — never by assuming it is option 1.\n *\n * This is the whole safety design (ENG-8213). Several rows on this modal cost\n * money or a human's attention: \"Switch to usage credits\" starts pay-as-you-go\n * spend, \"Switch to Team plan\" is a plan change, \"Ask your admin for more\n * usage\" pages a person to raise a budget. Selecting by position would mean a\n * future reordering of this menu silently turns an auto-answer into a purchase.\n * Deriving the digit from the matched text means a reorder just changes which\n * digit we send, and an unrecognised menu yields `null` (answer nothing) rather\n * than a guess.\n *\n * Returns the chosen row's digit (as a tmux key name) and the label it matched,\n * or `null` when no selectable option is present — failing to clear a modal is\n * recoverable; buying credits is not.\n */\nexport function findUsageLimitSafeOption(\n screen: string,\n): { key: string; label: string } | null {\n // Searched inside the modal's own block, so a numbered line elsewhere on the\n // pane can never supply the digit we are about to press.\n const block = usageLimitModalBlock(screen);\n if (!block) return null;\n // Preference order comes from USAGE_LIMIT_SAFE_OPTIONS, not from row order:\n // the OUTER loop is the preference list so `Wait here, then continue\n // automatically` wins wherever it sits on the menu. Iterating rows first\n // would make the answer depend on Claude Code's row ordering, which is the\n // select-by-position mistake this function exists to avoid — just one level\n // up.\n for (const label of USAGE_LIMIT_SAFE_OPTIONS) {\n for (const line of block) {\n const digit = optionRowDigit(line, label);\n if (digit !== null) return { key: digit, label };\n }\n }\n return null;\n}\n\n/** The digit alone, as before. */\nexport function findUsageLimitSafeOptionKey(screen: string): string | null {\n return findUsageLimitSafeOption(screen)?.key ?? null;\n}\n\n/**\n * How many option rows a two-choice consent dialog can span. Wider than the\n * rows themselves so the block still reaches the cursor row when Claude Code\n * pads the modal with blank lines (it does, between the prose and the options).\n */\nconst CONSENT_BLOCK_LINES = 12;\n\n/** Index of the LAST element satisfying `pred`, or -1. */\nfunction lastIndexWhere<T>(xs: readonly T[], pred: (x: T) => boolean): number {\n for (let i = xs.length - 1; i >= 0; i--) {\n if (pred(xs[i]!)) return i;\n }\n return -1;\n}\n\n/**\n * True when `line` is a COMPLETE option row for `label` — optionally preceded by\n * the `❯` cursor and/or a `N.` digit, and carrying nothing else.\n *\n * A substring test is not good enough, and the bypass dialog is exactly where\n * that bites. Its detector is `includes('Yes, I accept') && includes('Bypass\n * Permissions')`, and both strings show up in ordinary prose — an agent that\n * reads a manager log, or discusses this very incident, puts them in its own\n * transcript. A substring match would then find the prose line, measure the\n * cursor distance to it, and key that many Downs into whatever dialog is\n * actually focused. Anchoring to the whole row means prose can never be\n * mistaken for a selectable option; at worst we answer nothing.\n *\n * Anchored at both ends deliberately: every label this is called with names a\n * full row ('Yes, I accept', 'Yes, I trust this folder', \"Don't ask me again\"),\n * unlike USAGE_LIMIT_CONTINUE_OPTION, which is a prefix and is matched by\n * findUsageLimitSafeOption's own looser rule.\n */\n/**\n * True when `line` is a menu CURSOR row — the `❯` opens the line (leading\n * whitespace aside) and something follows it.\n *\n * A bare `includes('❯')` is not good enough: the agent's own input prompt\n * renders the same glyph, and so does any prose quoting a menu. Requiring the\n * glyph to START the row is what separates \"this is the selected option\" from\n * \"this line happens to contain an arrow\".\n */\nfunction isCursorRow(line: string): boolean {\n return /^[^\\S\\n]*❯[^\\S\\n]+\\S/.test(line);\n}\n\nfunction isOptionRowFor(line: string, label: string): boolean {\n const escaped = label.replace(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n return new RegExp(\n String.raw`^[^\\S\\n]*(?:❯[^\\S\\n]*)?(?:\\d\\.[^\\S\\n]*)?` +\n escaped +\n String.raw`[^\\S\\n]*$`,\n ).test(line);\n}\n\n/**\n * ENG-9575: keystrokes that select `label` on the FOCUSED modal, for either\n * shape Claude Code renders — or null when the row isn't there.\n *\n * The bug this exists to kill: every branch below used to answer by DIGIT\n * (`['2','Enter']`) or by BARE ENTER, both of which encode an assumption about\n * how the menu is drawn. Claude Code 2.1.250 draws these consent dialogs as an\n * arrow-select list with NO numbered rows, and — this is the part that turns a\n * cosmetic change into an outage — it defaults the cursor to the REFUSING row:\n *\n * ❯ No, exit\n * Yes, I accept\n * Enter to confirm · Esc to cancel\n *\n * A digit is swallowed (verified on 2.1.250: sending `2` does not move the\n * cursor), so `['2','Enter']` confirms whatever is selected — `No, exit`. Claude\n * exits 0, the manager sees a dead session and respawns, and the next spawn\n * lands on the same dialog. On the two hosts provisioned 2026-08-28 that ran\n * 847 and 1,974 times, every agent down from first boot, while the manager\n * logged `Auto-accepted bypass permissions` on each pass.\n *\n * It is self-perpetuating in a way worth naming: Claude records the consent\n * only after a SUCCESSFUL start, so answering it wrongly also prevents the\n * write that would stop it being asked again. One correct answer ends it for\n * good; a host can never get there on its own.\n *\n * Reading the row instead of assuming its position keeps both shapes working\n * and survives a reorder — the same reasoning as findUsageLimitSafeOption,\n * which derives the digit from the matched text rather than trusting row order.\n * Preserves DEFAULT-DENY: an unrecognised menu returns null, so the caller\n * answers nothing rather than keying a row it cannot see.\n */\nexport function selectRowKeys(\n screen: string,\n label: string,\n): readonly string[] | null {\n // FAIL CLOSED without a focused modal, for BOTH shapes. Every one of these\n // dialogs renders `Enter to confirm` (the numbered shape too — see\n // MCP_DIALOG_OPTIONS above), so no footer means no dialog we are entitled to\n // key. The alternative, searching the whole pane, reads lines the agent\n // itself wrote: a transcript listing the options verbatim (\" 2. Yes, I\n // accept\") is a complete option row by any structural test, and answering it\n // types into the REPL.\n const block = focusedModalBlock(screen, CONSENT_BLOCK_LINES);\n if (!block) return null;\n\n // Last match, not first: with an older render of the same dialog still in\n // the block, the live one is the most recent.\n const target = lastIndexWhere(block, (l) => isOptionRowFor(l, label));\n if (target < 0) return null;\n\n // Numbered shape (pre-2.1.250): the row carries its own digit, so press it.\n // Tried first so a host still on an older Claude Code answers as it always\n // has, and so this fix needs no knowledge of which version a host is running.\n const digit = optionRowDigit(block[target]!, label);\n if (digit !== null) return [digit, 'Enter'];\n\n // Arrow-select shape: RELATIVE movement, so we need the menu's own cursor.\n // Only a row whose `❯` STARTS the line is a cursor — prose that merely\n // contains the glyph is not, and neither is the agent's input prompt.\n const cursors: number[] = [];\n for (let i = 0; i < block.length; i++) {\n if (isCursorRow(block[i]!)) cursors.push(i);\n }\n // No cursor means we cannot know what Enter would confirm. Answer nothing:\n // on these dialogs the unknown row is the destructive one, and DEFAULT-DENY\n // is the module's contract.\n if (cursors.length === 0) return null;\n\n // Nearest cursor to the target — option rows are adjacent, so nearest is the\n // menu this row belongs to. A TIE means two candidate menus are equally\n // close and we cannot tell which owns the row; that is ambiguity, and\n // ambiguity is answered with silence rather than a guess.\n let cursor = cursors[0]!;\n let tied = false;\n for (const i of cursors.slice(1)) {\n const d = Math.abs(i - target);\n const best = Math.abs(cursor - target);\n if (d < best) {\n cursor = i;\n tied = false;\n } else if (d === best) {\n tied = true;\n }\n }\n if (tied) return null;\n\n const distance = target - cursor;\n if (distance === 0) return ['Enter'];\n const step = distance > 0 ? 'Down' : 'Up';\n return [...Array<string>(Math.abs(distance)).fill(step), 'Enter'];\n}\n\n/**\n * ENG-9006: the reset moment the modal names, verbatim, or null.\n *\n * The Team seat spend-limit variant renders its auto-continue row as\n *\n * 2. Wait here, then continue automatically at Aug 21, 10am\n *\n * and that tail is the single most authoritative reset string we ever get from\n * Claude Code. Everywhere else we RECONSTRUCT one: the saturated banner often\n * names only an hour (\"resets 1am (UTC)\") and `banner-parser.ts` resolves it to\n * the next occurrence of that hour, which can never be more than 24h out even\n * when the real reset is days away — the ENG-8901 defect, which had operators\n * scheduling against an instant that was three days early.\n *\n * Returned as the RAW STRING on purpose. Parsing it would mean inventing a\n * second date grammar that can drift from the banner parser's, and guessing a\n * timezone the modal does not state. The one consumer is a sentence shown to a\n * human, and \"until Aug 21, 10am\" is exactly as useful to them as a Date would\n * be, while being impossible to get subtly wrong.\n *\n * Bounded so a mis-parse cannot push an arbitrary pane line into a message that\n * reaches a customer.\n */\nexport function findUsageLimitResetHint(screen: string): string | null {\n const block = usageLimitModalBlock(screen);\n if (!block) return null;\n for (const line of block) {\n if (optionRowDigit(line, USAGE_LIMIT_CONTINUE_OPTION) === null) continue;\n const idx = line.indexOf(USAGE_LIMIT_CONTINUE_OPTION);\n const tail = line.slice(idx + USAGE_LIMIT_CONTINUE_OPTION.length).trim();\n // The row reads \"… continue automatically at <when>\". Drop the connective\n // so the caller can compose \"until <when>\" without doubling it up.\n const when = tail.replace(/^at\\s+/i, '').trim();\n if (!when) return null;\n return when.slice(0, 40);\n }\n return null;\n}\n\n/**\n * The usage-limit dialog is on screen but its safe option could not be\n * located, so there is no keystroke we are willing to send (ENG-8213).\n *\n * Callers MUST treat this as \"do not key this pane at all\" and log it: the\n * generic fallbacks (the watchdog's bounded Enter, acceptDialogs' `❯`\n * readiness branch) would otherwise press Enter on whatever row the cursor\n * happens to be sitting on, and on this dialog most of the rows either spend\n * money or page a human.\n */\nexport function isUnanswerableUsageLimitDialog(screen: string): boolean {\n return (\n isUsageLimitChoiceDialogVisible(screen) &&\n findUsageLimitSafeOptionKey(screen) === null\n );\n}\n\n/**\n * ENG-11865: the index, in `lines`, of a \"Press Enter to continue\" prompt the\n * session is PARKED on, or -1.\n *\n * Claude Code's first-run splashes have no \"Enter to confirm\" footer, so\n * `focusedConfirmDialogBlock` cannot see them. Their only anchor is this line, and\n * sweepDialogs() acts on the result, so a whole-pane substring test will not do: an\n * agent quoting the wizard in its transcript would have Enter pressed into its live\n * session. A quoted line has the input box below it. A parked one has nothing\n * below it but, at most, a blank or a short hint, so anything that looks like the\n * input box (a rule or the `❯` prompt) disqualifies it.\n */\nfunction parkedPressEnterLine(lines: readonly string[]): number {\n const tail = lines.length - 3;\n for (let i = lines.length - 1; i >= 0 && i >= tail; i--) {\n if (/[─━]{3}|❯/.test(lines[i]!)) return -1;\n if (/press enter to continue/i.test(lines[i]!)) return i;\n }\n return -1;\n}\n\nconst nonEmptyLines = (screen: string): string[] => screen.split('\\n').filter((l) => l.trim() !== '');\n\n/**\n * ENG-11865: Claude Code's first-run \"Security notes\" step, the screen after the\n * theme picker when the config has no completed onboarding:\n *\n * Security notes:\n * 1. Claude can make mistakes …\n * 2. Due to prompt injection risks, only use it with code you trust …\n *\n * Press Enter to continue…\n *\n * It offers no choice and has no default row to get wrong, unlike the consumer-terms\n * dialog, and the pairing flow already keys past it (claude-pair-runtime.ts). Unanswered,\n * the session never spawns its MCP servers, so the reaper restarts it into the same\n * screen until the breaker pauses the agent.\n */\nexport function isSecurityNotesSplashVisible(screen: string): boolean {\n const lines = nonEmptyLines(screen);\n const at = parkedPressEnterLine(lines);\n if (at < 0) return false;\n // Stop at an earlier prompt or input line: a heading above either isn't this splash's.\n for (let i = at - 1; i >= Math.max(0, at - 12); i--) {\n if (/press enter to continue|❯/i.test(lines[i]!)) return false;\n if (lines[i]!.includes('Security notes')) return true;\n }\n return false;\n}\n\n/**\n * ENG-11865: a \"Press Enter to continue\" splash nobody claimed. Same reasoning as\n * isUnclaimedConfirmDialog, for the shape that one cannot see: nothing keys it, so a\n * respawn lands on it again and the restart only burns breaker budget.\n */\nexport function isUnclaimedPressEnterSplash(screen: string): boolean {\n if (parkedPressEnterLine(nonEmptyLines(screen)) < 0) return false;\n // Not sweepDialogs(screen) === null: its other branches match anywhere on the pane,\n // so stale theme-picker text above this splash would read as a claim on it.\n return !isSecurityNotesSplashVisible(screen);\n}\n\n/**\n * Single-pass dialog recognition. Returns the dismissal action for the\n * first recognised dialog on screen, or `null` when no known dialog is\n * visible (including for the login picker, which must never be keyed\n * past — see isLoginPickerVisible).\n *\n * Branch order mirrors the original acceptDialogs() cascade: the theme\n * picker check must run before any generic `❯`-based readiness logic in\n * callers, since picker rows also render with `❯`.\n */\nexport function sweepDialogs(screen: string): DialogAction | null {\n if (isSecurityNotesSplashVisible(screen)) {\n return {\n kind: 'security-notes',\n keys: ['Enter'],\n interKeyDelayMs: 0,\n logMessage: 'Auto-acknowledged Security notes',\n };\n }\n // ENG-11865: first, because the branches below match anywhere on the pane, so text left\n // over from an earlier dialog would key a splash nobody here has read. Neither test\n // can match a live confirm modal: those end on their footer, not on this prompt.\n if (isUnclaimedPressEnterSplash(screen)) return null;\n // ENG-8213: before every other dialog branch. The usage-limit dialog renders\n // \"Enter to confirm\", and the mcp-servers branch below fires on\n // `'Enter to confirm' && 'MCP'` — with \"MCP\" trivially present in the\n // scrollback behind the modal, that branch would match this dialog and\n // send a BARE ENTER, confirming whichever row the cursor is on. Two of\n // those three rows are billing actions. Ordering is the guard.\n if (isUsageLimitChoiceDialogVisible(screen)) {\n const safe = findUsageLimitSafeOption(screen);\n // No recognised safe option => answer nothing. isUnanswerableUsageLimitDialog()\n // lets callers detect this state and stop their own fallbacks keying the pane.\n if (!safe) return null;\n return {\n kind: 'usage-limit-choice',\n // The log names the option ACTUALLY picked, not a fixed literal. With two\n // selectable rows now, a constant string would make a fleet sweep unable\n // to tell an agent that will resume by itself from one parked until a\n // human touches it.\n keys: [safe.key, 'Enter'],\n interKeyDelayMs: 300,\n logMessage: `Auto-answered usage-limit choice dialog (picked '${safe.label}')`,\n };\n }\n // ENG-10619: before the generic branches. The dialog renders\n // `Enter to confirm`, and its default row opts the account INTO model\n // training — so nothing below may get the chance to send a bare Enter.\n // Resolve before claiming (see the folder-trust branch): an unresolvable\n // OFF row falls through rather than suppressing later handlers, and\n // isUnclaimedConfirmDialog() still reports the pane.\n const termsKeys = consumerTermsOffKeys(screen);\n if (termsKeys) {\n return {\n kind: 'consumer-terms',\n keys: termsKeys,\n interKeyDelayMs: 300,\n logMessage: \"Auto-answered consumer-terms dialog (picked 'Help improve our AI models: OFF')\",\n };\n }\n if (\n screen.includes('Choose the text style') ||\n (screen.includes('Dark mode') && screen.includes('Light mode'))\n ) {\n return {\n kind: 'theme-picker',\n keys: ['Enter'],\n interKeyDelayMs: 0,\n logMessage: 'Auto-accepted theme picker',\n };\n }\n // ENG-9575: was a bare Enter. On 2.1.250 this dialog's default row is\n // \"No, exit\", so the bare Enter REFUSED the trust prompt and exited Claude.\n // Latent rather than firing on the hosts that broke (their agent projects\n // were already trusted), but it fires the first time an agent runs in a\n // project directory Claude has not seen — i.e. on every newly provisioned\n // agent. Select the row by name instead.\n //\n // RESOLVE BEFORE CLAIMING. These predicates are whole-pane substring tests,\n // so scrollback or the agent's own prose can match them while a DIFFERENT\n // dialog is focused. Returning null on an unresolved row would cancel the\n // sweep and suppress every branch below — so trust-folder prose sitting\n // behind a real bypass dialog would leave that dialog unanswered, which is\n // the exact wedge this change exists to prevent. Falling through instead\n // keeps the later handlers reachable and lets isUnclaimedConfirmDialog()\n // still report a pane nobody claimed. Same hazard the usage-limit branch\n // documents as the self-gating trap.\n const trustKeys = screen.includes('Yes, I trust this folder')\n ? selectRowKeys(screen, 'Yes, I trust this folder')\n : null;\n if (trustKeys) {\n return {\n kind: 'folder-trust',\n keys: trustKeys,\n interKeyDelayMs: 300,\n logMessage: 'Auto-accepted folder trust',\n };\n }\n // ENG-5364: picks \"Don't ask me again\", which Claude Code persists in config\n // so subsequent resumes skip the dialog entirely.\n // ENG-9575: was ['3','Enter']. The digit is swallowed on 2.1.250's\n // arrow-select shape, leaving Enter to confirm the default row — here that is\n // \"Resume from summary\", which is harmless but is NOT the option that stops\n // the dialog recurring, so the agent re-answered it on every single respawn.\n // Resolve before claiming — see the folder-trust branch above.\n const resumeKeys = isResumeModeDialogVisible(screen)\n ? selectRowKeys(screen, \"Don't ask me again\")\n : null;\n if (resumeKeys) {\n return {\n kind: 'resume-mode',\n keys: resumeKeys,\n interKeyDelayMs: 300,\n logMessage: \"Auto-dismissed resume-mode dialog (picked 'Don't ask me again')\",\n };\n }\n if (screen.includes('I am using this for local development')) {\n return {\n kind: 'dev-channels',\n keys: ['Enter'],\n interKeyDelayMs: 0,\n logMessage: 'Auto-accepted dev channels',\n };\n }\n // ENG-9224: both shapes of the same dialog — the pre-2.1.237 numbered list\n // and the 2.1.237 checkbox multi-select. Kept in ONE branch, in the position\n // the numbered one already held, so the ordering hazard ENG-8213 fixed (the\n // usage-limit branch must be evaluated first) is untouched by this change.\n if (isMcpServersDialogVisible(screen) || isMcpCheckboxDialogVisible(screen)) {\n return {\n kind: 'mcp-servers',\n keys: ['Enter'],\n interKeyDelayMs: 0,\n logMessage: 'Auto-accepted MCP servers',\n };\n }\n // ENG-9575: was ['2','Enter'] — the incident branch. See selectRowKeys.\n // Resolve before claiming — see the folder-trust branch above. This one\n // matters most: its two substrings are the ones an agent is likeliest to\n // have written itself, and suppressing the session-feedback branch below\n // leaves a rating prompt swallowing the input box (the koda wedge, ENG-6017).\n const bypassKeys =\n screen.includes('Yes, I accept') && screen.includes('Bypass Permissions')\n ? selectRowKeys(screen, 'Yes, I accept')\n : null;\n if (bypassKeys) {\n return {\n kind: 'bypass-permissions',\n keys: bypassKeys,\n interKeyDelayMs: 300,\n logMessage: 'Auto-accepted bypass permissions',\n };\n }\n // ENG-6017: the rating prompt acts on the bare digit — no Enter needed.\n if (isSessionFeedbackDialogVisible(screen)) {\n return {\n kind: 'session-feedback',\n keys: ['0'],\n interKeyDelayMs: 0,\n logMessage: 'Auto-dismissed session-feedback dialog',\n };\n }\n return null;\n}\n\n/**\n * Send a DialogAction's keystrokes to a tmux session, one send-keys call\n * per key with the action's inter-key delay. execFileSync (not execSync)\n * so the session name is an argv entry rather than shell-interpolated.\n */\nexport async function sendDialogKeys(\n tmuxSession: string,\n action: DialogAction,\n): Promise<void> {\n for (let i = 0; i < action.keys.length; i++) {\n if (i > 0 && action.interKeyDelayMs > 0) {\n await new Promise((r) => setTimeout(r, action.interKeyDelayMs));\n }\n execFileSync('tmux', ['send-keys', '-t', tmuxSession, action.keys[i]!], {\n stdio: 'ignore',\n });\n }\n}\n\n/**\n * ENG-9006 criterion 3: the block of a focused confirm-footer dialog that NO\n * handler in this module claimed, or null.\n *\n * This is the backstop for the failure mode that has now recurred three times\n * in three weeks, each time the same way: Claude Code reworded a modal, every\n * predicate above went false, the pane wedged, and the fleet found out because\n * a human looked at a screenshot.\n *\n * 2026-07-28 ENG-8213 \"Switch to usage credits\" / \"Switch to Team plan\"\n * 2026-08-17 ENG-9006 \"Upgrade your plan\" (two-option variant)\n * 2026-08-19 this \"Wait here, then continue automatically at …\"\n * / \"Ask your admin for more usage\" (Team seat spend)\n *\n * Adding each new string is necessary and is not sufficient — the detector is\n * anchored on vendor-authored copy that the vendor keeps changing, so the NEXT\n * rewording is already scheduled. What does not depend on the wording is the\n * shape: a modal is focused (it renders its confirm affordance) and nothing\n * claimed it.\n *\n * DEFAULT-DENY IS PRESERVED. This function keys nothing and returns no action;\n * it exists purely so an unclaimed modal becomes VISIBLE instead of silent.\n * Answering an unrecognised dialog is still forbidden — a future dialog's\n * default row could be destructive, which is the whole reason sweepDialogs()\n * returns null rather than guessing.\n *\n * Deliberately excludes `isUnanswerableUsageLimitDialog`: that state is\n * recognised, is refused on purpose, and already emits its own loud signal.\n * Counting it here too would double-report one pane.\n */\nexport function focusedConfirmDialogBlock(screen: string): string[] | null {\n const lines = screen.split('\\n');\n // The LIVE dialog is the last footer, same rule as usageLimitModalBlock():\n // an older modal still in the scrollback is not what is focused now.\n let footer = -1;\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i]!;\n if (line.includes('Enter to confirm')) {\n footer = i;\n break;\n }\n if (isToolPermissionFooter(line)) {\n // Only a footer that sits under a numbered option row counts; see\n // isToolPermissionFooter for why the footer alone is not enough.\n // ...and only when no input box was rendered after it (Obi Wan\n // ceb92dbbc62b): a VERBATIM quote of the whole dialog - an agent reading\n // this ticket, which reproduces eliza's pane - passes both structural\n // checks, but the session is still live, so its input box sits below.\n const block = lines.slice(Math.max(0, i - USAGE_LIMIT_BLOCK_LINES), i + 1);\n const inputBoxAfter = lines.slice(i + 1).some((l) => INPUT_BOX_RULE.test(l.trim()));\n if (!inputBoxAfter && block.some((l) => NUMBERED_OPTION_ROW.test(l))) {\n footer = i;\n break;\n }\n }\n }\n if (footer < 0) return null;\n return lines.slice(Math.max(0, footer - USAGE_LIMIT_BLOCK_LINES), footer + 1);\n}\n\n/**\n * ENG-10357: the footer Claude Code renders under a TOOL-PERMISSION prompt,\n * which is the dialog its dangerous-rm guard raises (and it raises it even with\n * bypass-permissions on):\n *\n * Dangerous rm operation on critical path: /tmp_rows.txt\n *\n * Do you want to proceed?\n * ❯ 1. Yes\n * 2. No\n * Esc to cancel · Tab to amend · ctrl+e to explain\n *\n * It does NOT say \"Enter to confirm\", so before this the whole blocked-prompt\n * stack (monitor, reaper, session gate) read that pane as clear. Five freezes\n * between 11 and 30 Sep (eliza, vigil, alfred, quinn, vera; up to ~15h each)\n * were every one found by a human reading a pane, never by an alert, while the\n * manager logged `decision=healthy` every cycle.\n *\n * Observed variants, both matched: with and without ` · ctrl+e to explain`.\n *\n * ANCHORED ON \"Tab to amend\", NOT \"Esc to cancel\". The usage-limit banner\n * renders `… · esc to cancel` on a line of its own, and it is not this dialog.\n *\n * QUOTES ARE THE HAZARD. Agents working this ticket (or reading an incident\n * write-up) will have this dialog in their own output, sometimes verbatim. The\n * caller requires three things, and each rejects a different quote shape:\n * - the footer STARTS the line -> rejects an inline prose mention\n * - a numbered option row sits above it -> rejects a bare footer line\n * - NO input-box rule is rendered after -> rejects a verbatim multi-line\n * quote, because a live session still shows its input box below it,\n * whereas a parked prompt has replaced the input box\n * A false positive is still only a noisy page, never a keystroke: nothing in\n * this module ANSWERS an unclaimed dialog (default-deny is unchanged).\n */\nexport function isToolPermissionFooter(line: string): boolean {\n return /^\\s*Esc to cancel · Tab to amend\\b/.test(line);\n}\n\n/** The Claude Code input box's top rule, as channel-input-watchdog reads it. */\nconst INPUT_BOX_RULE = /^[─━]{10,}/;\n\n/**\n * ENG-10357: true when the session is parked on a tool-permission prompt: the\n * pane's focused dialog is a permission footer under numbered options, and no\n * input box has been rendered after it (a quoted prompt has one below it).\n */\nexport function isParkedOnToolPermissionPrompt(screen: string): boolean {\n const block = focusedConfirmDialogBlock(screen);\n if (!block) return false;\n const footerLine = block[block.length - 1]!;\n if (!isToolPermissionFooter(footerLine)) return false;\n const lines = screen.split('\\n');\n let footerIdx = -1;\n for (let i = lines.length - 1; i >= 0; i--) {\n if (lines[i] === footerLine) {\n footerIdx = i;\n break;\n }\n }\n if (footerIdx < 0) return false;\n return !lines.slice(footerIdx + 1).some((l) => INPUT_BOX_RULE.test(l.trim()));\n}\n\n/** A numbered option row, e.g. `❯ 1. Yes` or ` 2. No`. */\nconst NUMBERED_OPTION_ROW = /^\\s*(?:❯\\s*)?\\d\\.\\s+\\S/;\n\n/**\n * True when a focused confirm-footer dialog is on screen and no handler in\n * this module claimed it. See focusedConfirmDialogBlock for why this exists.\n */\nexport function isUnclaimedConfirmDialog(screen: string): boolean {\n if (focusedConfirmDialogBlock(screen) === null) return false;\n if (sweepDialogs(screen) !== null) return false;\n // Already has its own signal — see the doc above.\n if (isUnanswerableUsageLimitDialog(screen)) return false;\n return true;\n}\n\n/**\n * Tiny non-cryptographic hash for hash-only logging of channel input\n * (prod logging policy: input may contain PII/secrets, so log hash+len,\n * never content). Shared by the watchdog and the inject-time hygiene.\n */\nexport function simpleTextHash(s: string): string {\n let h = 0;\n for (let i = 0; i < s.length; i++) {\n h = ((h << 5) - h + s.charCodeAt(i)) | 0;\n }\n return h.toString(16);\n}\n\n/**\n * ENG-9932: a pane state that NO keystroke this module is willing to send can\n * clear, and that therefore a session RESTART cannot clear either.\n *\n * The distinction this type draws is the whole point of the ticket. On\n * agt-aws-1 (2026-09-03) eight agents were auto-paused because\n * `mcp-presence-reaper` saw \"declared MCP(s) have no live children\" and\n * restarted the session — three times in ten minutes, into the circuit breaker\n * (ENG-5441). The MCP servers were not broken. Claude Code had never finished\n * booting, because it was sitting on the login picker, so no MCP child had ever\n * been spawned. Every restart re-presented the same modal.\n *\n * `no live MCP children` is therefore a SYMPTOM with (at least) two causes that\n * want opposite remedies:\n *\n * - an MCP server actually died -> restart the session (correct)\n * - the pane is blocked on a modal -> restarting is futile by\n * construction; surface it\n *\n * Nothing distinguished them, so the reaper applied the first remedy to the\n * second cause and the diagnosis landed two subsystems away from the fault.\n */\n/**\n * Every pane state a restart provably cannot recover.\n *\n * A RUNTIME array, with the type DERIVED from it, deliberately. The obvious\n * shape is a bare union plus a hand-written list in the test — but a\n * three-element `UnanswerablePaneKind[]` stays a valid `UnanswerablePaneKind[]`\n * after the union grows to four, so the coverage assertion would keep passing\n * while the new kind shipped untested. A `Record<UnanswerablePaneKind, true>` in\n * the test does not fix it either: `apps/cli/tsconfig.json` excludes\n * `**\\/*.test.ts`, and vitest strips types without checking them, so a\n * compile-time guard written in a test file is never evaluated by anything.\n *\n * Exporting the values and deriving the type means adding a kind here makes the\n * suite's coverage check fail at RUNTIME, which is the only mechanism that\n * actually runs.\n */\nexport const UNANSWERABLE_PANE_KINDS = [\n /** The login picker (ENG-4634). Needs an operator OAuth; no keystroke and no\n * respawn can complete it, and `acceptDialogs()` deliberately never keys\n * past it. This is the state marlow was found in. */\n 'login-picker',\n /** The usage-limit modal is up but no option we are willing to press is on\n * it (ENG-8213). Recognised and refused ON PURPOSE — every remaining row\n * either spends money or pages a human. A respawn re-presents it. */\n 'usage-limit-unanswerable',\n /** A modal is focused, or a \"Press Enter to continue\" splash is parked (ENG-11865),\n * and NO handler in this module claimed it (ENG-9006).\n * Unrecognised means neither the channel-input watchdog nor the spawn-time\n * `acceptDialogs()` cascade can answer it, so a respawn lands on the same\n * prompt. This is the branch that catches the NEXT dialog Claude Code adds,\n * which is the one we cannot enumerate in advance. */\n 'unclaimed-modal',\n] as const;\n\nexport type UnanswerablePaneKind = (typeof UNANSWERABLE_PANE_KINDS)[number];\n\n/**\n * ENG-10972 hardening: the kind of the modal that OWNS THE BOTTOM of the pane -\n * the one the session is actually sitting on - or null when none does.\n *\n * `classifyUnanswerablePane` is a whole-screen substring test, and measured on\n * 2026-09-24 it classifies all four of these as blocked: an agent's message that\n * mentions \"Select login method\", a code line containing the picker's option\n * text, and a usage-limit or unknown modal QUOTED mid-transcript with a live input\n * box below it (`focusedConfirmDialogBlock` finds the LAST \"Enter to confirm\"\n * anywhere on screen). The reaper and spawn-dialogs can use it anyway because they\n * carry a corroborating prior (see `BlockedPromptSource` in\n * session-blocked-prompt.ts). A per-poll watchdog sweep has none, so it uses this.\n *\n * Grounded in the real panes, not guessed: a live confirm modal ends on its\n * footer, and the host-captured login picker (eng-9932's LOGIN_PICKER_PANE) ends\n * on an option row. Anything after that - an input box, more transcript - means\n * the session is not parked on it.\n *\n * The kind is read off WHAT owns the last line, never off the whole screen\n * (CodeRabbit, #6485). The first version checked \"some modal owns the bottom\" and\n * then classified the full pane, where the login-picker test runs first - so a\n * usage-limit modal parked at the bottom with \"Select login method\" anywhere above\n * it was reported as a login picker. So:\n * - a confirm footer at the bottom is classified from its own focused block, and\n * the login-picker substring test never runs (the picker has no such footer);\n * - a picker option row at the bottom is a login picker, and nothing else.\n * Even the 7-line focused block can carry a transcript line above a short modal,\n * which is why the confirm branch checks only the usage-limit and unclaimed kinds.\n * The one question it does NOT scope to the block is \"do we answer this dialog\n * ourselves?\" (sweepDialogs): that text can sit above the block (see below).\n *\n * Deliberately NOT folded into `classifyUnanswerablePane`: tightening that would\n * change the reaper's and spawn's behaviour without live-pane evidence that no\n * Claude Code version renders a hint line under its modals. For the watchdog's\n * busy-ack marker a false negative only restores the old generic notice, so this\n * is the safe place to be strict.\n */\nexport function parkedModalKind(screen: string | null | undefined): UnanswerablePaneKind | null {\n if (!screen) return null;\n const lines = screen.split('\\n').filter((l) => l.trim() !== '');\n const last = lines[lines.length - 1] ?? '';\n if (last.includes('Enter to confirm')) {\n const block = focusedConfirmDialogBlock(screen);\n if (!block) return null;\n const text = block.join('\\n');\n if (isUnanswerableUsageLimitDialog(text)) return 'usage-limit-unanswerable';\n // Obi Wan 9307eb1cbdd8: \"is this a dialog we ANSWER?\" is a whole-screen\n // question. sweepDialogs recognises dialogs by text that can sit far above the\n // footer - the real Bypass Permissions pane's is 11+ lines up, outside the\n // 7-line block - so a block-only check turned claimed dialogs into \"unclaimed\"\n // and marked an agent stuck on a prompt acceptDialogs was about to answer.\n // A claimed dialog merely QUOTED above an unknown modal now reads as claimed:\n // a false negative, which only restores the generic busy notice.\n if (sweepDialogs(screen) !== null) return null;\n if (isUnclaimedConfirmDialog(text)) return 'unclaimed-modal';\n return null;\n }\n // ENG-10357 (Obi Wan b0cdec049c2b): the tool-permission prompt does NOT end on\n // its footer - both real captures carry lines below it (eliza: `⎿ Waiting…`, a\n // spinner and the bypass-mode line; vera: queued direct-chat previews). So the\n // \"last line is the footer\" rule above never sees it, and the watchdog cleared\n // the blocked-prompt marker on every poll for exactly the pane that froze vera.\n // What separates a PARKED permission prompt from a QUOTED one is the thing the\n // 2026-09-24 measurement named: a quoted modal has a live input box below it,\n // and a parked one has replaced the input box. So: the last permission footer\n // (structurally checked by focusedConfirmDialogBlock), with no input-box divider\n // after it.\n if (isParkedOnToolPermissionPrompt(screen)) {\n if (sweepDialogs(screen) !== null) return null;\n return 'unclaimed-modal';\n }\n if (/Claude account with subscription|Anthropic Console account|3rd-party platform/.test(last)) {\n return isLoginPickerVisible(screen) ? 'login-picker' : null;\n }\n if (isUnclaimedPressEnterSplash(screen)) return 'unclaimed-modal';\n return null;\n}\n\n/**\n * Classify a pane that a session restart provably cannot recover, or null.\n *\n * ## Why a RECOGNISED, answerable dialog is deliberately not in this set\n *\n * The tempting version of this function returns non-null for any dialog at\n * all. That would be wrong, and in the dangerous direction: it would add a new\n * way to suppress a restart that is genuinely needed.\n *\n * A dialog `sweepDialogs()` claims gets answered by two independent paths — the\n * per-poll `channel-input-watchdog`, and the spawn-time `acceptDialogs()`\n * cascade in persistent-session.ts. The second one means a restart is a real\n * remedy for an answerable dialog: the fresh session hits the same prompt and\n * the cascade keys past it. So an answerable dialog must keep the pre-ENG-9932\n * behaviour and fall through to the restart.\n *\n * Every kind above is the opposite case: no path answers it, in this session or\n * the next. Holding the restart costs nothing that a restart would have gained,\n * and saves the breaker budget that today gets burned discovering that.\n *\n * DEFAULT-DENY IS PRESERVED, and note the direction. This function keys\n * nothing and returns no `DialogAction`; a pane it does not recognise returns\n * null, which means \"carry on with the restart\" — i.e. unrecognised falls\n * through to the EXISTING behaviour, never to a new suppression.\n */\nexport function classifyUnanswerablePane(\n screen: string | null | undefined,\n): UnanswerablePaneKind | null {\n // A pane we could not read is not evidence of a blocked pane. Fail open to\n // the legacy restart path: a tmux hiccup must never become a silent,\n // fleet-wide suppression of MCP recovery.\n if (!screen) return null;\n if (isLoginPickerVisible(screen)) return 'login-picker';\n if (isUnanswerableUsageLimitDialog(screen)) return 'usage-limit-unanswerable';\n if (isUnclaimedConfirmDialog(screen)) return 'unclaimed-modal';\n if (isUnclaimedPressEnterSplash(screen)) return 'unclaimed-modal';\n return null;\n}\n\n/**\n * A CONTENT-FREE fingerprint of the blocking modal: a stable hash plus the\n * block's length — or null when there is no focused modal block.\n *\n * ## Why a hash and not the text (CodeRabbit, PR #5504)\n *\n * The first version of this returned a 200-character excerpt of the pane. The\n * bound was the wrong control. The modal this fires on most often is the\n * UNCLAIMED one, whose content is by definition unknown to us, and the block is\n * simply the six lines above a confirm footer — which on a busy agent is the\n * transcript it was mid-way through writing. Truncating a customer's message to\n * 200 characters still forwards a customer's message, and `onPaneBlocked`\n * persists this into a control-plane alert row, so it would leave the host.\n *\n * This module's own `simpleTextHash` already states the policy this has to\n * follow — \"input may contain PII/secrets, so log hash+len, never content\" —\n * and `channel-input-watchdog` already reports exactly this data, the unclaimed\n * dialog block, as `unclaimedDialogHash`. The decision was made; this just\n * failed to follow it.\n *\n * Nothing diagnostic is lost. The `UnanswerablePaneKind` is the actual\n * diagnosis, and the operator-facing line names the one action that resolves\n * it (`tmux attach`), where the real pane is a keystroke away. The hash adds\n * the thing an excerpt could not: correlation. Eight agents blocked on the same\n * unknown modal share a hash, which is how you tell one wedged agent from a\n * fleet-wide dialog rollout.\n */\nexport function summarizeUnanswerablePane(\n screen: string,\n): { hash: string; length: number } | null {\n const block = focusedConfirmDialogBlock(screen);\n if (!block) return null;\n const flat = block.join('\\n');\n return { hash: simpleTextHash(flat), length: flat.length };\n}\n"],"mappings":";AA8BA,SAAS,oBAAoB;AA0DtB,SAAS,qBAAqB,QAAyB;AAC5D,SACE,OAAO,SAAS,qBAAqB,KACpC,OAAO,SAAS,kCAAkC,KACjD,OAAO,SAAS,2BAA2B;AAEjD;AAmBO,IAAM,4BACX;AAQK,SAAS,6BAA6B,QAAyB;AACpE,SACE,OAAO,SAAS,2BAA2B,KAC3C,OAAO,SAAS,yBAAyB;AAE7C;AAQO,SAAS,qBAAqB,QAA0C;AAC7E,MAAI,CAAC,6BAA6B,MAAM,EAAG,QAAO;AAClD,SAAO,cAAc,QAAQ,yBAAyB;AACxD;AA2BO,SAAS,WAAW,UAAkB,sBAA8C;AACzF,QAAM,SAAS,sBAAsB,QAAQ;AAC7C,MAAI,yBAAyB,MAAM;AACjC;AAAA;AAAA;AAAA;AAAA,MAIE,GAAG,MAAM,oIAC8C,yBAAyB;AAAA;AAAA,EAEpF;AACA,MAAI,yBAAyB,MAAM;AACjC,WACE,GAAG,MAAM,0FACE,yBAAyB;AAAA,EAExC;AACA,SAAO;AACT;AAEA,IAAM,6BAA6B;AAO5B,SAAS,4BAA4B,QAAyB;AACnE,QAAM,QAAQ,kBAAkB,QAAQ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;AA6BO,SAAS,0BACd,QACyC;AACzC,QAAM,QAAQ,0BAA0B,MAAM;AAC9C,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,OAAO,MAAM,KAAK,IAAI;AAC5B,SAAO,EAAE,MAAM,eAAe,IAAI,GAAG,QAAQ,KAAK,OAAO;AAC3D;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/claude-pair-runtime.ts","../src/lib/claude-pair-parser.ts"],"sourcesContent":["/**\n * ENG-4580: manager-side runtime for the Claude Code OAuth pairing flow.\n *\n * These functions own the actual tmux dance — sending `/login`,\n * polling the pane until Claude Code prints the OAuth URL, sending\n * the auth code, and detecting success/failure. They are the\n * counterpart to the pure parser in `claude-pair-parser.ts`.\n *\n * The API surface in ENG-4581 will wrap these — they don't include\n * any HTTP / DB code so the unit tests can target the parser layer\n * without spinning up a fake API. Errors are classified into the\n * `SessionError` shape so the API can translate them into structured\n * 4xx responses (e.g. `session_missing`).\n *\n * Architectural note: tmux capture-pane on a session that doesn't\n * exist exits non-zero with `can't find session`. Same goes for tmux\n * not being installed. classifyTmuxError covers both.\n */\n\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\n// ENG-10862: `readFileSync` so finalize can tell a written config from a torn\n// one — an mtime that advances onto unparseable JSON is not a success.\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir, userInfo } from 'node:os';\nimport {\n claudeConfigDir as claudeConfigDirFor,\n claudeJsonPath as claudeJsonPathFor,\n effectiveClaudeJsonPath,\n inspectClaudeConfig,\n CLAUDE_CONFIG_DIR_ENV,\n} from './claude-config-location.js';\n\nimport {\n classifyTmuxError,\n detectAuthOutcome,\n extractOAuthUrl,\n isUrlPromptReady,\n type AuthOutcome,\n type SessionError,\n} from './claude-pair-parser.js';\nimport { redactPaneFrame, sanitizeTerminalFrame } from '@augmented/core';\nimport { hostClaudePairCommand } from './claude-host-args.js';\nimport { consumerTermsOffKeys, selectRowKeys } from './claude-dialogs.js';\n\nconst execFileAsync = promisify(execFile);\n\n// Pair-scoped tmux session name. The pairing flow runs inside a\n// throwaway `claude` instance — never inside an agent's persistent\n// session — so first-time auth on a fresh host works (no chicken-and-\n// egg) and re-auth doesn't disrupt an in-flight agent conversation.\nexport function pairTmuxSession(pairId: string): string {\n return `agt-pair-${pairId.slice(0, 12)}`;\n}\n\n/** The pair pane's width (`new-session -x`). tmux soft-wraps at exactly this many columns. */\nexport const PAIR_PANE_COLUMNS = 240;\n\n// ---------------------------------------------------------------------------\n// Low-level helpers\n// ---------------------------------------------------------------------------\n\ninterface CapturePaneOpts {\n /** How many lines of scrollback to include (negative = lines back). Default -200. */\n scrollback?: number;\n}\n\nasync function capturePane(session: string, opts: CapturePaneOpts = {}): Promise<string> {\n const scrollback = opts.scrollback ?? -200;\n const { stdout } = await execFileAsync('tmux', [\n 'capture-pane',\n '-t',\n session,\n '-p',\n '-S',\n String(scrollback),\n ]);\n return stdout;\n}\n\nasync function sendKeys(session: string, ...keys: string[]): Promise<void> {\n await execFileAsync('tmux', ['send-keys', '-t', session, ...keys]);\n}\n\nasync function sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\n/**\n * ENG-10619: answer Claude Code's consumer-terms dialog with\n * \"Help improve our AI models: OFF\" if it is focused. Returns true when\n * keys were sent. One send-keys call per key with a beat between them —\n * batching arrow keys into one call risks a bracketed paste (see\n * sendDialogKeys in claude-dialogs.ts).\n */\nasync function answerConsumerTermsDialog(session: string, pane: string): Promise<boolean> {\n const keys = consumerTermsOffKeys(pane);\n if (!keys) return false;\n await sendKeySequence(session, keys);\n return true;\n}\n\nasync function sendKeySequence(session: string, keys: readonly string[]): Promise<void> {\n for (let i = 0; i < keys.length; i++) {\n if (i > 0) await sleep(300);\n await sendKeys(session, keys[i]!);\n }\n}\n\n/**\n * ENG-10653: how long to wait, after a pane goes dead, for tmux to publish its\n * exit status. A wall-clock deadline, deliberately not an iteration count —\n * see the bound's derivation below for why that distinction is not cosmetic.\n *\n * MEASURED (`scripts/measure-tmux-dead-status.mjs`, macOS 15, tmux 3.7b,\n * 2026-09-18, across three load regimes — unloaded, 12-way CPU saturation and\n * a fork storm): **not once** did a poll see the `Pane is dead (...)` banner\n * drawn while `pane_dead_status` was still empty.\n *\n * That is stated as a count of a single-instant observation, deliberately, and\n * not as a timing gap. An earlier draft of this comment claimed \"gap 0 ms at\n * p100\"; that was an artefact of polling — two values read in the same poll\n * bound the gap by one poll width (~9–15 ms here), they do not measure it as\n * zero — and the companion claim that the banner \"followed by 3–24 ms\" was\n * just the cost of the second tmux call in the same iteration. Both are gone.\n *\n * Two consequences, and the second is why ENG-10631 did not close this:\n *\n * 1. The banner is not an independent source of the status. tmux draws it\n * only once it has reaped the child, so the state ENG-10631's fallback\n * exists to exploit — banner present, status absent — is one this tmux\n * never actually entered. The fallback is still right and stays (it\n * recovers a status the format read itself lost), but it could not win the\n * reap race it was written for, which is why ENG-10643's queue run still\n * read \"exit status unknown\" with all three of its fixes in the tree.\n * 2. The banner IS a completion marker. Once drawn, tmux has published\n * everything it is going to, so it ends the wait as definitively as a\n * numeric status does.\n *\n * The BOUND is therefore not derived from that measurement — a 0 ms gap would\n * justify no wait at all. It is derived from the CI tail, the only place the\n * gap has ever opened. ENG-10631 measured >1 s. The ENG-10643 ejection (run\n * 35223527037, job `tests (packages)`) then exhausted the 30 × 100 ms loop\n * that replaced it: the test took 4624 ms, which decomposes to the 500 ms\n * spawn settle + 3000 ms of sleeps + ~33 tmux client spawns at ~35 ms each.\n * That is the point about wall clock — the loop's nominal \"3 s\" was really\n * ~4.1 s, because each iteration also paid to spawn a tmux client, and the\n * number in the code did not say so.\n *\n * 15 s is ~3.7× the bound that was observed losing. It is affordable because\n * this wait is on a TERMINAL path — the pane is dead, the pair flow is over —\n * and it sits inside a single poll of callers budgeting 60 s\n * (`startClaudePair`) and 30 s (`submitClaudePairCode`). An alive pane never\n * reaches it.\n *\n * ENG-10714 — \"sits inside\" is true of the DEFAULT budgets and not of the\n * mechanism, so read it as a statement about today's callers rather than a\n * bound this wait respects. `checkPairPaneAlive` is called from INSIDE\n * `startClaudePair`'s poll loop, and that loop tests its deadline only\n * BETWEEN iterations — so one poll can overrun a caller's whole budget by up\n * to `DEAD_PANE_STATUS_WAIT_MS`, and the caller has no way to cut it short.\n * Measured 2026-09-19: a caller passing `timeoutMs: 10_000` returned after\n * 15050 ms. Nothing is broken by that today (the path is terminal and the\n * overrun buys the answer the caller wanted), but a future caller with a\n * genuinely tight budget needs `waitMs` threading through\n * `DeadPaneWaitOpts` — which `checkPairPaneAlive` already accepts and no\n * caller yet passes — rather than a smaller global bound. Raising this\n * constant without that is what would turn the overrun into a real one.\n */\nexport const DEAD_PANE_STATUS_WAIT_MS = 15_000;\n\n/** One `#{pane_dead}|#{pane_dead_status}|#{pane_dead_signal}` reading. */\nexport interface DeadPaneReading {\n dead: string;\n exitStatus: string;\n /** Empty string on tmux builds with no `pane_dead_signal` format. */\n signal: string;\n}\n\nexport interface DeadPaneWaitOpts {\n waitMs?: number;\n pollMs?: number;\n /** How often to spend a capture-pane looking for the completion banner. */\n captureEveryMs?: number;\n /**\n * ENG-10714: how long the FINAL capture may keep retrying while the dead\n * pane still shows nothing. Bounded and only entered when there is nothing\n * to show — a pane that already has content costs one capture, as before.\n */\n captureRetryMs?: number;\n /** Gap between those retries. */\n captureRetryPollMs?: number;\n}\n\nexport interface DeadPaneVerdict {\n exitStatus: string;\n pane: string;\n /**\n * How the wait ended. Four of these are answers; only `timeout` means tmux\n * never told us. `signal` is a genuinely status-less death, not a missing\n * status — the distinction the operator message depends on.\n */\n resolved: 'status' | 'signal' | 'banner' | 'session-gone' | 'timeout';\n waitedMs: number;\n polls: number;\n readFailures: number;\n /**\n * ENG-10714: transient `capture-pane` failures. These used to be swallowed\n * by a bare `catch {}`, which made \"the capture failed\" and \"claude printed\n * nothing\" the same observable — so the message could not tell the operator\n * which had happened, and the after-window could not tell which was fixed.\n */\n captureFailures: number;\n /** ENG-10714: extra captures spent waiting for a dead pane to show content. */\n recaptures: number;\n /** Filled in only on `timeout`, where it is worth knowing. */\n tmuxVersion?: string;\n}\n\n/**\n * The pane lines that are claude's OUTPUT — everything except tmux's own\n * dead-pane banner and blank padding.\n *\n * Shared by the capture retry and the operator message deliberately: they are\n * answering the same question (\"is there anything to show?\") and a second copy\n * of the filter would let them disagree about it, so the retry could give up\n * on a pane the message then renders, or keep retrying one it would discard.\n */\nfunction paneOutputLines(pane: string): string[] {\n return pane\n .split('\\n')\n .map((l) => l.trimEnd())\n .filter((l) => l.length > 0 && !/^Pane is dead\\b/.test(l));\n}\n\n// ---------------------------------------------------------------------------\n// ENG-11659: what of the pair pane may leave the host\n// ---------------------------------------------------------------------------\n\n/**\n * Scrub pair-pane text before it goes anywhere a person reads it (the console\n * modal, via `error_message`).\n *\n * The pair pane is the one terminal on the host that is ABOUT credentials, so\n * the shared frame scrub (`redactPaneFrame`: known token shapes + `.augmented`\n * paths) is necessary but not enough. On top of it:\n * - every URL, because the only URLs this pane prints are the OAuth authorize\n * link (single-use `state`) and callback links carrying a `code`;\n * - every email address, because claude prints `Logged in as <email>`;\n * - any 32+ character opaque run, which is the shape of a pasted\n * authorization code (`<code>#<state>`) that no named pattern catches.\n *\n * Order matters: URLs before emails (a URL can contain `@`), and both before\n * the opaque-run rule, which would otherwise eat part of a URL and leave the\n * rest behind.\n *\n * Best-effort, like the shared scrub it builds on (see its header). It is a\n * belt, not the reason this is safe to show: the reader is already an owner or\n * admin of the host.\n */\nexport function redactPairPaneText(text: string): string {\n // Rejoin soft-wrapped URLs FIRST (Obi Wan 17220305e9e7 / CodeRabbit on\n // #7129): the OAuth URL (~350 chars) is wider than the pane, so tmux hands it\n // back as two or more lines, and a line-by-line URL rule would leave the tail\n // (query values under the 32-char rule) in plain text.\n return redactUrlTailRows(\n redactPaneFrame(joinWrappedUrlLines(sanitizeTerminalFrame(text))).replace(/https?:\\/\\/[^\\s<>\"'`]+/g, '<url>'),\n )\n .replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/g, '<email>')\n .replace(/[A-Za-z0-9_#~-]{32,}/g, '<redacted>');\n}\n\n/**\n * Rejoin a URL that tmux soft-wrapped. A soft-wrapped row fills the pane to\n * exactly PAIR_PANE_COLUMNS, so a row carrying a URL at that width continues on\n * the next row. Width, not \"the next row starts with a non-space\": that would\n * also glue the prompt under a short URL (\"Paste code here\") onto it.\n * Not `capture-pane -J`: every screen parser reads that capture, and this is\n * the one consumer that needs the join. Escapes are already stripped here.\n */\nexport function joinWrappedUrlLines(text: string, columns: number = PAIR_PANE_COLUMNS): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let inUrl = false;\n for (const line of lines) {\n if (inUrl && out.length > 0) out[out.length - 1] += line;\n else out.push(line);\n const row = line;\n inUrl = row.length >= columns && (inUrl || /https?:\\/\\//.test(row));\n }\n return out.join('\\n');\n}\n\n/**\n * Backstop for a URL that wrapped in a way the width rule cannot see (Obi Wan\n * a303399d1837 on #7129): Claude Code's UI may hard-wrap the link itself,\n * inside an indent or a box, at less than the pane width, and a row holding\n * wide glyphs is shorter in JS than in columns. So a row directly under a\n * redacted URL whose first token (after indent / box edge) looks like a query\n * continuation, carrying `=`, `&` or `%`, is redacted too, repeatedly for a\n * multi-row wrap. So is a row that is NOTHING but one URL-safe token (CodeRabbit\n * on #7129): a wrap straight after `state=` leaves the bare value on its own\n * row, with none of those characters and under the 32-char opaque-run rule.\n * Prose under a link (\"Paste code here if prompted >\") has spaces and so\n * survives either rule. Over-redacting a stray `a=b`, or a one-word row under\n * a link, is the safe direction.\n */\nexport function redactUrlTailRows(text: string): string {\n const query = /<url>([ \\t│|]*)\\n([ \\t│|]*)([^\\s│|]*[=&%][^\\s│|]*)/g;\n const valueOnly = /<url>([ \\t│|]*)\\n([ \\t│|]*)[A-Za-z0-9._~%+/-]+(?=[ \\t│|]*(?:\\n|$))/g;\n let prev = '';\n let out = text;\n while (prev !== out) {\n prev = out;\n out = out.replace(query, '<url>$1\\n$2<url>').replace(valueOnly, '<url>$1\\n$2<url>');\n }\n return out;\n}\n\n/** ENG-11659: how much of the stuck screen the console is shown. */\nexport const PAIR_PANE_EXCERPT_MAX_LINES = 20;\nexport const PAIR_PANE_EXCERPT_MAX_CHARS = 1200;\n\n/**\n * ENG-11659: the redacted, trimmed visible text of the pair pane: the \"what was\n * on the screen\" an operator would otherwise need SSM to see. Blank lines and\n * tmux's own dead-pane banner are dropped; the TAIL is kept, because whatever\n * claude is waiting on is at the bottom.\n */\nexport function pairPaneExcerpt(pane: string): string {\n const lines = paneOutputLines(redactPairPaneText(pane));\n let out = lines.slice(-PAIR_PANE_EXCERPT_MAX_LINES).join('\\n');\n if (out.length > PAIR_PANE_EXCERPT_MAX_CHARS) out = `…${out.slice(-PAIR_PANE_EXCERPT_MAX_CHARS)}`;\n return out;\n}\n\nfunction withScreen(excerpt: string): string {\n return excerpt\n ? `What Claude Code is showing on the host:\\n${excerpt}`\n : 'Its screen on the host was blank.';\n}\n\n/**\n * ENG-11659: the operator copy for \"the deadline passed and no sign-in link\n * appeared\". Carries the stuck screen, so the console can show what claude was\n * actually waiting on instead of a spinner and a generic timeout.\n */\nexport function describeUrlPromptNotSeen(waitedMs: number, excerpt: string): string {\n return (\n `Claude Code did not show a sign-in link within ${Math.round(waitedMs / 1000)}s. ` +\n `${withScreen(excerpt)}\\n` +\n 'Try again. If the same screen comes back, use \"Reset sign-in and try again\" to clear ' +\n 'the saved Claude sign-in on this host first.'\n );\n}\n\n/**\n * ENG-11659: the operator copy for claude sitting on a failed earlier sign-in.\n * Replaces \"SSH to the host and clear ~/.claude/.credentials.json\", which asked\n * a console user for a step only someone with shell access can take.\n */\nexport function describeOAuthRetryStuck(excerpt: string): string {\n return (\n 'Claude Code on this host is stuck on a failed earlier sign-in ' +\n '(\"OAuth error ... Press Enter to retry\"), so Re-login cannot reach a sign-in link. ' +\n 'Use \"Reset sign-in and try again\" to clear the saved Claude sign-in on this host, ' +\n 'then sign in fresh. ' +\n withScreen(excerpt)\n );\n}\n\n/**\n * ENG-10653: wait for tmux to publish a dead pane's exit status, and report\n * how the wait ended.\n *\n * tmux marks a pane dead when the pty hits EOF but only fills in\n * `pane_dead_status` once it has reaped the child — separate events, so a read\n * in between sees a dead pane with an EMPTY status. Ending the wait on the\n * first of those and reporting \"unknown\" is the defect this closes.\n *\n * The I/O is injected so the wait can be proven against a fake that publishes\n * late or fails transiently. It cannot be proven against real tmux on a\n * developer machine: the gap there is 0 ms (see `DEAD_PANE_STATUS_WAIT_MS`),\n * so the race simply does not occur.\n *\n * ENG-10714: it DOES occur in CI, and harder than this comment implied — on\n * tmux 3.4 the full 15 s bound has been seen to expire with no status, no\n * signal and no banner, i.e. tmux published nothing at all rather than\n * publishing late. So the real-tmux test above asserts only what does not\n * depend on the race; anything that asserts the status is recovered belongs\n * against the injected fake, where the timing is the test's to choose.\n */\nexport async function awaitDeadPaneVerdict(\n io: { read: () => Promise<DeadPaneReading>; capture: () => Promise<string> },\n initial: DeadPaneReading,\n opts: DeadPaneWaitOpts = {},\n): Promise<DeadPaneVerdict> {\n const waitMs = opts.waitMs ?? DEAD_PANE_STATUS_WAIT_MS;\n const pollMs = opts.pollMs ?? 100;\n const captureEveryMs = opts.captureEveryMs ?? 1_000;\n\n const numeric = (v: string): boolean => /^\\d+$/.test(v.trim());\n // NOT `numeric`: tmux reports the signal by NAME, not number. Measured on\n // tmux 3.7b, `#{pane_dead_signal}` for a SIGTERM death is the string `term`\n // — so a numeric test never matches, and a signal death would sit out the\n // whole bound before reporting the unknown it already knew about. Any\n // non-empty value is the answer; builds without the format expand it to ''.\n //\n // The `#{` rejection is the fail-safe direction. A build that echoed the\n // format back unexpanded would otherwise make EVERY dead pane resolve as a\n // signal on the first read — skipping the status wait entirely and turning\n // this fix into a faster version of the bug it closes.\n const signalled = (v: string): boolean => v.trim().length > 0 && !v.includes('#{');\n const started = Date.now();\n const deadline = started + waitMs;\n\n let reading = initial;\n let pane = '';\n let polls = 0;\n let readFailures = 0;\n // ENG-10714 (CodeRabbit): declared HERE, not beside the retry below, because\n // the periodic banner capture inside the loop can fail too — and if it does\n // while the pane is still empty, a later final capture that succeeds-and-is-\n // empty would report zero failures and `describeClaudeExit` would go back to\n // claiming \"It printed nothing\". That is this change's own defect, one loop up.\n let captureFailures = 0;\n let nextCaptureAt = started + captureEveryMs;\n let resolved: DeadPaneVerdict['resolved'] = 'timeout';\n if (numeric(reading.exitStatus)) resolved = 'status';\n else if (signalled(reading.signal)) resolved = 'signal';\n\n while (resolved === 'timeout' && Date.now() < deadline) {\n await sleep(pollMs);\n polls++;\n try {\n reading = await io.read();\n } catch (err) {\n readFailures++;\n // A transient tmux client spawn failure under load must NOT collapse the\n // wait. The previous `catch { break }` here turned one such failure into\n // an immediate \"exit status unknown\", which is the same wrong answer\n // this whole wait exists to avoid — and it left no trace of having\n // happened. Only a session that has genuinely gone away ends the wait,\n // and even then the pane was already dead, so the verdict is still\n // `claude-exited` rather than a bare `no-session`.\n if (classifyTmuxError(err).kind !== 'unknown') { resolved = 'session-gone'; break; }\n continue;\n }\n if (numeric(reading.exitStatus)) { resolved = 'status'; break; }\n if (signalled(reading.signal)) { resolved = 'signal'; break; }\n if (Date.now() >= nextCaptureAt) {\n nextCaptureAt = Date.now() + captureEveryMs;\n try { pane = await io.capture(); } catch { captureFailures++; }\n // Costs one capture per second, and covers the tmux builds that publish\n // no `pane_dead_signal`: on those, a signal death would otherwise sit\n // here for the full bound before admitting it has no status.\n if (/^Pane is dead \\(/m.test(pane)) { resolved = 'banner'; break; }\n }\n }\n\n // Capture last, so the pane read is the freshest one available — on `status`\n // the banner is 3–24 ms behind and may only now have landed. Attempted even\n // on `session-gone`: a `display-message` that classified as no-session does\n // not prove `capture-pane` fails in the same instant, and the pane content\n // is the last thing recoverable about why claude exited.\n //\n // ENG-10714: this was one `try { pane = await io.capture(); } catch {}`, and\n // that single line produced a quarter of the CI failures on this path — 5 of\n // 20 over the test file's first 38.7 h were an EMPTY pane, once on a pane\n // whose exit status had already been published. The operator was told\n // \"It printed nothing\" about a pane that had printed.\n //\n // Two candidate causes, and the swallowing is what made them\n // indistinguishable: tmux had not yet drained the pty into the pane buffer\n // (the pane is marked dead at EOF, which is earlier), or the capture's own\n // tmux client spawn failed transiently under load — the very class the read\n // loop above already retries and COUNTS. Retrying fixes both; counting is\n // what lets the next occurrence say which one it was.\n //\n // Bounded, and entered only when there is nothing to show: a pane with\n // content costs exactly one capture, exactly as before.\n // Snapshot BEFORE the capture retry: `waitedMs` is how long tmux was given\n // to publish a STATUS, and the operator message quotes it as exactly that.\n // Letting the capture retry inflate it would make the reported wait disagree\n // with the bound it is being compared against.\n const waitedMs = Date.now() - started;\n const captureDeadline = Date.now() + (opts.captureRetryMs ?? 1_000);\n const captureRetryPollMs = opts.captureRetryPollMs ?? 200;\n let recaptures = 0;\n for (;;) {\n try {\n const fresh = await io.capture();\n // Never trade content away for a later, emptier read: an in-loop banner\n // capture may already hold claude's output, and on `session-gone` the\n // pane can legitimately go blank between reads.\n //\n // Compared by CHARACTER length of the filtered output, not by line count\n // (CodeRabbit): two captures can both hold one line while the later one\n // is a truncated version of the earlier, and a line-count test would\n // swap the diagnostic for the fragment.\n const freshOutput = paneOutputLines(fresh).join('\\n');\n const savedOutput = paneOutputLines(pane).join('\\n');\n if (freshOutput.length >= savedOutput.length) pane = fresh;\n } catch (err) {\n captureFailures++;\n // Same rule as the read loop: only a session that has genuinely gone\n // away ends this, because retrying a vanished session cannot succeed.\n if (classifyTmuxError(err).kind !== 'unknown') break;\n }\n if (paneOutputLines(pane).length > 0 || Date.now() >= captureDeadline) break;\n recaptures++;\n await sleep(captureRetryPollMs);\n }\n return {\n exitStatus: reading.exitStatus,\n pane,\n resolved,\n waitedMs,\n polls,\n readFailures,\n captureFailures,\n recaptures,\n };\n}\n\n/**\n * ENG-10617: turn a dead pair pane into an operator-readable message.\n *\n * Pair sessions run with `remain-on-exit on`, so when claude exits the\n * pane stays behind holding its final screen plus tmux's own\n * `Pane is dead (status N, <date>)` banner. That screen is the only record\n * of why claude exited — without it the operator got a raw\n * `can't find pane` and nothing to act on.\n *\n * Exported for unit testing.\n */\nexport function describeClaudeExit(exitStatus: string, pane: string, wait?: DeadPaneVerdict): string {\n // ENG-10631: `pane_dead_status` can still be empty after the reap wait under\n // heavy load (seen in CI with a 1s wait), but tmux's own banner in the pane\n // carries the same number. Use it rather than report \"exit status unknown\".\n // The LAST banner: claude's own output above it could contain banner-shaped\n // text, and tmux always writes the real one after everything claude printed.\n // Take the final banner of ANY kind first (a signal death writes\n // `Pane is dead (signal N, ...)`), and only then read a status out of it.\n const finalBanner = [...pane.matchAll(/^Pane is dead \\(.*$/gm)].at(-1)?.[0] ?? '';\n const bannerStatus = /^Pane is dead \\(status (\\d+)/.exec(finalBanner)?.[1] ?? '';\n if (!/^\\d+$/.test(exitStatus.trim()) && bannerStatus) exitStatus = bannerStatus;\n // ENG-11659: redacted like every other pair-pane excerpt that leaves the host.\n const lines = paneOutputLines(redactPairPaneText(pane));\n let output = lines.slice(-15).join('\\n');\n if (output.length > 800) output = `…${output.slice(-800)}`;\n const known = /^\\d+$/.test(exitStatus.trim());\n // ENG-10653: \"we waited and tmux never said\" and \"tmux said there is no exit\n // status\" are different facts, and only the first is a defect. A signal death\n // is a real status-less exit and keeps the plain wording; a wait that ran out\n // says so, and carries what it saw — otherwise the next occurrence of this\n // flake is as undiagnosable as the one that opened this issue.\n let unresolved = '';\n if (wait?.resolved === 'timeout') {\n unresolved = ` — tmux had not published one after ${wait.waitedMs}ms (${wait.polls} polls, ` +\n `${wait.readFailures} read failure(s), ` +\n `${finalBanner ? 'banner present' : 'no dead-pane banner'}` +\n `${wait.tmuxVersion ? `; ${wait.tmuxVersion}` : ''})`;\n } else if (wait?.resolved === 'session-gone') {\n // Also unanswered, just for a different reason, and it needs saying for\n // the same one: without it this reads as a plain status-less exit, which\n // is the bare-diff shape this whole change exists to remove.\n unresolved = ` — the tmux session disappeared after ${wait.waitedMs}ms ` +\n `(${wait.polls} polls) before tmux published one`;\n }\n const status = known ? `exit status ${exitStatus.trim()}` : `exit status unknown${unresolved}`;\n // ENG-10714: \"It printed nothing\" is a CLAIM about claude, and it must only\n // be made when the capture actually succeeded and came back empty — which,\n // after the bounded retry above, means several clean reads spread over a\n // second. If a capture FAILED we do not know what claude printed, and saying\n // it printed nothing is the same shape of confident falsehood ENG-10617\n // exists to remove: the operator stops looking for output that was there.\n const nothing = (wait?.captureFailures ?? 0) > 0\n ? `Its output could not be read back from the dead pane ` +\n `(${wait?.captureFailures} capture failure(s)), so it may have printed something. `\n : 'It printed nothing. ';\n return (\n `Claude Code exited on the host (${status}) before login finished. ` +\n (output ? `Its last output:\\n${output}\\n` : nothing) +\n 'Run `claude` on the host as the manager\\'s user to reproduce, then Start over.'\n );\n}\n\n/**\n * ENG-10617: null while claude is still running in the pair pane; a\n * `claude-exited` error (with its last output) once it has exited; or the\n * classified tmux error if the session itself is gone.\n */\nasync function checkPairPaneAlive(session: string, opts: DeadPaneWaitOpts = {}): Promise<SessionError | null> {\n const read = async (): Promise<DeadPaneReading> => {\n const { stdout } = await execFileAsync('tmux', [\n 'display-message',\n '-p',\n '-t',\n session,\n // `|`-separated, not space-separated: an unset format expands to the\n // empty string, so splitting three fields on a space would shift them\n // left and read the signal as the status.\n '#{pane_dead}|#{pane_dead_status}|#{pane_dead_signal}',\n ]);\n const [dead = '', exitStatus = '', signal = ''] = stdout.trim().split('|');\n return { dead, exitStatus, signal };\n };\n let initial: DeadPaneReading;\n try {\n initial = await read();\n } catch (err) {\n return classifyTmuxError(err);\n }\n // Fast path: an alive pane costs exactly one tmux call and never captures.\n if (initial.dead !== '1') return null;\n const verdict = await awaitDeadPaneVerdict(\n { read, capture: () => capturePane(session, { scrollback: -50 }) },\n initial,\n opts,\n );\n if (verdict.resolved === 'timeout') {\n try {\n const { stdout } = await execFileAsync('tmux', ['-V']);\n verdict.tmuxVersion = stdout.trim();\n } catch { /* best-effort: the version is a diagnostic, not a requirement */ }\n }\n return { kind: 'claude-exited', message: describeClaudeExit(verdict.exitStatus, verdict.pane, verdict) };\n}\n\n// ---------------------------------------------------------------------------\n// Pair-scoped tmux session lifecycle\n// ---------------------------------------------------------------------------\n\n/**\n * ENG-10653: the dead-pane banner, pinned rather than inherited.\n *\n * The banner text is an OPTION (`remain-on-exit-format`, tmux 3.3+), not a\n * constant, and a pair session is created on whatever tmux server the host\n * already runs — so it inherits the host user's `~/.tmux.conf`. A host that\n * sets its own format silently disables BOTH readers of that banner:\n * ENG-10631's status fallback and ENG-10653's completion marker. Verified:\n * with `remain-on-exit-format \"child gone: #{pane_dead_status}\"` the pane\n * holds `child gone: 3` and `/^Pane is dead \\(/` matches nothing, while the\n * status sits in plain view. No error, no log — the shape this whole issue is\n * about, one level down.\n *\n * So the pair session states the format it intends to parse.\n *\n * The `#{!=:...,}` guard is not decoration, and tmux's own default carries it\n * for the same reason: `#{?pane_dead_status,...}` would test TRUTHINESS, and\n * tmux reads `0` as false — so a clean `exit 0` would render as a signal\n * death. Comparing against the empty string asks the question actually meant,\n * \"did tmux publish a status\".\n */\nexport const PAIR_REMAIN_ON_EXIT_FORMAT =\n 'Pane is dead (#{?#{!=:#{pane_dead_status},},status #{pane_dead_status},signal #{pane_dead_signal}})';\n\n/**\n * Spawn a throwaway tmux session running `claude` for the pairing flow.\n * Idempotent — if the session already exists, returns success silently.\n * Caller is responsible for `killPairSession` once the pair reaches a\n * terminal state.\n *\n * Uses an absolute path to the claude binary so we don't depend on the\n * inherited PATH (the manager runs with cloud-init's minimal env on\n * EC2). resolveClaudeBinary checks CLAUDE_PATH, then `which`, then\n * canonical Linux/macOS Homebrew install dirs.\n */\nexport async function spawnPairSession(session: string): Promise<{ ok: true } | { ok: false; error: SessionError }> {\n try {\n await execFileAsync('tmux', ['has-session', '-t', session]);\n return { ok: true };\n } catch {\n // session doesn't exist yet — fall through to create it\n }\n\n const { resolveClaudeBinary } = await import('./persistent-session.js');\n const claudeBin = resolveClaudeBinary();\n\n // ENG-5070: backfill HOME/USER before spawning the pair tmux.\n // persistent-session.ts already does this for agent sessions\n // (ENG-4632) but the pair flow re-used execFileAsync's inherited\n // env, so the same SSM-launched-manager-strips-HOME trap fired the\n // moment an operator clicked \"Login via browser\" on a fresh host:\n // tmux inherits HOME='', the new claude process can't read or\n // write ~/.claude/, claude exits within milliseconds, and the\n // pairing UI surfaces the generic \"claude exited immediately\"\n // message. Treat empty-string as missing too — HOME=\"\" makes ~\n // resolve to cwd (whatever happens to be the manager's working\n // dir), which is the same broken outcome as no HOME, just better\n // hidden.\n const pairEnv: NodeJS.ProcessEnv = {\n ...process.env,\n HOME: (process.env.HOME?.trim()) || homedir(),\n USER: (process.env.USER?.trim()) || userInfo().username,\n };\n\n // ENG-10869 — the pair pane needs CLAUDE_CONFIG_DIR passed BY ARGV.\n //\n // `{ env: pairEnv }` below sets the environment of the tmux CLIENT, and a\n // tmux pane does not inherit that: it gets the SERVER's global environment,\n // merged with `-e` entries, plus only the names in `update-environment`\n // (ENG-8800 measured this on a live host — see the long note in\n // persistent-session.ts, which exists because a per-agent variable passed\n // this way leaked one agent's identity to every other agent on the box).\n //\n // The consequence here is specific and bad. Without the `-e`, `claude` in\n // this pane writes `<home>/.claude.json` while `finalizeClaudePairOnboarding`\n // polls `<configDir>/.claude.json` for an mtime that can never move. Every\n // pairing on every host then exhausts its dialog budget — which under\n // ENG-10862 is no longer a warning but a REPORTED FAILURE, an alert and an\n // instruction to start over, for pairings that actually worked. Meanwhile the\n // containers keep reading the pre-pair copy and the next spawn archives the\n // freshly-paired file.\n //\n // Only when the config dir already holds a usable config: on a host that has\n // never paired there is nothing there yet, and the bootstrap path is exactly\n // that claude writes the legacy file and the next spawn seeds from it.\n const pairConfigDir = claudeConfigDirFor();\n const pairConfigEnvArgs =\n inspectClaudeConfig(claudeJsonPathFor()) === 'usable'\n ? ['-e', `${CLAUDE_CONFIG_DIR_ENV}=${pairConfigDir}`]\n : [];\n\n try {\n // -x 240 -y 50 — wide enough that Claude Code's OAuth URL (~350\n // chars after PKCE expansion) doesn't soft-wrap. The dewrap pass in\n // extractOAuthUrl handles any leftover wrapping, but giving the URL\n // a single line in the first place is more robust against future\n // claude UI changes.\n // ENG-10617: `remain-on-exit on` is chained into the SAME tmux\n // invocation (`;` is tmux's command separator) so it is applied before\n // the server can reap an early-exiting claude. Without it, claude\n // exiting destroys the session and its last output with it, and every\n // later tmux call fails with a bare `can't find pane`.\n await execFileAsync(\n 'tmux',\n [\n 'new-session',\n '-d',\n '-x',\n String(PAIR_PANE_COLUMNS),\n '-y',\n '50',\n ...pairConfigEnvArgs,\n '-s',\n session,\n // ENG-11279 (4): retention-flag parity with the one-shots; see\n // hostClaudePairCommand for why it is one quoted string.\n hostClaudePairCommand(claudeBin),\n ';',\n 'set-option',\n '-w',\n '-t',\n session,\n 'remain-on-exit',\n 'on',\n ],\n { env: pairEnv },\n );\n } catch (err) {\n return { ok: false, error: classifyTmuxError(err) };\n }\n\n // ENG-10653: pin the banner, BEST-EFFORT AND DELIBERATELY NOT CHAINED.\n //\n // `remain-on-exit-format` is tmux 3.3+, and tmux exits 1 on an unknown\n // option while still creating the session — measured. Chained into the\n // new-session above, that would turn \"this host runs tmux 3.2\" into a failed\n // pair AND an orphaned session, trading a silent degradation for an outage.\n // Separate and swallowed, an old tmux simply keeps the host's banner, which\n // is exactly the behaviour it had before this change.\n //\n // The window this opens — claude dying between the two calls — resolves to\n // that same pre-existing behaviour, not to anything worse.\n try {\n await execFileAsync(\n 'tmux',\n ['set-option', '-w', '-t', session, 'remain-on-exit-format', PAIR_REMAIN_ON_EXIT_FORMAT],\n { env: pairEnv },\n );\n } catch { /* tmux < 3.3, or the option is gone: fall back to the host's banner */ }\n\n // `tmux new-session` returns 0 even if the command exited immediately\n // (binary missing, claude crashed, etc.) — the session is created and\n // then torn down. Without this verification we'd propagate a generic\n // `session_missing` to the operator on the next has-session call,\n // hiding the real failure. Sleep briefly to give claude a beat to\n // crash-or-stay-alive, then check.\n await sleep(500);\n const dead = await checkPairPaneAlive(session);\n if (dead?.kind === 'claude-exited') return { ok: false, error: dead };\n if (dead) {\n return {\n ok: false,\n error: {\n kind: 'unknown',\n message: `claude exited immediately after launch (binary at ${claudeBin}). Run \\`${claudeBin}\\` manually on the host to see why — likely missing TTY, missing HOME, or a startup error.`,\n },\n };\n }\n return { ok: true };\n}\n\n/**\n * Has a USABLE config landed at `path` since `sinceMtimeMs`?\n *\n * Both halves matter: the mtime advance distinguishes this pairing's write from\n * a file left by a previous attempt, and the parse distinguishes a write from a\n * tear (ENG-10140 truncations are a plausible size).\n *\n * Exported because finalize is not the only thing that has to ask. The caller\n * re-asks before it reports a failure — see {@link confirmPairFailure} — and a\n * second hand-written copy of this rule is how the two would come to disagree\n * about what \"landed\" means.\n */\nexport function pairConfigLandedSince(path: string, sinceMtimeMs: number): boolean {\n try {\n if (!existsSync(path)) return false;\n if (statSync(path).mtimeMs <= sinceMtimeMs) return false;\n // USABLE, not merely parseable.\n //\n // This was `JSON.parse(...)` and that is a false success. Measured on\n // dominet 2026-09-22T21:26Z, on a host running the ENG-10862 fix: claude\n // wrote a 45KB config carrying a real `oauthAccount` for dom@dominet.com,\n // `hasCompletedOnboarding` ABSENT. It parsed, so finalize reported\n // \"onboarding persisted\" and all five agents stayed on the login picker.\n // That is the exact condition ENG-10862 exists to end, surviving its own\n // fix because the fix corrected WHEN the check runs and not WHAT it tests.\n //\n // It is not only a mis-report, it is a CAUSE. The log read\n // `iterations=1 dialogEnter=0 consumerTerms=0`: finalize saw the first\n // write, declared success, and tore down the pane having dismissed ZERO\n // dialogs — leaving claude sitting on the onboarding prompt that would have\n // written the flag. Requiring the flag keeps the loop pressing Enter until\n // onboarding actually completes, which is what the loop is for.\n //\n // `inspectClaudeConfig` is the same rule the config-dir readiness and mount\n // gates use. Two definitions of \"a good config\" in one codebase is how this\n // got through; there is now one.\n return inspectClaudeConfig(path) === 'usable';\n } catch {\n return false;\n }\n}\n\n/**\n * ENG-10862 — give a late write one last chance before calling a pairing failed.\n *\n * `finalizeClaudePairOnboarding` can return `send-failed` or `pane-gone`\n * IMMEDIATELY after its last config check: those branches abort on a tmux error\n * rather than falling through to the grace pass, so unlike `not-flushed` they\n * have observed the file exactly once, milliseconds earlier. A write already in\n * flight then lands after the verdict.\n *\n * That matters more than it used to. Before this issue the verdict was a log\n * line; now it gates the report, and `reportAndCleanup` POSTs the result BEFORE\n * its three-second beat — so a pairing that actually worked would raise a\n * `warning` alert and tell the operator to start over.\n *\n * So the caller waits and re-asks. The wait is NOT the same as the beat in\n * `reportAndCleanup`: that one exists to let Claude Code finish persisting\n * `.credentials.json` before the pane is killed, and it happens after the POST.\n * This one exists to make the POST correct.\n */\nexport async function confirmPairFailure(opts: {\n configPath: string;\n sinceMtimeMs: number;\n graceMs?: number;\n sleep?: (ms: number) => Promise<void>;\n log?: (msg: string) => void;\n}): Promise<'landed-after-all' | 'confirmed'> {\n const graceMs = opts.graceMs ?? 3_000;\n const nap = opts.sleep ?? sleep;\n const log = opts.log ?? (() => {});\n if (pairConfigLandedSince(opts.configPath, opts.sinceMtimeMs)) {\n log(`[claude-pair] a usable config was already present at ${opts.configPath} — not a failure`);\n return 'landed-after-all';\n }\n await nap(graceMs);\n if (pairConfigLandedSince(opts.configPath, opts.sinceMtimeMs)) {\n log(\n `[claude-pair] ${opts.configPath} landed during the ${graceMs}ms confirm window — ` +\n `the pairing worked after all, reporting success`,\n );\n return 'landed-after-all';\n }\n return 'confirmed';\n}\n\n/**\n * Why finalize concluded that onboarding did not persist. ENG-10862.\n *\n * One WARN covered all of these before, which is what made the alyve incident\n * unreadable: the message asserted a timeout (\"reached 10 iterations\") for a\n * host whose config was simply unwritable. Only `not-flushed` is a timeout.\n */\nexport type PairFinalizeFailure =\n /** The watched path holds a file that does not parse — the ENG-10140 fault. */\n | 'config-corrupt'\n /** Nothing at the watched path at all. Claude Code never wrote one. */\n | 'config-absent'\n /** A parseable config is there, but its mtime never advanced in the window. */\n | 'not-flushed'\n /**\n * A DIRECTORY sits where the config file belongs.\n *\n * Not hypothetical, and not a corruption: `docker run -v /nonexistent:/path`\n * creates a directory at the target, which is how `/root/.claude.json` became\n * one on isolated hosts. `readFileSync` gives EISDIR, so without its own\n * reason this reported `config-corrupt` and told the operator to re-pair —\n * which cannot fix it, so they would loop.\n */\n | 'config-path-is-directory'\n /** The pane died, so nothing was left that could write the file. */\n | 'pane-gone'\n /** tmux refused a keystroke we needed to send to clear a dialog. */\n | 'send-failed';\n\n/**\n * ENG-10862 AC5: how the dialog loop actually spent its iterations.\n *\n * The question \"do real pairings need more than 10 dismissals?\" was\n * unanswerable because nothing recorded the breakdown. Counts only — never the\n * pane text, which carries `Logged in as <email>`.\n */\nexport interface PairDialogCounts {\n /** ENG-10619 consumer-terms dialog answered (option 2, training OFF). */\n consumerTerms: number;\n /** A generic post-OAuth dialog dismissed with Enter. */\n dialogEnter: number;\n /** Pane matched no known dialog — iterations spent purely waiting. */\n noMatch: number;\n}\n\nexport interface PairFinalizeResult {\n finalized: boolean;\n /**\n * Dialog-loop iterations only, capped at `maxIterations`. Deliberately NOT\n * inclusive of the grace pass below, so the number keeps the meaning callers\n * and tests already depend on.\n */\n iterations: number;\n /** Grace-pass waits consumed (ENG-10862). Zero unless the dialog loop ran out. */\n graceWaits: number;\n counts: PairDialogCounts;\n /** Set if and only if `finalized` is false. */\n reason?: PairFinalizeFailure;\n /**\n * The config path this call actually watched. Returned so the caller can\n * name it in the operator-facing message without recomputing the rule — the\n * two would drift, and the symptom would be an error message about a file\n * the flow never looked at.\n */\n configPath: string;\n}\n\n/** Stable machine-readable code per failure, for `claude_pair_sessions.error_code`. */\nexport const PAIR_FINALIZE_ERROR_CODES: Record<PairFinalizeFailure, string> = {\n 'config-corrupt': 'onboarding_config_corrupt',\n 'config-absent': 'onboarding_config_absent',\n 'config-path-is-directory': 'onboarding_config_path_is_directory',\n 'not-flushed': 'onboarding_not_flushed',\n 'pane-gone': 'onboarding_pane_gone',\n 'send-failed': 'onboarding_send_failed',\n};\n\n/**\n * Operator-facing text for a finalize failure.\n *\n * **Every message says the OAuth tokens are valid**, because the pairing is now\n * reported as a `failure` and the console renders this string in a danger box.\n * Without that sentence the operator reads \"failed\" and goes hunting a token\n * fault that does not exist — the tokens were written to\n * `~/.claude/.credentials.json` before finalize ever ran. What failed is the\n * onboarding state that stops the next agent spawn landing on the login picker.\n */\nexport function describePairFinalizeFailure(\n reason: PairFinalizeFailure,\n configPath: string,\n): string {\n const valid =\n 'The OAuth tokens themselves are valid, so this is not a credential problem.';\n const retry = 'Start over to re-run pairing.';\n switch (reason) {\n case 'config-corrupt':\n // Deliberately carries NO ticket id: this string renders in the console,\n // which customers use to pair their own hosts, and they cannot read\n // Linear. The ENG-10140 pointer is in the host's log line instead, where\n // the audience is us.\n return `Signed in, but ${configPath} on this host is unreadable and Claude Code did not replace it, so agents here would start on the login picker. ${valid} ${retry} If it recurs on this host, contact support — the host's config is being corrupted by something outside pairing.`;\n case 'config-path-is-directory':\n // The remedy is genuinely different, so the message has to be too:\n // re-pairing cannot help until the directory is gone.\n return `Signed in, but ${configPath} on this host is a DIRECTORY, not a file, so Claude Code cannot write its config there and agents here would start on the login picker. ${valid} Re-pairing will NOT fix this on its own: remove that directory on the host, then pair again.`;\n case 'config-absent':\n return `Signed in, but Claude Code never wrote ${configPath}, so agents on this host would start on the login picker. ${valid} ${retry}`;\n case 'not-flushed':\n // Covers BOTH \"never written\" and the dominet case: written, parseable,\n // carrying a real account, with `hasCompletedOnboarding` absent. The old\n // wording claimed the file was not written, which on that host was false\n // and sent the operator looking for a disk problem.\n return `Signed in, but Claude Code did not finish onboarding on this host, so ${configPath} is not usable yet and agents here would start on the login picker. ${valid} ${retry}`;\n case 'pane-gone':\n return `Signed in, but the temporary Claude Code session on the host closed before it wrote ${configPath}, so agents here would start on the login picker. ${valid} ${retry}`;\n case 'send-failed':\n return `Signed in, but tmux refused a keystroke needed to clear Claude Code's post-login dialogs, so ${configPath} was never written and agents here would start on the login picker. ${valid} ${retry}`;\n }\n}\n\n/**\n * The `.claude.json` the pair flow watches.\n *\n * Exported so a caller can snapshot the SAME path finalize will watch. Two\n * independent spellings of this rule is how the baseline below would silently\n * stop applying.\n */\n/**\n * The path finalize watches, reconciling ENG-10862 and ENG-10869.\n *\n * An explicitly-set CLAUDE_CONFIG_DIR wins because the pair process inherits\n * it and WILL write there — including before that directory holds a usable\n * config, which is precisely the window `effectiveClaudeJsonPath()` still\n * resolves to the legacy path. Everywhere else, the shared resolution, so\n * finalize and the pane's environment cannot disagree about which file this\n * pairing is writing.\n */\nexport function finalizeWatchPath(env: NodeJS.ProcessEnv = process.env): string {\n if (env['CLAUDE_CONFIG_DIR']?.trim()) return pairClaudeJsonPath(env);\n return effectiveClaudeJsonPath();\n}\n\nexport function pairClaudeJsonPath(env: NodeJS.ProcessEnv = process.env): string {\n // CLAUDE_CONFIG_DIR FIRST, because that is what the pair process itself\n // obeys. `spawnPairSession` builds the pair env as `{...process.env, HOME}`,\n // so a CLAUDE_CONFIG_DIR in the manager's environment is inherited and\n // Claude Code writes `$CLAUDE_CONFIG_DIR/.claude.json`. Watching\n // `~/.claude.json` unconditionally would watch a file nothing writes.\n //\n // Before ENG-10862 that mismatch cost a WARN and a `success` report. It is\n // strictly worse now: `flushed()` never fires, the give-up classifier says\n // `config-absent`, the re-ask confirms against the same wrong path, and the\n // pairing reports `failure` — a page, plus a console box telling the\n // operator to start over, which re-runs the identical mismatch. Every\n // pairing on such a host would fail forever with no way out from the\n // console. Precedent for the precedence: `claudeConfigCandidatePaths` in\n // `claude-account-fingerprint.ts` puts CLAUDE_CONFIG_DIR first for the same\n // reason.\n const configDir = env['CLAUDE_CONFIG_DIR']?.trim();\n if (configDir) return join(configDir, '.claude.json');\n return join(homedir(), '.claude.json');\n}\n\n/** A path plus the mtime it had at some earlier instant. */\nexport interface PairConfigBaseline {\n path: string;\n mtimeMs: number;\n}\n\n/**\n * ENG-10862 — snapshot the config's mtime BEFORE the auth code is submitted.\n *\n * ## Why the caller has to take this, and finalize cannot\n *\n * finalize runs only after `submitClaudePairCode` has seen the success marker\n * in the pane, so a snapshot taken at its entry is already too late: Claude\n * Code may have written the config between the marker appearing and finalize\n * starting, and those are concurrent events, not ordered ones. The mtime has\n * then ALREADY advanced, finalize compares against the post-write value, sees\n * no further change, and reports a failure for a pairing that worked.\n *\n * Under the old code that produced a WARN and a `success` report, so the\n * mistake was invisible. Now that the report is gated on this verdict it would\n * be a page, a red console and an instruction to start over, against a host\n * that is fine — a strictly worse failure than the one being fixed, and\n * introduced by fixing it.\n */\nexport function snapshotPairConfig(claudeJsonPath = finalizeWatchPath()): PairConfigBaseline {\n return {\n path: claudeJsonPath,\n mtimeMs: existsSync(claudeJsonPath) ? statSync(claudeJsonPath).mtimeMs : 0,\n };\n}\n\n/**\n * ENG-4633: drive Claude Code through its post-OAuth dialogs so it\n * persists `~/.claude.json` (the device-state + onboarding-complete\n * file) before we tear down the pair tmux session.\n *\n * Without this step, the pair flow leaves the host with only\n * `~/.claude/.credentials.json` written. On the next agent launch,\n * Claude Code interactive mode sees no `~/.claude.json` and falls\n * back to the login picker — even though the OAuth tokens are\n * sitting right there. This was the root cause of the 2026-05-01\n * prod scout outage.\n *\n * After successful code submission, claude shows in sequence:\n * 1. \"Logged in as <email> / Login successful. Press Enter to continue…\"\n * 2. \"Security notes / Press Enter to continue…\"\n * 3. (depending on cwd) trust-folder prompt and/or bypass-permissions\n * warning. The pair tmux session has neither a project dir nor\n * `--dangerously-skip-permissions`, so we usually only see the\n * first two.\n *\n * ## ENG-10862: the success check has to come FIRST\n *\n * This loop used to stat the config at the BOTTOM, after the dialog matchers —\n * and both matcher branches `continue`. The matchers are deliberately loose\n * (claude's wording shifts between versions) and `Logged in as <email>` stays\n * visible in the pane after login, so on any run where that text persisted the\n * loop sent Enter ten times and **never looked at the file at all**. Exhausting\n * the cap was then guaranteed whether or not Claude Code had written the\n * config, and the give-up message blamed a timeout either way.\n *\n * That is the alyve-host-1 failure of 2026-09-21: one pairing in three gave up\n * at the cap, four agents latched on the login picker for up to 9h50m, and the\n * only signal was a WARN nobody read for nine hours. The runs that succeed log\n * `after 3 dialog dismissal(s)`, which establishes that the pane *usually*\n * clears by the third iteration — not that it must.\n *\n * So the file is checked at the top of every iteration, before any matcher runs\n * and before the pane-liveness probe: a config that landed is a success even if\n * the pane has since died, and no amount of residual dialog text can mask it.\n *\n * ## Success now requires the file to PARSE, not merely to change\n *\n * mtime-only was the old contract, on the stated grounds that we trust claude\n * to write a coherent file. ENG-10140 falsified that: on a containerised host\n * the shared config is routinely torn by concurrent truncate-in-place writes,\n * and an mtime that advances onto a corrupt file is not onboarding having\n * succeeded — it is the next spawn's login picker with a fresher timestamp. A\n * transient mid-write read is covered by simply continuing to poll.\n *\n * ## The grace pass, and where its budget comes from\n *\n * `maxIterations` reads like a dialog count and is really a timer: 10 × 1500ms\n * is a **15-second** total budget. When it runs out, this makes one longer,\n * quieter pass before returning, because the caller's next act is to kill the\n * pane and the pane is the only thing left that can still write the file. The\n * grace pass sends no blind Enter — ten have already gone — but it does keep\n * answering the consumer-terms dialog, since a bare Enter on that one opts the\n * account into model training (ENG-10619) and leaving it unanswered is itself a\n * way to never get the write.\n *\n * **10 more intervals, i.e. 30s total.** An earlier version of this comment\n * derived that number from a heartbeat constraint, and the constraint does not\n * exist: it argued that because `processClaudePairSessions` is awaited inside\n * the refresh cycle, a longer finalize starves `last_seen_at` and a failing\n * pairing could make its own host look stale. ENG-7273 decoupled those —\n * `livenessTimer` is an independent 30s `setInterval` that POSTs\n * `/host/heartbeat` regardless of how long a cycle takes, and finalize only\n * ever awaits `sleep()` and `execFileAsync`, so the interval keeps firing\n * throughout. Reported by a reviewer, and confirmed against\n * `LIVENESS_HEARTBEAT_INTERVAL_MS` before this was rewritten.\n *\n * So the budget is a JUDGEMENT, not a derivation, and it should be read as one:\n * 30s is long enough to catch a write that the 15s dialog loop missed, short\n * enough that an operator watching the pairing UI is not left on a spinner, and\n * it delays only a pairing that is already failing. The real constraint is the\n * console's patience, and nobody has measured that. Anyone extending it is not\n * fighting a heartbeat bound — that reason was wrong.\n *\n * Nothing upstream races the longer window — checked rather than assumed. The\n * console polls `code_submitted` with a spinner and no deadline, and no cron\n * sweeps a stale pair row, so the only cost of waiting is the spinner running\n * longer on a pairing that was going to fail anyway.\n *\n * Returns `finalized` plus a `reason` the caller reports as a FAILED pairing.\n * The OAuth tokens are valid regardless, which every operator-facing message\n * says explicitly — see {@link describePairFinalizeFailure}.\n */\nexport async function finalizeClaudePairOnboarding(\n session: string,\n log: (msg: string) => void,\n opts: {\n maxIterations?: number;\n intervalMs?: number;\n claudeJsonPath?: string;\n graceIterations?: number;\n /**\n * ENG-10862: the mtime to measure against, taken by the caller BEFORE the\n * auth code was submitted. See {@link snapshotPairConfig} for why a\n * snapshot taken at entry here is already too late.\n */\n baseline?: PairConfigBaseline;\n } = {},\n): Promise<PairFinalizeResult> {\n const maxIterations = opts.maxIterations ?? 10;\n const graceIterations = opts.graceIterations ?? 10;\n const intervalMs = opts.intervalMs ?? 1500;\n // ENG-10869 x ENG-10862: which file finalize watches. BOTH sides of this\n // merge were needed; neither alone is correct.\n //\n // finalize polls ONE path's mtime to decide whether onboarding took, so it\n // has to watch the file `claude` is actually writing.\n //\n // - ENG-10869 resolves the config dir only once it holds a USABLE config,\n // falling back to the legacy file. That keeps finalize in step with the\n // pane's environment, which is gated on the same condition.\n // - ENG-10862 honours an explicitly-set CLAUDE_CONFIG_DIR, because\n // `spawnPairSession` builds the pair env as `{...process.env, HOME}` and\n // the pair process therefore INHERITS it.\n //\n // They disagree in exactly one window, and it is the window that matters:\n // CLAUDE_CONFIG_DIR set while the config dir does not YET hold a usable\n // config — the first pairing on a migrated host. There, `claude` writes into\n // the config dir while the effective resolution still points at the legacy\n // file, so finalize would watch a file nothing writes. Under ENG-10862 that\n // is not a WARN any more: it is a reported FAILURE, an alert, and a console\n // box telling the operator to start over, which re-runs the identical\n // mismatch. Every pairing on such a host, forever.\n //\n // So: an explicit CLAUDE_CONFIG_DIR wins outright, and the shared resolution\n // answers everywhere else.\n //\n // `opts.baseline?.path` is deliberately NOT in this chain, though the first\n // draft of this merge put it there. Deriving the watch path FROM the baseline\n // does two bad things at once. It silently adopts whatever file the caller\n // happened to snapshot — and `snapshotPairConfig()` defaulted to\n // `pairClaudeJsonPath()`, so on a migrated host whose MANAGER env carries no\n // CLAUDE_CONFIG_DIR it returns the legacy file while ENG-10869 hands the pane\n // `-e CLAUDE_CONFIG_DIR=<dir>` and `claude` writes the config dir: finalize\n // watching a file nothing writes, which is the exact failure both these\n // tickets exist to remove. And it makes the mismatch guard below unfalsifiable,\n // since a path derived from the baseline can never disagree with it.\n //\n // Resolve independently; let the guard compare. The caller's snapshot is\n // still what the mtime is measured against — that is ENG-10862's late-write\n // fix and it is untouched — but only once the two agree about the file.\n const claudeJsonPath = opts.claudeJsonPath ?? finalizeWatchPath();\n\n // The mtime we measure against. Existence alone will not do: a stale file\n // from a previous pairing would satisfy that on the first iteration.\n //\n // The caller's baseline wins when it describes the same path, because it was\n // taken before the code was submitted and this one is taken after the login\n // already happened. A baseline for a DIFFERENT path is refused rather than\n // quietly ignored — ignoring it would reinstate exactly the too-late\n // snapshot it exists to prevent, with nothing to show for it.\n let initialMtime: number;\n if (opts.baseline && opts.baseline.path === claudeJsonPath) {\n initialMtime = opts.baseline.mtimeMs;\n } else {\n if (opts.baseline) {\n log(\n `[claude-pair] finalize: IGNORING a baseline for ${opts.baseline.path} — this run watches ` +\n `${claudeJsonPath}. A write that landed before the code was submitted may now read as a failure.`,\n );\n }\n initialMtime = existsSync(claudeJsonPath) ? statSync(claudeJsonPath).mtimeMs : 0;\n }\n\n const counts: PairDialogCounts = { consumerTerms: 0, dialogEnter: 0, noMatch: 0 };\n\n /**\n * Has claude written a USABLE config since we entered? Both halves matter:\n * the mtime advance distinguishes this pairing's write from a stale file left\n * by a previous attempt, and the parse distinguishes a write from a tear.\n */\n // Delegated, not reimplemented: the caller re-asks the same question before it\n // reports a failure, and two copies of \"did a usable config land\" would drift.\n // A parse failure here is either a mid-write or a genuine tear; keep polling,\n // and let the give-up classification below re-read and say which.\n const flushed = (): boolean => pairConfigLandedSince(claudeJsonPath, initialMtime);\n\n /** Fresh observation of the watched path, made at give-up time. */\n const classifyAtGiveUp = (): PairFinalizeFailure => {\n if (!existsSync(claudeJsonPath)) return 'config-absent';\n try {\n // Checked BEFORE the read, because a directory throws EISDIR from\n // `readFileSync` and would otherwise be reported as corruption — with a\n // remedy (re-pair) that cannot clear it.\n if (statSync(claudeJsonPath).isDirectory()) return 'config-path-is-directory';\n JSON.parse(readFileSync(claudeJsonPath, 'utf-8'));\n return 'not-flushed';\n } catch {\n return 'config-corrupt';\n }\n };\n\n const describeCounts = () =>\n `consumerTerms=${counts.consumerTerms} dialogEnter=${counts.dialogEnter} noMatch=${counts.noMatch}`;\n\n for (let i = 0; i < maxIterations; i++) {\n await sleep(intervalMs);\n\n // ENG-10862: FIRST, before the matchers and before the liveness probe. A\n // config that landed is a success even if the pane has since exited, and\n // residual dialog text must not be able to skip this.\n if (flushed()) {\n log(\n `[claude-pair] finalize: ${claudeJsonPath} updated (after ${i + 1} dialog dismissal(s); ${describeCounts()})`,\n );\n return { finalized: true, iterations: i + 1, graceWaits: 0, counts, configPath: claudeJsonPath };\n }\n\n const dead = await checkPairPaneAlive(session);\n if (dead) {\n log(`[claude-pair] finalize: pair session no longer running (${dead.kind}); aborting onboarding flow`);\n return { finalized: false, iterations: i, graceWaits: 0, counts, reason: 'pane-gone', configPath: claudeJsonPath };\n }\n let pane: string;\n try {\n pane = await capturePane(session);\n } catch (err) {\n const classified = classifyTmuxError(err);\n log(`[claude-pair] finalize: capture-pane failed (${classified.kind}); aborting onboarding flow`);\n return { finalized: false, iterations: i, graceWaits: 0, counts, reason: 'pane-gone', configPath: claudeJsonPath };\n }\n\n // ENG-10619: must run before the generic Enter branch below — a bare\n // Enter on this dialog confirms its default row, which opts the\n // account into model training.\n try {\n if (await answerConsumerTermsDialog(session, pane)) {\n counts.consumerTerms += 1;\n continue;\n }\n } catch {\n log('[claude-pair] finalize: send-keys failed on consumer-terms dialog; aborting onboarding flow');\n return { finalized: false, iterations: i, graceWaits: 0, counts, reason: 'send-failed', configPath: claudeJsonPath };\n }\n\n // Pattern-match the post-OAuth dialogs claude shows in succession.\n // Keep these matchers loose — claude's wording shifts between\n // versions, and a missed match just means we wait out this iteration\n // and re-check the file at the top of the next one.\n if (\n pane.includes('Login successful') ||\n pane.includes('Logged in as') ||\n /Press Enter to continue/i.test(pane) ||\n pane.includes('Security notes')\n ) {\n try {\n await sendKeys(session, 'C-m');\n } catch {\n // sendKeys failure → session dead. Same fallthrough as above.\n log('[claude-pair] finalize: send-keys failed; aborting onboarding flow');\n return { finalized: false, iterations: i, graceWaits: 0, counts, reason: 'send-failed', configPath: claudeJsonPath };\n }\n counts.dialogEnter += 1;\n continue;\n }\n\n counts.noMatch += 1;\n }\n\n // ENG-10862 AC4: one longer, quieter pass before the caller kills the pane.\n // No blind Enter here (ten have gone already); consumer-terms is still\n // answered because leaving it up is itself a reason the write never comes.\n log(\n `[claude-pair] finalize: ${maxIterations} dialog iterations elapsed (${describeCounts()}); waiting up to ${graceIterations} more intervals for the config`,\n );\n let graceWaits = 0;\n /**\n * Why the grace pass stopped early, if it did.\n *\n * It outranks the OBSERVED state for everything except a config that names a\n * specific fault. \"The session died before writing\" tells the operator\n * something that neither \"no config\" nor \"not written in time\" does.\n *\n * The first version let it win only over `config-absent`, which threw it away\n * on every host that has ever been paired: those have a parseable\n * `~/.claude.json`, so `classifyAtGiveUp()` returns `not-flushed` and a pane\n * that DIED during the grace pass was reported as a timeout — with the\n * message \"Claude Code did not write … within the onboarding window\" for a\n * session that had exited, and the wrong kind in the alert payload. The main\n * loop reports `pane-gone` for the identical event, so the two paths\n * disagreed. That is the timeout-for-everything conflation this type exists\n * to remove; `PairFinalizeFailure`'s own docblock says only `not-flushed` is\n * a timeout.\n *\n * A CORRUPT config, or a DIRECTORY at the path, still wins: those name an\n * actionable fault the pane's fate does not explain, and each carries its own\n * remedy.\n */\n let graceAborted: PairFinalizeFailure | null = null;\n for (let g = 0; g < graceIterations; g++) {\n await sleep(intervalMs);\n graceWaits = g + 1;\n if (flushed()) {\n log(\n `[claude-pair] finalize: ${claudeJsonPath} updated during grace pass (wait ${graceWaits}; ${describeCounts()})`,\n );\n return { finalized: true, iterations: maxIterations, graceWaits, counts, configPath: claudeJsonPath };\n }\n const dead = await checkPairPaneAlive(session);\n if (dead) {\n // Nothing is left that could write the file; waiting longer is theatre.\n log(`[claude-pair] finalize: pair session ended during grace pass (${dead.kind})`);\n graceAborted = 'pane-gone';\n break;\n }\n let pane: string;\n try {\n pane = await capturePane(session);\n } catch {\n graceAborted = 'pane-gone';\n break;\n }\n try {\n if (await answerConsumerTermsDialog(session, pane)) counts.consumerTerms += 1;\n } catch {\n graceAborted = 'send-failed';\n break;\n }\n }\n\n const observed = classifyAtGiveUp();\n // A config that names its own fault wins; otherwise an abort beats the\n // observed state, including `not-flushed`.\n const selfExplaining = observed === 'config-corrupt' || observed === 'config-path-is-directory';\n const reason = !selfExplaining && graceAborted ? graceAborted : observed;\n // The ticket pointers live HERE, not in the operator-facing message: this\n // line goes to manager.log, whose audience is us.\n const hint =\n reason === 'config-corrupt'\n ? ' — see ENG-10140 (shared-config corruption on containerised hosts)'\n : reason === 'config-path-is-directory'\n ? ' — a docker bind created a directory at this path; see ENG-10869'\n : '';\n log(\n `[claude-pair] finalize: giving up after ${maxIterations} dialog iterations + ${graceWaits} grace wait(s) — ` +\n `reason=${reason} (${describeCounts()}); ${claudeJsonPath} was not updated${hint}`,\n );\n return { finalized: false, iterations: maxIterations, graceWaits, counts, reason, configPath: claudeJsonPath };\n}\n\n/**\n * Returns true if the session is gone afterwards (either kill succeeded\n * or it was already missing). Returns false only if `kill-session`\n * failed for a non-missing-session reason — caller should treat this\n * as \"still tracked, will retry next poll\".\n */\nexport async function killPairSession(session: string): Promise<boolean> {\n try {\n await execFileAsync('tmux', ['kill-session', '-t', session]);\n return true;\n } catch (err) {\n // \"can't find session\" is success-equivalent — the desired end state\n // is \"this session does not exist\" and that's already true.\n if (classifyTmuxError(err).kind === 'no-session') return true;\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Result shapes\n// ---------------------------------------------------------------------------\n\nexport type ClaudePairStartResult =\n | { kind: 'url'; url: string }\n /** ENG-11659: the deadline passed with no sign-in link. `pane` is the\n * REDACTED excerpt (`pairPaneExcerpt`), never raw pane text. */\n | { kind: 'timeout'; waitedMs: number; pane: string }\n | { kind: 'error'; error: SessionError };\n\nexport type ClaudePairSubmitResult =\n | { kind: 'success'; rawMatch: string }\n | { kind: 'failure'; rawMatch: string }\n | { kind: 'timeout' }\n | { kind: 'error'; error: SessionError };\n\nexport type ClaudePairStatusResult =\n | { kind: 'idle' }\n | { kind: 'awaiting-code'; url: string }\n | { kind: 'success' }\n | { kind: 'failure'; rawMatch: string }\n | { kind: 'session-missing' }\n | { kind: 'error'; error: SessionError };\n\n/**\n * Detect Claude Code's workspace-trust dialog in a captured pane.\n *\n * ENG-5375: Claude Code 2.1.146 reworded the prompt from \"Do you trust\n * the files in this folder?\" to \"Quick safety check: Is this a project\n * you created or one you trust?\". Match on the option text instead of\n * the question — same shape as `acceptDialogs` in persistent-session.ts,\n * stable across Anthropic's question rewordings.\n *\n * Exported for unit testing.\n */\nexport function isTrustDialogVisible(pane: string): boolean {\n return /Yes,\\s+I\\s+trust\\s+this\\s+folder/i.test(pane);\n}\n\n/**\n * Detect Claude Code's regular interactive prompt in a captured pane.\n *\n * ENG-5377: Claude Code 2.1.146 replaced the older boxed `│ > ` cursor\n * with `❯ ` (U+276F) and the tip text is variable (\"Try \\\"fix lint\n * errors\\\"\" today — no \" to \"). Detect on the stable 2.1.146 markers:\n * the `❯` cursor and/or the `? for shortcuts` footer. Keep the legacy\n * shapes for back-compat with hosts that haven't picked up the newer\n * Claude Code binary yet.\n *\n * IMPORTANT: callers must check the dialog detectors (theme, trust,\n * login picker) BEFORE this, since `❯` also appears on those screens\n * as the selected-option indicator.\n *\n * Exported for unit testing.\n */\nexport function isInteractivePromptReady(pane: string): boolean {\n return (\n /❯/.test(pane) ||\n /\\?\\s+for\\s+shortcuts/i.test(pane) ||\n /[│|]\\s*>\\s/.test(pane) ||\n /^\\s*>\\s*$/m.test(pane)\n );\n}\n\n// ---------------------------------------------------------------------------\n// start — send `/login`, wait for the OAuth URL prompt\n// ---------------------------------------------------------------------------\n\nexport interface ClaudePairStartOpts {\n /** Pair-scoped tmux session name (see pairTmuxSession). */\n session: string;\n /** Total time to wait for Claude Code to print the URL prompt. Default 60s. */\n timeoutMs?: number;\n /** How often to re-capture and check the pane. Default 500ms. */\n pollIntervalMs?: number;\n}\n\nexport async function startClaudePair(opts: ClaudePairStartOpts): Promise<ClaudePairStartResult> {\n const { session } = opts;\n // Pair sessions cold-start `claude` from scratch — first-run on a fresh\n // host can take 10-30s before the prompt is interactive enough to\n // accept `/login`. Stay generous.\n const timeoutMs = opts.timeoutMs ?? 60_000;\n const pollIntervalMs = opts.pollIntervalMs ?? 500;\n const startedAt = Date.now();\n\n // Quick precheck — fail fast if the tmux session doesn't exist\n // rather than blasting `/login` into an unrelated pane.\n try {\n await execFileAsync('tmux', ['has-session', '-t', session]);\n } catch (err) {\n return { kind: 'error', error: classifyTmuxError(err) };\n }\n\n // Drive claude through its first-run onboarding to reach a state\n // where the OAuth URL is on screen. Possible paths:\n //\n // • Fresh host: theme picker → \"Trust folder?\" → login method picker\n // (option 1 = Claude subscription, already highlighted) → OAuth URL.\n // No `/login` needed — option 1 IS the login.\n // • Already onboarded: regular prompt → we send `/login` ourselves →\n // login method picker → OAuth URL.\n //\n // Auto-advance every onboarding screen we recognize. Keep going until\n // we either see the URL prompt or hit the deadline.\n const onboardingDeadline = Date.now() + Math.min(45_000, timeoutMs);\n let lastDispatchAt = 0;\n let loginCommandSent = false;\n const dispatchEnter = async (): Promise<void> => {\n if (Date.now() - lastDispatchAt < 1_500) return;\n lastDispatchAt = Date.now();\n try { await sendKeys(session, 'C-m'); } catch { /* keep polling */ }\n };\n\n while (Date.now() < onboardingDeadline) {\n await sleep(pollIntervalMs);\n const dead = await checkPairPaneAlive(session);\n if (dead) return { kind: 'error', error: dead };\n let pane: string;\n try {\n // VIEWPORT ONLY (no scrollback). With scrollback included, the\n // theme picker / login picker text lingers in the buffer after\n // claude advances to the URL-paste prompt. The match would then\n // dispatch Enter on the empty paste field — submitting an empty\n // code and triggering \"OAuth error: Invalid code\". Visible-only\n // capture ensures we only react to what's actually on screen.\n pane = await capturePane(session, { scrollback: 0 });\n } catch (err) {\n return { kind: 'error', error: classifyTmuxError(err) };\n }\n\n // Already at the URL prompt — done driving onboarding, fall through\n // to the URL-extraction loop below.\n if (isUrlPromptReady(pane)) {\n const url = extractOAuthUrl(pane);\n if (url) return { kind: 'url', url };\n }\n\n // Stuck on \"OAuth error: Invalid code. Press Enter to retry\" — usually\n // because claude has cached partial state from a previous failed login\n // attempt on this host. Pressing Enter would just resubmit the bad\n // code and loop forever, so bail with an actionable error.\n //\n // Capture WITH scrollback for this check: claude's TUI sometimes\n // re-renders the splash/banner over the OAuth error so the viewport\n // alone misses it (we'd then time out instead of giving the operator\n // an actionable error). OAuth-retry is a sticky state — claude waits\n // for input — so checking recent scrollback is safe; a false positive\n // from stale scrollback would only fire if a previous attempt actually\n // failed, in which case bailing is the right call.\n let scrollPane = pane;\n try {\n scrollPane = await capturePane(session, { scrollback: -50 });\n } catch { /* fall back to viewport-only check */ }\n const hasOAuthInvalidCode = /OAuth error[\\s\\S]*Invalid code/i.test(scrollPane);\n const hasOAuthRetryPrompt = /OAuth error/i.test(scrollPane) && /Press Enter to retry/i.test(scrollPane);\n if (hasOAuthInvalidCode || hasOAuthRetryPrompt) {\n return {\n kind: 'error',\n error: {\n kind: 'oauth-retry-stuck',\n // ENG-11659: carries the (redacted) screen, and no longer tells a\n // console user to SSH to the host.\n message: describeOAuthRetryStuck(pairPaneExcerpt(pane)),\n },\n };\n }\n\n // ENG-10619: the consumer-terms dialog renders a `❯` cursor, so without\n // this the interactive-prompt branch below types `/login` into it.\n // Throttled like dispatchEnter: a relative arrow sequence re-sent before\n // claude re-renders would overshoot the row.\n if (consumerTermsOffKeys(pane)) {\n if (Date.now() - lastDispatchAt >= 1_500) {\n lastDispatchAt = Date.now();\n try {\n await answerConsumerTermsDialog(session, pane);\n } catch (err) {\n return { kind: 'error', error: classifyTmuxError(err) };\n }\n }\n continue;\n }\n\n // Login method picker — option 1 (Claude subscription) is already\n // highlighted, Enter selects it.\n if (/Select login method:/i.test(pane)) {\n await dispatchEnter();\n continue;\n }\n // First-run theme picker. Accept the highlighted default; operator\n // can change it later via /theme.\n if (/\\bDark mode\\b/.test(pane) && /\\bLight mode\\b/.test(pane)) {\n await dispatchEnter();\n continue;\n }\n // \"Trust this folder?\" — select \"Yes, I trust this folder\" BY NAME.\n // ENG-10619: this used to be a bare Enter on the assumption the default\n // row is Yes. Since Claude Code 2.1.250 the dialog is an arrow-select\n // list whose cursor defaults to \"No, exit\", so Enter refused trust and\n // claude exited 1 — every re-login on a host whose workspace was not yet\n // trusted failed (surfaced as \"can't find pane\" before ENG-10617, and as\n // the trust dialog in the exit output after). Same defect sweepDialogs()\n // fixed for agents in ENG-9575. An unresolvable row sends nothing.\n if (isTrustDialogVisible(pane)) {\n const keys = selectRowKeys(pane, 'Yes, I trust this folder');\n if (keys && Date.now() - lastDispatchAt >= 1_500) {\n lastDispatchAt = Date.now();\n try {\n await sendKeySequence(session, keys);\n } catch (err) {\n return { kind: 'error', error: classifyTmuxError(err) };\n }\n }\n continue;\n }\n // Onboarding \"Press Enter to continue\" splashes.\n if (/press\\s+enter\\s+to\\s+continue/i.test(pane)) {\n await dispatchEnter();\n continue;\n }\n // Regular interactive prompt — this means claude was already\n // onboarded. Send `/login` once to surface the login picker, then\n // the next iteration handles it via the picker branch above.\n // ENG-5377: detect both the 2.1.146 `❯` cursor + `? for shortcuts`\n // footer AND the legacy boxed/bare prompt shapes. This branch must\n // come AFTER the dialog detectors above, since `❯` ALSO renders on\n // theme/trust/login dialogs.\n if (isInteractivePromptReady(pane) && !loginCommandSent) {\n loginCommandSent = true;\n try {\n await sendKeys(session, '/login', 'C-m');\n } catch (err) {\n return { kind: 'error', error: classifyTmuxError(err) };\n }\n continue;\n }\n }\n\n // Onboarding deadline hit without seeing a URL — surface the pane so\n // operators can see what was on screen when we gave up.\n //\n // ENG-11659: this used to come back as `error`/`unknown` with the last 500\n // RAW characters of the pane in the message, which made the `timeout` arm of\n // this result type (and the manager's `url_prompt_not_seen` report) dead\n // code. It is now the timeout it always was, and the screen it carries is\n // the visible viewport, redacted, which is what the operator would have seen.\n let lastPane = '';\n try { lastPane = await capturePane(session, { scrollback: 0 }); } catch { /* best-effort */ }\n return { kind: 'timeout', waitedMs: Date.now() - startedAt, pane: pairPaneExcerpt(lastPane) };\n}\n\n/**\n * ENG-11659: what the manager reports for a `startClaudePair` result, and the\n * manager.log line that records it. Before this, neither outcome was logged:\n * the only trace of a re-login on the host was \"dispatching /login\", so a URL\n * that reached the console and a failure that never did read the same.\n *\n * Pure so the mapping and the log line are testable without the manager. The\n * log line carries the outcome KIND only: never the URL (single-use, but\n * still a live sign-in link) and never pane text.\n */\nexport interface PairStartReport {\n body: {\n status: 'awaiting_code' | 'timeout' | 'failure' | 'session_missing';\n url?: string;\n error_code?: string;\n error_message?: string;\n /** ENG-11659: present only when the pair asked for a sign-in reset. */\n signin_reset?: 'moved' | 'absent' | 'failed';\n };\n logLine: string;\n}\n\nexport function planPairStartReport(\n pairId: string,\n result: ClaudePairStartResult,\n /** ENG-11659: what the reset did, when this pair asked for one. */\n signinReset?: 'moved' | 'absent',\n): PairStartReport {\n const report = planPairStartReportBody(pairId, result);\n if (signinReset) report.body.signin_reset = signinReset;\n return report;\n}\n\nfunction planPairStartReportBody(pairId: string, result: ClaudePairStartResult): PairStartReport {\n const pair = pairId.slice(0, 8);\n if (result.kind === 'url') {\n return {\n body: { status: 'awaiting_code', url: result.url },\n logLine: `[claude-pair] start result pair=${pair} kind=url -> awaiting_code`,\n };\n }\n if (result.kind === 'timeout') {\n return {\n body: {\n status: 'timeout',\n error_code: 'url_prompt_not_seen',\n error_message: describeUrlPromptNotSeen(result.waitedMs, result.pane),\n },\n logLine:\n `[claude-pair] start result pair=${pair} kind=timeout waited_ms=${result.waitedMs} ` +\n `screen=${result.pane ? 'captured' : 'blank'} -> timeout`,\n };\n }\n const errKind = result.error.kind;\n const status = errKind === 'no-session' ? 'session_missing' : 'failure';\n return {\n body: {\n status,\n error_code: errKind,\n // Forward the message for any kind that carries one (`oauth-retry-stuck`\n // and `claude-exited` carry the operator's only view of the screen).\n error_message: 'message' in result.error ? result.error.message : undefined,\n },\n logLine: `[claude-pair] start result pair=${pair} kind=error:${errKind} -> ${status}`,\n };\n}\n\n// ---------------------------------------------------------------------------\n// submit-code — paste the auth code, wait for outcome\n// ---------------------------------------------------------------------------\n\nexport interface ClaudePairSubmitOpts {\n /** Pair-scoped tmux session name (see pairTmuxSession). */\n session: string;\n code: string;\n /** Total time to wait for the success/failure marker. Default 30s. */\n timeoutMs?: number;\n pollIntervalMs?: number;\n}\n\nexport async function submitClaudePairCode(\n opts: ClaudePairSubmitOpts,\n): Promise<ClaudePairSubmitResult> {\n const { session } = opts;\n const timeoutMs = opts.timeoutMs ?? 30_000;\n const pollIntervalMs = opts.pollIntervalMs ?? 500;\n\n // Validate code shape minimally — Claude Code's auth codes are\n // alphanumeric with dashes, ~40-80 chars. Accept anything within\n // that envelope; reject blank or whitespace-only to avoid\n // accidentally submitting an empty buffer.\n if (!opts.code || !opts.code.trim()) {\n return {\n kind: 'error',\n error: { kind: 'unknown', message: 'empty auth code' },\n };\n }\n if (opts.code.length > 1024) {\n return {\n kind: 'error',\n error: { kind: 'unknown', message: 'auth code suspiciously long' },\n };\n }\n\n // Send the code + Enter. We use the literal value as one send-keys\n // argument; tmux handles spaces fine, but newlines would terminate\n // early so reject those as well.\n if (/[\\r\\n]/.test(opts.code)) {\n return {\n kind: 'error',\n error: { kind: 'unknown', message: 'auth code contains newline' },\n };\n }\n\n // Send the code as LITERAL text (-l) so tmux doesn't try to interpret\n // any chars as key tokens. Then a 250ms breather so claude's\n // ink/React render loop finishes processing the paste before Enter\n // lands. Without that wait the Enter often gets swallowed mid-render\n // and the code stays in the input box unsubmitted.\n try {\n await execFileAsync('tmux', ['send-keys', '-t', session, '-l', opts.code.trim()]);\n } catch (err) {\n return { kind: 'error', error: classifyTmuxError(err) };\n }\n await sleep(250);\n try {\n // Use Enter (semantic) plus a fallback C-m on the next iteration if\n // claude still hasn't moved.\n await sendKeys(session, 'Enter');\n } catch (err) {\n return { kind: 'error', error: classifyTmuxError(err) };\n }\n\n const deadline = Date.now() + timeoutMs;\n let enterRetried = false;\n let lastPane = '';\n while (Date.now() < deadline) {\n await sleep(pollIntervalMs);\n try {\n lastPane = await capturePane(session);\n } catch (err) {\n return { kind: 'error', error: classifyTmuxError(err) };\n }\n const outcome: AuthOutcome = detectAuthOutcome(lastPane);\n if (outcome.kind === 'success') return { kind: 'success', rawMatch: outcome.rawMatch };\n if (outcome.kind === 'failure') return { kind: 'failure', rawMatch: outcome.rawMatch };\n // ENG-10617: checked after the outcome so a success/failure marker\n // on claude's final screen still wins over \"it exited\".\n const dead = await checkPairPaneAlive(session);\n if (dead) return { kind: 'error', error: dead };\n\n // After ~5s with no outcome, retry Enter once — covers the case\n // where the first Enter landed mid-render and claude swallowed it.\n // The \"Paste code here\" prompt is still on screen if submission\n // didn't take; if it advanced, we'd already have an outcome above.\n if (!enterRetried && Date.now() - (deadline - timeoutMs) > 5_000 && /Paste code here/i.test(lastPane)) {\n enterRetried = true;\n try { await sendKeys(session, 'C-m'); } catch { /* keep polling */ }\n }\n }\n // Include pane snippet in the error path so operators can see what\n // claude was actually showing — outcome detection is brittle and the\n // session is killed immediately after this returns, so this is our\n // only chance to capture state for debugging regex updates.\n return {\n kind: 'error',\n error: {\n kind: 'unknown',\n // ENG-11659: redacted. This pane has just had the authorization code\n // pasted into it, so the raw tail is the one place it would leak.\n message: `submit timed out after ${timeoutMs}ms — outcome regex didn't match. ${withScreen(pairPaneExcerpt(lastPane))}`,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// status — non-mutating peek at the pane state\n// ---------------------------------------------------------------------------\n\nexport async function getClaudePairStatus(session: string): Promise<ClaudePairStatusResult> {\n const dead = await checkPairPaneAlive(session);\n if (dead?.kind === 'no-session') return { kind: 'session-missing' };\n if (dead) return { kind: 'error', error: dead };\n\n let pane: string;\n try {\n pane = await capturePane(session);\n } catch (err) {\n return { kind: 'error', error: classifyTmuxError(err) };\n }\n\n // Outcome takes priority — if the pane already shows success/failure\n // from a recent submission, the API can short-circuit without\n // restarting the flow.\n const outcome = detectAuthOutcome(pane);\n if (outcome.kind === 'success') return { kind: 'success' };\n if (outcome.kind === 'failure') return { kind: 'failure', rawMatch: outcome.rawMatch };\n\n if (isUrlPromptReady(pane)) {\n const url = extractOAuthUrl(pane);\n if (url) return { kind: 'awaiting-code', url };\n }\n return { kind: 'idle' };\n}\n","/**\n * ENG-4580: pane-scrape parser for Claude Code's `/login` OAuth flow.\n *\n * The manager drives the flow by sending `/login` into the agent's\n * persistent tmux session, capturing the pane after a short poll, and\n * extracting the OAuth URL Claude Code prints. After the operator\n * pastes the auth code via the UI, the manager sends it back into the\n * pane and polls for a success / failure marker.\n *\n * Everything in this module is pure — no tmux calls, no fs I/O. The\n * runtime side (apps/cli/src/lib/manager-worker.ts) shells out and\n * feeds the captured pane string through these functions.\n *\n * Why a dedicated module: pane scraping is fragile across Claude Code\n * versions, terminal widths, and locale changes. Centralising the\n * regexes + the ANSI stripper makes them easy to fixture-test and\n * iterate on without touching the runtime path.\n */\n\n// ---------------------------------------------------------------------------\n// ANSI escape sequence stripper\n// ---------------------------------------------------------------------------\n\n/**\n * Strip the ANSI escape sequences a terminal emits for colour, cursor\n * movement, screen clears, and bracketed paste mode. The pattern below\n * covers:\n *\n * - CSI sequences: `ESC [ ... <final byte>` where the final byte is\n * in the 0x40-0x7E range (covers SGR colour, cursor-position,\n * erase-in-line/display, etc.)\n * - OSC sequences: `ESC ] ... BEL` or `ESC ] ... ESC \\` (used for\n * window titles and hyperlinks)\n * - Single-character `ESC <char>` two-byte escapes (e.g. `ESC =`,\n * `ESC >`, the `ESC c` reset)\n *\n * We keep newlines and printable text intact so pane content remains\n * matchable after stripping.\n *\n * The regex uses Unicode-friendly character classes; we explicitly\n * avoid `\\x1b` named escapes in source to keep the file ASCII-safe.\n */\nconst ANSI_ESC = String.fromCharCode(0x1b);\nconst ANSI_BEL = String.fromCharCode(0x07);\n\nconst CSI_RE = new RegExp(`${ANSI_ESC}\\\\[[0-?]*[ -/]*[@-~]`, 'g');\nconst OSC_RE = new RegExp(\n `${ANSI_ESC}\\\\][^${ANSI_BEL}${ANSI_ESC}]*(?:${ANSI_BEL}|${ANSI_ESC}\\\\\\\\)`,\n 'g',\n);\nconst TWO_BYTE_RE = new RegExp(`${ANSI_ESC}[=>cM78]`, 'g');\n\nexport function stripAnsi(text: string): string {\n return text.replace(CSI_RE, '').replace(OSC_RE, '').replace(TWO_BYTE_RE, '');\n}\n\n// ---------------------------------------------------------------------------\n// OAuth URL extraction\n// ---------------------------------------------------------------------------\n\n/**\n * Anchored to Anthropic-owned domains that Claude Code's `/login`\n * actually prints. Adding more hosts is fine — keep them allowlisted\n * rather than matching arbitrary `https://` to avoid pulling random\n * URLs from the user's previous shell output.\n *\n * Note: Claude Code currently emits URLs at `claude.com/cai/oauth/...`\n * (the consumer-facing domain), but `claude.ai` and the console hosts\n * have appeared historically and are kept here for tolerance.\n */\nconst OAUTH_URL_RE =\n /https:\\/\\/(?:claude\\.com|claude\\.ai|platform\\.claude\\.com|console\\.anthropic\\.com|auth\\.anthropic\\.com)\\/[^\\s)\\]]*/;\n\n/**\n * Strip ANSI + reassemble URLs that were soft-wrapped across terminal\n * lines. tmux capture-pane emits hard newlines for wrapped lines, and\n * Claude Code's OAuth URL routinely runs >300 chars — much wider than\n * the manager's default tmux window. Iteratively strip newlines that\n * fall inside what looks like a URL until convergence (a single URL\n * can wrap 5+ times).\n *\n * Shared between extractOAuthUrl and isUrlPromptReady so the readiness\n * check sees the same string the extractor would.\n */\nfunction dewrapPane(rawPane: string): string {\n const stripped = stripAnsi(rawPane);\n let dewrapped = stripped;\n let prev = '';\n while (prev !== dewrapped) {\n prev = dewrapped;\n dewrapped = dewrapped.replace(/(https?:\\/\\/\\S+?)\\n(?=\\S)/, (_m, head: string) => head);\n }\n return dewrapped;\n}\n\nexport function extractOAuthUrl(rawPane: string): string | null {\n const match = OAUTH_URL_RE.exec(dewrapPane(rawPane));\n if (!match) return null;\n // Trim trailing punctuation that often clings to URLs in TUIs.\n return match[0].replace(/[.,;:!?]+$/, '');\n}\n\n// ---------------------------------------------------------------------------\n// Prompt readiness — \"we've printed the URL, now waiting for a code\"\n// ---------------------------------------------------------------------------\n\nconst URL_PROMPT_RE =\n /(?:Paste code here|Paste your code|Enter (?:the )?code|Authorization code)/i;\n\nexport function isUrlPromptReady(rawPane: string): boolean {\n const dewrapped = dewrapPane(rawPane);\n // Both anchors must be present: the URL itself AND the paste-code\n // prompt. The prompt alone could appear during a stale screen redraw;\n // the URL alone could be a stray match in command history. Use the\n // dewrapped pane so a wrapped URL still matches OAUTH_URL_RE.\n return OAUTH_URL_RE.test(dewrapped) && URL_PROMPT_RE.test(dewrapped);\n}\n\n// ---------------------------------------------------------------------------\n// Outcome detection after submitting the code\n// ---------------------------------------------------------------------------\n\n// Claude Code's success/failure copy has drifted across versions\n// (\"Logged in\" → \"Login successful\" → \"Signed in as ...\" → etc.).\n// Keep the alternations broad-but-specific — phrases that only appear\n// after a real auth roundtrip, never in welcome / tutorial text.\n// \"Welcome back\" was tried and rejected: it shows up in onboarding\n// help blurbs and produced false positives.\nconst SUCCESS_RE =\n /(?:Logged in|Login successful|Successfully (?:logged in|authenticated|signed in)|Authentication successful|Sign-?in (?:complete|successful)|You(?:'|’)?re signed in|Signed in as)/i;\nconst FAILURE_RE =\n /(?:Invalid (?:code|authorization code)|OAuth error|Authentication failed|Error (?:logging in|during authentication)|Login failed|Sign-?in failed|Failed to (?:authenticate|sign in|log in))/i;\n\nexport type AuthOutcome =\n | { kind: 'success'; rawMatch: string }\n | { kind: 'failure'; rawMatch: string }\n | { kind: 'pending' };\n\nexport function detectAuthOutcome(rawPane: string): AuthOutcome {\n const stripped = stripAnsi(rawPane);\n // Failure first — Claude Code sometimes prints a stale \"logged in\" from\n // a previous successful session above the new failure banner. The\n // most-recent line wins, so we scan from the end of the pane.\n const failureMatch = lastMatch(stripped, FAILURE_RE);\n const successMatch = lastMatch(stripped, SUCCESS_RE);\n\n if (failureMatch && successMatch) {\n // Whichever is later on the pane is the live state.\n if (failureMatch.index > successMatch.index) {\n return { kind: 'failure', rawMatch: failureMatch.match };\n }\n return { kind: 'success', rawMatch: successMatch.match };\n }\n if (failureMatch) return { kind: 'failure', rawMatch: failureMatch.match };\n if (successMatch) return { kind: 'success', rawMatch: successMatch.match };\n return { kind: 'pending' };\n}\n\nfunction lastMatch(haystack: string, re: RegExp): { match: string; index: number } | null {\n // Construct a sticky/global variant if needed. Most of our REs are\n // anchored to small phrases; iterating with a `g`-flagged RegExp is\n // cheap and correct.\n const globalRe = new RegExp(re.source, re.flags.includes('g') ? re.flags : `${re.flags}g`);\n let last: RegExpExecArray | null = null;\n let m: RegExpExecArray | null;\n while ((m = globalRe.exec(haystack)) !== null) {\n last = m;\n // Prevent zero-length matches from looping.\n if (m.index === globalRe.lastIndex) globalRe.lastIndex++;\n }\n return last ? { match: last[0], index: last.index } : null;\n}\n\n// ---------------------------------------------------------------------------\n// \"Session not running / tmux missing\" — surface as a structured signal\n// ---------------------------------------------------------------------------\n\n/**\n * The runtime path will throw when `tmux capture-pane` fails. This\n * helper classifies the failure for the API layer so the UI can show\n * \"start a session first\" rather than a generic 500.\n */\nexport type SessionError =\n | { kind: 'no-session' }\n | { kind: 'tmux-missing' }\n | { kind: 'pane-empty' }\n /** Claude is sitting on the \"OAuth error: Invalid code. Press Enter to\n * retry.\" prompt from a previous failed login — pressing Enter would\n * resubmit the bad code, so the runtime bails with operator-actionable\n * guidance instead. Distinct from `unknown` so telemetry / UI can\n * surface a specific message rather than a generic 500. */\n | { kind: 'oauth-retry-stuck'; message: string }\n /** ENG-10617: the pair `claude` process exited mid-flow. The pair\n * session runs with `remain-on-exit on`, so the dead pane survives and\n * `message` carries claude's exit status and last output — the only\n * record of WHY it exited. */\n | { kind: 'claude-exited'; message: string }\n | { kind: 'unknown'; message: string };\n\nexport function classifyTmuxError(err: unknown): SessionError {\n const msg = err instanceof Error ? err.message : String(err);\n // ENG-10617: tmux 3.x phrases a `-t` miss by the target type it resolved\n // — `can't find pane` from capture-pane/send-keys, `can't find window` from\n // window-scoped commands — not only `can't find session`. Unmatched, those\n // fell to `unknown` and the raw command line reached the operator.\n if (/can't find (session|pane|window)|no server running/i.test(msg)) return { kind: 'no-session' };\n if (/command not found.*tmux|ENOENT.*tmux/i.test(msg)) return { kind: 'tmux-missing' };\n return { kind: 'unknown', message: msg };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmBA,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAG1B,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,YAAY;AACrB,SAAS,SAAS,gBAAgB;;;ACiBlC,IAAM,WAAW,OAAO,aAAa,EAAI;AACzC,IAAM,WAAW,OAAO,aAAa,CAAI;AAEzC,IAAM,SAAS,IAAI,OAAO,GAAG,QAAQ,wBAAwB,GAAG;AAChE,IAAM,SAAS,IAAI;AAAA,EACjB,GAAG,QAAQ,QAAQ,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,IAAI,QAAQ;AAAA,EAClE;AACF;AACA,IAAM,cAAc,IAAI,OAAO,GAAG,QAAQ,YAAY,GAAG;AAElD,SAAS,UAAU,MAAsB;AAC9C,SAAO,KAAK,QAAQ,QAAQ,EAAE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