@usulpro/codex-bee 0.1.1 → 0.1.3

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.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/bee-agent.ts","../src/transcript.ts","../src/continuation-source.ts","../src/continuation.ts","../src/auto-continue.ts","../src/cli-options.ts","../src/continuation-watcher.ts","../src/hook-server.ts","../src/verification.ts","../src/hook-event-watcher.ts","../src/hook-config.ts","../src/passthrough.ts","../src/pty-proxy.ts","../src/runtime-log.ts","../src/ui/core/commands.ts","../src/ui/core/types.ts","../src/ui/core/controller.ts","../src/ui/live-overlay.ts","../src/ui/input-shortcuts.ts","../src/ui/renderers/ink/app.tsx","../src/ui/core/view-model.ts","../src/ui/renderers/ink/renderer-utils.tsx","../src/ui/runtime/live-runtime.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { randomUUID } from \"node:crypto\";\nimport { execFile } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport * as readline from \"node:readline/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { promisify } from \"node:util\";\nimport { ContinuationController } from \"./auto-continue.js\";\nimport { generateBeeAgentPrompt, readBeeAgentConfig } from \"./bee-agent.js\";\nimport { HELP_TEXT, parseWrapperOptions } from \"./cli-options.js\";\nimport { runContinuationWatcher } from \"./continuation-watcher.js\";\nimport { isBeeAgentSource } from \"./continuation-source.js\";\nimport { readContinuationTemplate } from \"./continuation.js\";\nimport { runHookEventWatcher } from \"./hook-event-watcher.js\";\nimport {\n collectCodexFeatureProbeArgs,\n getGlobalCodexConfigPath,\n inspectCodexHookSetup,\n inspectCodexHooksFeatureListOutput,\n resolveCodexProfile,\n upsertCodexHooksFeatureConfigText,\n upsertStopHookConfigText,\n writeCodexConfigFile,\n writeHookConfigFile,\n type CodexHooksFeatureInspection,\n type HookSetupInspection\n} from \"./hook-config.js\";\nimport { resolveExecutionMode, runPassthroughCommand } from \"./passthrough.js\";\nimport { PtyProxy } from \"./pty-proxy.js\";\nimport { createRuntimeEventLogger } from \"./runtime-log.js\";\nimport { UiController } from \"./ui/core/controller.js\";\nimport { LiveInkOverlayManager } from \"./ui/live-overlay.js\";\nimport { LiveUiRuntimeHost } from \"./ui/runtime/live-runtime.js\";\nimport type { UiConnectionState } from \"./ui/core/types.js\";\nimport { runVerificationCommand } from \"./verification.js\";\n\nconst require = createRequire(import.meta.url);\nconst packageJson = require(\"../package.json\") as {\n version?: unknown;\n};\nconst CLI_VERSION = typeof packageJson.version === \"string\"\n ? packageJson.version\n : \"0.0.0\";\nconst execFileAsync = promisify(execFile);\nconst CODEX_INTERACTIVE_SUBCOMMANDS = new Set([\n \"fork\",\n \"resume\"\n]);\nconst CODEX_NONINTERACTIVE_SUBCOMMANDS = new Set([\n \"app-server\",\n \"apply\",\n \"cloud\",\n \"completion\",\n \"debug\",\n \"exec\",\n \"features\",\n \"help\",\n \"login\",\n \"logout\",\n \"mcp\",\n \"mcp-server\",\n \"review\",\n \"sandbox\"\n]);\nconst CODEX_OPTIONS_WITH_VALUE = new Set([\n \"-a\",\n \"-c\",\n \"-C\",\n \"-i\",\n \"-m\",\n \"-p\",\n \"-s\",\n \"--add-dir\",\n \"--ask-for-approval\",\n \"--cd\",\n \"--config\",\n \"--disable\",\n \"--enable\",\n \"--image\",\n \"--local-provider\",\n \"--model\",\n \"--profile\",\n \"--remote\",\n \"--remote-auth-token-env\",\n \"--sandbox\"\n]);\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction getBundledStopHookPath(): string {\n return path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"..\", \"hooks\", \"stop-hook.cjs\");\n}\n\nfunction isCodexCommand(command: string): boolean {\n return path.basename(command) === \"codex\";\n}\n\nfunction shouldPrepareInteractiveCodexHooks(commandArgs: readonly string[]): boolean {\n if (commandArgs.includes(\"-h\") || commandArgs.includes(\"--help\") || commandArgs.includes(\"-V\") || commandArgs.includes(\"--version\")) {\n return false;\n }\n\n for (let index = 0; index < commandArgs.length; index += 1) {\n const argument = commandArgs[index];\n\n if (CODEX_OPTIONS_WITH_VALUE.has(argument)) {\n index += 1;\n continue;\n }\n\n if (argument.startsWith(\"-\")) {\n continue;\n }\n\n if (CODEX_NONINTERACTIVE_SUBCOMMANDS.has(argument)) {\n return false;\n }\n\n if (CODEX_INTERACTIVE_SUBCOMMANDS.has(argument)) {\n return true;\n }\n\n return true;\n }\n\n return true;\n}\n\nasync function promptYesNo(question: string, options?: {\n defaultValue?: boolean;\n}): Promise<boolean> {\n const defaultValue = options?.defaultValue ?? true;\n const promptLabel = defaultValue ? \"[Y/n]\" : \"[y/N]\";\n const terminal = readline.createInterface({\n input: process.stdin,\n output: process.stderr\n });\n\n try {\n const answer = (await terminal.question(`[codex-bee] ${question} ${promptLabel} `))\n .trim()\n .toLowerCase();\n\n if (answer.length === 0) {\n return defaultValue;\n }\n\n return answer === \"y\" || answer === \"yes\";\n } finally {\n terminal.close();\n }\n}\n\nasync function inspectCodexHooksFeature(options: {\n command: string;\n commandArgs: readonly string[];\n cwd: string;\n}): Promise<CodexHooksFeatureInspection> {\n const profile = resolveCodexProfile(options.commandArgs);\n const configPath = getGlobalCodexConfigPath();\n\n try {\n const { stdout } = await execFileAsync(options.command, [\n ...collectCodexFeatureProbeArgs(options.commandArgs),\n \"features\",\n \"list\"\n ], {\n cwd: options.cwd,\n encoding: \"utf8\"\n });\n\n return inspectCodexHooksFeatureListOutput({\n configPath,\n output: stdout,\n profile\n });\n } catch (error) {\n return {\n configPath,\n enabled: null,\n health: \"unknown\",\n message: `Unable to determine the effective codex_hooks feature state before launch: ${toErrorMessage(error)}`,\n profile\n };\n }\n}\n\nfunction buildLaunchBlockerMessage(options: {\n featureInspection: CodexHooksFeatureInspection;\n hookSetup: HookSetupInspection;\n}): string {\n const issues: string[] = [];\n\n if (options.featureInspection.health === \"disabled\") {\n issues.push(options.featureInspection.message);\n } else if (options.featureInspection.health === \"unknown\") {\n issues.push(options.featureInspection.message);\n }\n\n if (options.hookSetup.status !== \"ready\") {\n issues.push(options.hookSetup.message);\n }\n\n if (issues.length === 0) {\n return \"Codex hook bootstrap is ready.\";\n }\n\n return issues.join(\" \");\n}\n\nasync function ensureInteractiveCodexHooks(options: {\n command: string;\n commandArgs: readonly string[];\n cwd: string;\n hookScriptPath: string;\n log: (eventType: string, data?: Record<string, unknown>) => void;\n}): Promise<{\n featureInspection: CodexHooksFeatureInspection;\n hookSetup: HookSetupInspection;\n}> {\n let hookSetup = inspectCodexHookSetup({\n cwd: options.cwd,\n hookScriptPath: options.hookScriptPath\n });\n let featureInspection = await inspectCodexHooksFeature({\n command: options.command,\n commandArgs: options.commandArgs,\n cwd: options.cwd\n });\n\n options.log(\"hook_bootstrap_inspected\", {\n featureHealth: featureInspection.health,\n featureProfile: featureInspection.profile,\n hookConfigPath: hookSetup.activeConfig?.path ?? hookSetup.globalPath,\n hookStatus: hookSetup.status\n });\n\n if (featureInspection.health === \"disabled\") {\n const featureTargetDescription = featureInspection.profile\n ? `${featureInspection.configPath} for profile \"${featureInspection.profile}\"`\n : featureInspection.configPath;\n const shouldEnableFeature = await promptYesNo(\n `Enable codex_hooks in ${featureTargetDescription} so codex-bee can receive Stop events?`\n );\n\n options.log(\"hook_bootstrap_feature_prompted\", {\n accepted: shouldEnableFeature,\n profile: featureInspection.profile\n });\n\n if (!shouldEnableFeature) {\n throw new Error(buildLaunchBlockerMessage({\n featureInspection,\n hookSetup\n }));\n }\n\n const existingConfigText = fs.existsSync(featureInspection.configPath)\n ? fs.readFileSync(featureInspection.configPath, \"utf8\")\n : null;\n\n writeCodexConfigFile(\n featureInspection.configPath,\n upsertCodexHooksFeatureConfigText(existingConfigText, featureInspection.profile)\n );\n\n featureInspection = await inspectCodexHooksFeature({\n command: options.command,\n commandArgs: options.commandArgs,\n cwd: options.cwd\n });\n options.log(\"hook_bootstrap_feature_updated\", {\n health: featureInspection.health,\n profile: featureInspection.profile\n });\n }\n\n if (hookSetup.status === \"missing\") {\n const shouldCreateHooksFile = await promptYesNo(\n `Create ${hookSetup.globalPath} with the codex-bee Stop hook?`\n );\n\n options.log(\"hook_bootstrap_hooks_prompted\", {\n accepted: shouldCreateHooksFile,\n action: \"create-global\",\n path: hookSetup.globalPath\n });\n\n if (!shouldCreateHooksFile) {\n throw new Error(buildLaunchBlockerMessage({\n featureInspection,\n hookSetup\n }));\n }\n\n writeHookConfigFile(\n hookSetup.globalPath,\n upsertStopHookConfigText(null, options.hookScriptPath)\n );\n\n hookSetup = inspectCodexHookSetup({\n cwd: options.cwd,\n hookScriptPath: options.hookScriptPath\n });\n options.log(\"hook_bootstrap_hooks_updated\", {\n path: hookSetup.globalPath,\n status: hookSetup.status\n });\n } else if (hookSetup.status === \"missing-stop-hook\" || hookSetup.status === \"stale-stop-hook\") {\n const targetConfig = hookSetup.activeConfig ?? hookSetup.globalConfig;\n const shouldUpdateHooksFile = await promptYesNo(\n `Update ${targetConfig.path} so it points at the current codex-bee Stop hook script?`\n );\n\n options.log(\"hook_bootstrap_hooks_prompted\", {\n accepted: shouldUpdateHooksFile,\n action: \"update-existing\",\n path: targetConfig.path\n });\n\n if (!shouldUpdateHooksFile) {\n throw new Error(buildLaunchBlockerMessage({\n featureInspection,\n hookSetup\n }));\n }\n\n const existingHooksText = fs.existsSync(targetConfig.path)\n ? fs.readFileSync(targetConfig.path, \"utf8\")\n : null;\n\n writeHookConfigFile(\n targetConfig.path,\n upsertStopHookConfigText(existingHooksText, options.hookScriptPath)\n );\n\n hookSetup = inspectCodexHookSetup({\n cwd: options.cwd,\n hookScriptPath: options.hookScriptPath\n });\n options.log(\"hook_bootstrap_hooks_updated\", {\n path: targetConfig.path,\n status: hookSetup.status\n });\n }\n\n if (featureInspection.health === \"disabled\" || hookSetup.status !== \"ready\") {\n throw new Error(buildLaunchBlockerMessage({\n featureInspection,\n hookSetup\n }));\n }\n\n return {\n featureInspection,\n hookSetup\n };\n}\n\nasync function main(): Promise<void> {\n const options = parseWrapperOptions(process.argv.slice(2));\n\n if (options.showHelp || (!options.showVersion && options.command === null)) {\n console.log(HELP_TEXT.trim());\n return;\n }\n\n if (options.showVersion) {\n console.log(CLI_VERSION);\n return;\n }\n\n const wrappedCommand = options.command;\n\n if (wrappedCommand === null) {\n console.log(HELP_TEXT.trim());\n return;\n }\n\n const runId = randomUUID();\n const runStartedAt = Date.now();\n const hasContinuation = Boolean(options.continueLoopSource || options.continueOnceSource);\n const executionMode = resolveExecutionMode({\n hasContinuation,\n stdinIsTTY: process.stdin.isTTY,\n stdoutIsTTY: process.stdout.isTTY\n });\n\n if (executionMode === \"passthrough\") {\n process.exitCode = await runPassthroughCommand({\n args: options.commandArgs,\n command: wrappedCommand,\n cwd: process.cwd(),\n env: process.env\n });\n return;\n }\n\n const logger = createRuntimeEventLogger(process.cwd(), {\n runId\n });\n logger.log(\"wrapper_started\", {\n command: wrappedCommand,\n commandArgs: options.commandArgs,\n runId\n });\n const hookScriptPath = getBundledStopHookPath();\n let startupAnnouncement: string | null = null;\n let initialConnectionState: UiConnectionState = \"connected\";\n\n if (isCodexCommand(wrappedCommand) && shouldPrepareInteractiveCodexHooks(options.commandArgs)) {\n const { featureInspection, hookSetup } = await ensureInteractiveCodexHooks({\n command: wrappedCommand,\n commandArgs: options.commandArgs,\n cwd: process.cwd(),\n hookScriptPath,\n log: (eventType, data) => logger.log(eventType, data)\n });\n\n startupAnnouncement = featureInspection.health === \"unknown\"\n ? `${hookSetup.message} ${featureInspection.message}`\n : hookSetup.message;\n initialConnectionState = \"ready\";\n logger.log(\"hook_bootstrap_ready\", {\n announcement: startupAnnouncement,\n configPath: hookSetup.activeConfig?.path ?? hookSetup.globalPath\n });\n }\n\n const initialContinuation = options.continueLoopSource\n ? {\n enabled: true,\n maxContinues: options.maxContinues,\n maxDurationMs: options.maxDurationMs,\n promptSource: options.continueLoopSource\n }\n : options.continueOnceSource\n ? {\n enabled: true,\n maxContinues: 1,\n maxDurationMs: options.maxDurationMs,\n promptSource: options.continueOnceSource\n }\n : null;\n\n if (initialContinuation) {\n if (isBeeAgentSource(initialContinuation.promptSource)) {\n readBeeAgentConfig(initialContinuation.promptSource, {\n cwd: process.cwd()\n });\n } else {\n readContinuationTemplate(initialContinuation.promptSource, {\n cwd: process.cwd()\n });\n }\n }\n\n const proxy = new PtyProxy({\n command: wrappedCommand,\n commandArgs: options.commandArgs,\n env: {\n ...process.env,\n CODEX_BEE_CAPTURE_ROOT: process.cwd(),\n CODEX_BEE_RUN_ID: runId\n }\n });\n const continuation = new ContinuationController({\n cwd: process.cwd(),\n initial: initialContinuation ?? undefined\n });\n const runtimeHost = new LiveUiRuntimeHost({\n beeVersion: CLI_VERSION,\n codexCommand: wrappedCommand,\n continuation,\n cwd: process.cwd(),\n initialAnnouncementMessage: startupAnnouncement,\n initialConnectionState,\n initialVerificationCommand: options.verificationCommand,\n promptProxy: proxy\n });\n const controller = new UiController(runtimeHost);\n const watcherAbortController = new AbortController();\n const overlay = new LiveInkOverlayManager({\n controller,\n onQuitRequested: () => {\n logger.log(\"wrapper_exit_requested_from_ui\");\n watcherAbortController.abort();\n proxy.setInputInterceptor(null);\n proxy.setOutputMuted(false);\n void proxy.stop();\n },\n proxy,\n title: \"codex-bee\"\n });\n\n await controller.initialize();\n void runtimeHost.refreshEnvironmentMetadata().catch((error: unknown) => {\n logger.log(\"ui_runtime_metadata_refresh_failed\", {\n message: error instanceof Error ? error.message : String(error)\n });\n });\n\n await proxy.start();\n proxy.setInputInterceptor((chunk) => overlay.handleInput(chunk));\n\n if (initialContinuation) {\n if (initialContinuation.maxContinues > 1) {\n console.error(\n `[codex-bee] Auto-continue loop armed for up to ${initialContinuation.maxContinues} injections with ${continuation.getSnapshot().promptSourceLabel}.`\n );\n } else {\n console.error(\n `[codex-bee] One-shot continuation armed with ${continuation.getSnapshot().promptSourceLabel}.`\n );\n }\n }\n\n if (initialConnectionState === \"ready\") {\n void runHookEventWatcher({\n cwd: process.cwd(),\n eventNames: [\"SessionStart\", \"UserPromptSubmit\"],\n logger,\n onEvent: (capture) => {\n runtimeHost.recordAuxiliaryHookEvent(capture);\n },\n runId,\n runStartedAt,\n signal: watcherAbortController.signal\n }).catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.log(\"hook_event_watcher_stopped\", {\n message\n });\n console.error(`[codex-bee] Hook event watcher stopped: ${message}`);\n });\n }\n\n void runContinuationWatcher({\n generateBeeAgentPrompt: (capture, source) => generateBeeAgentPrompt({\n capture,\n cwd: process.cwd(),\n logger,\n runId,\n source\n }),\n continuation,\n cwd: process.cwd(),\n getVerificationCommand: () => runtimeHost.getVerificationCommand(),\n injectDelayMs: options.injectDelayMs,\n logger,\n onPromptInjected: (event) => {\n runtimeHost.recordContinuationPromptInjected(event);\n },\n onStopCaptureHandled: (event) => {\n runtimeHost.recordStopCaptureHandled(event);\n },\n proxy,\n runId,\n runStartedAt,\n runVerificationCommand,\n signal: watcherAbortController.signal,\n verificationCommand: options.verificationCommand\n }).catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.log(\"continuation_watcher_stopped\", {\n message\n });\n console.error(`[codex-bee] Continuation watcher stopped: ${message}`);\n });\n\n process.exitCode = await proxy.waitForExit();\n watcherAbortController.abort();\n overlay.dispose();\n runtimeHost.markDisconnected();\n}\n\ntry {\n await main();\n} catch (error) {\n console.error(`[codex-bee] ${toErrorMessage(error)}`);\n process.exitCode = 1;\n}\n","import { mkdirSync, readFileSync, writeFileSync, appendFileSync, existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport process from \"node:process\";\nimport { summarizeTranscriptFile, type TranscriptMessage, type TranscriptSummary } from \"./transcript.js\";\nimport type { BeeAgentSource } from \"./continuation-source.js\";\nimport type { StopCapture } from \"./hook-server.js\";\nimport type { RuntimeEventLogger } from \"./runtime-log.js\";\n\nconst BEE_AGENT_RESULT_SCHEMA = {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n additionalProperties: false,\n properties: {\n next_prompt: {\n minLength: 1,\n type: \"string\"\n },\n note: {\n type: [\"string\", \"null\"]\n }\n },\n required: [\"next_prompt\", \"note\"],\n type: \"object\"\n} as const;\n\nconst DEFAULT_BEE_AGENT_MODEL = \"gpt-5.4\";\nconst DEFAULT_MAX_LAST_ASSISTANT_CHARS = 4000;\nconst DEFAULT_MAX_NOTE_CHARS = 4000;\nconst DEFAULT_MAX_OBJECTIVE_CHARS = 1500;\nconst DEFAULT_MAX_RECENT_MESSAGES = 6;\n\nexport interface BeeAgentConfig {\n maxLastAssistantChars: number;\n maxNoteChars: number;\n maxObjectiveChars: number;\n maxRecentMessages: number;\n model: string | null;\n profile: string | null;\n sessionPrompt: string;\n systemPrompt: string;\n}\n\nexport interface BeeAgentContext {\n beeNotes: string;\n capturedAt: string;\n cwd: string;\n lastAssistantMessage: string;\n model: string | null;\n permissionMode: string | null;\n recentMessages: TranscriptMessage[];\n sessionId: string;\n sessionObjective: string | null;\n transcriptPath: string | null;\n wrapperRunId: string;\n}\n\nexport interface BeeAgentGenerationResult {\n context: BeeAgentContext;\n nextPrompt: string;\n note: string | null;\n sessionStateDirectory: string;\n}\n\nexport interface BeeAgentExecRequest {\n args: string[];\n cwd: string;\n outputPath: string;\n prompt: string;\n stderrPath: string;\n stdoutPath: string;\n}\n\nexport interface BeeAgentExecResult {\n code: number;\n stderr: string;\n stdout: string;\n}\n\nexport type BeeAgentExecRunner = (request: BeeAgentExecRequest) => Promise<BeeAgentExecResult>;\n\ninterface BeeAgentRawConfig {\n maxLastAssistantChars?: unknown;\n maxNoteChars?: unknown;\n maxObjectiveChars?: unknown;\n maxRecentMessages?: unknown;\n model?: unknown;\n profile?: unknown;\n sessionPromptPath?: unknown;\n systemPromptPath?: unknown;\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction clampText(value: string, maxChars: number): string {\n if (value.length <= maxChars) {\n return value;\n }\n\n return value.slice(0, maxChars).trimEnd();\n}\n\nfunction readJsonFile(filePath: string): unknown {\n return JSON.parse(readFileSync(filePath, \"utf8\"));\n}\n\nfunction readNonEmptyTextFile(filePath: string, label: string): string {\n const value = readFileSync(filePath, \"utf8\").replace(/\\r\\n?/g, \"\\n\").trim();\n\n if (!value) {\n throw new Error(`${label} is empty: ${filePath}`);\n }\n\n return value;\n}\n\nfunction readPositiveInteger(value: unknown, label: string, fallback: number): number {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 1) {\n throw new Error(`${label} must be a positive integer.`);\n }\n\n return value;\n}\n\nfunction readOptionalString(value: unknown, label: string): string | null {\n if (value === undefined || value === null || value === \"\") {\n return null;\n }\n\n if (typeof value !== \"string\") {\n throw new Error(`${label} must be a string.`);\n }\n\n return value;\n}\n\nfunction sanitizePathSegment(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n}\n\nfunction getSessionStateDirectory(cwd: string, sessionId: string): string {\n return path.join(cwd, \".codex\", \"tmp\", \"bee-agent\", sanitizePathSegment(sessionId));\n}\n\nfunction getCurrentTimestampSlug(): string {\n return new Date().toISOString().replace(/[:.]/g, \"-\");\n}\n\nfunction readNotesFile(filePath: string, maxChars: number): string {\n if (!existsSync(filePath)) {\n return \"\";\n }\n\n const content = readFileSync(filePath, \"utf8\");\n\n if (content.length <= maxChars) {\n return content.trim();\n }\n\n return content.slice(-maxChars).trim();\n}\n\nfunction appendSessionNote(notesPath: string, note: string, capturedAt: string): void {\n mkdirSync(path.dirname(notesPath), {\n recursive: true\n });\n appendFileSync(\n notesPath,\n [\n `## ${capturedAt}`,\n note.trim(),\n \"\"\n ].join(\"\\n\"),\n \"utf8\"\n );\n}\n\nfunction buildTranscriptSummary(capture: StopCapture, maxRecentMessages: number): TranscriptSummary | null {\n const transcriptPath = capture.payload?.transcript_path;\n\n if (!transcriptPath) {\n return null;\n }\n\n try {\n return summarizeTranscriptFile(transcriptPath, {\n maxRecentMessages\n });\n } catch {\n return null;\n }\n}\n\nfunction buildGeneratorPrompt(config: BeeAgentConfig, context: BeeAgentContext): string {\n return [\n \"# Bee-Agent System Prompt\",\n config.systemPrompt,\n \"\",\n \"# Bee-Agent Session Prompt\",\n config.sessionPrompt,\n \"\",\n \"# Output Contract\",\n \"Return a JSON object with exactly these keys:\",\n '- `next_prompt`: a non-empty string that can be sent to the main Codex session as the next input',\n '- `note`: either `null` or a short persistent note for future bee-agent iterations',\n \"\",\n \"# Main Session Context\",\n \"```json\",\n JSON.stringify(context, null, 2),\n \"```\"\n ].join(\"\\n\");\n}\n\nfunction readParsedResult(outputPath: string): {\n next_prompt: string;\n note: string | null;\n} {\n const output = readFileSync(outputPath, \"utf8\").trim();\n\n if (!output) {\n throw new Error(\"Bee-agent output file is empty.\");\n }\n\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(output);\n } catch (error) {\n throw new Error(`Bee-agent output is not valid JSON: ${toErrorMessage(error)}`);\n }\n\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new Error(\"Bee-agent output is not an object.\");\n }\n\n const nextPrompt = (parsed as {\n next_prompt?: unknown;\n }).next_prompt;\n const note = (parsed as {\n note?: unknown;\n }).note;\n\n if (typeof nextPrompt !== \"string\" || !nextPrompt.trim()) {\n throw new Error(\"Bee-agent output field `next_prompt` must be a non-empty string.\");\n }\n\n if (note !== null && note !== undefined && typeof note !== \"string\") {\n throw new Error(\"Bee-agent output field `note` must be a string or null.\");\n }\n\n return {\n next_prompt: nextPrompt.trim(),\n note: note === undefined ? null : note\n };\n}\n\nasync function runBeeAgentExec(request: BeeAgentExecRequest): Promise<BeeAgentExecResult> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"codex\", [...request.args, request.prompt], {\n cwd: request.cwd,\n env: process.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"]\n });\n let stdout = \"\";\n let stderr = \"\";\n\n child.stdout.setEncoding(\"utf8\");\n child.stderr.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk;\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk;\n });\n child.once(\"error\", reject);\n child.once(\"exit\", (code) => {\n writeFileSync(request.stdoutPath, stdout, \"utf8\");\n writeFileSync(request.stderrPath, stderr, \"utf8\");\n resolve({\n code: code ?? 1,\n stderr,\n stdout\n });\n });\n });\n}\n\nexport function describeBeeAgentSource(source: BeeAgentSource): string {\n return `bee-agent config ${source.path}`;\n}\n\nexport function readBeeAgentConfig(source: BeeAgentSource, options?: {\n cwd?: string;\n}): BeeAgentConfig {\n const cwd = options?.cwd ?? process.cwd();\n const resolvedConfigPath = path.resolve(cwd, source.path);\n const configDirectory = path.dirname(resolvedConfigPath);\n const rawConfig = readJsonFile(resolvedConfigPath) as BeeAgentRawConfig;\n\n if (!rawConfig || typeof rawConfig !== \"object\") {\n throw new Error(`Bee-agent config must be an object: ${source.path}`);\n }\n\n if (typeof rawConfig.systemPromptPath !== \"string\" || !rawConfig.systemPromptPath.trim()) {\n throw new Error(`Bee-agent config is missing \\`systemPromptPath\\`: ${source.path}`);\n }\n\n if (typeof rawConfig.sessionPromptPath !== \"string\" || !rawConfig.sessionPromptPath.trim()) {\n throw new Error(`Bee-agent config is missing \\`sessionPromptPath\\`: ${source.path}`);\n }\n\n return {\n maxLastAssistantChars: readPositiveInteger(\n rawConfig.maxLastAssistantChars,\n \"Bee-agent config field `maxLastAssistantChars`\",\n DEFAULT_MAX_LAST_ASSISTANT_CHARS\n ),\n maxNoteChars: readPositiveInteger(\n rawConfig.maxNoteChars,\n \"Bee-agent config field `maxNoteChars`\",\n DEFAULT_MAX_NOTE_CHARS\n ),\n maxObjectiveChars: readPositiveInteger(\n rawConfig.maxObjectiveChars,\n \"Bee-agent config field `maxObjectiveChars`\",\n DEFAULT_MAX_OBJECTIVE_CHARS\n ),\n maxRecentMessages: readPositiveInteger(\n rawConfig.maxRecentMessages,\n \"Bee-agent config field `maxRecentMessages`\",\n DEFAULT_MAX_RECENT_MESSAGES\n ),\n model: readOptionalString(rawConfig.model, \"Bee-agent config field `model`\") ?? DEFAULT_BEE_AGENT_MODEL,\n profile: readOptionalString(rawConfig.profile, \"Bee-agent config field `profile`\"),\n sessionPrompt: readNonEmptyTextFile(\n path.resolve(configDirectory, rawConfig.sessionPromptPath),\n \"Bee-agent session prompt\"\n ),\n systemPrompt: readNonEmptyTextFile(\n path.resolve(configDirectory, rawConfig.systemPromptPath),\n \"Bee-agent system prompt\"\n )\n };\n}\n\nexport function buildBeeAgentContext(capture: StopCapture, config: BeeAgentConfig, options: {\n cwd: string;\n runId: string;\n}): BeeAgentContext {\n const sessionId = capture.payload?.session_id;\n\n if (!sessionId) {\n throw new Error(\"Bee-agent generation requires `session_id` in the matched Stop capture.\");\n }\n\n const transcriptSummary = buildTranscriptSummary(capture, config.maxRecentMessages);\n const sessionStateDirectory = getSessionStateDirectory(options.cwd, sessionId);\n const notesPath = path.join(sessionStateDirectory, \"notes.md\");\n\n return {\n beeNotes: readNotesFile(notesPath, config.maxNoteChars),\n capturedAt: capture.capturedAt ?? new Date().toISOString(),\n cwd: capture.payload?.cwd ?? capture.cwd ?? options.cwd,\n lastAssistantMessage: clampText(\n String(capture.payload?.last_assistant_message ?? \"\"),\n config.maxLastAssistantChars\n ),\n model: typeof capture.payload?.model === \"string\" ? capture.payload.model : null,\n permissionMode: typeof capture.payload?.permission_mode === \"string\" ? capture.payload.permission_mode : null,\n recentMessages: transcriptSummary?.recentMessages ?? [],\n sessionId,\n sessionObjective: transcriptSummary?.sessionObjective\n ? clampText(transcriptSummary.sessionObjective, config.maxObjectiveChars)\n : null,\n transcriptPath: transcriptSummary?.path ?? null,\n wrapperRunId: options.runId\n };\n}\n\nexport async function generateBeeAgentPrompt(options: {\n capture: StopCapture;\n cwd: string;\n logger: RuntimeEventLogger;\n runId: string;\n runner?: BeeAgentExecRunner;\n source: BeeAgentSource;\n}): Promise<BeeAgentGenerationResult> {\n const config = readBeeAgentConfig(options.source, {\n cwd: options.cwd\n });\n const context = buildBeeAgentContext(options.capture, config, {\n cwd: options.cwd,\n runId: options.runId\n });\n const sessionStateDirectory = getSessionStateDirectory(options.cwd, context.sessionId);\n const runDirectory = path.join(sessionStateDirectory, \"runs\", getCurrentTimestampSlug());\n const outputPath = path.join(runDirectory, \"output.json\");\n const stderrPath = path.join(runDirectory, \"stderr.log\");\n const stdoutPath = path.join(runDirectory, \"stdout.log\");\n const schemaPath = path.join(runDirectory, \"result.schema.json\");\n const contextPath = path.join(runDirectory, \"context.json\");\n const promptPath = path.join(runDirectory, \"generator-prompt.md\");\n const resultPath = path.join(runDirectory, \"result.json\");\n const notesPath = path.join(sessionStateDirectory, \"notes.md\");\n const prompt = buildGeneratorPrompt(config, context);\n const runner = options.runner ?? runBeeAgentExec;\n const args = [\n \"exec\",\n \"--color\",\n \"never\",\n \"--disable\",\n \"codex_hooks\",\n \"--skip-git-repo-check\",\n \"--ephemeral\",\n \"-C\",\n runDirectory,\n \"--output-schema\",\n schemaPath,\n \"-o\",\n outputPath\n ];\n\n if (config.profile) {\n args.push(\"--profile\", config.profile);\n }\n\n if (config.model) {\n args.push(\"--model\", config.model);\n }\n\n mkdirSync(runDirectory, {\n recursive: true\n });\n writeFileSync(schemaPath, `${JSON.stringify(BEE_AGENT_RESULT_SCHEMA, null, 2)}\\n`, \"utf8\");\n writeFileSync(contextPath, `${JSON.stringify(context, null, 2)}\\n`, \"utf8\");\n writeFileSync(promptPath, prompt, \"utf8\");\n\n options.logger.log(\"bee_agent_generation_started\", {\n configPath: options.source.path,\n sessionId: context.sessionId\n });\n\n const execResult = await runner({\n args,\n cwd: runDirectory,\n outputPath,\n prompt,\n stderrPath,\n stdoutPath\n });\n\n if (execResult.code !== 0) {\n throw new Error(\n `Bee-agent generator exited with code ${execResult.code}. See ${stdoutPath} and ${stderrPath}.`\n );\n }\n\n const parsedResult = readParsedResult(outputPath);\n\n if (parsedResult.note && parsedResult.note.trim()) {\n appendSessionNote(notesPath, parsedResult.note, options.capture.capturedAt ?? new Date().toISOString());\n }\n\n writeFileSync(\n resultPath,\n `${JSON.stringify({\n nextPrompt: parsedResult.next_prompt,\n note: parsedResult.note\n }, null, 2)}\\n`,\n \"utf8\"\n );\n\n options.logger.log(\"bee_agent_generation_completed\", {\n nextPromptLength: parsedResult.next_prompt.length,\n noteLength: parsedResult.note?.length ?? 0,\n sessionId: context.sessionId\n });\n\n return {\n context,\n nextPrompt: parsedResult.next_prompt,\n note: parsedResult.note,\n sessionStateDirectory\n };\n}\n","import { readFileSync } from \"node:fs\";\n\nexport interface TranscriptMessage {\n role: \"assistant\" | \"user\";\n text: string;\n}\n\nexport interface TranscriptTokenUsage {\n cachedInputTokens: number;\n inputTokens: number;\n outputTokens: number;\n reasoningOutputTokens: number;\n totalTokens: number;\n}\n\nexport interface TranscriptTokenCountSnapshot {\n lastTokenUsage: TranscriptTokenUsage | null;\n modelContextWindow: number | null;\n timestamp: string | null;\n totalTokenUsage: TranscriptTokenUsage | null;\n}\n\nexport interface TranscriptSummary {\n path: string;\n recentMessages: TranscriptMessage[];\n sessionObjective: string | null;\n totalMessages: number;\n}\n\nfunction readMessageText(payload: {\n content?: unknown;\n}): string {\n if (!Array.isArray(payload.content)) {\n return \"\";\n }\n\n const textParts = payload.content\n .filter((item): item is {\n text?: unknown;\n type?: unknown;\n } => typeof item === \"object\" && item !== null)\n .filter((item) => item.type === \"input_text\" || item.type === \"output_text\")\n .map((item) => typeof item.text === \"string\" ? item.text : \"\")\n .filter(Boolean);\n\n return textParts.join(\"\\n\").trim();\n}\n\nfunction readTokenUsage(value: unknown): TranscriptTokenUsage | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n\n const usage = value as {\n cached_input_tokens?: unknown;\n input_tokens?: unknown;\n output_tokens?: unknown;\n reasoning_output_tokens?: unknown;\n total_tokens?: unknown;\n };\n\n if (\n typeof usage.input_tokens !== \"number\"\n || typeof usage.cached_input_tokens !== \"number\"\n || typeof usage.output_tokens !== \"number\"\n || typeof usage.reasoning_output_tokens !== \"number\"\n || typeof usage.total_tokens !== \"number\"\n ) {\n return null;\n }\n\n return {\n cachedInputTokens: usage.cached_input_tokens,\n inputTokens: usage.input_tokens,\n outputTokens: usage.output_tokens,\n reasoningOutputTokens: usage.reasoning_output_tokens,\n totalTokens: usage.total_tokens\n };\n}\n\nexport function parseTranscriptMessages(content: string): TranscriptMessage[] {\n const eventMessages: TranscriptMessage[] = [];\n const responseMessages: TranscriptMessage[] = [];\n\n for (const line of content.split(/\\r?\\n/u)) {\n if (!line.trim()) {\n continue;\n }\n\n let item: unknown;\n\n try {\n item = JSON.parse(line);\n } catch {\n continue;\n }\n\n if (typeof item !== \"object\" || item === null) {\n continue;\n }\n\n const typedItem = item as {\n payload?: {\n content?: unknown;\n last_agent_message?: unknown;\n message?: unknown;\n role?: unknown;\n type?: unknown;\n };\n type?: unknown;\n };\n\n if (typedItem.type === \"event_msg\") {\n if (typedItem.payload?.type === \"user_message\" && typeof typedItem.payload.message === \"string\") {\n const text = typedItem.payload.message.trim();\n\n if (text) {\n eventMessages.push({\n role: \"user\",\n text\n });\n }\n }\n\n if (typedItem.payload?.type === \"task_complete\" && typeof typedItem.payload.last_agent_message === \"string\") {\n const text = typedItem.payload.last_agent_message.trim();\n\n if (text) {\n eventMessages.push({\n role: \"assistant\",\n text\n });\n }\n }\n\n continue;\n }\n\n if (typedItem.type !== \"response_item\" || typedItem.payload?.type !== \"message\") {\n continue;\n }\n\n if (typedItem.payload.role !== \"assistant\" && typedItem.payload.role !== \"user\") {\n continue;\n }\n\n const text = readMessageText(typedItem.payload);\n\n if (!text) {\n continue;\n }\n\n responseMessages.push({\n role: typedItem.payload.role,\n text\n });\n }\n\n return eventMessages.length > 0 ? eventMessages : responseMessages;\n}\n\nexport function parseTranscriptTokenCounts(content: string): TranscriptTokenCountSnapshot[] {\n const snapshots: TranscriptTokenCountSnapshot[] = [];\n\n for (const line of content.split(/\\r?\\n/u)) {\n if (!line.trim()) {\n continue;\n }\n\n let item: unknown;\n\n try {\n item = JSON.parse(line);\n } catch {\n continue;\n }\n\n if (typeof item !== \"object\" || item === null) {\n continue;\n }\n\n const typedItem = item as {\n payload?: {\n info?: {\n last_token_usage?: unknown;\n model_context_window?: unknown;\n total_token_usage?: unknown;\n };\n type?: unknown;\n };\n timestamp?: unknown;\n type?: unknown;\n };\n\n if (typedItem.type !== \"event_msg\" || typedItem.payload?.type !== \"token_count\") {\n continue;\n }\n\n const info = typedItem.payload.info;\n\n snapshots.push({\n lastTokenUsage: readTokenUsage(info?.last_token_usage),\n modelContextWindow: typeof info?.model_context_window === \"number\"\n ? info.model_context_window\n : null,\n timestamp: typeof typedItem.timestamp === \"string\" ? typedItem.timestamp : null,\n totalTokenUsage: readTokenUsage(info?.total_token_usage)\n });\n }\n\n return snapshots;\n}\n\nexport function summarizeTranscriptFile(transcriptPath: string, options?: {\n maxRecentMessages?: number;\n}): TranscriptSummary {\n const maxRecentMessages = options?.maxRecentMessages ?? 6;\n const content = readFileSync(transcriptPath, \"utf8\");\n const messages = parseTranscriptMessages(content);\n const sessionObjective = messages.find((message) => message.role === \"user\")?.text ?? null;\n\n return {\n path: transcriptPath,\n recentMessages: messages.slice(-maxRecentMessages),\n sessionObjective,\n totalMessages: messages.length\n };\n}\n","import type { ContinuationTemplateSource } from \"./continuation.js\";\n\nexport interface BeeAgentSource {\n kind: \"bee-agent\";\n path: string;\n}\n\nexport type ContinuationSource = BeeAgentSource | ContinuationTemplateSource;\n\nexport function isBeeAgentSource(source: ContinuationSource): source is BeeAgentSource {\n return source.kind === \"bee-agent\";\n}\n\nexport function isContinuationTemplateSource(source: ContinuationSource): source is ContinuationTemplateSource {\n return source.kind === \"file\" || source.kind === \"inline\";\n}\n","import { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { StopCapture } from \"./hook-server.js\";\n\nconst SUPPORTED_PLACEHOLDERS = [\n \"captured_at\",\n \"cwd\",\n \"hook_event_name\",\n \"last_assistant_message_excerpt\",\n \"last_assistant_message_json\",\n \"last_assistant_message_single_line\",\n \"last_assistant_message\",\n \"model\",\n \"permission_mode\",\n \"run_id\",\n \"session_id\",\n \"stop_hook_active\",\n \"transcript_path\"\n] as const;\n\nconst PLACEHOLDER_PATTERN = /{{\\s*([a-z0-9_]+)\\s*}}/gi;\nconst SINGLE_LINE_WHITESPACE_PATTERN = /\\s+/g;\nconst LAST_ASSISTANT_MESSAGE_EXCERPT_LENGTH = 280;\nconst WINDOWS_LINE_ENDING_PATTERN = /\\r\\n?/g;\n\ntype ContinuationPlaceholder = (typeof SUPPORTED_PLACEHOLDERS)[number];\n\nexport type ContinuationTemplateSource =\n | {\n kind: \"file\";\n path: string;\n }\n | {\n kind: \"inline\";\n template: string;\n };\n\nexport interface RenderedContinuationPrompt {\n prompt: string;\n unknownPlaceholders: string[];\n usedPlaceholders: string[];\n}\n\nfunction stringifyTemplateValue(value: boolean | null | string | undefined): string {\n if (value === null || value === undefined) {\n return \"\";\n }\n\n return String(value);\n}\n\nfunction toSingleLine(value: string): string {\n return value.replace(SINGLE_LINE_WHITESPACE_PATTERN, \" \").trim();\n}\n\nfunction toExcerpt(value: string): string {\n const singleLineValue = toSingleLine(value);\n\n if (singleLineValue.length <= LAST_ASSISTANT_MESSAGE_EXCERPT_LENGTH) {\n return singleLineValue;\n }\n\n return `${singleLineValue.slice(0, LAST_ASSISTANT_MESSAGE_EXCERPT_LENGTH - 3).trimEnd()}...`;\n}\n\nfunction normalizeTemplateContent(value: string): string {\n const normalizedLineEndings = value.replace(WINDOWS_LINE_ENDING_PATTERN, \"\\n\");\n\n return normalizedLineEndings.endsWith(\"\\n\")\n ? normalizedLineEndings.slice(0, -1)\n : normalizedLineEndings;\n}\n\nfunction buildPlaceholderValues(capture: StopCapture): Record<ContinuationPlaceholder, string> {\n const payload = capture.payload ?? {};\n const lastAssistantMessage = stringifyTemplateValue(payload.last_assistant_message);\n\n return {\n captured_at: stringifyTemplateValue(capture.capturedAt),\n cwd: stringifyTemplateValue(payload.cwd ?? capture.cwd),\n hook_event_name: stringifyTemplateValue(payload.hook_event_name),\n last_assistant_message_excerpt: toExcerpt(lastAssistantMessage),\n last_assistant_message_json: JSON.stringify(lastAssistantMessage),\n last_assistant_message_single_line: toSingleLine(lastAssistantMessage),\n last_assistant_message: lastAssistantMessage,\n model: stringifyTemplateValue(payload.model),\n permission_mode: stringifyTemplateValue(payload.permission_mode),\n run_id: stringifyTemplateValue(capture.env?.CODEX_BEE_RUN_ID),\n session_id: stringifyTemplateValue(payload.session_id),\n stop_hook_active: stringifyTemplateValue(payload.stop_hook_active),\n transcript_path: stringifyTemplateValue(payload.transcript_path)\n };\n}\n\nexport function listSupportedContinuationPlaceholders(): string[] {\n return [...SUPPORTED_PLACEHOLDERS];\n}\n\nexport function describeContinuationTemplateSource(source: ContinuationTemplateSource): string {\n return source.kind === \"file\"\n ? `file ${source.path}`\n : \"inline prompt\";\n}\n\nexport function readContinuationTemplate(\n source: ContinuationTemplateSource,\n options?: {\n cwd?: string;\n }\n): string {\n if (source.kind === \"inline\") {\n return source.template;\n }\n\n const cwd = options?.cwd ?? process.cwd();\n const resolvedPath = resolve(cwd, source.path);\n\n let rawTemplate: string;\n\n try {\n rawTemplate = readFileSync(resolvedPath, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Unable to read continuation template file ${source.path}: ${message}`);\n }\n\n const template = normalizeTemplateContent(rawTemplate);\n\n if (!template.trim()) {\n throw new Error(`Continuation template file is empty: ${source.path}`);\n }\n\n return template;\n}\n\nexport function renderContinuationPrompt(\n promptTemplate: string,\n capture: StopCapture\n): RenderedContinuationPrompt {\n const placeholderValues = buildPlaceholderValues(capture);\n const unknownPlaceholders = new Set<string>();\n const usedPlaceholders = new Set<string>();\n const prompt = promptTemplate.replace(PLACEHOLDER_PATTERN, (match, rawPlaceholderName: string) => {\n const placeholderName = rawPlaceholderName.toLowerCase();\n\n if (!Object.hasOwn(placeholderValues, placeholderName)) {\n unknownPlaceholders.add(rawPlaceholderName);\n return match;\n }\n\n usedPlaceholders.add(placeholderName);\n return placeholderValues[placeholderName as ContinuationPlaceholder];\n });\n\n return {\n prompt,\n unknownPlaceholders: [...unknownPlaceholders],\n usedPlaceholders: [...usedPlaceholders]\n };\n}\n","import { describeBeeAgentSource, readBeeAgentConfig } from \"./bee-agent.js\";\nimport {\n isBeeAgentSource,\n isContinuationTemplateSource,\n type BeeAgentSource,\n type ContinuationSource\n} from \"./continuation-source.js\";\nimport {\n describeContinuationTemplateSource,\n readContinuationTemplate,\n renderContinuationPrompt,\n} from \"./continuation.js\";\nimport type { StopCapture } from \"./hook-server.js\";\n\nexport interface InteractiveContinuationDraft {\n maxContinues: number;\n maxDurationMs: number | null;\n prompt: string;\n}\n\nexport interface ContinuationSnapshot {\n enabled: boolean;\n injectionsUsed: number;\n maxContinues: number;\n maxDurationMs: number | null;\n promptSource: ContinuationSource;\n promptSourceLabel: string;\n promptText: string;\n remainingContinues: number;\n remainingDurationMs: number | null;\n startedAt: number | null;\n}\n\nexport interface ContinuationDecision {\n kind: \"disabled\" | \"empty-prompt\" | \"error\" | \"expired\" | \"generate\" | \"guardrail\" | \"inject\";\n guardrailReached?: boolean;\n injectionNumber?: number;\n maxContinues?: number;\n message?: string;\n prompt?: string;\n source?: BeeAgentSource;\n sourceLabel?: string;\n unknownPlaceholders?: string[];\n usedPlaceholders?: string[];\n}\n\nconst DURATION_INPUT_PATTERN = /^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/i;\nconst PROMPT_PREVIEW_LENGTH = 96;\nconst SINGLE_LINE_WHITESPACE_PATTERN = /\\s+/g;\n\nexport const DEFAULT_CONTINUATION_PROMPT = \"continue\";\nexport const DEFAULT_MAX_CONTINUES = 3;\nexport const UNBOUNDED_MAX_CONTINUES = Number.POSITIVE_INFINITY;\n\nfunction toSingleLine(value: string): string {\n return value.replace(SINGLE_LINE_WHITESPACE_PATTERN, \" \").trim();\n}\n\nfunction toPromptPreview(value: string): string {\n const singleLine = toSingleLine(value);\n\n if (!singleLine) {\n return \"(empty prompt)\";\n }\n\n if (singleLine.length <= PROMPT_PREVIEW_LENGTH) {\n return singleLine;\n }\n\n return `${singleLine.slice(0, PROMPT_PREVIEW_LENGTH - 3).trimEnd()}...`;\n}\n\nfunction describeContinuationSource(source: ContinuationSource): string {\n return isBeeAgentSource(source)\n ? describeBeeAgentSource(source)\n : describeContinuationTemplateSource(source);\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function parseDurationInput(value: string, options?: {\n allowEmpty?: boolean;\n}): number | null {\n const trimmedValue = value.trim();\n\n if (!trimmedValue || /^off$/i.test(trimmedValue)) {\n if (options?.allowEmpty ?? true) {\n return null;\n }\n\n throw new Error(\"Duration is required.\");\n }\n\n const match = trimmedValue.match(DURATION_INPUT_PATTERN);\n\n if (!match) {\n throw new Error(`Unsupported duration value: ${value}`);\n }\n\n const amount = Number.parseFloat(match[1]);\n const unit = (match[2] ?? \"m\").toLowerCase();\n\n if (!Number.isFinite(amount) || amount <= 0) {\n throw new Error(`Unsupported duration value: ${value}`);\n }\n\n const multiplier = {\n h: 60 * 60 * 1000,\n m: 60 * 1000,\n ms: 1,\n s: 1000\n }[unit];\n\n if (multiplier === undefined) {\n throw new Error(`Unsupported duration value: ${value}`);\n }\n\n const durationMs = Math.round(amount * multiplier);\n\n if (durationMs <= 0) {\n throw new Error(`Unsupported duration value: ${value}`);\n }\n\n return durationMs;\n}\n\nexport function formatDurationMs(value: number | null): string {\n if (value === null) {\n return \"off\";\n }\n\n if (value % (60 * 60 * 1000) === 0) {\n return `${value / (60 * 60 * 1000)}h`;\n }\n\n if (value % (60 * 1000) === 0) {\n return `${value / (60 * 1000)}m`;\n }\n\n if (value % 1000 === 0) {\n return `${value / 1000}s`;\n }\n\n return `${value}ms`;\n}\n\nexport class ContinuationController {\n #cwd: string;\n #enabled = false;\n #injectionsUsed = 0;\n #maxContinues = UNBOUNDED_MAX_CONTINUES;\n #maxDurationMs: number | null = null;\n #promptSource: ContinuationSource = {\n kind: \"inline\",\n template: DEFAULT_CONTINUATION_PROMPT\n };\n #startedAt: number | null = null;\n #warnedUnknownPlaceholders = new Set<string>();\n\n constructor(options: {\n cwd: string;\n initial?: {\n enabled: boolean;\n maxContinues: number;\n maxDurationMs: number | null;\n promptSource: ContinuationSource;\n };\n }) {\n this.#cwd = options.cwd;\n\n if (options.initial) {\n this.#enabled = options.initial.enabled;\n this.#maxContinues = options.initial.maxContinues;\n this.#maxDurationMs = options.initial.maxDurationMs;\n this.#promptSource = options.initial.promptSource;\n this.#startedAt = options.initial.enabled ? Date.now() : null;\n }\n }\n\n armWithPromptSource(options: {\n maxContinues: number;\n maxDurationMs: number | null;\n promptSource: ContinuationSource;\n }): ContinuationSnapshot {\n this.#enabled = true;\n this.#injectionsUsed = 0;\n this.#maxContinues = options.maxContinues;\n this.#maxDurationMs = options.maxDurationMs;\n this.#promptSource = options.promptSource;\n this.#startedAt = Date.now();\n this.#warnedUnknownPlaceholders.clear();\n\n return this.getSnapshot();\n }\n\n applyInteractiveDraft(draft: InteractiveContinuationDraft): ContinuationSnapshot {\n return this.updateInteractiveDraft(draft, {\n enable: true\n });\n }\n\n updateInteractiveDraft(\n draft: InteractiveContinuationDraft,\n options?: {\n enable?: boolean;\n }\n ): ContinuationSnapshot {\n const shouldEnable = options?.enable ?? this.#enabled;\n const previousDurationMs = this.#maxDurationMs;\n const wasEnabled = this.#enabled;\n const nextPromptSource: ContinuationSource = {\n kind: \"inline\",\n template: draft.prompt\n };\n\n this.#maxContinues = draft.maxContinues;\n this.#maxDurationMs = draft.maxDurationMs;\n this.#promptSource = nextPromptSource;\n this.#warnedUnknownPlaceholders.clear();\n\n if (shouldEnable) {\n if (!wasEnabled) {\n this.#injectionsUsed = 0;\n\n if (draft.maxDurationMs === null) {\n this.#startedAt = null;\n } else {\n this.#startedAt = this.#startedAt ?? Date.now();\n }\n }\n\n this.#enabled = true;\n } else {\n this.#enabled = false;\n\n if (draft.maxDurationMs === null) {\n this.#startedAt = null;\n } else if (this.#startedAt === null || previousDurationMs !== draft.maxDurationMs) {\n this.#startedAt = Date.now();\n }\n }\n\n return this.getSnapshot();\n }\n\n disable(): ContinuationSnapshot {\n this.#enabled = false;\n this.#startedAt = null;\n\n return this.getSnapshot();\n }\n\n getSnapshot(): ContinuationSnapshot {\n const promptText = this.#readPromptText();\n const remainingDurationMs = this.#getRemainingDurationMs();\n\n return {\n enabled: this.#enabled,\n injectionsUsed: this.#injectionsUsed,\n maxContinues: this.#maxContinues,\n maxDurationMs: this.#maxDurationMs,\n promptSource: this.#promptSource,\n promptSourceLabel: describeContinuationSource(this.#promptSource),\n promptText,\n remainingContinues: Number.isFinite(this.#maxContinues)\n ? Math.max(this.#maxContinues - this.#injectionsUsed, 0)\n : Number.POSITIVE_INFINITY,\n remainingDurationMs,\n startedAt: this.#startedAt\n };\n }\n\n getPromptPreview(): string {\n return toPromptPreview(this.#readPromptText());\n }\n\n handleStop(capture: StopCapture): ContinuationDecision {\n if (!this.#enabled) {\n return {\n kind: \"disabled\"\n };\n }\n\n const remainingDurationMs = this.#getRemainingDurationMs();\n\n if (remainingDurationMs !== null && remainingDurationMs <= 0) {\n this.disable();\n\n return {\n kind: \"expired\",\n message: `[codex-bee] Auto-continue session duration limit reached (${formatDurationMs(this.#maxDurationMs)}).`\n };\n }\n\n if (Number.isFinite(this.#maxContinues) && this.#injectionsUsed >= this.#maxContinues) {\n this.disable();\n\n return {\n kind: \"guardrail\",\n message: `[codex-bee] Auto-continue guardrail reached (${this.#maxContinues} injections). No further prompts will be sent.`\n };\n }\n\n if (isBeeAgentSource(this.#promptSource)) {\n this.#injectionsUsed += 1;\n\n const guardrailReached = Number.isFinite(this.#maxContinues)\n ? this.#injectionsUsed >= this.#maxContinues\n : false;\n\n if (guardrailReached) {\n this.#enabled = false;\n this.#startedAt = null;\n }\n\n return {\n guardrailReached,\n injectionNumber: this.#injectionsUsed,\n kind: \"generate\",\n maxContinues: this.#maxContinues,\n source: this.#promptSource,\n sourceLabel: describeContinuationSource(this.#promptSource)\n };\n }\n\n let promptTemplate: string;\n\n try {\n promptTemplate = readContinuationTemplate(this.#promptSource, {\n cwd: this.#cwd\n });\n } catch (error) {\n this.disable();\n\n return {\n kind: \"error\",\n message: `[codex-bee] ${toErrorMessage(error)}`\n };\n }\n\n const renderedPrompt = renderContinuationPrompt(promptTemplate, capture);\n const unknownPlaceholders = renderedPrompt.unknownPlaceholders.filter((placeholder) => {\n if (this.#warnedUnknownPlaceholders.has(placeholder)) {\n return false;\n }\n\n this.#warnedUnknownPlaceholders.add(placeholder);\n return true;\n });\n\n if (!renderedPrompt.prompt.trim()) {\n this.disable();\n\n return {\n kind: \"empty-prompt\",\n message: \"[codex-bee] Continuation template rendered to an empty prompt. Auto-continue will stop.\"\n };\n }\n\n this.#injectionsUsed += 1;\n\n const guardrailReached = Number.isFinite(this.#maxContinues)\n ? this.#injectionsUsed >= this.#maxContinues\n : false;\n\n if (guardrailReached) {\n this.#enabled = false;\n this.#startedAt = null;\n }\n\n return {\n guardrailReached,\n injectionNumber: this.#injectionsUsed,\n kind: \"inject\",\n maxContinues: this.#maxContinues,\n prompt: renderedPrompt.prompt,\n sourceLabel: describeContinuationSource(this.#promptSource),\n unknownPlaceholders,\n usedPlaceholders: renderedPrompt.usedPlaceholders\n };\n }\n\n #getRemainingDurationMs(): number | null {\n if (this.#maxDurationMs === null || this.#startedAt === null) {\n return null;\n }\n\n return this.#maxDurationMs - (Date.now() - this.#startedAt);\n }\n\n #readPromptText(): string {\n try {\n if (isBeeAgentSource(this.#promptSource)) {\n const config = readBeeAgentConfig(this.#promptSource, {\n cwd: this.#cwd\n });\n\n return `[bee-agent] ${toPromptPreview(config.sessionPrompt)}`;\n }\n\n return readContinuationTemplate(this.#promptSource, {\n cwd: this.#cwd\n });\n } catch {\n if (isContinuationTemplateSource(this.#promptSource) && this.#promptSource.kind === \"inline\") {\n return this.#promptSource.template;\n }\n\n return \"\";\n }\n }\n}\n","import { parseDurationInput } from \"./auto-continue.js\";\nimport type { ContinuationSource } from \"./continuation-source.js\";\n\nexport const HELP_TEXT = `\nbee\n\nAutonomous wrapper around Codex CLI.\n\nUsage:\n bee [options] <command> [commandArgs]\n bee [options] -- <command> [commandArgs]\n\nOptions:\n -h, --help Show help\n --version Show version\n --continue-once <prompt> Inject one follow-up prompt after the first Stop event\n --continue-once-file <path> Load the one-shot follow-up prompt from a file\n --continue-once-agent-file <path>\n Load a one-shot bee-agent config from a file\n --continue-loop <prompt> Inject the same follow-up prompt after multiple Stop events\n --continue-loop-file <path> Load the loop follow-up prompt from a file\n --continue-loop-agent-file <path>\n Load a loop bee-agent config from a file\n --max-continues <count> Guardrail for loop injections (default: 3)\n --max-duration <duration> Session guardrail, for example 90m or 1.5h\n --verify-command <command> Run a verification shell command after each Stop; continue only while it fails\n --inject-delay-ms <milliseconds> Optional debug delay before prompt injection\n\nInline and file-based continuation prompts accept {{placeholder}} tokens from the matched Stop payload.\nBee-agent continuation configs are JSON files that point to system/session prompt files and optional generator settings.\n`;\n\nexport interface ParsedWrapperOptions {\n command: string | null;\n commandArgs: string[];\n continueLoopSource: ContinuationSource | null;\n continueOnceSource: ContinuationSource | null;\n injectDelayMs: number;\n maxContinues: number;\n maxDurationMs: number | null;\n showHelp: boolean;\n showVersion: boolean;\n verificationCommand: string | null;\n}\n\nfunction setContinuationSource(\n currentSource: ContinuationSource | null,\n nextSource: ContinuationSource,\n modeLabel: string\n): ContinuationSource {\n if (currentSource) {\n throw new Error(`Use only one ${modeLabel} continuation source.`);\n }\n\n return nextSource;\n}\n\nconst WRAPPER_FLAGS_WITH_VALUE = new Set([\n \"--continue-loop\",\n \"--continue-loop-agent-file\",\n \"--continue-loop-file\",\n \"--continue-once\",\n \"--continue-once-agent-file\",\n \"--continue-once-file\",\n \"--inject-delay-ms\",\n \"--max-continues\",\n \"--max-duration\",\n \"--verify-command\"\n]);\n\nconst WRAPPER_FLAGS_WITHOUT_VALUE = new Set([\n \"-h\",\n \"--help\",\n \"--version\"\n]);\n\nfunction parseCommandInvocation(wrapperArgs: string[], commandInvocation: string[]): {\n command: string | null;\n commandArgs: string[];\n wrapperArgs: string[];\n} {\n return {\n command: commandInvocation[0] ?? null,\n commandArgs: commandInvocation.slice(1),\n wrapperArgs\n };\n}\n\nexport function parseCliArguments(rawArgs: string[]): {\n command: string | null;\n commandArgs: string[];\n wrapperArgs: string[];\n} {\n const separatorIndex = rawArgs.indexOf(\"--\");\n\n if (separatorIndex >= 0) {\n return parseCommandInvocation(\n rawArgs.slice(0, separatorIndex),\n rawArgs.slice(separatorIndex + 1)\n );\n }\n\n const wrapperArgs: string[] = [];\n let index = 0;\n\n while (index < rawArgs.length) {\n const argument = rawArgs[index];\n\n if (argument === \"codex\") {\n return {\n command: argument,\n commandArgs: rawArgs.slice(index + 1),\n wrapperArgs\n };\n }\n\n if (WRAPPER_FLAGS_WITHOUT_VALUE.has(argument)) {\n wrapperArgs.push(argument);\n index += 1;\n continue;\n }\n\n if (WRAPPER_FLAGS_WITH_VALUE.has(argument)) {\n wrapperArgs.push(argument);\n const value = rawArgs[index + 1];\n\n if (value !== undefined) {\n wrapperArgs.push(value);\n index += 2;\n } else {\n index += 1;\n }\n\n continue;\n }\n\n return {\n command: argument,\n commandArgs: rawArgs.slice(index + 1),\n wrapperArgs\n };\n }\n\n return {\n command: null,\n commandArgs: [],\n wrapperArgs\n };\n}\n\nexport function parseWrapperOptions(rawArgs: string[]): ParsedWrapperOptions {\n const { command, commandArgs, wrapperArgs } = parseCliArguments(rawArgs);\n let continueLoopSource: ContinuationSource | null = null;\n let continueOnceSource: ContinuationSource | null = null;\n let injectDelayMs = 0;\n let maxContinues = 3;\n let maxDurationMs: number | null = null;\n let showHelp = false;\n let showVersion = false;\n let verificationCommand: string | null = null;\n\n for (let index = 0; index < wrapperArgs.length; index += 1) {\n const argument = wrapperArgs[index];\n\n if (argument === \"-h\" || argument === \"--help\") {\n showHelp = true;\n continue;\n }\n\n if (argument === \"--version\") {\n showVersion = true;\n continue;\n }\n\n if (argument === \"--continue-once\") {\n const prompt = wrapperArgs[index + 1];\n\n if (!prompt) {\n throw new Error(\"Missing value for --continue-once.\");\n }\n\n continueOnceSource = setContinuationSource(\n continueOnceSource,\n {\n kind: \"inline\",\n template: prompt\n },\n \"one-shot\"\n );\n index += 1;\n continue;\n }\n\n if (argument === \"--continue-once-file\") {\n const path = wrapperArgs[index + 1];\n\n if (!path) {\n throw new Error(\"Missing value for --continue-once-file.\");\n }\n\n continueOnceSource = setContinuationSource(\n continueOnceSource,\n {\n kind: \"file\",\n path\n },\n \"one-shot\"\n );\n index += 1;\n continue;\n }\n\n if (argument === \"--continue-once-agent-file\") {\n const path = wrapperArgs[index + 1];\n\n if (!path) {\n throw new Error(\"Missing value for --continue-once-agent-file.\");\n }\n\n continueOnceSource = setContinuationSource(\n continueOnceSource,\n {\n kind: \"bee-agent\",\n path\n },\n \"one-shot\"\n );\n index += 1;\n continue;\n }\n\n if (argument === \"--continue-loop\") {\n const prompt = wrapperArgs[index + 1];\n\n if (!prompt) {\n throw new Error(\"Missing value for --continue-loop.\");\n }\n\n continueLoopSource = setContinuationSource(\n continueLoopSource,\n {\n kind: \"inline\",\n template: prompt\n },\n \"loop\"\n );\n index += 1;\n continue;\n }\n\n if (argument === \"--continue-loop-file\") {\n const path = wrapperArgs[index + 1];\n\n if (!path) {\n throw new Error(\"Missing value for --continue-loop-file.\");\n }\n\n continueLoopSource = setContinuationSource(\n continueLoopSource,\n {\n kind: \"file\",\n path\n },\n \"loop\"\n );\n index += 1;\n continue;\n }\n\n if (argument === \"--continue-loop-agent-file\") {\n const path = wrapperArgs[index + 1];\n\n if (!path) {\n throw new Error(\"Missing value for --continue-loop-agent-file.\");\n }\n\n continueLoopSource = setContinuationSource(\n continueLoopSource,\n {\n kind: \"bee-agent\",\n path\n },\n \"loop\"\n );\n index += 1;\n continue;\n }\n\n if (argument === \"--max-continues\") {\n const value = wrapperArgs[index + 1];\n\n if (!value) {\n throw new Error(\"Missing value for --max-continues.\");\n }\n\n const parsed = Number.parseInt(value, 10);\n\n if (!Number.isFinite(parsed) || parsed < 1) {\n throw new Error(`Invalid --max-continues value: ${value}`);\n }\n\n maxContinues = parsed;\n index += 1;\n continue;\n }\n\n if (argument === \"--inject-delay-ms\") {\n const value = wrapperArgs[index + 1];\n\n if (!value) {\n throw new Error(\"Missing value for --inject-delay-ms.\");\n }\n\n const parsed = Number.parseInt(value, 10);\n\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new Error(`Invalid --inject-delay-ms value: ${value}`);\n }\n\n injectDelayMs = parsed;\n index += 1;\n continue;\n }\n\n if (argument === \"--max-duration\") {\n const value = wrapperArgs[index + 1];\n\n if (!value) {\n throw new Error(\"Missing value for --max-duration.\");\n }\n\n maxDurationMs = parseDurationInput(value, {\n allowEmpty: false\n });\n index += 1;\n continue;\n }\n\n if (argument === \"--verify-command\") {\n const value = wrapperArgs[index + 1];\n\n if (!value) {\n throw new Error(\"Missing value for --verify-command.\");\n }\n\n verificationCommand = value;\n index += 1;\n continue;\n }\n\n throw new Error(`Unknown bee option: ${argument}`);\n }\n\n if (continueLoopSource && continueOnceSource) {\n throw new Error(\"Use either --continue-once or --continue-loop, not both.\");\n }\n\n if (!continueLoopSource && maxContinues !== 3) {\n throw new Error(\"--max-continues requires --continue-loop.\");\n }\n\n if (!continueLoopSource && !continueOnceSource && maxDurationMs !== null) {\n throw new Error(\"--max-duration requires --continue-once or --continue-loop.\");\n }\n\n if (!continueLoopSource && !continueOnceSource && verificationCommand !== null) {\n throw new Error(\"--verify-command requires --continue-once or --continue-loop.\");\n }\n\n const hasWrapperBehavior = continueLoopSource !== null\n || continueOnceSource !== null\n || injectDelayMs !== 0\n || maxContinues !== 3\n || maxDurationMs !== null\n || verificationCommand !== null;\n\n if (!showHelp && !showVersion && command === null && hasWrapperBehavior) {\n throw new Error(\"Missing command to wrap. Use `bee <command> [args]`.\");\n }\n\n return {\n command,\n commandArgs,\n continueLoopSource,\n continueOnceSource,\n injectDelayMs,\n maxContinues,\n maxDurationMs,\n showHelp,\n showVersion,\n verificationCommand\n };\n}\n","import { setTimeout as delay } from \"node:timers/promises\";\nimport process from \"node:process\";\nimport { ContinuationController, type ContinuationDecision } from \"./auto-continue.js\";\nimport type { BeeAgentGenerationResult } from \"./bee-agent.js\";\nimport type { BeeAgentSource } from \"./continuation-source.js\";\nimport { waitForMatchingStopCapture } from \"./hook-server.js\";\nimport type { StopCapture } from \"./hook-server.js\";\nimport type { RuntimeEventLogger } from \"./runtime-log.js\";\nimport {\n formatVerificationFailurePrompt,\n runVerificationCommand as runVerificationCommandDefault,\n type VerificationCommandResult\n} from \"./verification.js\";\n\nexport interface ContinuationPromptProxy {\n injectPrompt(prompt: string): Promise<void>;\n}\n\nexport interface ContinuationWatcherOptions {\n continuation: ContinuationController;\n cwd: string;\n generateBeeAgentPrompt?: (capture: StopCapture, source: BeeAgentSource) => Promise<BeeAgentGenerationResult>;\n getVerificationCommand?: () => string | null;\n injectDelayMs: number;\n logger: RuntimeEventLogger;\n onPromptInjected?: (event: {\n capture: StopCapture;\n decision: ContinuationDecision;\n prompt: string;\n sessionId: string;\n }) => Promise<void> | void;\n onStopCaptureHandled?: (event: {\n capture: StopCapture;\n decision: ContinuationDecision;\n sessionId: string;\n verificationCommand: string | null;\n verificationErrorMessage: string | null;\n verificationResult: VerificationCommandResult | null;\n willInject: boolean;\n }) => Promise<void> | void;\n proxy: ContinuationPromptProxy;\n runVerificationCommand?: (options: {\n command: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n }) => Promise<VerificationCommandResult>;\n runId: string;\n runStartedAt: number;\n signal?: AbortSignal;\n verificationCommand?: string | null;\n waitTimeoutMs?: number | null;\n unrefTimers?: boolean;\n}\n\nfunction isTimeoutError(error: unknown): boolean {\n return error instanceof Error && error.message.startsWith(\"Timed out waiting for \");\n}\n\nfunction appendVerificationBlock(prompt: string, verificationFailurePrompt: string | null): string {\n if (!verificationFailurePrompt) {\n return prompt;\n }\n\n return `${prompt.trimEnd()}\\n\\n${verificationFailurePrompt}`.trim();\n}\n\nexport async function runContinuationWatcher(options: ContinuationWatcherOptions): Promise<void> {\n const seenFilePaths = new Set<string>();\n options.logger.log(\"continuation_watcher_started\", {\n runId: options.runId\n });\n\n while (!options.signal?.aborted) {\n let capture;\n\n try {\n capture = await waitForMatchingStopCapture({\n afterTimeMs: options.runStartedAt,\n cwd: options.cwd,\n runId: options.runId,\n seenFilePaths,\n timeoutMs: options.waitTimeoutMs ?? null,\n unrefTimers: options.unrefTimers\n });\n } catch (error) {\n if (options.signal?.aborted && isTimeoutError(error)) {\n break;\n }\n\n if (options.waitTimeoutMs !== undefined && options.waitTimeoutMs !== null && isTimeoutError(error)) {\n continue;\n }\n\n throw error;\n }\n\n const decision = options.continuation.handleStop(capture);\n const sessionId = capture.payload?.session_id ?? \"unknown\";\n options.logger.log(\"stop_capture_matched\", {\n decisionKind: decision.kind,\n sessionId,\n turnId: capture.payload?.turn_id ?? null\n });\n\n if (decision.kind === \"disabled\") {\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand: null,\n verificationErrorMessage: null,\n verificationResult: null,\n willInject: false\n });\n continue;\n }\n\n if (decision.kind === \"guardrail\" || decision.kind === \"expired\" || decision.kind === \"empty-prompt\" || decision.kind === \"error\") {\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand: null,\n verificationErrorMessage: null,\n verificationResult: null,\n willInject: false\n });\n\n if (decision.message) {\n console.error(decision.message);\n }\n\n continue;\n }\n\n const verificationCommand = options.getVerificationCommand?.() ?? options.verificationCommand ?? null;\n let verificationFailurePrompt: string | null = null;\n let verificationErrorMessage: string | null = null;\n let verificationResult: VerificationCommandResult | null = null;\n\n if (verificationCommand) {\n const runVerificationCommand = options.runVerificationCommand ?? runVerificationCommandDefault;\n\n options.logger.log(\"verification_command_started\", {\n command: verificationCommand,\n sessionId\n });\n\n try {\n verificationResult = await runVerificationCommand({\n command: verificationCommand,\n cwd: options.cwd,\n env: process.env\n });\n\n if (verificationResult.succeeded) {\n options.continuation.disable();\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage: null,\n verificationResult,\n willInject: false\n });\n options.logger.log(\"verification_command_succeeded\", {\n code: verificationResult.code,\n command: verificationResult.command,\n sessionId\n });\n console.error(\n `[codex-bee] Verification command succeeded (exit ${verificationResult.code}) for session ${sessionId}. Auto-continue will stop.`\n );\n continue;\n }\n\n verificationFailurePrompt = formatVerificationFailurePrompt(verificationResult);\n options.logger.log(\"verification_command_failed\", {\n code: verificationResult.code,\n command: verificationResult.command,\n sessionId,\n stderrLength: verificationResult.stderr.length,\n stdoutLength: verificationResult.stdout.length\n });\n console.error(\n `[codex-bee] Verification command failed (exit ${verificationResult.code}) for session ${sessionId}. Auto-continue will keep going.`\n );\n } catch (error) {\n options.continuation.disable();\n verificationErrorMessage = error instanceof Error ? error.message : String(error);\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage,\n verificationResult: null,\n willInject: false\n });\n options.logger.log(\"verification_command_error\", {\n command: verificationCommand,\n message: verificationErrorMessage,\n sessionId\n });\n console.error(\n `[codex-bee] Verification command failed to run: ${verificationErrorMessage}`\n );\n continue;\n }\n }\n\n if (decision.kind === \"generate\") {\n if (!decision.source) {\n options.continuation.disable();\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage: null,\n verificationResult,\n willInject: false\n });\n console.error(\"[codex-bee] Bee-agent continuation source is missing. Auto-continue will stop.\");\n continue;\n }\n\n if (!options.generateBeeAgentPrompt) {\n options.continuation.disable();\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage: null,\n verificationResult,\n willInject: false\n });\n console.error(\"[codex-bee] Bee-agent continuation runner is not configured. Auto-continue will stop.\");\n continue;\n }\n\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage: null,\n verificationResult,\n willInject: true\n });\n\n console.error(\n `[codex-bee] Stop capture matched for bee-agent generation in session ${sessionId} (${decision.injectionNumber}/${decision.maxContinues}).`\n );\n\n try {\n const generation = await options.generateBeeAgentPrompt(capture, decision.source);\n\n if (options.injectDelayMs > 0) {\n await delay(options.injectDelayMs);\n }\n\n const prompt = appendVerificationBlock(generation.nextPrompt, verificationFailurePrompt);\n\n await options.proxy.injectPrompt(prompt);\n options.logger.log(\"continuation_prompt_injected\", {\n injectionNumber: decision.injectionNumber,\n maxContinues: decision.maxContinues,\n noteLength: generation.note?.length ?? 0,\n promptLength: prompt.length,\n sessionId,\n sourceLabel: decision.sourceLabel ?? null\n });\n console.error(\n `[codex-bee] Bee-agent prompt injected (${decision.injectionNumber}/${decision.maxContinues}) with ${decision.sourceLabel}.`\n );\n await options.onPromptInjected?.({\n capture,\n decision,\n prompt,\n sessionId\n });\n\n if (generation.note) {\n console.error(\"[codex-bee] Bee-agent note persisted for this session.\");\n }\n } catch (error) {\n options.continuation.disable();\n options.logger.log(\"bee_agent_generation_failed\", {\n message: error instanceof Error ? error.message : String(error),\n sessionId,\n sourceLabel: decision.sourceLabel ?? null\n });\n console.error(\n `[codex-bee] Bee-agent generation failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n if (decision.guardrailReached) {\n console.error(\n `[codex-bee] Auto-continue guardrail reached (${decision.maxContinues} injections). No further prompts will be sent.`\n );\n }\n\n continue;\n }\n\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage: null,\n verificationResult,\n willInject: true\n });\n\n console.error(\n `[codex-bee] Stop capture matched for session ${sessionId} (${decision.injectionNumber}/${decision.maxContinues}).`\n );\n\n for (const placeholder of decision.unknownPlaceholders ?? []) {\n console.error(\n `[codex-bee] Continuation template placeholder is not recognized and will be left as-is: {{${placeholder}}}.`\n );\n }\n\n if (options.injectDelayMs > 0) {\n await delay(options.injectDelayMs);\n }\n\n const prompt = appendVerificationBlock(decision.prompt ?? \"\", verificationFailurePrompt);\n\n await options.proxy.injectPrompt(prompt);\n options.logger.log(\"continuation_prompt_injected\", {\n injectionNumber: decision.injectionNumber,\n maxContinues: decision.maxContinues,\n promptLength: prompt.length,\n sessionId,\n sourceLabel: decision.sourceLabel ?? null\n });\n const placeholderSuffix = decision.usedPlaceholders && decision.usedPlaceholders.length > 0\n ? ` using ${decision.usedPlaceholders.map((placeholder) => `{{${placeholder}}}`).join(\", \")}`\n : \"\";\n console.error(\n `[codex-bee] Continuation prompt injected (${decision.injectionNumber}/${decision.maxContinues}) with ${decision.sourceLabel}${placeholderSuffix}.`\n );\n await options.onPromptInjected?.({\n capture,\n decision,\n prompt,\n sessionId\n });\n\n if (decision.guardrailReached) {\n console.error(\n `[codex-bee] Auto-continue guardrail reached (${decision.maxContinues} injections). No further prompts will be sent.`\n );\n }\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\nexport interface HookCapture {\n capturedAt?: string;\n cwd?: string;\n env?: Record<string, string | undefined>;\n payload?: {\n cwd?: string;\n hook_event_name?: string;\n last_assistant_message?: string | null;\n model?: string;\n permission_mode?: string;\n prompt?: string;\n session_id?: string;\n source?: string;\n stop_hook_active?: boolean;\n tool_input?: unknown;\n tool_response?: unknown;\n tool_use_id?: string;\n tool_name?: string;\n transcript_path?: string;\n turn_id?: string;\n };\n transcript?: {\n error?: string;\n exists?: boolean;\n mtimeMs?: number;\n path?: string | null;\n size?: number;\n };\n}\n\nexport type StopCapture = HookCapture;\n\nexport interface HookCaptureWaitOptions {\n afterTimeMs: number;\n cwd: string;\n eventNames?: string[];\n runId: string;\n seenFilePaths?: Set<string>;\n timeoutMs?: number | null;\n unrefTimers?: boolean;\n}\n\nexport type StopCaptureWaitOptions = HookCaptureWaitOptions;\n\nfunction getTempRoot(cwd?: string): string {\n return path.join(cwd ?? process.cwd(), \".codex\", \"tmp\");\n}\n\nfunction getStopCaptureDirectory(cwd?: string): string {\n return path.join(getTempRoot(cwd), \"stop-captures\");\n}\n\nfunction getHookCaptureDirectory(cwd?: string): string {\n return path.join(getTempRoot(cwd), \"hook-captures\");\n}\n\nfunction getLastCapturePath(cwd?: string): string {\n return path.join(getTempRoot(cwd), \"last-stop-capture.json\");\n}\n\nfunction getLastHookCapturePath(cwd?: string): string {\n return path.join(getTempRoot(cwd), \"last-hook-capture.json\");\n}\n\nfunction getCaptureDirectories(options: HookCaptureWaitOptions): string[] {\n const directories = [getHookCaptureDirectory(options.cwd)];\n\n if (options.eventNames?.length === 1 && options.eventNames[0] === \"Stop\") {\n directories.push(getStopCaptureDirectory(options.cwd));\n }\n\n return directories;\n}\n\nfunction readCaptureFile(filePath: string): HookCapture | null {\n try {\n return JSON.parse(fs.readFileSync(filePath, \"utf8\")) as HookCapture;\n } catch {\n return null;\n }\n}\n\nfunction isMatchingCapture(capture: HookCapture | null, options: HookCaptureWaitOptions): boolean {\n if (!capture) {\n return false;\n }\n\n if (capture.cwd !== options.cwd) {\n return false;\n }\n\n const eventName = capture.payload?.hook_event_name;\n\n if (!eventName) {\n return false;\n }\n\n if (options.eventNames && !options.eventNames.includes(eventName)) {\n return false;\n }\n\n const runId = capture.env?.CODEX_BEE_RUN_ID;\n\n if (runId !== options.runId) {\n return false;\n }\n\n const capturedAt = capture.capturedAt ? Date.parse(capture.capturedAt) : Number.NaN;\n\n if (Number.isFinite(capturedAt) && capturedAt < options.afterTimeMs) {\n return false;\n }\n\n return true;\n}\n\nexport function clearStopCaptureArtifacts(cwd?: string): void {\n fs.rmSync(getHookCaptureDirectory(cwd), {\n force: true,\n recursive: true\n });\n fs.rmSync(getLastHookCapturePath(cwd), {\n force: true\n });\n fs.rmSync(getStopCaptureDirectory(cwd), {\n force: true,\n recursive: true\n });\n fs.rmSync(getLastCapturePath(cwd), {\n force: true\n });\n}\n\nexport function waitForMatchingHookCapture(options: HookCaptureWaitOptions): Promise<HookCapture> {\n const timeoutMs = options.timeoutMs ?? null;\n const seenFiles = options.seenFilePaths ?? new Set<string>();\n const unrefTimers = options.unrefTimers ?? true;\n const eventLabel = options.eventNames?.join(\", \") ?? \"hook\";\n\n return new Promise<HookCapture>((resolve, reject) => {\n const timeout = timeoutMs === null\n ? null\n : setTimeout(() => {\n clearInterval(interval);\n reject(new Error(`Timed out waiting for ${eventLabel} capture(s) for run ${options.runId}.`));\n }, timeoutMs);\n\n if (unrefTimers) {\n timeout?.unref();\n }\n\n const interval = setInterval(() => {\n for (const captureDirectory of getCaptureDirectories(options)) {\n if (!fs.existsSync(captureDirectory)) {\n continue;\n }\n\n const entries = fs.readdirSync(captureDirectory).sort();\n\n for (const entry of entries) {\n if (!entry.endsWith(\".json\")) {\n continue;\n }\n\n const filePath = path.join(captureDirectory, entry);\n\n if (seenFiles.has(filePath)) {\n continue;\n }\n\n const capture = readCaptureFile(filePath);\n\n if (!capture) {\n continue;\n }\n\n seenFiles.add(filePath);\n\n if (!isMatchingCapture(capture, options)) {\n continue;\n }\n\n if (timeout) {\n clearTimeout(timeout);\n }\n clearInterval(interval);\n resolve(capture);\n return;\n }\n }\n }, 250);\n\n if (unrefTimers) {\n interval.unref();\n }\n });\n}\n\nexport function waitForMatchingStopCapture(options: StopCaptureWaitOptions): Promise<StopCapture> {\n return waitForMatchingHookCapture({\n ...options,\n eventNames: [\"Stop\"]\n });\n}\n","import { spawn, type ChildProcess, type SpawnOptions } from \"node:child_process\";\n\nconst DEFAULT_MAX_OUTPUT_CHARS = 4000;\nconst MIN_SECTION_OUTPUT_CHARS = 400;\nconst WINDOWS_LINE_ENDING_PATTERN = /\\r\\n?/g;\n\nexport interface VerificationCommandOptions {\n command: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n maxOutputChars?: number;\n spawnImpl?: (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess;\n}\n\nexport interface VerificationCommandResult {\n code: number;\n command: string;\n stderr: string;\n stdout: string;\n succeeded: boolean;\n}\n\nfunction normalizeOutput(value: string): string {\n return value.replace(WINDOWS_LINE_ENDING_PATTERN, \"\\n\").trim();\n}\n\nfunction tailText(value: string, maxChars: number): string {\n if (value.length <= maxChars) {\n return value;\n }\n\n return `...${value.slice(-(maxChars - 3))}`;\n}\n\nfunction getSectionLimit(maxOutputChars: number): number {\n return Math.max(Math.floor(maxOutputChars / 2), MIN_SECTION_OUTPUT_CHARS);\n}\n\nexport async function runVerificationCommand(options: VerificationCommandOptions): Promise<VerificationCommandResult> {\n const spawnImpl = options.spawnImpl ?? spawn;\n const commandText = options.command.trim();\n\n if (!commandText) {\n throw new Error(\"Verification command is empty.\");\n }\n\n return new Promise((resolve) => {\n const child = spawnImpl(\"sh\", [\"-lc\", commandText], {\n cwd: options.cwd,\n env: options.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"]\n });\n let stdout = \"\";\n let stderr = \"\";\n let resolved = false;\n\n child.stdout?.setEncoding(\"utf8\");\n child.stderr?.setEncoding(\"utf8\");\n child.stdout?.on(\"data\", (chunk) => {\n stdout += chunk;\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr += chunk;\n });\n child.once(\"error\", (error) => {\n if (resolved) {\n return;\n }\n\n resolved = true;\n resolve({\n code: 1,\n command: commandText,\n stderr: `Unable to start verification command: ${error instanceof Error ? error.message : String(error)}`,\n stdout: \"\",\n succeeded: false\n });\n });\n child.once(\"exit\", (code, signal) => {\n if (resolved) {\n return;\n }\n\n resolved = true;\n const exitCode = signal ? 1 : code ?? 0;\n const signalMessage = signal\n ? `Verification command exited with signal ${signal}.`\n : \"\";\n const normalizedStdout = normalizeOutput(stdout);\n const normalizedStderr = normalizeOutput(\n signalMessage\n ? [stderr, signalMessage].filter(Boolean).join(\"\\n\")\n : stderr\n );\n\n resolve({\n code: exitCode,\n command: commandText,\n stderr: normalizedStderr,\n stdout: normalizedStdout,\n succeeded: exitCode === 0\n });\n });\n });\n}\n\nexport function formatVerificationFailurePrompt(\n result: VerificationCommandResult,\n options?: {\n maxOutputChars?: number;\n }\n): string {\n const maxOutputChars = options?.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n const sectionLimit = getSectionLimit(maxOutputChars);\n const stdout = tailText(result.stdout, sectionLimit);\n const stderr = tailText(result.stderr, sectionLimit);\n const lines = [\n \"Verification command failed.\",\n `Command: ${result.command}`,\n `Exit code: ${result.code}`\n ];\n\n if (stderr) {\n lines.push(\"\", \"stderr:\", stderr);\n }\n\n if (stdout) {\n lines.push(\"\", \"stdout:\", stdout);\n }\n\n return lines.join(\"\\n\").trim();\n}\n","import { waitForMatchingHookCapture, type HookCapture } from \"./hook-server.js\";\nimport type { RuntimeEventLogger } from \"./runtime-log.js\";\n\nexport interface HookEventWatcherOptions {\n cwd: string;\n eventNames: string[];\n logger: RuntimeEventLogger;\n onEvent?: (capture: HookCapture) => Promise<void> | void;\n runId: string;\n runStartedAt: number;\n signal?: AbortSignal;\n waitTimeoutMs?: number | null;\n unrefTimers?: boolean;\n}\n\nfunction isTimeoutError(error: unknown): boolean {\n return error instanceof Error && error.message.startsWith(\"Timed out waiting for \");\n}\n\nexport async function runHookEventWatcher(options: HookEventWatcherOptions): Promise<void> {\n const seenFilePaths = new Set<string>();\n options.logger.log(\"hook_event_watcher_started\", {\n eventNames: options.eventNames,\n runId: options.runId\n });\n\n while (!options.signal?.aborted) {\n let capture;\n\n try {\n capture = await waitForMatchingHookCapture({\n afterTimeMs: options.runStartedAt,\n cwd: options.cwd,\n eventNames: options.eventNames,\n runId: options.runId,\n seenFilePaths,\n timeoutMs: options.waitTimeoutMs ?? null,\n unrefTimers: options.unrefTimers\n });\n } catch (error) {\n if (options.signal?.aborted && isTimeoutError(error)) {\n break;\n }\n\n if (options.waitTimeoutMs !== undefined && options.waitTimeoutMs !== null && isTimeoutError(error)) {\n continue;\n }\n\n throw error;\n }\n\n options.logger.log(\"hook_event_matched\", {\n eventName: capture.payload?.hook_event_name ?? null,\n sessionId: capture.payload?.session_id ?? null,\n turnId: capture.payload?.turn_id ?? null\n });\n await options.onEvent?.(capture);\n }\n}\n","import fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nexport type CodexHooksScope = \"global\" | \"local\";\nexport type HookConfigHealth =\n | \"invalid\"\n | \"missing\"\n | \"missing-stop-hook\"\n | \"ready\"\n | \"stale-stop-hook\";\nexport type CodexHooksFeatureHealth = \"disabled\" | \"enabled\" | \"unknown\";\n\nexport interface HookConfigInspection {\n configuredHookPath: string | null;\n exists: boolean;\n health: HookConfigHealth;\n hookEvents: string[];\n matchesExpectedScript: boolean;\n missingHookEvents: string[];\n parseError: string | null;\n path: string;\n scope: CodexHooksScope;\n stopHookCommand: string | null;\n targetExists: boolean;\n}\n\nexport interface HookSetupInspection {\n activeConfig: HookConfigInspection | null;\n globalConfig: HookConfigInspection;\n globalPath: string;\n hookCommand: string;\n hookScriptPath: string;\n localConfig: HookConfigInspection;\n localPath: string;\n message: string;\n status: HookConfigHealth;\n}\n\nexport interface CodexHooksFeatureInspection {\n configPath: string;\n enabled: boolean | null;\n health: CodexHooksFeatureHealth;\n message: string;\n profile: string | null;\n}\n\ninterface HookConfigDocument {\n hooks?: Record<string, unknown>;\n}\n\nconst CODEX_FEATURE_FLAGS_WITH_VALUE = new Set([\n \"-c\",\n \"--config\",\n \"--disable\",\n \"--enable\",\n \"-p\",\n \"--profile\",\n \"-C\",\n \"--cd\"\n]);\nconst REQUIRED_HOOK_EVENTS = [\"SessionStart\", \"UserPromptSubmit\", \"Stop\"] as const;\n\nfunction shellEscape(argument: string): string {\n return `'${argument.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction readFileText(filePath: string): string | null {\n try {\n return fs.readFileSync(filePath, \"utf8\");\n } catch {\n return null;\n }\n}\n\nfunction extractStopHookPath(command: string | null): string | null {\n if (!command || !command.includes(\"stop-hook.cjs\")) {\n return null;\n }\n\n const singleQuotedMatch = command.match(/'([^']*stop-hook\\.cjs)'/u);\n\n if (singleQuotedMatch?.[1]) {\n return path.resolve(singleQuotedMatch[1]);\n }\n\n const doubleQuotedMatch = command.match(/\"([^\"]*stop-hook\\.cjs)\"/u);\n\n if (doubleQuotedMatch?.[1]) {\n return path.resolve(doubleQuotedMatch[1]);\n }\n\n const bareMatch = command.match(/(\\S*stop-hook\\.cjs)/u);\n\n if (bareMatch?.[1]) {\n return path.resolve(bareMatch[1]);\n }\n\n return null;\n}\n\nfunction findCodexBeeHookCommand(document: HookConfigDocument, eventName: string): string | null {\n const entries = document.hooks && typeof document.hooks === \"object\"\n ? (document.hooks as Record<string, unknown>)[eventName]\n : null;\n\n if (!Array.isArray(entries)) {\n return null;\n }\n\n for (const entry of entries) {\n if (!entry || typeof entry !== \"object\") {\n continue;\n }\n\n const hooks = (entry as {\n hooks?: unknown;\n }).hooks;\n\n if (!Array.isArray(hooks)) {\n continue;\n }\n\n for (const hook of hooks) {\n if (!hook || typeof hook !== \"object\") {\n continue;\n }\n\n const command = (hook as {\n command?: unknown;\n }).command;\n\n if (typeof command === \"string\" && command.includes(\"stop-hook.cjs\")) {\n return command;\n }\n }\n }\n\n return null;\n}\n\nfunction inspectHookConfigFile(options: {\n expectedHookText: string | null;\n hookCommand: string;\n path: string;\n scope: CodexHooksScope;\n}): HookConfigInspection {\n if (!fs.existsSync(options.path)) {\n return {\n configuredHookPath: null,\n exists: false,\n health: \"missing\",\n hookEvents: [],\n matchesExpectedScript: false,\n missingHookEvents: [...REQUIRED_HOOK_EVENTS],\n parseError: null,\n path: options.path,\n scope: options.scope,\n stopHookCommand: null,\n targetExists: false\n };\n }\n\n const rawText = readFileText(options.path);\n\n if (rawText === null) {\n return {\n configuredHookPath: null,\n exists: true,\n health: \"invalid\",\n hookEvents: [],\n matchesExpectedScript: false,\n missingHookEvents: [...REQUIRED_HOOK_EVENTS],\n parseError: `Unable to read ${options.path}.`,\n path: options.path,\n scope: options.scope,\n stopHookCommand: null,\n targetExists: false\n };\n }\n\n let parsed: HookConfigDocument;\n\n try {\n parsed = JSON.parse(rawText) as HookConfigDocument;\n } catch (error) {\n return {\n configuredHookPath: null,\n exists: true,\n health: \"invalid\",\n hookEvents: [],\n matchesExpectedScript: false,\n missingHookEvents: [...REQUIRED_HOOK_EVENTS],\n parseError: toErrorMessage(error),\n path: options.path,\n scope: options.scope,\n stopHookCommand: null,\n targetExists: false\n };\n }\n\n const hookEvents = REQUIRED_HOOK_EVENTS.filter((eventName) => findCodexBeeHookCommand(parsed, eventName) !== null);\n const missingHookEvents = REQUIRED_HOOK_EVENTS.filter((eventName) => !hookEvents.includes(eventName));\n const stopHookCommand =\n findCodexBeeHookCommand(parsed, \"SessionStart\")\n ?? findCodexBeeHookCommand(parsed, \"UserPromptSubmit\")\n ?? findCodexBeeHookCommand(parsed, \"Stop\");\n\n if (!stopHookCommand || missingHookEvents.length > 0) {\n return {\n configuredHookPath: null,\n exists: true,\n health: \"missing-stop-hook\",\n hookEvents,\n matchesExpectedScript: false,\n missingHookEvents,\n parseError: null,\n path: options.path,\n scope: options.scope,\n stopHookCommand,\n targetExists: false\n };\n }\n\n const configuredHookPath = extractStopHookPath(stopHookCommand);\n const targetExists = configuredHookPath !== null && fs.existsSync(configuredHookPath);\n const targetText = configuredHookPath ? readFileText(configuredHookPath) : null;\n const matchesExpectedScript = Boolean(\n targetExists\n && targetText !== null\n && options.expectedHookText !== null\n && targetText === options.expectedHookText\n );\n\n return {\n configuredHookPath,\n exists: true,\n health: targetExists && matchesExpectedScript\n ? \"ready\"\n : \"stale-stop-hook\",\n hookEvents,\n matchesExpectedScript,\n missingHookEvents,\n parseError: null,\n path: options.path,\n scope: options.scope,\n stopHookCommand,\n targetExists\n };\n}\n\nfunction describeHookStatus(activeConfig: HookConfigInspection | null): string {\n if (!activeConfig) {\n return \"No active Codex hooks config was found. codex-bee cannot receive SessionStart, UserPromptSubmit, or Stop events until its hook entries are installed.\";\n }\n\n const displayPath = activeConfig.path.replace(os.homedir(), \"~\");\n const scopeLabel = activeConfig.scope === \"local\" ? \"project-local\" : \"global\";\n\n switch (activeConfig.health) {\n case \"ready\":\n return `codex-bee hooks are ready via ${scopeLabel} config ${displayPath}. Waiting for SessionStart.`;\n case \"invalid\":\n return `The active ${scopeLabel} hooks config at ${displayPath} is not valid JSON, so codex-bee cannot trust it.`;\n case \"missing-stop-hook\":\n return activeConfig.missingHookEvents.length > 0\n ? `The active ${scopeLabel} hooks config at ${displayPath} is missing required codex-bee hook entries for ${activeConfig.missingHookEvents.join(\", \")}.`\n : `The active ${scopeLabel} hooks config at ${displayPath} does not include the required codex-bee hook entries.`;\n case \"stale-stop-hook\":\n return activeConfig.configuredHookPath && activeConfig.targetExists\n ? `The active ${scopeLabel} hooks config at ${displayPath} points to a stop hook that does not match the current codex-bee script.`\n : `The active ${scopeLabel} hooks config at ${displayPath} points to a missing or unreadable stop-hook.cjs target.`;\n default:\n return `The active ${scopeLabel} hooks config at ${displayPath} is missing.`;\n }\n}\n\nexport function buildStopHookCommand(hookScriptPath: string): string {\n return `node ${shellEscape(hookScriptPath)}`;\n}\n\nexport function getGlobalHooksConfigPath(homeDirectory = os.homedir()): string {\n return path.join(homeDirectory, \".codex\", \"hooks.json\");\n}\n\nexport function getGlobalCodexConfigPath(homeDirectory = os.homedir()): string {\n return path.join(homeDirectory, \".codex\", \"config.toml\");\n}\n\nexport function getLocalHooksConfigPath(cwd: string): string {\n return path.join(cwd, \".codex\", \"hooks.json\");\n}\n\nexport function collectCodexFeatureProbeArgs(commandArgs: readonly string[]): string[] {\n const probeArgs: string[] = [];\n\n for (let index = 0; index < commandArgs.length; index += 1) {\n const argument = commandArgs[index];\n\n if (!CODEX_FEATURE_FLAGS_WITH_VALUE.has(argument)) {\n continue;\n }\n\n const value = commandArgs[index + 1];\n\n if (value === undefined) {\n continue;\n }\n\n probeArgs.push(argument, value);\n index += 1;\n }\n\n return probeArgs;\n}\n\nexport function resolveCodexProfile(commandArgs: readonly string[]): string | null {\n for (let index = commandArgs.length - 1; index >= 0; index -= 1) {\n const argument = commandArgs[index];\n\n if (argument !== \"-p\" && argument !== \"--profile\") {\n continue;\n }\n\n const profile = commandArgs[index + 1];\n\n return profile ?? null;\n }\n\n return null;\n}\n\nfunction getFeatureTableHeader(profile: string | null): string {\n return profile ? `[profiles.${profile}.features]` : \"[features]\";\n}\n\nfunction replaceTomlKeyInTable(existingText: string | null, options: {\n header: string;\n key: string;\n value: string;\n}): string {\n const sourceText = existingText ?? \"\";\n const lines = sourceText.length > 0\n ? sourceText.split(/\\r?\\n/u)\n : [];\n const normalizedKeyPattern = new RegExp(`^\\\\s*${options.key}\\\\s*=`, \"u\");\n let tableStart = -1;\n let tableEnd = lines.length;\n\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index]?.trim();\n\n if (line === options.header) {\n tableStart = index;\n break;\n }\n }\n\n if (tableStart >= 0) {\n for (let index = tableStart + 1; index < lines.length; index += 1) {\n const line = lines[index]?.trim() ?? \"\";\n\n if (line.startsWith(\"[\") && line.endsWith(\"]\")) {\n tableEnd = index;\n break;\n }\n }\n\n for (let index = tableStart + 1; index < tableEnd; index += 1) {\n const line = lines[index];\n\n if (!line || !normalizedKeyPattern.test(line)) {\n continue;\n }\n\n lines[index] = `${options.key} = ${options.value}`;\n\n return `${lines.join(\"\\n\").replace(/\\n*$/u, \"\\n\")}`;\n }\n\n lines.splice(tableEnd, 0, `${options.key} = ${options.value}`);\n\n return `${lines.join(\"\\n\").replace(/\\n*$/u, \"\\n\")}`;\n }\n\n const prefix = sourceText.length > 0 && !sourceText.endsWith(\"\\n\")\n ? `${sourceText}\\n`\n : sourceText;\n const separator = prefix.trim().length > 0 ? \"\\n\" : \"\";\n\n return `${prefix}${separator}${options.header}\\n${options.key} = ${options.value}\\n`;\n}\n\nexport function inspectCodexHooksFeatureListOutput(options: {\n configPath?: string;\n output: string;\n profile?: string | null;\n}): CodexHooksFeatureInspection {\n const featureLine = options.output\n .split(/\\r?\\n/u)\n .map((line) => line.trim())\n .find((line) => line.startsWith(\"codex_hooks \"));\n const configPath = options.configPath ?? getGlobalCodexConfigPath();\n const profile = options.profile ?? null;\n\n if (!featureLine) {\n return {\n configPath,\n enabled: null,\n health: \"unknown\",\n message: \"Unable to determine the effective codex_hooks feature state from `codex features list`.\",\n profile\n };\n }\n\n const enabled = /\\btrue$/u.test(featureLine);\n const targetLabel = profile\n ? `profile \"${profile}\"`\n : \"global Codex config\";\n\n return {\n configPath,\n enabled,\n health: enabled ? \"enabled\" : \"disabled\",\n message: enabled\n ? `codex_hooks is enabled for the ${targetLabel}.`\n : `codex_hooks is disabled for the ${targetLabel}. codex-bee will not receive SessionStart, UserPromptSubmit, or Stop events until it is enabled.`,\n profile\n };\n}\n\nexport function upsertCodexHooksFeatureConfigText(existingText: string | null, profile: string | null): string {\n return replaceTomlKeyInTable(existingText, {\n header: getFeatureTableHeader(profile),\n key: \"codex_hooks\",\n value: \"true\"\n });\n}\n\nexport function inspectCodexHookSetup(options: {\n cwd: string;\n hookScriptPath: string;\n homeDirectory?: string;\n}): HookSetupInspection {\n const homeDirectory = options.homeDirectory ?? os.homedir();\n const localPath = getLocalHooksConfigPath(options.cwd);\n const globalPath = getGlobalHooksConfigPath(homeDirectory);\n const hookCommand = buildStopHookCommand(options.hookScriptPath);\n const expectedHookText = readFileText(options.hookScriptPath);\n const localConfig = inspectHookConfigFile({\n expectedHookText,\n hookCommand,\n path: localPath,\n scope: \"local\"\n });\n const globalConfig = inspectHookConfigFile({\n expectedHookText,\n hookCommand,\n path: globalPath,\n scope: \"global\"\n });\n const activeConfig = localConfig.exists\n ? localConfig\n : globalConfig.exists\n ? globalConfig\n : null;\n const status = activeConfig?.health ?? \"missing\";\n\n return {\n activeConfig,\n globalConfig,\n globalPath,\n hookCommand,\n hookScriptPath: options.hookScriptPath,\n localConfig,\n localPath,\n message: describeHookStatus(activeConfig),\n status\n };\n}\n\nexport function upsertStopHookConfigText(existingText: string | null, hookScriptPath: string): string {\n let document: HookConfigDocument = {};\n\n if (existingText) {\n document = JSON.parse(existingText) as HookConfigDocument;\n }\n\n if (!document || typeof document !== \"object\" || Array.isArray(document)) {\n document = {};\n }\n\n const hooks = document.hooks && typeof document.hooks === \"object\" && !Array.isArray(document.hooks)\n ? { ...(document.hooks as Record<string, unknown>) }\n : {};\n const hookCommand = buildStopHookCommand(hookScriptPath);\n const nextHooks = { ...hooks };\n\n for (const eventName of REQUIRED_HOOK_EVENTS) {\n const eventEntries = Array.isArray(nextHooks[eventName])\n ? [...(nextHooks[eventName] as unknown[])]\n : [];\n let replaced = false;\n\n const nextEntries = eventEntries.map((entry) => {\n if (!entry || typeof entry !== \"object\") {\n return entry;\n }\n\n const hooksList = (entry as {\n hooks?: unknown;\n }).hooks;\n\n if (!Array.isArray(hooksList)) {\n return entry;\n }\n\n const nextHooksList = hooksList.map((hook) => {\n if (!hook || typeof hook !== \"object\") {\n return hook;\n }\n\n const command = (hook as {\n command?: unknown;\n }).command;\n\n if (typeof command !== \"string\" || !command.includes(\"stop-hook.cjs\")) {\n return hook;\n }\n\n replaced = true;\n\n return {\n ...hook,\n command: hookCommand,\n timeout: 30,\n type: \"command\"\n };\n });\n\n return {\n ...entry,\n hooks: nextHooksList\n };\n });\n\n if (!replaced) {\n nextEntries.push({\n hooks: [\n {\n command: hookCommand,\n timeout: 30,\n type: \"command\"\n }\n ]\n });\n }\n\n nextHooks[eventName] = nextEntries;\n }\n\n return `${JSON.stringify({\n ...document,\n hooks: nextHooks\n }, null, 2)}\\n`;\n}\n\nexport function writeHookConfigFile(filePath: string, content: string): void {\n fs.mkdirSync(path.dirname(filePath), {\n recursive: true\n });\n fs.writeFileSync(filePath, content, \"utf8\");\n}\n\nexport function writeCodexConfigFile(filePath: string, content: string): void {\n fs.mkdirSync(path.dirname(filePath), {\n recursive: true\n });\n fs.writeFileSync(filePath, content, \"utf8\");\n}\n","import { spawn, type ChildProcess, type SpawnOptions } from \"node:child_process\";\n\nexport interface PassthroughModeOptions {\n hasContinuation: boolean;\n stdinIsTTY: boolean | undefined;\n stdoutIsTTY: boolean | undefined;\n}\n\nexport interface PassthroughRunOptions {\n args: string[];\n command: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n spawnImpl?: (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess;\n}\n\nexport function resolveExecutionMode(options: PassthroughModeOptions): \"interactive\" | \"passthrough\" {\n if (options.stdinIsTTY && options.stdoutIsTTY) {\n return \"interactive\";\n }\n\n if (options.hasContinuation) {\n throw new Error(\"auto-continue requires both stdin and stdout to be TTYs. Run `bee codex ...` from an interactive terminal.\");\n }\n\n return \"passthrough\";\n}\n\nexport function runPassthroughCommand(options: PassthroughRunOptions): Promise<number> {\n const spawnImpl = options.spawnImpl ?? spawn;\n\n return new Promise<number>((resolve, reject) => {\n const child = spawnImpl(options.command, options.args, {\n cwd: options.cwd,\n env: options.env,\n stdio: \"inherit\"\n }) as ChildProcess;\n\n child.once(\"error\", (error) => {\n reject(error);\n });\n\n child.once(\"exit\", (code, signal) => {\n if (signal) {\n resolve(1);\n return;\n }\n\n resolve(code ?? 0);\n });\n });\n}\n","import { readFile, readlink } from \"node:fs/promises\";\nimport { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport process from \"node:process\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nexport interface PtyProxyOptions {\n command: string;\n commandArgs: string[];\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n}\n\ntype InputInterceptor = (chunk: Buffer | string) => boolean;\n\ninterface TerminalSize {\n columns: number;\n rows: number;\n}\n\nconst BRACKETED_PASTE_END = \"\\u001b[201~\";\nconst BRACKETED_PASTE_START = \"\\u001b[200~\";\nconst CLEAR_SCROLLBACK_SEQUENCE = \"\\u001b[3J\";\n\nfunction shellEscape(argument: string): string {\n return `'${argument.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nfunction resolveTerminalSize(): TerminalSize {\n const columns = process.stdout.columns && process.stdout.columns > 0\n ? process.stdout.columns\n : 80;\n const rows = process.stdout.rows && process.stdout.rows > 0\n ? process.stdout.rows\n : 24;\n\n return { columns, rows };\n}\n\nfunction buildWrappedProcessCommand(command: string, commandArgs: string[]): string {\n return [command, ...commandArgs].map(shellEscape).join(\" \");\n}\n\nfunction buildWrappedCommand(command: string, commandArgs: string[], terminalSize: TerminalSize): string {\n const wrappedCommand = buildWrappedProcessCommand(command, commandArgs);\n const rows = String(terminalSize.rows);\n const columns = String(terminalSize.columns);\n\n return [\n `stty rows ${rows} cols ${columns} >/dev/null 2>&1`,\n `export LINES=${rows}`,\n `export COLUMNS=${columns}`,\n `exec ${wrappedCommand}`\n ].join(\"; \");\n}\n\nexport function formatBracketedPaste(prompt: string): string {\n return `${BRACKETED_PASTE_START}${prompt}${BRACKETED_PASTE_END}`;\n}\n\nfunction createInteractiveError(message: string): Error {\n return new Error(`codex-bee interactive wrapper error: ${message}`);\n}\n\nfunction sanitizeTerminalOutput(chunk: Buffer): Buffer {\n const text = chunk.toString(\"utf8\");\n\n if (!text.includes(CLEAR_SCROLLBACK_SEQUENCE)) {\n return chunk;\n }\n\n return Buffer.from(text.replaceAll(CLEAR_SCROLLBACK_SEQUENCE, \"\"), \"utf8\");\n}\n\nexport class PtyProxy {\n readonly #options: PtyProxyOptions;\n #bufferedStderrChunks: Buffer[] = [];\n #bufferedStdoutChunks: Buffer[] = [];\n #child: ChildProcessWithoutNullStreams | null = null;\n #exitPromise: Promise<number> | null = null;\n #cleanupCallbacks: Array<() => void> = [];\n #terminalSize: TerminalSize | null = null;\n #childTtyPath: string | null = null;\n #inputInterceptor: InputInterceptor | null = null;\n #outputMuted = false;\n #windowSyncInFlight = false;\n\n constructor(options: PtyProxyOptions) {\n this.#options = options;\n }\n\n async start(): Promise<void> {\n if (this.#child) {\n throw createInteractiveError(\"PTY proxy already started.\");\n }\n\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n throw createInteractiveError(\"interactive mode requires both stdin and stdout to be TTYs.\");\n }\n\n if (process.platform !== \"linux\") {\n throw createInteractiveError(\"the current PTY prototype supports Linux only.\");\n }\n\n this.#terminalSize = resolveTerminalSize();\n\n const command = buildWrappedCommand(this.#options.command, this.#options.commandArgs, this.#terminalSize);\n const child = spawn(\"script\", [\"-qfc\", command, \"/dev/null\"], {\n cwd: this.#options.cwd ?? process.cwd(),\n env: this.#options.env ?? process.env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"]\n });\n\n this.#child = child;\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n const normalizedChunk = sanitizeTerminalOutput(chunk);\n\n if (this.#outputMuted) {\n this.#bufferedStdoutChunks.push(Buffer.from(normalizedChunk));\n return;\n }\n\n process.stdout.write(normalizedChunk);\n });\n\n child.stderr.on(\"data\", (chunk: Buffer) => {\n const normalizedChunk = sanitizeTerminalOutput(chunk);\n\n if (this.#outputMuted) {\n this.#bufferedStderrChunks.push(Buffer.from(normalizedChunk));\n return;\n }\n\n process.stderr.write(normalizedChunk);\n });\n\n const handleInput = (chunk: Buffer | string) => {\n if (this.#inputInterceptor?.(chunk)) {\n return;\n }\n\n child.stdin.write(chunk);\n };\n\n process.stdin.resume();\n process.stdin.setRawMode(true);\n process.stdin.on(\"data\", handleInput);\n\n this.#cleanupCallbacks.push(() => {\n process.stdin.off(\"data\", handleInput);\n process.stdin.setRawMode(false);\n process.stdin.pause();\n });\n\n const handleResize = () => {\n this.#terminalSize = resolveTerminalSize();\n void this.#syncWindowSize();\n\n if (!child.pid) {\n return;\n }\n\n try {\n process.kill(child.pid, \"SIGWINCH\");\n } catch {\n // Ignore resize propagation failures during shutdown.\n }\n };\n\n process.on(\"SIGWINCH\", handleResize);\n this.#cleanupCallbacks.push(() => {\n process.off(\"SIGWINCH\", handleResize);\n });\n\n void this.#syncWindowSize();\n\n this.#exitPromise = new Promise<number>((resolve, reject) => {\n child.once(\"error\", (error) => {\n this.#cleanup();\n\n if (\"code\" in error && error.code === \"ENOENT\") {\n reject(createInteractiveError(\"`script` command was not found on this machine.\"));\n return;\n }\n\n reject(error);\n });\n\n child.once(\"exit\", (code, signal) => {\n this.#cleanup();\n\n if (signal) {\n resolve(1);\n return;\n }\n\n resolve(code ?? 0);\n });\n });\n }\n\n write(data: string): void {\n if (!this.#child) {\n throw createInteractiveError(\"cannot write before the PTY proxy starts.\");\n }\n\n this.#child.stdin.write(data);\n }\n\n setInputInterceptor(inputInterceptor: InputInterceptor | null): void {\n this.#inputInterceptor = inputInterceptor;\n }\n\n setOutputMuted(muted: boolean): void {\n if (this.#outputMuted === muted) {\n return;\n }\n\n this.#outputMuted = muted;\n\n if (muted) {\n return;\n }\n\n for (const chunk of this.#bufferedStdoutChunks.splice(0, this.#bufferedStdoutChunks.length)) {\n process.stdout.write(chunk);\n }\n\n for (const chunk of this.#bufferedStderrChunks.splice(0, this.#bufferedStderrChunks.length)) {\n process.stderr.write(chunk);\n }\n }\n\n async injectPrompt(prompt: string, options?: {\n submitDelayMs?: number;\n }): Promise<void> {\n const submitDelayMs = options?.submitDelayMs ?? 75;\n\n // Sending the prompt as bracketed paste keeps multiline content intact without early submits.\n this.write(formatBracketedPaste(prompt));\n await delay(submitDelayMs);\n this.write(\"\\r\");\n }\n\n async stop(signal: NodeJS.Signals = \"SIGTERM\"): Promise<void> {\n if (!this.#child || !this.#exitPromise) {\n return;\n }\n\n if (this.#child.exitCode === null && !this.#child.killed) {\n this.#child.kill(signal);\n }\n\n await this.#exitPromise.catch(() => undefined);\n }\n\n requestRedraw(): void {\n if (!this.#child || !this.#child.pid) {\n return;\n }\n\n void this.#syncWindowSize();\n this.write(\"\\f\");\n\n try {\n process.kill(this.#child.pid, \"SIGWINCH\");\n } catch {\n // Ignore redraw propagation failures during shutdown.\n }\n }\n\n waitForExit(): Promise<number> {\n if (!this.#exitPromise) {\n throw createInteractiveError(\"cannot wait for exit before the PTY proxy starts.\");\n }\n\n return this.#exitPromise;\n }\n\n #cleanup(): void {\n const callbacks = this.#cleanupCallbacks.splice(0, this.#cleanupCallbacks.length);\n\n for (const callback of callbacks.reverse()) {\n callback();\n }\n }\n\n async #syncWindowSize(): Promise<void> {\n if (this.#windowSyncInFlight) {\n return;\n }\n\n const childPid = this.#child?.pid;\n const terminalSize = this.#terminalSize;\n\n if (!childPid || !terminalSize) {\n return;\n }\n\n this.#windowSyncInFlight = true;\n\n try {\n const ttyPath = await this.#resolveChildTtyPath(childPid);\n\n if (!ttyPath) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n const resizeProcess = spawn(\n \"stty\",\n [\"-F\", ttyPath, \"rows\", String(terminalSize.rows), \"cols\", String(terminalSize.columns)],\n {\n stdio: \"ignore\"\n }\n );\n\n resizeProcess.once(\"error\", () => {\n resolve();\n });\n\n resizeProcess.once(\"exit\", () => {\n resolve();\n });\n });\n } finally {\n this.#windowSyncInFlight = false;\n }\n }\n\n async #resolveChildTtyPath(rootPid: number): Promise<string | null> {\n if (this.#childTtyPath) {\n return this.#childTtyPath;\n }\n\n const queue = await readProcessChildren(rootPid);\n const seen = new Set<number>(queue);\n\n while (queue.length > 0) {\n const candidatePid = queue.shift();\n\n if (!candidatePid) {\n continue;\n }\n\n const ttyPath = await readProcessTtyPath(candidatePid);\n\n if (ttyPath) {\n this.#childTtyPath = ttyPath;\n return ttyPath;\n }\n\n const children = await readProcessChildren(candidatePid);\n\n for (const childPid of children) {\n if (seen.has(childPid)) {\n continue;\n }\n\n seen.add(childPid);\n queue.push(childPid);\n }\n }\n\n return null;\n }\n}\n\nasync function readProcessChildren(pid: number): Promise<number[]> {\n try {\n const children = await readFile(`/proc/${pid}/task/${pid}/children`, \"utf8\");\n\n return children\n .trim()\n .split(/\\s+/u)\n .filter(Boolean)\n .map((value) => Number.parseInt(value, 10))\n .filter((value) => Number.isInteger(value) && value > 0);\n } catch {\n return [];\n }\n}\n\nasync function readProcessTtyPath(pid: number): Promise<string | null> {\n try {\n const ttyPath = await readlink(`/proc/${pid}/fd/0`);\n\n return ttyPath.startsWith(\"/dev/pts/\") ? ttyPath : null;\n } catch {\n return null;\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface RuntimeEventLogger {\n log(eventType: string, data?: Record<string, unknown>): void;\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function createRuntimeEventLogger(cwd: string, options: {\n runId: string;\n}): RuntimeEventLogger {\n const tempRoot = path.join(cwd, \".codex\", \"tmp\");\n const logPath = path.join(tempRoot, \"bee-events.jsonl\");\n let sequence = 0;\n\n return {\n log(eventType, data) {\n try {\n fs.mkdirSync(tempRoot, {\n recursive: true\n });\n fs.appendFileSync(\n logPath,\n `${JSON.stringify({\n data: data ?? {},\n eventType,\n runId: options.runId,\n sequence: sequence += 1,\n timestamp: new Date().toISOString()\n })}\\n`,\n \"utf8\"\n );\n } catch (error) {\n console.error(`[codex-bee] Failed to write runtime event log: ${toErrorMessage(error)}`);\n }\n }\n };\n}\n","import type { UiCommandId, UiCommandInvocation } from \"./types.js\";\n\nconst SLEEP_INPUT_PATTERN = /^(\\d{1,2}):(\\d{2})$/;\n\nexport interface UiSlashCommandDefinition {\n description: string;\n id: UiCommandId;\n name: string;\n placeholder: string | null;\n}\n\nexport interface UiSlashCommandParseError {\n error: string;\n}\n\nexport const UI_SLASH_COMMANDS: UiSlashCommandDefinition[] = [\n {\n description: \"Set session duration\",\n id: \"duration\",\n name: \"/duration\",\n placeholder: \"<minutes>\"\n },\n {\n description: \"Set absolute stop time\",\n id: \"sleep\",\n name: \"/sleep\",\n placeholder: \"<HH:MM>\"\n },\n {\n description: \"Set max turns count\",\n id: \"steps-count\",\n name: \"/steps-count\",\n placeholder: \"<number>\"\n },\n {\n description: \"Set post-turn hook script\",\n id: \"stop-script\",\n name: \"/stop-script\",\n placeholder: \"<command>\"\n },\n {\n description: \"Clear log output\",\n id: \"clear-log\",\n name: \"/clear-log\",\n placeholder: null\n },\n {\n description: \"Exit codex-bee\",\n id: \"quit\",\n name: \"/quit\",\n placeholder: null\n }\n];\n\nfunction parsePositiveInteger(value: string, label: string): number | UiSlashCommandParseError {\n const parsedValue = Number.parseInt(value.trim(), 10);\n\n if (!Number.isFinite(parsedValue) || parsedValue < 1) {\n return {\n error: `${label} must be a positive integer.`\n };\n }\n\n return parsedValue;\n}\n\nexport function filterSlashCommands(query: string): UiSlashCommandDefinition[] {\n const normalizedQuery = query.trim().toLowerCase();\n\n if (!normalizedQuery) {\n return [...UI_SLASH_COMMANDS];\n }\n\n return UI_SLASH_COMMANDS.filter((command) => command.name.slice(1).startsWith(normalizedQuery));\n}\n\nexport function findSlashCommandById(id: UiCommandId): UiSlashCommandDefinition | undefined {\n return UI_SLASH_COMMANDS.find((command) => command.id === id);\n}\n\nexport function getSlashQuery(composerText: string): string | null {\n if (!composerText.startsWith(\"/\") || composerText.includes(\"\\n\")) {\n return null;\n }\n\n const trailingText = composerText.slice(1);\n\n if (/\\s/.test(trailingText)) {\n return null;\n }\n\n return trailingText.toLowerCase();\n}\n\nexport function isSlashCommandInput(value: string): boolean {\n return value.trimStart().startsWith(\"/\");\n}\n\nexport function parseSlashCommandInput(value: string): UiCommandInvocation | UiSlashCommandParseError {\n const trimmedValue = value.trim();\n\n if (!trimmedValue.startsWith(\"/\")) {\n return {\n error: \"Commands must start with '/'.\"\n };\n }\n\n const [name, ...argumentParts] = trimmedValue.split(/\\s+/);\n const argument = argumentParts.join(\" \").trim();\n\n switch (name) {\n case \"/duration\": {\n if (!argument) {\n return {\n error: \"/duration requires <minutes>.\"\n };\n }\n\n const parsedMinutes = parsePositiveInteger(argument, \"Duration\");\n\n if (typeof parsedMinutes !== \"number\") {\n return parsedMinutes;\n }\n\n return {\n id: \"duration\",\n minutes: parsedMinutes,\n raw: trimmedValue\n };\n }\n case \"/sleep\": {\n if (!argument) {\n return {\n error: \"/sleep requires <HH:MM>.\"\n };\n }\n\n const match = argument.match(SLEEP_INPUT_PATTERN);\n\n if (!match) {\n return {\n error: \"/sleep expects a 24-hour time like 23:15.\"\n };\n }\n\n const hours = Number.parseInt(match[1], 10);\n const minutes = Number.parseInt(match[2], 10);\n\n if (hours > 23 || minutes > 59) {\n return {\n error: \"/sleep expects a 24-hour time like 23:15.\"\n };\n }\n\n return {\n hours,\n id: \"sleep\",\n minutes,\n raw: trimmedValue,\n time: `${String(hours).padStart(2, \"0\")}:${String(minutes).padStart(2, \"0\")}`\n };\n }\n case \"/steps-count\": {\n if (!argument) {\n return {\n error: \"/steps-count requires <number>.\"\n };\n }\n\n const parsedSteps = parsePositiveInteger(argument, \"Steps count\");\n\n if (typeof parsedSteps !== \"number\") {\n return parsedSteps;\n }\n\n return {\n id: \"steps-count\",\n raw: trimmedValue,\n steps: parsedSteps\n };\n }\n case \"/stop-script\":\n if (!argument) {\n return {\n error: \"/stop-script requires <command>.\"\n };\n }\n\n return {\n command: argument,\n id: \"stop-script\",\n raw: trimmedValue\n };\n case \"/clear-log\":\n return {\n id: \"clear-log\",\n raw: trimmedValue\n };\n case \"/quit\":\n return {\n id: \"quit\",\n raw: trimmedValue\n };\n default:\n return {\n error: `Unknown command: ${name}`\n };\n }\n}\n","export type UiMode = \"agent\" | \"off\" | \"static\" | \"thinking\";\nexport type UiVisibleScreen = \"bee\" | \"codex\";\nexport type UiConnectionState = \"connected\" | \"disconnected\" | \"ready\";\nexport type UiRunState = \"idle\" | \"running\";\nexport type UiLogEntryKind = \"hook\" | \"model\" | \"status\" | \"summary\" | \"user\";\nexport type UiNoticeKind = \"error\" | \"info\" | \"warning\";\nexport type UiCommandId = \"clear-log\" | \"duration\" | \"quit\" | \"sleep\" | \"steps-count\" | \"stop-script\";\n\nexport const UI_MODES: UiMode[] = [\"off\", \"static\"];\n\nexport interface UiAnnouncement {\n message: string;\n}\n\nexport interface UiHookStatus {\n code: number;\n ok: boolean;\n}\n\nexport interface UiLogEntry {\n id: string;\n kind: UiLogEntryKind;\n text: string;\n timestamp: number;\n}\n\nexport interface UiTurnGroup {\n durationMs: number | null;\n entries: UiLogEntry[];\n id: string;\n totalTurns: number | null;\n turn: number;\n}\n\nexport interface UiSessionInfo {\n currentTurn: number | null;\n hookStatus: UiHookStatus | null;\n stopAt: number | null;\n stopScript: string | null;\n totalTurns: number | null;\n}\n\nexport interface UiWorkspaceInfo {\n ahead: number;\n behind: number;\n cwd: string;\n gitBranch: string;\n}\n\nexport interface UiRuntimeSnapshot {\n activeScenarioId: string | null;\n announcement: UiAnnouncement | null;\n beeVersion: string;\n codexBufferLines: string[];\n codexVersion: string;\n connectionState: UiConnectionState;\n logs: UiTurnGroup[];\n prompts: Record<UiMode, string>;\n runState: UiRunState;\n session: UiSessionInfo;\n workspace: UiWorkspaceInfo;\n}\n\nexport interface UiScenarioOption {\n description: string;\n id: string;\n label: string;\n}\n\nexport interface UiNotice {\n expiresInMs?: number;\n id: number;\n kind: UiNoticeKind;\n message: string;\n}\n\nexport interface UiDropdownState {\n interacted: boolean;\n open: boolean;\n selectedIndex: number;\n}\n\nexport interface UiState {\n activeMode: UiMode;\n composerCursorOffset: number;\n composerText: string;\n currentScreen: UiVisibleScreen;\n dropdown: UiDropdownState;\n exitRequested: boolean;\n isInitialized: boolean;\n notice: UiNotice | null;\n runtime: UiRuntimeSnapshot;\n scenarios: UiScenarioOption[];\n}\n\nexport type UiCommandInvocation =\n | {\n id: \"clear-log\";\n raw: string;\n }\n | {\n id: \"duration\";\n minutes: number;\n raw: string;\n }\n | {\n id: \"quit\";\n raw: string;\n }\n | {\n hours: number;\n id: \"sleep\";\n minutes: number;\n raw: string;\n time: string;\n }\n | {\n id: \"steps-count\";\n raw: string;\n steps: number;\n }\n | {\n command: string;\n id: \"stop-script\";\n raw: string;\n };\n\nexport type UiIntent =\n | {\n text: string;\n type: \"appendInput\";\n }\n | {\n type: \"backspace\";\n }\n | {\n type: \"clearExitRequest\";\n }\n | {\n type: \"closeDropdown\";\n }\n | {\n type: \"cycleMode\";\n }\n | {\n type: \"dismissNotice\";\n }\n | {\n type: \"insertNewline\";\n }\n | {\n offset: number;\n type: \"setComposerCursorOffset\";\n }\n | {\n text: string;\n type: \"pasteInput\";\n }\n | {\n type: \"refreshFromRuntime\";\n }\n | {\n scenarioId: string;\n type: \"selectScenario\";\n }\n | {\n type: \"selectNextCommand\";\n }\n | {\n type: \"selectPreviousCommand\";\n }\n | {\n type: \"showExitHint\";\n }\n | {\n type: \"submitComposer\";\n }\n | {\n type: \"toggleScreen\";\n };\n","import { filterSlashCommands, parseSlashCommandInput, getSlashQuery } from \"./commands.js\";\nimport { UI_MODES } from \"./types.js\";\nimport type {\n UiNotice,\n UiIntent,\n UiMode,\n UiRuntimeSnapshot,\n UiScenarioOption,\n UiState\n} from \"./types.js\";\nimport type { UiHostUpdate, UiRuntimeHost } from \"../runtime/types.js\";\n\ntype Listener = () => void;\n\nfunction clampCodepointOffset(value: string, offset: number): number {\n return Math.max(0, Math.min(offset, Array.from(value).length));\n}\n\nfunction replaceRangeAtCodepointOffset(\n value: string,\n startOffset: number,\n endOffset: number,\n replacement: string\n): {\n nextOffset: number;\n nextValue: string;\n} {\n const codepoints = Array.from(value);\n const replacementCodepoints = Array.from(replacement);\n const clampedStartOffset = clampCodepointOffset(value, startOffset);\n const clampedEndOffset = clampCodepointOffset(value, endOffset);\n const nextValue = [\n ...codepoints.slice(0, clampedStartOffset),\n ...replacementCodepoints,\n ...codepoints.slice(clampedEndOffset)\n ].join(\"\");\n\n return {\n nextOffset: clampedStartOffset + replacementCodepoints.length,\n nextValue\n };\n}\n\nfunction stripTrailingSlashMarkers(value: string): string {\n return value\n .split(\"\\n\")\n .map((line) => line.replace(/\\s*\\/\\s*$/u, \"\"))\n .join(\"\\n\");\n}\n\nfunction createDefaultRuntimeSnapshot(): UiRuntimeSnapshot {\n return {\n activeScenarioId: null,\n announcement: null,\n beeVersion: \"0.1.0\",\n codexBufferLines: [\n \"$ codex mock session booted\",\n \"Waiting for codex-bee to hand control back.\"\n ],\n codexVersion: \"0.118.0\",\n connectionState: \"connected\",\n logs: [],\n prompts: {\n off: \"Off mode is passive. Codex-bee keeps collecting turn stats and logs, but it will not stage or inject prompts.\",\n agent: \"Agent mode placeholder. Dynamic planning will be wired later.\",\n static: \"continue\",\n thinking: \"Thinking mode placeholder. Bee reasoning controls will land later.\"\n },\n runState: \"idle\",\n session: {\n currentTurn: 0,\n hookStatus: {\n code: 0,\n ok: true\n },\n stopAt: null,\n stopScript: \"pnpm test\",\n totalTurns: null\n },\n workspace: {\n ahead: 2,\n behind: 0,\n cwd: \"~/projects/codex-bee\",\n gitBranch: \"main\"\n }\n };\n}\n\nfunction createInitialState(): UiState {\n return {\n activeMode: \"off\",\n composerCursorOffset: 0,\n composerText: \"\",\n currentScreen: \"bee\",\n dropdown: {\n interacted: false,\n open: false,\n selectedIndex: 0\n },\n exitRequested: false,\n isInitialized: false,\n notice: null,\n runtime: createDefaultRuntimeSnapshot(),\n scenarios: []\n };\n}\n\nfunction cloneRuntimeSnapshot(snapshot: UiRuntimeSnapshot): UiRuntimeSnapshot {\n return {\n ...snapshot,\n announcement: snapshot.announcement\n ? {\n ...snapshot.announcement\n }\n : null,\n codexBufferLines: [...snapshot.codexBufferLines],\n logs: snapshot.logs.map((group) => ({\n ...group,\n entries: group.entries.map((entry) => ({\n ...entry\n }))\n })),\n prompts: {\n ...snapshot.prompts\n },\n session: {\n ...snapshot.session,\n hookStatus: snapshot.session.hookStatus\n ? {\n ...snapshot.session.hookStatus\n }\n : null\n },\n workspace: {\n ...snapshot.workspace\n }\n };\n}\n\nexport class UiController {\n readonly #host: UiRuntimeHost;\n readonly #listeners = new Set<Listener>();\n #didInitialize = false;\n #hostUnsubscribe: (() => void) | null = null;\n #noticeCounter = 0;\n #state = createInitialState();\n\n constructor(host: UiRuntimeHost) {\n this.#host = host;\n }\n\n async dispatch(intent: UiIntent): Promise<void> {\n switch (intent.type) {\n case \"appendInput\":\n this.#replaceComposerRange(\n this.#state.composerCursorOffset,\n this.#state.composerCursorOffset,\n intent.text\n );\n return;\n case \"backspace\":\n if (this.#state.currentScreen !== \"bee\" || this.#state.composerCursorOffset === 0) {\n this.#clearNotice();\n return;\n }\n\n this.#replaceComposerRange(\n this.#state.composerCursorOffset - 1,\n this.#state.composerCursorOffset,\n \"\"\n );\n return;\n case \"clearExitRequest\":\n this.#setState({\n exitRequested: false\n });\n return;\n case \"closeDropdown\":\n this.#setState({\n dropdown: {\n interacted: false,\n open: false,\n selectedIndex: 0\n },\n notice: null\n });\n return;\n case \"cycleMode\":\n await this.#cycleMode();\n return;\n case \"dismissNotice\":\n this.#setState({\n notice: null\n });\n return;\n case \"insertNewline\":\n if (this.#state.currentScreen !== \"bee\") {\n this.#clearNotice();\n return;\n }\n\n this.#replaceComposerRange(\n this.#state.composerCursorOffset,\n this.#state.composerCursorOffset,\n \"\\n\"\n );\n return;\n case \"setComposerCursorOffset\":\n if (this.#state.currentScreen !== \"bee\") {\n this.#clearNotice();\n return;\n }\n\n this.#setState({\n composerCursorOffset: clampCodepointOffset(this.#state.composerText, intent.offset),\n notice: null\n });\n return;\n case \"pasteInput\":\n if (this.#state.currentScreen !== \"bee\") {\n this.#clearNotice();\n return;\n }\n\n this.#replaceComposerRange(\n this.#state.composerCursorOffset,\n this.#state.composerCursorOffset,\n intent.text\n );\n return;\n case \"refreshFromRuntime\":\n await this.#refreshState();\n return;\n case \"selectScenario\":\n await this.#selectScenario(intent.scenarioId);\n return;\n case \"selectNextCommand\":\n this.#moveCommandSelection(1);\n return;\n case \"selectPreviousCommand\":\n this.#moveCommandSelection(-1);\n return;\n case \"showExitHint\":\n this.#setState({\n notice: this.#createNotice({\n kind: \"warning\",\n message: \"Ctrl+B to exit\"\n })\n });\n return;\n case \"submitComposer\":\n await this.#submitComposer();\n return;\n case \"toggleScreen\":\n this.#setState({\n currentScreen: this.#state.currentScreen === \"bee\" ? \"codex\" : \"bee\",\n notice: null\n });\n return;\n default:\n return;\n }\n }\n\n getState(): UiState {\n return {\n ...this.#state,\n dropdown: {\n ...this.#state.dropdown\n },\n notice: this.#state.notice\n ? {\n ...this.#state.notice\n }\n : null,\n runtime: cloneRuntimeSnapshot(this.#state.runtime),\n scenarios: this.#state.scenarios.map((scenario) => ({\n ...scenario\n }))\n };\n }\n\n async initialize(): Promise<void> {\n if (this.#didInitialize) {\n return;\n }\n\n this.#didInitialize = true;\n this.#hostUnsubscribe = this.#host.subscribe?.(() => {\n void this.#refreshState();\n }) ?? null;\n await this.#refreshState();\n }\n\n subscribe(listener: Listener): () => void {\n this.#listeners.add(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #applyHostUpdate(update: UiHostUpdate, options?: {\n clearComposer?: boolean;\n }): void {\n this.#state = {\n ...this.#state,\n composerText: options?.clearComposer ? \"\" : this.#state.composerText,\n composerCursorOffset: options?.clearComposer ? 0 : this.#state.composerCursorOffset,\n dropdown: {\n interacted: false,\n open: false,\n selectedIndex: 0\n },\n exitRequested: update.exitRequested ?? this.#state.exitRequested,\n isInitialized: true,\n notice: update.notice ? this.#createNotice(update.notice) : null,\n runtime: cloneRuntimeSnapshot(update.snapshot)\n };\n this.#notify();\n }\n\n #clearNotice(): void {\n if (!this.#state.notice) {\n return;\n }\n\n this.#setState({\n notice: null\n });\n }\n\n #createNotice(notice: Omit<UiNotice, \"id\">): UiNotice {\n this.#noticeCounter += 1;\n\n return {\n ...notice,\n id: this.#noticeCounter\n };\n }\n\n #getNextMode(currentMode: UiMode): UiMode {\n const currentIndex = UI_MODES.indexOf(currentMode);\n const nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % UI_MODES.length;\n\n return UI_MODES[nextIndex] ?? \"off\";\n }\n\n async #cycleMode(): Promise<void> {\n const nextMode = this.#getNextMode(this.#state.activeMode);\n\n if (this.#host.setMode) {\n const update = await this.#host.setMode(nextMode);\n\n this.#state = {\n ...this.#state,\n activeMode: nextMode\n };\n this.#applyHostUpdate(update);\n return;\n }\n\n this.#setState({\n activeMode: nextMode,\n notice: null\n });\n }\n\n #moveCommandSelection(direction: 1 | -1): void {\n if (!this.#state.dropdown.open) {\n return;\n }\n\n const visibleCommands = filterSlashCommands(getSlashQuery(this.#state.composerText) ?? \"\");\n\n if (visibleCommands.length === 0) {\n this.#setState({\n notice: null\n });\n return;\n }\n\n const nextIndex = Math.max(\n 0,\n Math.min(visibleCommands.length - 1, this.#state.dropdown.selectedIndex + direction)\n );\n\n this.#setState({\n dropdown: {\n interacted: true,\n open: true,\n selectedIndex: nextIndex\n },\n notice: null\n });\n }\n\n async #refreshState(options?: {\n notice?: Omit<UiNotice, \"id\"> | null;\n }): Promise<void> {\n const snapshot = await this.#host.getSnapshot();\n const scenarios = this.#host.listScenarios\n ? await this.#host.listScenarios()\n : this.#state.scenarios;\n\n this.#state = {\n ...this.#state,\n isInitialized: true,\n notice: options?.notice ? this.#createNotice(options.notice) : this.#state.notice,\n runtime: cloneRuntimeSnapshot(snapshot),\n scenarios: scenarios.map((scenario) => ({\n ...scenario\n }))\n };\n this.#notify();\n }\n\n async #selectScenario(scenarioId: string): Promise<void> {\n if (!this.#host.selectScenario) {\n this.#setState({\n notice: this.#createNotice({\n kind: \"error\",\n message: \"This runtime host does not support scenario switching.\"\n })\n });\n return;\n }\n\n const snapshot = await this.#host.selectScenario(scenarioId);\n const scenario = this.#state.scenarios.find((candidate) => candidate.id === scenarioId);\n\n this.#state = {\n ...this.#state,\n composerText: \"\",\n composerCursorOffset: 0,\n dropdown: {\n interacted: false,\n open: false,\n selectedIndex: 0\n },\n isInitialized: true,\n notice: this.#createNotice({\n kind: \"info\",\n message: scenario\n ? `Loaded scenario: ${scenario.label}.`\n : `Loaded scenario: ${scenarioId}.`\n }),\n runtime: cloneRuntimeSnapshot(snapshot)\n };\n this.#notify();\n }\n\n #setState(patch: Partial<UiState>): void {\n this.#state = {\n ...this.#state,\n ...patch\n };\n this.#notify();\n }\n\n async #submitComposer(): Promise<void> {\n if (this.#state.currentScreen !== \"bee\") {\n return;\n }\n\n if (this.#state.dropdown.open) {\n const visibleCommands = filterSlashCommands(getSlashQuery(this.#state.composerText) ?? \"\");\n const selectedCommand = visibleCommands[this.#state.dropdown.selectedIndex] ?? null;\n\n if (!selectedCommand) {\n this.#setState({\n notice: this.#createNotice({\n kind: \"error\",\n message: \"No slash commands match the current filter.\"\n })\n });\n return;\n }\n\n this.#updateComposer(`${selectedCommand.name} `, {\n cursorOffset: Array.from(`${selectedCommand.name} `).length\n });\n return;\n }\n\n if (!this.#state.composerText.trim()) {\n return;\n }\n\n if (this.#state.composerText.trimStart().startsWith(\"/\")) {\n const parsedCommand = parseSlashCommandInput(this.#state.composerText);\n\n if (\"error\" in parsedCommand) {\n this.#setState({\n notice: this.#createNotice({\n kind: \"error\",\n message: parsedCommand.error\n })\n });\n return;\n }\n\n const update = await this.#host.executeCommand(parsedCommand);\n this.#applyHostUpdate(update, {\n clearComposer: !update.exitRequested\n });\n return;\n }\n\n if (this.#state.activeMode === \"off\") {\n this.#setState({\n notice: this.#createNotice({\n kind: \"info\",\n message: \"Off mode is passive. Switch to Static to stage the next continuation prompt.\"\n })\n });\n return;\n }\n\n if (this.#state.activeMode !== \"static\") {\n this.#setState({\n notice: this.#createNotice({\n kind: \"warning\",\n message: `${this.#state.activeMode[0]?.toUpperCase() ?? \"\"}${this.#state.activeMode.slice(1)} mode is visual-only in the isolated harness right now.`\n })\n });\n return;\n }\n\n const stagedPrompt = stripTrailingSlashMarkers(this.#state.composerText);\n\n if (!stagedPrompt.trim()) {\n return;\n }\n\n this.#setState({\n notice: null,\n runtime: {\n ...cloneRuntimeSnapshot(this.#state.runtime),\n runState: \"running\"\n }\n });\n\n const update = await this.#host.submitPrompt({\n mode: \"static\",\n text: stagedPrompt\n });\n\n this.#applyHostUpdate(update, {\n clearComposer: true\n });\n }\n\n #replaceComposerRange(startOffset: number, endOffset: number, replacement: string): void {\n const { nextOffset, nextValue } = replaceRangeAtCodepointOffset(\n this.#state.composerText,\n startOffset,\n endOffset,\n replacement\n );\n\n this.#updateComposer(nextValue, {\n cursorOffset: nextOffset\n });\n }\n\n #updateComposer(nextComposerText: string, options?: {\n cursorOffset?: number;\n }): void {\n const query = getSlashQuery(nextComposerText);\n const matchingCommands = query === null ? [] : filterSlashCommands(query);\n const nextCursorOffset = clampCodepointOffset(\n nextComposerText,\n options?.cursorOffset ?? Array.from(nextComposerText).length\n );\n\n this.#state = {\n ...this.#state,\n composerCursorOffset: nextCursorOffset,\n composerText: nextComposerText,\n dropdown: {\n interacted: false,\n open: query !== null,\n selectedIndex: matchingCommands.length === 0\n ? 0\n : Math.min(this.#state.dropdown.selectedIndex, matchingCommands.length - 1)\n },\n notice: null\n };\n this.#notify();\n }\n\n #notify(): void {\n for (const listener of this.#listeners) {\n listener();\n }\n }\n}\n","import process from \"node:process\";\nimport { render } from \"ink\";\nimport React from \"react\";\nimport { PtyProxy } from \"../pty-proxy.js\";\nimport { UiController } from \"./core/controller.js\";\nimport { isCtrlBInput } from \"./input-shortcuts.js\";\nimport { InkControlApp } from \"./renderers/ink/app.js\";\n\nconst ALT_SCREEN_ENTER = \"\\u001b[?1049h\";\nconst ALT_SCREEN_EXIT = \"\\u001b[?1049l\";\nconst CLEAR_VISIBLE_SCREEN = \"\\u001b[2J\\u001b[H\";\nconst DISABLE_MOUSE_TRACKING = \"\\u001b[?1000l\\u001b[?1006l\";\nconst ENABLE_MOUSE_TRACKING = \"\\u001b[?1000h\\u001b[?1006h\";\nconst SHELL_TOGGLE_DEBOUNCE_MS = 200;\nconst SHOW_CURSOR = \"\\u001b[?25h\";\n\nexport interface LiveInkOverlayManagerOptions {\n controller: UiController;\n onQuitRequested: () => void;\n proxy: PtyProxy;\n renderApp?: typeof render;\n title?: string;\n}\n\nexport class LiveInkOverlayManager {\n readonly #controller: UiController;\n readonly #onQuitRequested: () => void;\n readonly #proxy: PtyProxy;\n readonly #renderApp: typeof render;\n readonly #title: string;\n #app: ReturnType<typeof render> | null = null;\n #controllerUnsubscribe: (() => void) | null = null;\n #ignoreShellToggleUntil = 0;\n #quitting = false;\n\n constructor(options: LiveInkOverlayManagerOptions) {\n this.#controller = options.controller;\n this.#onQuitRequested = options.onQuitRequested;\n this.#proxy = options.proxy;\n this.#renderApp = options.renderApp ?? render;\n this.#title = options.title ?? \"codex-bee\";\n }\n\n handleInput(chunk: Buffer | string): boolean {\n const input = typeof chunk === \"string\" ? chunk : chunk.toString(\"utf8\");\n\n if (this.#app) {\n if (isCtrlBInput(input) && Date.now() >= this.#ignoreShellToggleUntil) {\n this.close();\n }\n\n return true;\n }\n\n if (!isCtrlBInput(input)) {\n return false;\n }\n\n this.open();\n return true;\n }\n\n open(): void {\n if (this.#app) {\n return;\n }\n\n this.#proxy.setOutputMuted(true);\n process.stdout.write(`${ALT_SCREEN_ENTER}${ENABLE_MOUSE_TRACKING}${CLEAR_VISIBLE_SCREEN}`);\n this.#ignoreShellToggleUntil = Date.now() + SHELL_TOGGLE_DEBOUNCE_MS;\n void this.#controller.dispatch({\n type: \"refreshFromRuntime\"\n });\n\n this.#controllerUnsubscribe = this.#controller.subscribe(() => {\n const state = this.#controller.getState();\n\n if (!state.exitRequested || this.#quitting) {\n return;\n }\n\n this.#quitting = true;\n void this.#quitWrapper();\n });\n this.#app = this.#renderApp(\n React.createElement(InkControlApp, {\n allowQuit: false,\n controller: this.#controller,\n enableShellToggle: false,\n title: this.#title\n }),\n {\n exitOnCtrlC: false,\n kittyKeyboard: {\n flags: [\"disambiguateEscapeCodes\", \"reportEventTypes\"],\n mode: \"auto\"\n },\n patchConsole: false\n }\n );\n }\n\n close(): void {\n if (!this.#app) {\n return;\n }\n\n this.#controllerUnsubscribe?.();\n this.#controllerUnsubscribe = null;\n this.#app.unmount();\n this.#app = null;\n process.stdout.write(`${SHOW_CURSOR}${DISABLE_MOUSE_TRACKING}${ALT_SCREEN_EXIT}`);\n this.#proxy.setOutputMuted(false);\n\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(true);\n process.stdin.resume();\n }\n }\n\n dispose(): void {\n this.close();\n }\n\n async #quitWrapper(): Promise<void> {\n this.close();\n this.#onQuitRequested();\n }\n}\n","const CTRL_B_PATTERNS = [\n /^\\u0002$/,\n /^\\u001b\\[(?:66|98);5u$/,\n /^\\u001b\\[27;5;(?:66|98)~$/\n];\nconst FOCUS_EVENT_PATTERNS = [\n /^(?:\\u001b)?\\[I$/,\n /^(?:\\u001b)?\\[O$/\n];\nconst MOUSE_SCROLL_DOWN_PATTERN = /^(?:\\u001b)?\\[<65;\\d+;\\d+[Mm]$/;\nconst MOUSE_EVENT_PATTERN = /^(?:\\u001b)?\\[<\\d+;\\d+;\\d+[Mm]$/;\nconst MOUSE_SCROLL_UP_PATTERN = /^(?:\\u001b)?\\[<64;\\d+;\\d+[Mm]$/;\n\nconst SUBMIT_PATTERNS = [\n /^\\r$/,\n /^\\n$/,\n /^\\u001b\\[(?:10|13);(?:2|5|6)u$/,\n /^\\u001b\\[27;(?:2|5|6);(?:10|13)~$/\n];\n\nconst NEWLINE_PATTERNS = [\n /^\\u001b\\[(?:10|13);(?:3|4)u$/,\n /^\\u001b\\[27;(?:3|4);(?:10|13)~$/\n];\n\ninterface InputKeyState {\n ctrl?: boolean;\n return?: boolean;\n shift?: boolean;\n}\n\nexport function isCtrlBInput(input: string): boolean {\n return CTRL_B_PATTERNS.some((pattern) => pattern.test(input));\n}\n\nexport function getMouseScrollDelta(input: string): -1 | 1 | null {\n if (MOUSE_SCROLL_UP_PATTERN.test(input)) {\n return -1;\n }\n\n if (MOUSE_SCROLL_DOWN_PATTERN.test(input)) {\n return 1;\n }\n\n return null;\n}\n\nexport function isIgnorableTerminalInput(input: string): boolean {\n if (FOCUS_EVENT_PATTERNS.some((pattern) => pattern.test(input))) {\n return true;\n }\n\n return MOUSE_EVENT_PATTERN.test(input);\n}\n\nexport function isSubmitComposerInput(input: string, key?: InputKeyState): boolean {\n if (key?.return) {\n return true;\n }\n\n return SUBMIT_PATTERNS.some((pattern) => pattern.test(input));\n}\n\nexport function isInsertNewlineInput(input: string, key?: InputKeyState): boolean {\n return NEWLINE_PATTERNS.some((pattern) => pattern.test(input));\n}\n","import figlet from \"figlet\";\nimport { Box, useApp, useInput, useStdin, useStdout } from \"ink\";\nimport React, { useEffect, useState } from \"react\";\nimport { UiController } from \"../../core/controller.js\";\nimport type { UiMode, UiState } from \"../../core/types.js\";\nimport {\n getMouseScrollDelta,\n isIgnorableTerminalInput,\n isCtrlBInput,\n isInsertNewlineInput,\n isSubmitComposerInput\n} from \"../../input-shortcuts.js\";\nimport {\n formatClockTime,\n formatCompactDuration,\n formatPromptPreview,\n formatSessionInfo,\n formatWorkspaceLine,\n getActivePrompt,\n getModeLabel,\n getModeTone,\n getVisibleSlashCommands,\n getVisibleSlashPlaceholder,\n normalizeLogEntryText\n} from \"../../core/view-model.js\";\nimport {\n measureText,\n renderLine,\n truncateDisplayWidth,\n type InkLineSpec,\n type InkLineSegment,\n wrapAndLimit,\n wrapText\n} from \"./renderer-utils.js\";\n\nexport interface InkControlAppProps {\n allowQuit?: boolean;\n controller: UiController;\n enableShellToggle?: boolean;\n onShellToggle?: () => void;\n title?: string;\n}\n\ninterface InkPalette {\n accent?: string;\n announcementBackground?: string;\n announcementBorder?: string;\n announcementText?: string;\n bodyText?: string;\n error?: string;\n footerBase?: string;\n footerMutedBackground?: string;\n inputBackground?: string;\n logBackground?: string;\n logBorder?: string;\n muted?: string;\n primary?: string;\n promptBackground?: string;\n promptBorder?: string;\n secondary?: string;\n statusBottomBackground?: string;\n statusTopBackground?: string;\n success?: string;\n warning?: string;\n}\n\nconst MAX_CONTENT_WIDTH = 200;\nconst MIN_CONTENT_WIDTH = 80;\nconst PROMPT_BAR = \"┃\";\nconst TIMESTAMP_WIDTH = 8;\n\nconst LOADER_FRAMES = [\n [\"■\", \"■\", \"□\", \"□\"],\n [\"□\", \"■\", \"■\", \"□\"],\n [\"□\", \"□\", \"■\", \"■\"],\n [\"□\", \"■\", \"□\", \"■\"]\n];\n\ninterface ComposerVisualLine {\n endOffset: number;\n startOffset: number;\n text: string;\n}\n\nfunction createPalette(stylesEnabled: boolean): InkPalette {\n if (!stylesEnabled) {\n return {};\n }\n\n return {\n accent: \"#4C86FF\",\n announcementBackground: \"#15233A\",\n announcementBorder: \"#4C86FF\",\n announcementText: \"#D9E8FF\",\n bodyText: \"#F5F5F5\",\n error: \"#FF6B6B\",\n footerBase: \"#101317\",\n footerMutedBackground: \"#13171D\",\n inputBackground: \"#202833\",\n logBackground: \"#101113\",\n logBorder: \"#2D3138\",\n muted: \"#9098A4\",\n primary: \"#FFBF00\",\n promptBackground: \"#151A22\",\n promptBorder: \"#38404E\",\n secondary: \"#FF8C00\",\n statusBottomBackground: \"#222B1E\",\n statusTopBackground: \"#1B2633\",\n success: \"#4FD18B\",\n warning: \"#E7C85C\"\n };\n}\n\nfunction createLine(\n key: string,\n segments: InkLineSegment[],\n backgroundColor?: string\n): InkLineSpec {\n return {\n backgroundColor,\n key,\n segments\n };\n}\n\nfunction createTextLine(\n key: string,\n text: string,\n options?: Omit<InkLineSegment, \"text\">\n): InkLineSpec {\n return createLine(key, [\n {\n ...options,\n text\n }\n ], options?.backgroundColor);\n}\n\nfunction createSpacerLine(key: string, backgroundColor?: string): InkLineSpec {\n return createTextLine(key, \"\", {\n backgroundColor\n });\n}\n\nfunction padDisplayWidth(value: string, width: number): string {\n return `${value}${\" \".repeat(Math.max(width - measureText(value), 0))}`;\n}\n\nfunction buildGradientSegments(value: string, palette: InkPalette): InkLineSegment[] {\n if (!palette.primary || !palette.secondary) {\n return [\n {\n bold: true,\n text: value\n }\n ];\n }\n\n const gradientStops = [\"#FFD700\", \"#FFC300\", palette.primary, \"#FFAA00\", \"#FF9800\", palette.secondary];\n const characters = Array.from(value);\n\n return characters.map((character, index) => {\n if (character === \" \") {\n return {\n text: character\n };\n }\n\n const stopIndex = Math.min(\n gradientStops.length - 1,\n Math.floor((index / Math.max(characters.length - 1, 1)) * (gradientStops.length - 1))\n );\n\n return {\n bold: true,\n color: gradientStops[stopIndex],\n text: character\n };\n });\n}\n\nfunction getModeColor(mode: UiMode, palette: InkPalette): string | undefined {\n const tone = getModeTone(mode);\n\n if (tone === \"gray\") {\n return \"#D4D9E2\";\n }\n\n if (tone === \"cyan\") {\n return \"#55D6FF\";\n }\n\n if (tone === \"yellow\") {\n return palette.primary ?? \"yellow\";\n }\n\n return palette.secondary ?? \"#FF8C00\";\n}\n\nfunction getConnectionTokenSpec(\n connectionState: UiState[\"runtime\"][\"connectionState\"],\n palette: InkPalette\n): {\n color: string | undefined;\n compactLabel: string;\n label: string;\n} {\n if (connectionState === \"connected\") {\n return {\n color: palette.success,\n compactLabel: \"Conn\",\n label: \"Connected\"\n };\n }\n\n if (connectionState === \"ready\") {\n return {\n color: palette.warning ?? palette.primary,\n compactLabel: \"Ready\",\n label: \"Hooks ready\"\n };\n }\n\n return {\n color: palette.error,\n compactLabel: \"Disc\",\n label: \"Disconnected\"\n };\n}\n\nfunction buildFigletLines(title: string, maxWidth: number): string[] {\n const fonts = [\"ANSI Shadow\", \"Electronic\"];\n\n for (const font of fonts) {\n try {\n const nextLines = figlet.textSync(title, {\n font,\n horizontalLayout: \"default\"\n }).replace(/\\s+$/gm, \"\").split(\"\\n\");\n\n if (nextLines.every((line) => measureText(line) <= maxWidth)) {\n return nextLines;\n }\n } catch {\n continue;\n }\n }\n\n return [title];\n}\n\nfunction buildAnnouncementPanelLines(\n state: UiState,\n width: number,\n palette: InkPalette\n): InkLineSpec[] {\n if (!state.runtime.announcement || width < 8) {\n return [];\n }\n\n const innerWidth = Math.max(width - 4, 4);\n const contentLines = wrapText(state.runtime.announcement.message, innerWidth);\n const borderColor = palette.announcementBorder ?? palette.accent ?? palette.primary;\n\n return [\n createTextLine(\"announcement-top\", `╭${\"─\".repeat(Math.max(width - 2, 0))}╮`, {\n backgroundColor: palette.announcementBackground,\n color: borderColor\n }),\n ...contentLines.map((line, index) => createLine(`announcement-${index}`, [\n {\n backgroundColor: palette.announcementBackground,\n color: borderColor,\n text: \"│ \"\n },\n {\n backgroundColor: palette.announcementBackground,\n color: palette.announcementText ?? palette.bodyText,\n text: padDisplayWidth(line, innerWidth)\n },\n {\n backgroundColor: palette.announcementBackground,\n color: borderColor,\n text: \" │\"\n }\n ], palette.announcementBackground)),\n createTextLine(\"announcement-bottom\", `╰${\"─\".repeat(Math.max(width - 2, 0))}╯`, {\n backgroundColor: palette.announcementBackground,\n color: borderColor\n })\n ];\n}\n\nfunction buildHeaderColumnLines(\n state: UiState,\n title: string,\n width: number,\n palette: InkPalette\n): InkLineSpec[] {\n const titleLines = buildFigletLines(title.toUpperCase(), Math.max(width, 16));\n\n return [\n ...titleLines.map((line, index) => createLine(`header-${index}`, buildGradientSegments(line, palette))),\n createTextLine(\"versions\", `codex-bee v${state.runtime.beeVersion} • codex v${state.runtime.codexVersion}`, {\n color: palette.muted,\n dimColor: !palette.muted\n }),\n ...buildAnnouncementPanelLines(state, width, palette)\n ];\n}\n\nfunction buildHeaderLines(\n state: UiState,\n title: string,\n width: number,\n palette: InkPalette\n): InkLineSpec[] {\n return buildHeaderColumnLines(state, title, width, palette);\n}\n\nfunction getLogColor(\n kind: UiState[\"runtime\"][\"logs\"][number][\"entries\"][number][\"kind\"],\n palette: InkPalette\n): string | undefined {\n if (kind === \"user\") {\n return \"#55D6FF\";\n }\n\n if (kind === \"model\") {\n return palette.secondary;\n }\n\n if (kind === \"summary\") {\n return palette.accent;\n }\n\n if (kind === \"hook\") {\n return palette.success;\n }\n\n return palette.muted;\n}\n\nfunction buildDividerLabel(turn: number, totalTurns: number | null, durationMs: number | null, width: number): string {\n const parts = [totalTurns === null ? `${turn} turns` : `${turn}/${totalTurns} turns`];\n\n if (durationMs !== null) {\n parts.push(formatCompactDuration(durationMs));\n }\n\n const label = `──── ${parts.join(\" • \")} `;\n const fillWidth = Math.max(width - measureText(label), 0);\n\n return `${label}${\"─\".repeat(fillWidth)}`;\n}\n\nfunction buildComposerVisualLines(value: string, width: number): ComposerVisualLine[] {\n if (width <= 0) {\n return [\n {\n endOffset: 0,\n startOffset: 0,\n text: \"\"\n }\n ];\n }\n\n const codepoints = Array.from(value);\n const lines: ComposerVisualLine[] = [];\n let currentText = \"\";\n let currentStartOffset = 0;\n\n for (let index = 0; index < codepoints.length; index += 1) {\n const character = codepoints[index] ?? \"\";\n\n if (character === \"\\n\") {\n lines.push({\n endOffset: index,\n startOffset: currentStartOffset,\n text: currentText\n });\n currentStartOffset = index + 1;\n currentText = \"\";\n continue;\n }\n\n if (measureText(currentText + character) > width) {\n lines.push({\n endOffset: index,\n startOffset: currentStartOffset,\n text: currentText\n });\n currentStartOffset = index;\n currentText = character;\n continue;\n }\n\n currentText += character;\n }\n\n lines.push({\n endOffset: codepoints.length,\n startOffset: currentStartOffset,\n text: currentText\n });\n\n return lines.length > 0\n ? lines\n : [\n {\n endOffset: 0,\n startOffset: 0,\n text: \"\"\n }\n ];\n}\n\nfunction getComposerCursorLineIndex(lines: ComposerVisualLine[], cursorOffset: number): number {\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index];\n\n if (!line || cursorOffset < line.startOffset || cursorOffset > line.endOffset) {\n continue;\n }\n\n const previousLine = index > 0 ? lines[index - 1] : null;\n const isWrappedBoundary = cursorOffset === line.startOffset && previousLine && previousLine.endOffset === line.startOffset;\n\n if (isWrappedBoundary) {\n continue;\n }\n\n return index;\n }\n\n return Math.max(lines.length - 1, 0);\n}\n\nfunction getComposerCursorColumn(line: ComposerVisualLine, cursorOffset: number): number {\n const relativeOffset = Math.max(0, Math.min(cursorOffset - line.startOffset, Array.from(line.text).length));\n const prefix = Array.from(line.text).slice(0, relativeOffset).join(\"\");\n\n return measureText(prefix);\n}\n\nfunction getOffsetForComposerLineColumn(\n lines: ComposerVisualLine[],\n lineIndex: number,\n targetColumn: number\n): number {\n const line = lines[lineIndex];\n\n if (!line) {\n return 0;\n }\n\n const codepoints = Array.from(line.text);\n let bestOffset = line.startOffset;\n\n for (let index = 0; index <= codepoints.length; index += 1) {\n const prefix = codepoints.slice(0, index).join(\"\");\n const nextColumn = measureText(prefix);\n\n if (nextColumn > targetColumn) {\n break;\n }\n\n bestOffset = line.startOffset + index;\n }\n\n return bestOffset;\n}\n\nfunction buildLogLines(state: UiState, width: number, palette: InkPalette): InkLineSpec[] {\n const logLines: InkLineSpec[] = [\n createTextLine(\"log-top-border\", \"─\".repeat(width), {\n backgroundColor: palette.logBackground,\n color: palette.logBorder ?? palette.muted\n })\n ];\n const contentWidth = Math.max(width - TIMESTAMP_WIDTH - 2, 16);\n\n if (state.runtime.logs.length === 0) {\n return [\n ...logLines,\n createTextLine(\"log-empty\", \"No turns recorded yet. Submit a Static prompt or switch scenarios.\", {\n backgroundColor: palette.logBackground,\n color: palette.muted,\n dimColor: !palette.muted\n }),\n createTextLine(\"log-bottom-border\", \"─\".repeat(width), {\n backgroundColor: palette.logBackground,\n color: palette.logBorder ?? palette.muted\n })\n ];\n }\n\n state.runtime.logs.forEach((group, groupIndex) => {\n if (groupIndex > 0) {\n logLines.push(createSpacerLine(`divider-gap-${group.id}`, palette.logBackground));\n logLines.push(createTextLine(`divider-${group.id}`, buildDividerLabel(\n group.turn,\n group.totalTurns,\n group.durationMs,\n width\n ), {\n backgroundColor: palette.logBackground,\n color: palette.muted,\n dimColor: !palette.muted\n }));\n }\n\n group.entries.forEach((entry) => {\n const previewLines = wrapAndLimit(normalizeLogEntryText(entry), contentWidth, 3);\n\n previewLines.forEach((line, lineIndex) => {\n logLines.push(createLine(`${entry.id}-${lineIndex}`, [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: lineIndex === 0\n ? truncateDisplayWidth(formatClockTime(entry.timestamp), TIMESTAMP_WIDTH)\n : \" \".repeat(TIMESTAMP_WIDTH)\n },\n {\n text: \" \"\n },\n {\n color: entry.kind === \"hook\" && entry.text.includes(\"✗\")\n ? palette.error\n : getLogColor(entry.kind, palette),\n text: line\n }\n ], palette.logBackground));\n });\n });\n });\n\n logLines.push(createTextLine(\"log-bottom-border\", \"─\".repeat(width), {\n backgroundColor: palette.logBackground,\n color: palette.logBorder ?? palette.muted\n }));\n\n return logLines;\n}\n\nfunction buildBodyLines(\n state: UiState,\n title: string,\n width: number,\n palette: InkPalette\n): InkLineSpec[] {\n return [\n ...buildHeaderLines(state, title, width, palette),\n createSpacerLine(\"header-gap\"),\n ...buildLogLines(state, width, palette)\n ];\n}\n\nfunction buildLoaderSegments(palette: InkPalette, animationTick: number): InkLineSegment[] {\n const modeIndex = animationTick % LOADER_FRAMES.length;\n const frame = LOADER_FRAMES[modeIndex] ?? LOADER_FRAMES[0];\n\n return frame.map((glyph, index) => ({\n color: [\"#FFD700\", palette.primary, \"#FFAA00\", palette.secondary][index] ?? palette.primary,\n text: glyph\n }));\n}\n\nfunction measureSegmentsWidth(segments: InkLineSegment[]): number {\n return segments.reduce((total, segment) => total + measureText(segment.text), 0);\n}\n\nfunction buildStatusTokens(\n state: UiState,\n palette: InkPalette,\n animationTick: number,\n width: number\n): InkLineSegment[][] {\n const loaderToken = state.runtime.runState === \"running\"\n ? buildLoaderSegments(palette, animationTick)\n : LOADER_FRAMES[0].map((glyph, index) => ({\n color: [\"#FFD700\", palette.primary, \"#FFAA00\", palette.secondary][index] ?? palette.primary,\n text: glyph\n }));\n const connectionSpec = getConnectionTokenSpec(state.runtime.connectionState, palette);\n const connectionToken: InkLineSegment[] = [\n {\n color: connectionSpec.color,\n text: connectionSpec.label\n }\n ];\n const compactConnectionToken: InkLineSegment[] = [\n {\n color: connectionSpec.color,\n text: connectionSpec.compactLabel\n }\n ];\n const versionToken: InkLineSegment[] = [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: `codex v${state.runtime.codexVersion}`\n }\n ];\n const shortVersionToken: InkLineSegment[] = [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: `v${state.runtime.codexVersion}`\n }\n ];\n const runStateToken: InkLineSegment[] = [\n {\n color: state.runtime.runState === \"running\" ? palette.primary : palette.muted,\n text: state.runtime.runState === \"running\" ? \"Running\" : \"Idle\"\n }\n ];\n const hotkeyToken: InkLineSegment[] = [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: \"Ctrl+B codex\"\n }\n ];\n const shortHotkeyToken: InkLineSegment[] = [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: \"Ctrl+B\"\n }\n ];\n const commandsToken: InkLineSegment[] = [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: \"/ commands\"\n }\n ];\n const shortCommandsToken: InkLineSegment[] = [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: \"/\"\n }\n ];\n const variants: InkLineSegment[][][] = [\n [loaderToken, connectionToken, versionToken, runStateToken, hotkeyToken, commandsToken],\n [loaderToken, connectionToken, shortVersionToken, runStateToken, hotkeyToken, commandsToken],\n [loaderToken, connectionToken, shortVersionToken, runStateToken, hotkeyToken, shortCommandsToken],\n [loaderToken, compactConnectionToken, runStateToken, shortHotkeyToken, shortCommandsToken]\n ];\n\n for (const variant of variants) {\n const totalWidth = variant.reduce((total, token, index) => {\n const separatorWidth = index === 0 ? 0 : measureText(\" • \");\n\n return total + separatorWidth + measureSegmentsWidth(token);\n }, 0);\n\n if (totalWidth <= width) {\n return variant;\n }\n }\n\n return variants[variants.length - 1] ?? [];\n}\n\nfunction buildStatusBarLine(\n state: UiState,\n palette: InkPalette,\n animationTick: number,\n width: number\n): InkLineSpec {\n const backgroundColor = palette.statusBottomBackground;\n const tokens = buildStatusTokens(state, palette, animationTick, width);\n const segments = tokens.flatMap((token, index) => index === 0\n ? token\n : [\n {\n text: \" • \"\n },\n ...token\n ]);\n\n return createLine(\"status-bar\", segments, backgroundColor);\n}\n\nfunction buildModeHintLine(\n state: UiState,\n width: number,\n palette: InkPalette\n): InkLineSpec {\n const prefix = width >= 34 ? \" Shift+Tab mode • \" : \" Tab • \";\n const modeLabel = getModeLabel(state.activeMode);\n const segments: InkLineSegment[] = [\n {\n backgroundColor: palette.promptBackground,\n color: palette.muted,\n dimColor: !palette.muted,\n text: prefix\n },\n {\n backgroundColor: palette.promptBackground,\n color: getModeColor(state.activeMode, palette),\n text: modeLabel\n }\n ];\n const usedWidth = measureSegmentsWidth(segments);\n\n if (usedWidth < width) {\n segments.push({\n backgroundColor: palette.promptBackground,\n text: \" \".repeat(width - usedWidth)\n });\n }\n\n return createLine(\"mode-hint\", segments, palette.promptBackground);\n}\n\nfunction buildDropdownLines(state: UiState, width: number, palette: InkPalette): InkLineSpec[] {\n const commands = getVisibleSlashCommands(state);\n const nameWidth = 16;\n const placeholderWidth = 12;\n const descriptionWidth = Math.max(width - nameWidth - placeholderWidth - 2, 12);\n\n if (commands.length === 0) {\n return [\n createTextLine(\"dropdown-empty\", \"No commands match the current filter.\", {\n backgroundColor: palette.promptBackground,\n color: palette.muted,\n dimColor: !palette.muted\n })\n ];\n }\n\n return commands.map((command, index) => {\n const isSelected = index === state.dropdown.selectedIndex;\n const backgroundColor = isSelected ? palette.inputBackground : palette.promptBackground;\n const description = truncateDisplayWidth(command.description, descriptionWidth);\n const placeholder = command.placeholder\n ? truncateDisplayWidth(command.placeholder, placeholderWidth)\n : \"\";\n\n return createLine(`dropdown-${command.id}`, [\n {\n backgroundColor,\n text: \" \"\n },\n {\n backgroundColor,\n bold: true,\n color: isSelected ? palette.primary : palette.bodyText,\n text: padDisplayWidth(command.name, nameWidth)\n },\n {\n backgroundColor,\n color: palette.muted,\n dimColor: !palette.muted,\n text: padDisplayWidth(description, descriptionWidth)\n },\n {\n backgroundColor,\n color: palette.muted,\n dimColor: !palette.muted,\n italic: true,\n text: padDisplayWidth(placeholder, placeholderWidth)\n }\n ], backgroundColor);\n });\n}\n\nfunction buildNoticeLine(state: UiState, palette: InkPalette): InkLineSpec | null {\n if (!state.notice) {\n return null;\n }\n\n return createTextLine(`notice-${state.notice.id}`, `⚠ ${state.notice.message}`, {\n backgroundColor: palette.statusBottomBackground,\n color: state.notice.kind === \"error\"\n ? palette.error\n : state.notice.kind === \"warning\"\n ? palette.warning\n : palette.primary\n });\n}\n\nfunction buildPromptFooterLines(\n state: UiState,\n width: number,\n palette: InkPalette,\n cursorVisible: boolean,\n animationTick: number,\n now: number\n): InkLineSpec[] {\n const lines: InkLineSpec[] = [];\n const modeColor = getModeColor(state.activeMode, palette);\n const promptPreviewWidth = Math.max(width - 2, 16);\n const promptLines = formatPromptPreview(getActivePrompt(state), 5)\n .flatMap((line) => wrapAndLimit(line, promptPreviewWidth, 5))\n .slice(0, 5);\n const inputFieldWidth = Math.max(width - 2, 12);\n const inputContentWidth = Math.max(inputFieldWidth - 1, 8);\n const composerLines = buildComposerVisualLines(state.composerText, inputContentWidth);\n const cursorLineIndex = getComposerCursorLineIndex(composerLines, state.composerCursorOffset);\n const placeholder = getVisibleSlashPlaceholder(state);\n\n lines.push(createTextLine(\"session-info\", formatSessionInfo(state.runtime, now) || \"Session metadata will appear after the first turn.\", {\n backgroundColor: palette.statusTopBackground,\n color: palette.bodyText\n }));\n lines.push(createSpacerLine(\"session-gap\", palette.footerBase));\n lines.push(createTextLine(\"prompt-top-border\", \"─\".repeat(width), {\n backgroundColor: palette.promptBackground,\n color: palette.promptBorder ?? palette.muted\n }));\n lines.push(createSpacerLine(\"prompt-padding-top\", palette.promptBackground));\n\n promptLines.forEach((line, index) => {\n lines.push(createLine(`prompt-${index}`, [\n {\n backgroundColor: palette.promptBackground,\n color: modeColor,\n text: PROMPT_BAR\n },\n {\n backgroundColor: palette.promptBackground,\n text: \" \"\n },\n {\n backgroundColor: palette.promptBackground,\n color: palette.bodyText,\n text: padDisplayWidth(line, width - 2)\n }\n ], palette.promptBackground));\n });\n\n composerLines.forEach((line, index) => {\n const isCursorLine = index === cursorLineIndex;\n const isLastLine = index === composerLines.length - 1;\n const relativeCursorOffset = Math.max(\n 0,\n Math.min(state.composerCursorOffset - line.startOffset, Array.from(line.text).length)\n );\n const beforeCursor = Array.from(line.text).slice(0, relativeCursorOffset).join(\"\");\n const afterCursor = Array.from(line.text).slice(relativeCursorOffset).join(\"\");\n const fieldSegments: InkLineSegment[] = [\n {\n backgroundColor: palette.inputBackground,\n color: palette.bodyText,\n text: beforeCursor\n }\n ];\n\n if (isCursorLine) {\n fieldSegments.push({\n backgroundColor: palette.inputBackground,\n color: modeColor,\n text: cursorVisible ? \"_\" : \" \"\n });\n }\n\n if (afterCursor) {\n fieldSegments.push({\n backgroundColor: palette.inputBackground,\n color: palette.bodyText,\n text: afterCursor\n });\n }\n\n const usedWidthBeforePlaceholder = fieldSegments.reduce(\n (total, segment) => total + measureText(segment.text),\n 0\n );\n\n if (isLastLine && placeholder && !state.composerText.trimEnd().includes(\" \") && usedWidthBeforePlaceholder < inputFieldWidth) {\n fieldSegments.push({\n backgroundColor: palette.inputBackground,\n color: palette.muted,\n italic: true,\n text: truncateDisplayWidth(placeholder, Math.max(inputFieldWidth - usedWidthBeforePlaceholder, 0))\n });\n }\n\n const usedWidth = fieldSegments.reduce((total, segment) => total + measureText(segment.text), 0);\n\n if (usedWidth < inputFieldWidth) {\n fieldSegments.push({\n backgroundColor: palette.inputBackground,\n text: \" \".repeat(inputFieldWidth - usedWidth)\n });\n }\n\n lines.push(createLine(`input-${index}`, [\n {\n backgroundColor: palette.promptBackground,\n color: modeColor,\n text: index === 0 ? \"❯ \" : \" \"\n },\n ...fieldSegments\n ], palette.promptBackground));\n });\n\n lines.push(buildModeHintLine(state, width, palette));\n\n if (state.dropdown.open) {\n lines.push(...buildDropdownLines(state, width, palette));\n }\n\n lines.push(createSpacerLine(\"prompt-padding-bottom\", palette.promptBackground));\n lines.push(createTextLine(\"prompt-bottom-border\", \"─\".repeat(width), {\n backgroundColor: palette.promptBackground,\n color: palette.promptBorder ?? palette.muted\n }));\n lines.push(createSpacerLine(\"footer-gap\", palette.footerBase));\n lines.push(buildStatusBarLine(state, palette, animationTick, width));\n lines.push(createSpacerLine(\"workspace-gap\", palette.footerBase));\n lines.push(createTextLine(\"workspace\", formatWorkspaceLine(state.runtime.workspace), {\n backgroundColor: palette.footerMutedBackground,\n color: palette.muted,\n dimColor: !palette.muted\n }));\n\n return lines;\n}\n\nfunction buildBeeScreenLines(\n state: UiState,\n title: string,\n columns: number,\n cursorVisible: boolean,\n palette: InkPalette,\n animationTick: number,\n now: number\n): InkLineSpec[] {\n const bodyLines = buildBodyLines(state, title, columns, palette);\n const footerLines = buildPromptFooterLines(state, columns, palette, cursorVisible, animationTick, now);\n const noticeLine = buildNoticeLine(state, palette);\n\n return noticeLine\n ? [...bodyLines, createSpacerLine(\"body-footer-gap\"), ...footerLines, createSpacerLine(\"notice-gap\", palette.footerBase), noticeLine]\n : [...bodyLines, createSpacerLine(\"body-footer-gap\"), ...footerLines];\n}\n\nfunction buildCodexScreenLines(\n state: UiState,\n columns: number,\n palette: InkPalette\n): InkLineSpec[] {\n const bodyLines = state.runtime.codexBufferLines.map((line, index) => createTextLine(`codex-${index}`, line, {\n color: palette.bodyText\n }));\n const footerLines: InkLineSpec[] = [\n createTextLine(\"codex-divider\", \"─\".repeat(columns), {\n color: palette.muted,\n dimColor: !palette.muted\n }),\n createTextLine(\"codex-hint\", \"Mocked Codex buffer • Ctrl+B reopen codex-bee • Ctrl+C shows the exit hint\", {\n backgroundColor: palette.statusBottomBackground,\n color: palette.bodyText\n }),\n createSpacerLine(\"codex-footer-gap\", palette.footerBase),\n createTextLine(\"codex-workspace\", formatWorkspaceLine(state.runtime.workspace), {\n backgroundColor: palette.footerMutedBackground,\n color: palette.muted,\n dimColor: !palette.muted\n })\n ];\n const noticeLine = buildNoticeLine(state, palette);\n\n return noticeLine\n ? [...bodyLines, createSpacerLine(\"codex-gap\"), ...footerLines, createSpacerLine(\"codex-notice-gap\", palette.footerBase), noticeLine]\n : [...bodyLines, createSpacerLine(\"codex-gap\"), ...footerLines];\n}\n\nfunction buildNarrowScreenLines(columns: number, palette: InkPalette): InkLineSpec[] {\n return [\n createTextLine(\"narrow-title\", \"Terminal too narrow. Minimum 80 columns required.\", {\n bold: true,\n color: palette.warning\n }),\n createTextLine(\"narrow-help\", \"Resize the terminal and codex-bee will redraw the isolated TUI automatically.\", {\n color: palette.muted,\n dimColor: !palette.muted\n }),\n createTextLine(\"narrow-width\", `Current width: ${columns} columns`, {\n color: palette.bodyText\n })\n ];\n}\n\nexport function InkControlApp({\n allowQuit = true,\n controller,\n enableShellToggle = true,\n onShellToggle,\n title = \"codex-bee\"\n}: InkControlAppProps): React.JSX.Element {\n const { exit } = useApp();\n const { isRawModeSupported } = useStdin();\n const { stdout } = useStdout();\n const [state, setState] = useState(() => controller.getState());\n const [isPinnedToBottom, setIsPinnedToBottom] = useState(true);\n const [scrollOffset, setScrollOffset] = useState(0);\n const [clockNow, setClockNow] = useState(() => Date.now());\n const animationTick = 0;\n const cursorVisible = true;\n const [viewport] = useState(() => ({\n columns: stdout.columns ?? 100,\n rows: stdout.rows ?? 40\n }));\n\n useEffect(() => {\n const unsubscribe = controller.subscribe(() => {\n setState(controller.getState());\n });\n\n void controller.initialize();\n\n return unsubscribe;\n }, [controller]);\n\n useEffect(() => {\n if (!state.exitRequested) {\n return;\n }\n\n if (allowQuit) {\n exit();\n return;\n }\n\n void controller.dispatch({\n type: \"clearExitRequest\"\n });\n }, [allowQuit, controller, exit, state.exitRequested]);\n\n useEffect(() => {\n if (state.runtime.session.stopAt === null) {\n return;\n }\n\n setClockNow(Date.now());\n const intervalId = setInterval(() => {\n setClockNow(Date.now());\n }, 1_000);\n\n return () => {\n clearInterval(intervalId);\n };\n }, [state.runtime.session.stopAt]);\n\n const palette = createPalette(stdout.isTTY !== false && !process.env.NO_COLOR && process.env.TERM !== \"dumb\");\n const contentWidth = Math.min(Math.max(viewport.columns, MIN_CONTENT_WIDTH), MAX_CONTENT_WIDTH);\n const renderWidth = viewport.columns < MIN_CONTENT_WIDTH ? viewport.columns : contentWidth;\n const contentLines = viewport.columns < MIN_CONTENT_WIDTH\n ? buildNarrowScreenLines(viewport.columns, palette)\n : (\n state.currentScreen === \"bee\"\n ? buildBeeScreenLines(\n state,\n title,\n contentWidth,\n cursorVisible,\n palette,\n animationTick,\n clockNow\n )\n : buildCodexScreenLines(\n state,\n contentWidth,\n palette\n )\n );\n const maxScrollOffset = Math.max(contentLines.length - viewport.rows, 0);\n\n useEffect(() => {\n setScrollOffset((current) => isPinnedToBottom ? maxScrollOffset : Math.min(current, maxScrollOffset));\n }, [isPinnedToBottom, maxScrollOffset]);\n\n const scrollBy = (deltaLines: number) => {\n if (maxScrollOffset === 0) {\n setScrollOffset(0);\n setIsPinnedToBottom(true);\n return;\n }\n\n setScrollOffset((current) => {\n const next = Math.max(0, Math.min(maxScrollOffset, current + deltaLines));\n\n setIsPinnedToBottom(next >= maxScrollOffset);\n return next;\n });\n };\n const shouldInsertSlashNewlineHack = (input: string, key: {\n ctrl?: boolean;\n return?: boolean;\n shift?: boolean;\n }): boolean => {\n const beforeCursor = Array.from(state.composerText).slice(0, state.composerCursorOffset).join(\"\");\n const currentLineBeforeCursor = beforeCursor.split(\"\\n\").at(-1) ?? \"\";\n\n if (!currentLineBeforeCursor.trimEnd().endsWith(\"/\")) {\n return false;\n }\n\n if (key.return) {\n return !key.shift && !key.ctrl;\n }\n\n return input === \"\\r\" || input === \"\\n\";\n };\n\n useInput((input, key) => {\n if ((key.ctrl && input === \"b\") || isCtrlBInput(input)) {\n if (!enableShellToggle) {\n return;\n }\n\n if (onShellToggle) {\n onShellToggle();\n } else {\n void controller.dispatch({\n type: \"toggleScreen\"\n });\n }\n return;\n }\n\n if (key.ctrl && input === \"c\") {\n void controller.dispatch({\n type: \"showExitHint\"\n });\n return;\n }\n\n const mouseScrollDelta = getMouseScrollDelta(input);\n\n if (mouseScrollDelta !== null) {\n scrollBy(mouseScrollDelta * 3);\n return;\n }\n\n if (isIgnorableTerminalInput(input)) {\n return;\n }\n\n if (state.currentScreen === \"codex\") {\n return;\n }\n\n if (key.pageUp || input === \"\\u001b[5~\") {\n scrollBy(-(viewport.rows - 4));\n return;\n }\n\n if (key.pageDown || input === \"\\u001b[6~\") {\n scrollBy(viewport.rows - 4);\n return;\n }\n\n if (key.home || input === \"\\u001b[H\" || input === \"\\u001b[1~\") {\n setIsPinnedToBottom(false);\n setScrollOffset(0);\n return;\n }\n\n if (key.end || input === \"\\u001b[F\" || input === \"\\u001b[4~\") {\n setIsPinnedToBottom(true);\n setScrollOffset(maxScrollOffset);\n return;\n }\n\n if ((key.tab && key.shift) || input === \"\\u001b[Z\") {\n void controller.dispatch({\n type: \"cycleMode\"\n });\n return;\n }\n\n if (key.escape) {\n void controller.dispatch({\n type: state.dropdown.open ? \"closeDropdown\" : \"dismissNotice\"\n });\n return;\n }\n\n const inputFieldWidth = Math.max(contentWidth - 2, 12);\n const inputContentWidth = Math.max(inputFieldWidth - 1, 8);\n const composerLines = buildComposerVisualLines(state.composerText, inputContentWidth);\n const cursorLineIndex = getComposerCursorLineIndex(composerLines, state.composerCursorOffset);\n const cursorColumn = getComposerCursorColumn(composerLines[cursorLineIndex] ?? composerLines[0] ?? {\n endOffset: 0,\n startOffset: 0,\n text: \"\"\n }, state.composerCursorOffset);\n const shouldUseDropdownNavigation = state.dropdown.open\n && !state.composerText.includes(\"\\n\")\n && state.composerCursorOffset === Array.from(state.composerText).length;\n\n if (shouldUseDropdownNavigation && key.upArrow) {\n void controller.dispatch({\n type: \"selectPreviousCommand\"\n });\n return;\n }\n\n if (shouldUseDropdownNavigation && key.downArrow) {\n void controller.dispatch({\n type: \"selectNextCommand\"\n });\n return;\n }\n\n if (key.leftArrow) {\n void controller.dispatch({\n offset: state.composerCursorOffset - 1,\n type: \"setComposerCursorOffset\"\n });\n return;\n }\n\n if (key.rightArrow) {\n void controller.dispatch({\n offset: state.composerCursorOffset + 1,\n type: \"setComposerCursorOffset\"\n });\n return;\n }\n\n if (key.upArrow) {\n const targetLineIndex = Math.max(cursorLineIndex - 1, 0);\n\n void controller.dispatch({\n offset: getOffsetForComposerLineColumn(composerLines, targetLineIndex, cursorColumn),\n type: \"setComposerCursorOffset\"\n });\n return;\n }\n\n if (key.downArrow) {\n const targetLineIndex = Math.min(cursorLineIndex + 1, composerLines.length - 1);\n\n void controller.dispatch({\n offset: getOffsetForComposerLineColumn(composerLines, targetLineIndex, cursorColumn),\n type: \"setComposerCursorOffset\"\n });\n return;\n }\n\n if (state.dropdown.open && (key.tab || input === \"\\t\" || (state.dropdown.interacted && (key.return || input === \"\\r\" || input === \"\\n\")))) {\n void controller.dispatch({\n type: \"submitComposer\"\n });\n return;\n }\n\n if (shouldInsertSlashNewlineHack(input, key)) {\n void controller.dispatch({\n type: \"insertNewline\"\n });\n return;\n }\n\n if (key.backspace || key.delete) {\n void controller.dispatch({\n type: \"backspace\"\n });\n return;\n }\n\n if (isSubmitComposerInput(input, key)) {\n void controller.dispatch({\n type: \"submitComposer\"\n });\n return;\n }\n\n if (isInsertNewlineInput(input, key)) {\n void controller.dispatch({\n type: \"insertNewline\"\n });\n return;\n }\n\n if (!input) {\n return;\n }\n\n void controller.dispatch({\n text: input,\n type: \"appendInput\"\n });\n }, {\n isActive: isRawModeSupported\n });\n const visibleLines = maxScrollOffset > 0\n ? contentLines.slice(scrollOffset, scrollOffset + viewport.rows)\n : contentLines;\n\n return (\n <Box justifyContent={viewport.columns > MAX_CONTENT_WIDTH ? \"center\" : \"flex-start\"} width=\"100%\">\n <Box flexDirection=\"column\" width={renderWidth}>\n {visibleLines.map((line) => renderLine(line, renderWidth))}\n </Box>\n </Box>\n );\n}\n","import { filterSlashCommands, getSlashQuery } from \"./commands.js\";\nimport type { UiLogEntry, UiMode, UiRuntimeSnapshot, UiState, UiWorkspaceInfo } from \"./types.js\";\n\nexport const LOG_ENTRY_LINE_LIMIT = 3;\nexport const PROMPT_PREVIEW_LINE_LIMIT = 5;\n\nconst CODE_BLOCK_PATTERN = /```[\\s\\S]*?```/g;\n\nfunction toSingleLine(value: string): string {\n return value.replace(/\\s+/g, \" \").trim();\n}\n\nexport function formatClockTime(timestamp: number): string {\n return new Date(timestamp).toLocaleTimeString(\"en-GB\", {\n hour12: false\n });\n}\n\nexport function formatCompactDuration(durationMs: number | null): string {\n if (durationMs === null || durationMs <= 0) {\n return \"0s\";\n }\n\n const totalSeconds = Math.max(1, Math.round(durationMs / 1000));\n const minutes = Math.floor(totalSeconds / 60);\n const seconds = totalSeconds % 60;\n\n if (minutes === 0) {\n return `${seconds}s`;\n }\n\n if (minutes < 60) {\n return `${minutes}m ${String(seconds).padStart(2, \"0\")}s`;\n }\n\n const hours = Math.floor(minutes / 60);\n const remainingMinutes = minutes % 60;\n\n return `${hours}h ${String(remainingMinutes).padStart(2, \"0\")}m`;\n}\n\nexport function formatTimeLeft(stopAt: number | null, now = Date.now()): string | null {\n if (stopAt === null) {\n return null;\n }\n\n const remainingMs = Math.max(stopAt - now, 0);\n const totalSeconds = Math.ceil(remainingMs / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n\n return `time left: ${hours}:${String(minutes).padStart(2, \"0\")}:${String(seconds).padStart(2, \"0\")}`;\n}\n\nexport function formatHookStatus(snapshot: UiRuntimeSnapshot): string | null {\n if (!snapshot.session.hookStatus) {\n return snapshot.connectionState === \"ready\"\n ? \"hook: ready\"\n : null;\n }\n\n return `hook: ${snapshot.session.hookStatus.ok ? \"✓\" : \"✗\"} ${snapshot.session.hookStatus.code}`;\n}\n\nexport function formatSessionInfo(snapshot: UiRuntimeSnapshot, now = Date.now()): string {\n const parts: string[] = [];\n\n if (snapshot.session.currentTurn !== null && snapshot.session.totalTurns !== null) {\n parts.push(`${snapshot.session.currentTurn}/${snapshot.session.totalTurns} turns`);\n } else if (snapshot.session.currentTurn !== null) {\n parts.push(`${snapshot.session.currentTurn} turns`);\n }\n\n const timeLeftLabel = formatTimeLeft(snapshot.session.stopAt, now);\n\n if (timeLeftLabel) {\n parts.push(timeLeftLabel);\n }\n\n const hookStatusLabel = formatHookStatus(snapshot);\n\n if (hookStatusLabel) {\n parts.push(hookStatusLabel);\n }\n\n return parts.join(\" • \");\n}\n\nexport function formatWorkspaceLine(workspace: UiWorkspaceInfo): string {\n const parts = [workspace.cwd, workspace.gitBranch];\n const gitParts: string[] = [];\n\n if (workspace.ahead > 0) {\n gitParts.push(`↑${workspace.ahead} ahead`);\n }\n\n if (workspace.behind > 0) {\n gitParts.push(`↓${workspace.behind} behind`);\n }\n\n if (gitParts.length > 0) {\n parts.push(gitParts.join(\" \"));\n }\n\n return parts.join(\" • \");\n}\n\nexport function getActivePrompt(state: UiState): string {\n return state.runtime.prompts[state.activeMode];\n}\n\nexport function getModeLabel(mode: UiMode): string {\n if (mode === \"off\") {\n return \"Off\";\n }\n\n if (mode === \"static\") {\n return \"Static\";\n }\n\n if (mode === \"thinking\") {\n return \"Thinking\";\n }\n\n return \"Agent\";\n}\n\nexport function getModeTone(mode: UiMode): \"cyan\" | \"gray\" | \"orange\" | \"yellow\" {\n if (mode === \"off\") {\n return \"gray\";\n }\n\n if (mode === \"static\") {\n return \"cyan\";\n }\n\n if (mode === \"thinking\") {\n return \"yellow\";\n }\n\n return \"orange\";\n}\n\nexport function getModeUnavailableMessage(mode: UiMode): string | null {\n if (mode === \"off\") {\n return \"Off mode is passive. Codex-bee only records stats and turn logs.\";\n }\n\n if (mode === \"static\") {\n return null;\n }\n\n return `${getModeLabel(mode)} mode is visual-only in the isolated harness right now.`;\n}\n\nexport function getVisibleSlashCommands(state: UiState) {\n const query = getSlashQuery(state.composerText);\n\n if (query === null) {\n return [];\n }\n\n return filterSlashCommands(query);\n}\n\nexport function getVisibleSlashPlaceholder(state: UiState): string | null {\n const trimmedComposer = state.composerText.trimEnd();\n\n for (const command of filterSlashCommands(\"\")) {\n if (trimmedComposer !== command.name) {\n continue;\n }\n\n return command.placeholder;\n }\n\n if (!state.composerText.endsWith(\" \")) {\n return null;\n }\n\n const command = filterSlashCommands(\"\").find((candidate) => state.composerText === `${candidate.name} `);\n\n return command?.placeholder ?? null;\n}\n\nexport function normalizeLogEntryText(entry: UiLogEntry): string {\n if (entry.kind !== \"model\") {\n return entry.text;\n }\n\n return entry.text.replace(CODE_BLOCK_PATTERN, \"[~code block~]\");\n}\n\nexport function splitPreservingEmptyLines(value: string): string[] {\n if (!value) {\n return [\"\"];\n }\n\n return value.split(\"\\n\");\n}\n\nexport function truncateLines(value: string, maxLines: number): string[] {\n const lines = splitPreservingEmptyLines(value);\n\n if (lines.length <= maxLines) {\n return lines;\n }\n\n const visibleLines = lines.slice(0, maxLines);\n const lastLine = visibleLines[maxLines - 1] ?? \"\";\n\n visibleLines[maxLines - 1] = `${lastLine}${lastLine ? \" \" : \"\"}...`;\n\n return visibleLines;\n}\n\nexport function formatPromptPreview(prompt: string, maxLines = PROMPT_PREVIEW_LINE_LIMIT): string[] {\n return truncateLines(prompt, maxLines);\n}\n\nexport function formatLogPreview(entry: UiLogEntry, maxLines = LOG_ENTRY_LINE_LIMIT): string[] {\n return truncateLines(normalizeLogEntryText(entry), maxLines);\n}\n\nexport function formatCodexEcho(prompt: string): string {\n const inlinePrompt = toSingleLine(prompt);\n\n if (!inlinePrompt) {\n return \"Waiting for the next prompt...\";\n }\n\n return inlinePrompt.length <= 72\n ? inlinePrompt\n : `${inlinePrompt.slice(0, 69).trimEnd()}...`;\n}\n\nexport function getPromptSourceLabel(state: UiState): string {\n const modeMessage = getModeUnavailableMessage(state.activeMode);\n\n if (!modeMessage) {\n return \"Static mode will submit the composer text to the mocked Codex runtime.\";\n }\n\n return modeMessage;\n}\n\nexport function getSelectedSlashCommand(state: UiState) {\n const commands = getVisibleSlashCommands(state);\n\n if (commands.length === 0) {\n return null;\n }\n\n const selectedIndex = Math.max(0, Math.min(commands.length - 1, state.dropdown.selectedIndex));\n\n return commands[selectedIndex] ?? null;\n}\n","import { Box, Text } from \"ink\";\nimport React from \"react\";\nimport stringWidth from \"string-width\";\n\nexport interface InkLineSegment {\n backgroundColor?: string;\n bold?: boolean;\n color?: string;\n dimColor?: boolean;\n italic?: boolean;\n text: string;\n}\n\nexport interface InkLineSpec {\n backgroundColor?: string;\n key: string;\n segments: InkLineSegment[];\n}\n\nexport function measureText(value: string): number {\n return stringWidth(value);\n}\n\nexport function takeDisplayWidth(value: string, width: number): string {\n if (width <= 0 || !value) {\n return \"\";\n }\n\n let result = \"\";\n\n for (const character of Array.from(value)) {\n if (measureText(result + character) > width) {\n break;\n }\n\n result += character;\n }\n\n return result;\n}\n\nexport function truncateDisplayWidth(value: string, width: number): string {\n if (measureText(value) <= width) {\n return value;\n }\n\n if (width <= 3) {\n return takeDisplayWidth(value, width);\n }\n\n return `${takeDisplayWidth(value, width - 3)}...`;\n}\n\nfunction wrapSingleLine(value: string, width: number): string[] {\n if (width <= 0) {\n return [\"\"];\n }\n\n if (!value) {\n return [\"\"];\n }\n\n const tokens = value.split(/(\\s+)/);\n const wrappedLines: string[] = [];\n let currentLine = \"\";\n\n for (const token of tokens) {\n if (!token) {\n continue;\n }\n\n if (/^\\s+$/.test(token)) {\n if (!currentLine) {\n continue;\n }\n\n if (measureText(currentLine + token) <= width) {\n currentLine += token;\n } else {\n wrappedLines.push(currentLine.trimEnd());\n currentLine = \"\";\n }\n\n continue;\n }\n\n if (measureText(token) > width) {\n if (currentLine) {\n wrappedLines.push(currentLine.trimEnd());\n currentLine = \"\";\n }\n\n let remaining = token;\n\n while (measureText(remaining) > width) {\n const slice = takeDisplayWidth(remaining, width);\n\n wrappedLines.push(slice);\n remaining = remaining.slice(slice.length);\n }\n\n currentLine = remaining;\n continue;\n }\n\n if (measureText(currentLine + token) <= width) {\n currentLine += token;\n continue;\n }\n\n wrappedLines.push(currentLine.trimEnd());\n currentLine = token;\n }\n\n wrappedLines.push(currentLine.trimEnd());\n\n return wrappedLines.length > 0 ? wrappedLines : [\"\"];\n}\n\nexport function wrapText(value: string, width: number): string[] {\n const sourceLines = value.split(\"\\n\");\n const wrappedLines: string[] = [];\n\n for (const line of sourceLines) {\n const nextLines = wrapSingleLine(line, width);\n\n wrappedLines.push(...nextLines);\n }\n\n return wrappedLines.length > 0 ? wrappedLines : [\"\"];\n}\n\nfunction wrapVerbatimLine(value: string, width: number): string[] {\n if (width <= 0) {\n return [\"\"];\n }\n\n if (!value) {\n return [\"\"];\n }\n\n const wrappedLines: string[] = [];\n let currentLine = \"\";\n\n for (const character of Array.from(value)) {\n if (measureText(currentLine + character) > width) {\n wrappedLines.push(currentLine);\n currentLine = character;\n continue;\n }\n\n currentLine += character;\n }\n\n wrappedLines.push(currentLine);\n\n return wrappedLines.length > 0 ? wrappedLines : [\"\"];\n}\n\nexport function wrapTextVerbatim(value: string, width: number): string[] {\n const sourceLines = value.split(\"\\n\");\n const wrappedLines: string[] = [];\n\n for (const line of sourceLines) {\n wrappedLines.push(...wrapVerbatimLine(line, width));\n }\n\n return wrappedLines.length > 0 ? wrappedLines : [\"\"];\n}\n\nexport function wrapAndLimit(value: string, width: number, maxLines: number): string[] {\n const wrappedLines = wrapText(value, width);\n\n if (wrappedLines.length <= maxLines) {\n return wrappedLines;\n }\n\n const visibleLines = wrappedLines.slice(0, maxLines);\n\n visibleLines[maxLines - 1] = truncateDisplayWidth(\n `${visibleLines[maxLines - 1] ?? \"\"} ...`.trim(),\n width\n );\n\n return visibleLines;\n}\n\nexport function padLine(line: InkLineSpec, width: number): InkLineSpec {\n const lineWidth = line.segments.reduce((total, segment) => total + measureText(segment.text), 0);\n const paddingWidth = Math.max(width - lineWidth, 0);\n\n if (paddingWidth === 0) {\n return line;\n }\n\n return {\n ...line,\n segments: [\n ...line.segments,\n {\n backgroundColor: line.backgroundColor,\n text: \" \".repeat(paddingWidth)\n }\n ]\n };\n}\n\nexport function overlayLines(\n lines: InkLineSpec[],\n overlay: InkLineSpec[],\n startIndex: number\n): InkLineSpec[] {\n if (overlay.length === 0) {\n return lines;\n }\n\n const nextLines = [...lines];\n\n for (let index = 0; index < overlay.length; index += 1) {\n const targetIndex = startIndex + index;\n\n if (targetIndex < 0 || targetIndex >= nextLines.length) {\n continue;\n }\n\n nextLines[targetIndex] = overlay[index];\n }\n\n return nextLines;\n}\n\nexport function renderLine(line: InkLineSpec, width: number): React.JSX.Element {\n const paddedLine = padLine(line, width);\n\n return (\n <Box key={line.key} width={width}>\n {paddedLine.segments.map((segment, index) => (\n <Text\n key={`${line.key}-${index}`}\n backgroundColor={segment.backgroundColor ?? line.backgroundColor}\n bold={segment.bold}\n color={segment.color}\n dimColor={segment.dimColor}\n italic={segment.italic}\n >\n {segment.text}\n </Text>\n ))}\n </Box>\n );\n}\n","import { execFile } from \"node:child_process\";\nimport process from \"node:process\";\nimport { promisify } from \"node:util\";\nimport type {\n ContinuationController,\n ContinuationDecision,\n ContinuationSnapshot\n} from \"../../auto-continue.js\";\nimport type { HookCapture, StopCapture } from \"../../hook-server.js\";\nimport type { ContinuationPromptProxy } from \"../../continuation-watcher.js\";\nimport { summarizeTranscriptFile } from \"../../transcript.js\";\nimport type { VerificationCommandResult } from \"../../verification.js\";\nimport { formatCodexEcho } from \"../core/view-model.js\";\nimport type {\n UiCommandInvocation,\n UiConnectionState,\n UiLogEntry,\n UiLogEntryKind,\n UiRuntimeSnapshot,\n UiTurnGroup,\n UiWorkspaceInfo\n} from \"../core/types.js\";\nimport type { UiHostUpdate, UiRuntimeHost } from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\nconst MAX_EVENT_LINES = 8;\n\ninterface PendingPrompt {\n startedAt: number;\n text: string;\n}\n\nexport interface LiveUiWatcherTurnEvent {\n capture: StopCapture;\n decision: ContinuationDecision;\n sessionId: string;\n verificationCommand: string | null;\n verificationErrorMessage: string | null;\n verificationResult: VerificationCommandResult | null;\n willInject: boolean;\n}\n\nexport interface LiveUiWatcherInjectionEvent {\n capture: StopCapture;\n decision: ContinuationDecision;\n prompt: string;\n sessionId: string;\n}\n\nexport interface LiveUiAuxiliaryHookEvent {\n capture: HookCapture;\n}\n\nexport interface LiveUiRuntimeHostOptions {\n beeVersion: string;\n codexCommand: string;\n codexVersion?: string;\n continuation: ContinuationController;\n cwd: string;\n initialAnnouncementMessage?: string | null;\n initialConnectionState?: UiConnectionState;\n initialVerificationCommand?: string | null;\n promptProxy: ContinuationPromptProxy;\n}\n\nfunction cloneLogEntry(entry: UiLogEntry): UiLogEntry {\n return {\n ...entry\n };\n}\n\nfunction cloneTurnGroup(group: UiTurnGroup): UiTurnGroup {\n return {\n ...group,\n entries: group.entries.map(cloneLogEntry)\n };\n}\n\nfunction cloneSnapshot(snapshot: UiRuntimeSnapshot): UiRuntimeSnapshot {\n return {\n ...snapshot,\n announcement: snapshot.announcement\n ? {\n ...snapshot.announcement\n }\n : null,\n codexBufferLines: [...snapshot.codexBufferLines],\n logs: snapshot.logs.map(cloneTurnGroup),\n prompts: {\n ...snapshot.prompts\n },\n session: {\n ...snapshot.session,\n hookStatus: snapshot.session.hookStatus\n ? {\n ...snapshot.session.hookStatus\n }\n : null\n },\n workspace: {\n ...snapshot.workspace\n }\n };\n}\n\nfunction normalizeAnnouncementMessage(message: string): string {\n return message.replace(/^\\[codex-bee\\]\\s*/i, \"\").trim();\n}\n\nfunction getStopAt(snapshot: ContinuationSnapshot): number | null {\n return snapshot.startedAt !== null && snapshot.maxDurationMs !== null\n ? snapshot.startedAt + snapshot.maxDurationMs\n : null;\n}\n\nfunction toUiTotalTurns(maxContinues: number): number | null {\n return Number.isFinite(maxContinues)\n ? maxContinues\n : null;\n}\n\nfunction createWorkspaceInfo(cwd: string): UiWorkspaceInfo {\n const homeDirectory = process.env.HOME ?? \"\";\n\n return {\n ahead: 0,\n behind: 0,\n cwd: homeDirectory && cwd.startsWith(homeDirectory)\n ? `~${cwd.slice(homeDirectory.length)}`\n : cwd,\n gitBranch: \"unknown\"\n };\n}\n\nfunction createInitialSnapshot(options: LiveUiRuntimeHostOptions): UiRuntimeSnapshot {\n const continuationSnapshot = options.continuation.getSnapshot();\n\n return {\n activeScenarioId: null,\n announcement: options.initialAnnouncementMessage\n ? {\n message: options.initialAnnouncementMessage\n }\n : null,\n beeVersion: options.beeVersion,\n codexBufferLines: [\n \"$ codex live session attached\",\n ...(options.initialAnnouncementMessage ? [options.initialAnnouncementMessage] : []),\n \"Ctrl+B returns to the Codex shell.\"\n ],\n codexVersion: options.codexVersion ?? \"unknown\",\n connectionState: options.initialConnectionState ?? \"ready\",\n logs: [],\n prompts: {\n off: \"Off mode is passive. Codex-bee will keep collecting stats and turn logs without sending prompts.\",\n agent: \"Agent mode is visual-only until the bee-agent runtime is wired into the new UI.\",\n static: continuationSnapshot.promptText,\n thinking: \"Thinking mode is visual-only until live reasoning controls are implemented.\"\n },\n runState: \"idle\",\n session: {\n currentTurn: 0,\n hookStatus: null,\n stopAt: getStopAt(continuationSnapshot),\n stopScript: options.initialVerificationCommand ?? null,\n totalTurns: toUiTotalTurns(continuationSnapshot.maxContinues)\n },\n workspace: createWorkspaceInfo(options.cwd)\n };\n}\n\nfunction getNextSleepTimestamp(hours: number, minutes: number, now = Date.now()): number {\n const nextTarget = new Date(now);\n\n nextTarget.setSeconds(0, 0);\n nextTarget.setHours(hours, minutes, 0, 0);\n\n if (nextTarget.getTime() <= now) {\n nextTarget.setDate(nextTarget.getDate() + 1);\n }\n\n return nextTarget.getTime();\n}\n\nfunction createLogEntry(id: string, kind: UiLogEntryKind, text: string, timestamp: number): UiLogEntry {\n return {\n id,\n kind,\n text,\n timestamp\n };\n}\n\nfunction buildHookSummary(event: LiveUiWatcherTurnEvent): {\n hookStatus: {\n code: number;\n ok: boolean;\n };\n text: string;\n} {\n if (event.verificationErrorMessage) {\n return {\n hookStatus: {\n code: 1,\n ok: false\n },\n text: `Hook: unable to run \"${event.verificationCommand ?? \"verification command\"}\".`\n };\n }\n\n if (event.verificationResult) {\n return {\n hookStatus: {\n code: event.verificationResult.code,\n ok: event.verificationResult.succeeded\n },\n text: event.verificationResult.succeeded\n ? `Hook: \"${event.verificationResult.command}\" succeeded with exit ${event.verificationResult.code}.`\n : `Hook: \"${event.verificationResult.command}\" failed with exit ${event.verificationResult.code}.`\n };\n }\n\n return {\n hookStatus: {\n code: 0,\n ok: true\n },\n text: \"Hook: Stop capture recorded successfully.\"\n };\n}\n\nfunction buildTerminalStatusMessage(event: LiveUiWatcherTurnEvent): string | null {\n if (event.verificationErrorMessage) {\n return \"Verification command failed to run, so auto-continue stopped.\";\n }\n\n if (event.verificationResult?.succeeded) {\n return \"Verification command succeeded, so auto-continue stopped.\";\n }\n\n if (event.decision.kind === \"disabled\") {\n return \"Auto-continue is currently disabled.\";\n }\n\n if (event.decision.kind === \"guardrail\" || event.decision.kind === \"expired\" || event.decision.kind === \"empty-prompt\" || event.decision.kind === \"error\") {\n return normalizeAnnouncementMessage(event.decision.message ?? \"The continuation flow stopped.\");\n }\n\n if (event.verificationResult && !event.verificationResult.succeeded) {\n return \"Verification failed, so codex-bee will keep going.\";\n }\n\n return null;\n}\n\nfunction readUserMessageFromCapture(capture: HookCapture): string | null {\n if (typeof capture.payload?.prompt === \"string\" && capture.payload.prompt.trim().length > 0) {\n return capture.payload.prompt;\n }\n\n const transcriptPath = capture.payload?.transcript_path ?? capture.transcript?.path ?? null;\n\n if (!transcriptPath) {\n return null;\n }\n\n try {\n const summary = summarizeTranscriptFile(transcriptPath, {\n maxRecentMessages: 8\n });\n const latestUserMessage = [...summary.recentMessages]\n .reverse()\n .find((message) => message.role === \"user\");\n\n return latestUserMessage?.text ?? null;\n } catch {\n return null;\n }\n}\n\nasync function readGitWorkspaceInfo(cwd: string): Promise<Partial<UiWorkspaceInfo>> {\n try {\n const [{ stdout: branchStdout }, countsResult] = await Promise.all([\n execFileAsync(\"git\", [\"branch\", \"--show-current\"], {\n cwd,\n encoding: \"utf8\"\n }),\n execFileAsync(\"git\", [\"rev-list\", \"--left-right\", \"--count\", \"@{upstream}...HEAD\"], {\n cwd,\n encoding: \"utf8\"\n }).catch(() => ({\n stdout: \"0\\t0\"\n }))\n ]);\n const [behindValue, aheadValue] = countsResult.stdout.trim().split(/\\s+/);\n const behind = Number.parseInt(behindValue ?? \"0\", 10);\n const ahead = Number.parseInt(aheadValue ?? \"0\", 10);\n\n return {\n ahead: Number.isFinite(ahead) ? ahead : 0,\n behind: Number.isFinite(behind) ? behind : 0,\n gitBranch: branchStdout.trim() || \"detached\"\n };\n } catch {\n return {};\n }\n}\n\nasync function readCodexVersion(command: string): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync(command, [\"--version\"], {\n encoding: \"utf8\"\n });\n const versionMatch = stdout.trim().match(/(\\d+\\.\\d+\\.\\d+)/);\n\n return versionMatch?.[1] ?? null;\n } catch {\n return null;\n }\n}\n\nexport class LiveUiRuntimeHost implements UiRuntimeHost {\n readonly #continuation: ContinuationController;\n readonly #codexCommand: string;\n readonly #cwd: string;\n readonly #listeners = new Set<() => void>();\n readonly #recentEvents: string[] = [];\n #entryCounter = 0;\n #pendingPrompts: PendingPrompt[] = [];\n #snapshot: UiRuntimeSnapshot;\n #verificationCommand: string | null;\n\n constructor(options: LiveUiRuntimeHostOptions) {\n this.#continuation = options.continuation;\n this.#codexCommand = options.codexCommand;\n this.#cwd = options.cwd;\n this.#verificationCommand = options.initialVerificationCommand ?? null;\n this.#snapshot = createInitialSnapshot(options);\n }\n\n subscribe(listener: () => void): () => void {\n this.#listeners.add(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n getSnapshot(): UiRuntimeSnapshot {\n return cloneSnapshot(this.#snapshot);\n }\n\n getVerificationCommand(): string | null {\n return this.#verificationCommand;\n }\n\n markDisconnected(): void {\n this.#snapshot = {\n ...this.#snapshot,\n connectionState: \"disconnected\",\n runState: \"idle\"\n };\n this.#pushEventLine(\"Codex session disconnected.\");\n this.#notify();\n }\n\n recordAuxiliaryHookEvent(capture: HookCapture): void {\n const eventName = capture.payload?.hook_event_name ?? null;\n\n if (eventName === \"SessionStart\") {\n const source = capture.payload?.source;\n this.#snapshot = {\n ...this.#snapshot,\n connectionState: \"connected\"\n };\n this.#pushEventLine(\n source === \"startup\" || source === \"resume\"\n ? `SessionStart received from ${source}. Hooks are attached to this Codex session.`\n : \"SessionStart received. Hooks are attached to this Codex session.\"\n );\n this.#notify();\n return;\n }\n\n if (eventName === \"UserPromptSubmit\") {\n const submittedAt = Date.now();\n const promptText = readUserMessageFromCapture(capture);\n\n this.#ensureTurnGroupStarted(capture, promptText, submittedAt);\n this.#snapshot = {\n ...this.#snapshot,\n connectionState: \"connected\",\n runState: \"running\",\n session: {\n ...this.#snapshot.session,\n currentTurn: this.#snapshot.logs.length\n }\n };\n this.#pushEventLine(\n promptText\n ? `UserPromptSubmit received. Codex turn is running: ${formatCodexEcho(promptText)}`\n : \"UserPromptSubmit received. Codex turn is running.\"\n );\n this.#notify();\n }\n }\n\n async refreshEnvironmentMetadata(): Promise<void> {\n const [workspaceInfo, codexVersion] = await Promise.all([\n readGitWorkspaceInfo(this.#cwd),\n readCodexVersion(this.#codexCommand)\n ]);\n\n this.#snapshot = {\n ...this.#snapshot,\n codexVersion: codexVersion ?? this.#snapshot.codexVersion,\n workspace: {\n ...this.#snapshot.workspace,\n ...workspaceInfo\n }\n };\n this.#notify();\n }\n\n async executeCommand(command: UiCommandInvocation): Promise<UiHostUpdate> {\n switch (command.id) {\n case \"clear-log\":\n this.#snapshot = {\n ...this.#snapshot,\n logs: [],\n session: {\n ...this.#snapshot.session,\n currentTurn: 0\n }\n };\n this.#pushEventLine(\"Cleared the live turn log.\");\n\n return this.#createUpdate(\"Cleared the live turn log.\");\n case \"duration\": {\n const currentContinuation = this.#continuation.getSnapshot();\n const updatedSnapshot = this.#continuation.updateInteractiveDraft({\n maxContinues: currentContinuation.maxContinues,\n maxDurationMs: command.minutes * 60 * 1000,\n prompt: currentContinuation.promptText\n });\n\n this.#syncContinuationState(updatedSnapshot);\n this.#pushEventLine(`Updated the session duration to ${command.minutes} minute(s).`);\n\n return this.#createUpdate(`Set the live session duration to ${command.minutes} minute(s).`);\n }\n case \"quit\":\n return this.#createUpdate(\"Exiting the current codex-bee session.\", {\n exitRequested: true,\n noticeKind: \"warning\"\n });\n case \"sleep\": {\n const stopAt = getNextSleepTimestamp(command.hours, command.minutes);\n const currentContinuation = this.#continuation.getSnapshot();\n const updatedSnapshot = this.#continuation.updateInteractiveDraft({\n maxContinues: currentContinuation.maxContinues,\n maxDurationMs: Math.max(stopAt - Date.now(), 1_000),\n prompt: currentContinuation.promptText\n });\n\n this.#syncContinuationState(updatedSnapshot);\n this.#pushEventLine(`Set the absolute stop time to ${command.time}.`);\n\n return this.#createUpdate(`Set the live stop time to ${command.time}.`);\n }\n case \"steps-count\": {\n const currentContinuation = this.#continuation.getSnapshot();\n const updatedSnapshot = this.#continuation.updateInteractiveDraft({\n maxContinues: command.steps,\n maxDurationMs: currentContinuation.maxDurationMs,\n prompt: currentContinuation.promptText\n });\n\n this.#syncContinuationState(updatedSnapshot);\n this.#pushEventLine(`Updated the max turns count to ${command.steps}.`);\n\n return this.#createUpdate(`Updated the live max turns count to ${command.steps}.`);\n }\n case \"stop-script\":\n this.#verificationCommand = command.command;\n this.#snapshot = {\n ...this.#snapshot,\n session: {\n ...this.#snapshot.session,\n stopScript: command.command\n }\n };\n this.#pushEventLine(`Stored the stop script: ${command.command}`);\n\n return this.#createUpdate(`Stored the live stop script: ${command.command}`);\n default:\n return this.#createUpdate(\"The live runtime ignored an unknown command.\", {\n noticeKind: \"error\"\n });\n }\n }\n\n setMode(mode: \"agent\" | \"off\" | \"static\" | \"thinking\"): UiHostUpdate {\n if (mode === \"off\") {\n const updatedSnapshot = this.#continuation.disable();\n\n this.#syncContinuationState(updatedSnapshot);\n this.#snapshot = {\n ...this.#snapshot,\n announcement: {\n message: \"Off mode is passive. Codex-bee keeps collecting stats and logs without sending prompts.\"\n },\n runState: \"idle\"\n };\n this.#pushEventLine(\"Switched to Off mode. Auto-continue is disabled.\");\n\n return this.#createUpdate(\"Off mode is passive. Codex-bee will only keep logging turns.\");\n }\n\n this.#snapshot = {\n ...this.#snapshot,\n announcement: null\n };\n\n return this.#createUpdate(\"Static mode is ready to stage the next Stop hook prompt.\");\n }\n\n async submitPrompt(options: {\n mode: \"agent\" | \"off\" | \"static\" | \"thinking\";\n text: string;\n }): Promise<UiHostUpdate> {\n if (options.mode !== \"static\") {\n return this.#createUpdate(`${options.mode} mode is visual-only right now.`, {\n noticeKind: \"warning\"\n });\n }\n\n const continuationSnapshot = this.#continuation.getSnapshot();\n const rearmedSnapshot = this.#continuation.applyInteractiveDraft({\n maxContinues: continuationSnapshot.maxContinues,\n maxDurationMs: continuationSnapshot.maxDurationMs,\n prompt: options.text\n });\n\n this.#syncContinuationState(rearmedSnapshot);\n this.#snapshot = {\n ...this.#snapshot,\n announcement: null\n };\n this.#pushEventLine(`Staged prompt: ${formatCodexEcho(options.text)}`);\n\n return this.#createUpdate(\"Stored the prompt for the next Stop hook.\");\n }\n\n recordContinuationPromptInjected(event: LiveUiWatcherInjectionEvent): void {\n const statusText = event.decision.kind === \"generate\"\n ? `Injected a bee-agent continuation prompt (${event.decision.injectionNumber ?? \"?\"}/${event.decision.maxContinues ?? \"?\"}).`\n : `Injected the next continuation prompt (${event.decision.injectionNumber ?? \"?\"}/${event.decision.maxContinues ?? \"?\"}).`;\n const completedTurnId = event.capture.payload?.turn_id ?? null;\n\n this.#pendingPrompts.push({\n startedAt: Date.now(),\n text: event.prompt\n });\n this.#appendEntryToTurn(completedTurnId, \"status\", statusText);\n\n if (event.decision.guardrailReached) {\n this.#appendEntryToTurn(\n completedTurnId,\n \"status\",\n `Guardrail reached at ${event.decision.maxContinues ?? \"?\"} injections. The next completed turn will stop the loop.`\n );\n this.#snapshot = {\n ...this.#snapshot,\n announcement: {\n message: `Guardrail reached after the latest injection (${event.decision.maxContinues ?? \"?\"} max turns).`\n }\n };\n }\n\n this.#pushEventLine(statusText);\n this.#notify();\n }\n\n recordStopCaptureHandled(event: LiveUiWatcherTurnEvent): void {\n const completedAt = Date.now();\n const pendingPrompt = this.#pendingPrompts.shift() ?? null;\n const transcriptUserMessage = readUserMessageFromCapture(event.capture);\n const existingGroupIndex = event.capture.payload?.turn_id\n ? this.#snapshot.logs.findIndex((group) => group.id === event.capture.payload?.turn_id)\n : -1;\n const existingGroup = existingGroupIndex >= 0\n ? this.#snapshot.logs[existingGroupIndex] ?? null\n : null;\n const turnNumber = existingGroup?.turn ?? (this.#snapshot.logs.length + 1);\n const continuationSnapshot = this.#continuation.getSnapshot();\n const hookSummary = buildHookSummary(event);\n const entries: UiLogEntry[] = existingGroup\n ? [...existingGroup.entries]\n : [];\n\n const userMessageText = pendingPrompt?.text ?? transcriptUserMessage;\n\n if (userMessageText && !entries.some((entry) => entry.kind === \"user\")) {\n entries.push(this.#nextLogEntry(\"user\", userMessageText, pendingPrompt?.startedAt ?? completedAt));\n }\n\n if (event.capture.payload?.last_assistant_message) {\n entries.push(\n this.#nextLogEntry(\n \"model\",\n event.capture.payload.last_assistant_message,\n completedAt\n )\n );\n }\n\n entries.push(this.#nextLogEntry(\"hook\", hookSummary.text, completedAt));\n\n const terminalStatusMessage = buildTerminalStatusMessage(event);\n\n if (terminalStatusMessage) {\n entries.push(this.#nextLogEntry(\"status\", terminalStatusMessage, completedAt));\n }\n\n const groupId = event.capture.payload?.turn_id ?? `turn-${turnNumber}-${completedAt}`;\n const turnStartedAt = existingGroup?.entries.find((entry) => entry.kind === \"user\")?.timestamp\n ?? pendingPrompt?.startedAt\n ?? null;\n const nextGroup: UiTurnGroup = {\n durationMs: turnStartedAt !== null\n ? Math.max(completedAt - turnStartedAt, 0)\n : existingGroup?.durationMs ?? null,\n entries,\n id: groupId,\n totalTurns: toUiTotalTurns(continuationSnapshot.maxContinues),\n turn: turnNumber\n };\n const nextLogs = existingGroupIndex >= 0\n ? this.#snapshot.logs.map((group, index) => index === existingGroupIndex ? nextGroup : group)\n : [...this.#snapshot.logs, nextGroup];\n\n this.#snapshot = {\n ...this.#snapshot,\n connectionState: \"connected\",\n announcement: this.#buildAnnouncement(event, terminalStatusMessage),\n logs: nextLogs,\n runState: \"idle\",\n session: {\n ...this.#snapshot.session,\n currentTurn: nextLogs.length,\n hookStatus: hookSummary.hookStatus,\n stopAt: getStopAt(continuationSnapshot),\n stopScript: this.#verificationCommand,\n totalTurns: toUiTotalTurns(continuationSnapshot.maxContinues)\n }\n };\n this.#pushEventLine(\n event.capture.payload?.last_assistant_message\n ? `Turn ${turnNumber} completed: ${formatCodexEcho(event.capture.payload.last_assistant_message)}`\n : `Turn ${turnNumber} completed without an assistant summary.`\n );\n this.#notify();\n }\n\n #appendEntryToTurn(turnId: string | null, kind: UiLogEntryKind, text: string): void {\n const targetIndex = turnId\n ? this.#snapshot.logs.findIndex((group) => group.id === turnId)\n : this.#snapshot.logs.length - 1;\n\n if (targetIndex < 0) {\n return;\n }\n\n const targetGroup = this.#snapshot.logs[targetIndex];\n\n if (!targetGroup) {\n return;\n }\n\n const updatedGroup: UiTurnGroup = {\n ...targetGroup,\n entries: [\n ...targetGroup.entries,\n this.#nextLogEntry(kind, text, Date.now())\n ]\n };\n const nextLogs = [...this.#snapshot.logs];\n\n nextLogs[targetIndex] = updatedGroup;\n this.#snapshot = {\n ...this.#snapshot,\n logs: nextLogs\n };\n }\n\n #ensureTurnGroupStarted(capture: HookCapture, promptText: string | null, startedAt: number): void {\n const turnId = capture.payload?.turn_id ?? `turn-pending-${startedAt}`;\n const targetIndex = this.#snapshot.logs.findIndex((group) => group.id === turnId);\n\n if (targetIndex >= 0) {\n const targetGroup = this.#snapshot.logs[targetIndex];\n\n if (!targetGroup) {\n return;\n }\n\n if (!promptText || targetGroup.entries.some((entry) => entry.kind === \"user\")) {\n return;\n }\n\n const nextLogs = [...this.#snapshot.logs];\n\n nextLogs[targetIndex] = {\n ...targetGroup,\n entries: [\n this.#nextLogEntry(\"user\", promptText, startedAt),\n ...targetGroup.entries\n ]\n };\n this.#snapshot = {\n ...this.#snapshot,\n logs: nextLogs\n };\n\n return;\n }\n\n if (!promptText) {\n return;\n }\n\n const turnNumber = this.#snapshot.logs.length + 1;\n const nextGroup: UiTurnGroup = {\n durationMs: null,\n entries: [\n this.#nextLogEntry(\"user\", promptText, startedAt)\n ],\n id: turnId,\n totalTurns: toUiTotalTurns(this.#continuation.getSnapshot().maxContinues),\n turn: turnNumber\n };\n\n this.#snapshot = {\n ...this.#snapshot,\n logs: [...this.#snapshot.logs, nextGroup]\n };\n }\n\n #buildAnnouncement(event: LiveUiWatcherTurnEvent, terminalStatusMessage: string | null): {\n message: string;\n } | null {\n if (event.verificationErrorMessage) {\n return {\n message: \"Verification command failed to run, so the loop stopped.\"\n };\n }\n\n if (event.verificationResult && !event.verificationResult.succeeded) {\n return {\n message: \"Verification failed after the latest turn. Codex-bee kept the loop alive.\"\n };\n }\n\n if (event.verificationResult?.succeeded) {\n return {\n message: \"Verification succeeded after the latest turn. Auto-continue stopped.\"\n };\n }\n\n if (!terminalStatusMessage) {\n return null;\n }\n\n return {\n message: terminalStatusMessage\n };\n }\n\n #createUpdate(\n message: string,\n options?: {\n exitRequested?: boolean;\n noticeKind?: \"error\" | \"info\" | \"warning\";\n }\n ): UiHostUpdate {\n return {\n exitRequested: options?.exitRequested,\n notice: {\n kind: options?.noticeKind ?? \"info\",\n message\n },\n snapshot: cloneSnapshot(this.#snapshot)\n };\n }\n\n #nextLogEntry(kind: UiLogEntryKind, text: string, timestamp: number): UiLogEntry {\n this.#entryCounter += 1;\n\n return createLogEntry(`entry-${this.#entryCounter}`, kind, text, timestamp);\n }\n\n #notify(): void {\n for (const listener of this.#listeners) {\n listener();\n }\n }\n\n #pushEventLine(text: string): void {\n this.#recentEvents.push(text);\n\n while (this.#recentEvents.length > MAX_EVENT_LINES) {\n this.#recentEvents.shift();\n }\n\n this.#snapshot = {\n ...this.#snapshot,\n codexBufferLines: [\n \"$ codex live session attached\",\n ...this.#recentEvents\n ]\n };\n }\n\n #syncContinuationState(snapshot: ContinuationSnapshot): void {\n const connectionState: UiConnectionState = this.#snapshot.connectionState;\n const currentTurn = this.#snapshot.logs.length;\n\n this.#snapshot = {\n ...this.#snapshot,\n connectionState,\n prompts: {\n ...this.#snapshot.prompts,\n static: snapshot.promptText\n },\n runState: this.#snapshot.runState,\n session: {\n ...this.#snapshot.session,\n currentTurn,\n stopAt: getStopAt(snapshot),\n stopScript: this.#verificationCommand,\n totalTurns: toUiTotalTurns(snapshot.maxContinues)\n }\n };\n }\n}\n"],"mappings":";;;AAEA,SAAS,kBAAk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AC1B,wBAAwB,CAAC,SAAS,WAAW,uBAAuB;AAAA,MAClE;AAAA,MACA,KAAKA,SAAQ,IAAI;AAAA,MACjB;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAAA,IACD;AAAA,IACA,KAAKA,SAAQ,IAAI;AAAA,IACjB,wBAAwB,MAAM,YAAY,uBAAuB;AAAA,IACjE,eAAe,QAAQ;AAAA,IACvB;AAAA,IACA,kBAAkB,CAAC,UAAU;AAC3B,kBAAY,iCAAiC,KAAK;AAAA,IACpD;AAAA,IACA,sBAAsB,CAAC,UAAU;AAC/B,kBAAY,yBAAyB,KAAK;AAAA,IAC5C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ,uBAAuB;AAAA,IAC/B,qBAAqB,QAAQ;AAAA,EAC/B,CAAC,EAAE,MAAM,CAAC,UAAmB;AAC3B,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,WAAO,IAAI,gCAAgC;AAAA,MACzC;AAAA,IACF,CAAC;AACD,YAAQ,MAAM,6CAA6C,OAAO,EAAE;AAAA,EACtE,CAAC;AAED,EAAAA,SAAQ,WAAW,MAAM,MAAM,YAAY;AAC3C,yBAAuB,MAAM;AAC7B,UAAQ,QAAQ;AAChB,cAAY,iBAAiB;AAC/B;AAEA,IAAI;AACF,QAAM,KAAK;AACb,SAAS,OAAO;AACd,UAAQ,MAAM,eAAeF,gBAAe,KAAK,CAAC,EAAE;AACpD,EAAAE,SAAQ,WAAW;AACrB;","names":["execFile","fs","path","process","promisify","readFileSync","process","text","readFileSync","resolve","process","readFileSync","readFileSync","SINGLE_LINE_WHITESPACE_PATTERN","toSingleLine","SINGLE_LINE_WHITESPACE_PATTERN","toErrorMessage","guardrailReached","path","process","path","process","resolve","path","spawn","WINDOWS_LINE_ENDING_PATTERN","resolve","runVerificationCommand","process","prompt","isTimeoutError","fs","path","toErrorMessage","spawn","resolve","spawn","process","delay","shellEscape","resolve","fs","path","toErrorMessage","update","process","React","Box","toSingleLine","command","toSingleLine","jsx","Box","process","React","process","process","require","execFileAsync","promisify","execFile","toErrorMessage","path","process","fs"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/bee-agent.ts","../src/transcript.ts","../src/continuation-source.ts","../src/continuation.ts","../src/auto-continue.ts","../src/cli-options.ts","../src/continuation-watcher.ts","../src/hook-server.ts","../src/verification.ts","../src/hook-event-watcher.ts","../src/hook-config.ts","../src/passthrough.ts","../src/pty-proxy.ts","../src/runtime-log.ts","../src/ui/core/commands.ts","../src/ui/core/types.ts","../src/ui/core/controller.ts","../src/ui/live-overlay.ts","../src/ui/input-shortcuts.ts","../src/ui/renderers/ink/app.tsx","../src/ui/core/view-model.ts","../src/ui/renderers/ink/renderer-utils.tsx","../src/ui/runtime/live-runtime.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { randomUUID } from \"node:crypto\";\nimport { execFile } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport * as readline from \"node:readline/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { promisify } from \"node:util\";\nimport { ContinuationController } from \"./auto-continue.js\";\nimport { generateBeeAgentPrompt } from \"./bee-agent.js\";\nimport { HELP_TEXT, parseWrapperOptions } from \"./cli-options.js\";\nimport { runContinuationWatcher } from \"./continuation-watcher.js\";\nimport { runHookEventWatcher } from \"./hook-event-watcher.js\";\nimport {\n collectCodexFeatureProbeArgs,\n getGlobalCodexConfigPath,\n inspectCodexHookSetup,\n inspectCodexHooksFeatureListOutput,\n resolveCodexProfile,\n upsertCodexHooksFeatureConfigText,\n upsertStopHookConfigText,\n writeCodexConfigFile,\n writeHookConfigFile,\n type CodexHooksFeatureInspection,\n type HookSetupInspection\n} from \"./hook-config.js\";\nimport { resolveExecutionMode, runPassthroughCommand } from \"./passthrough.js\";\nimport { PtyProxy } from \"./pty-proxy.js\";\nimport { createRuntimeEventLogger } from \"./runtime-log.js\";\nimport { UiController } from \"./ui/core/controller.js\";\nimport { LiveInkOverlayManager } from \"./ui/live-overlay.js\";\nimport { LiveUiRuntimeHost } from \"./ui/runtime/live-runtime.js\";\nimport type { UiConnectionState } from \"./ui/core/types.js\";\nimport { runVerificationCommand } from \"./verification.js\";\n\nconst require = createRequire(import.meta.url);\nconst packageJson = require(\"../package.json\") as {\n version?: unknown;\n};\nconst CLI_VERSION = typeof packageJson.version === \"string\"\n ? packageJson.version\n : \"0.0.0\";\nconst execFileAsync = promisify(execFile);\nconst CODEX_INTERACTIVE_SUBCOMMANDS = new Set([\n \"fork\",\n \"resume\"\n]);\nconst CODEX_NONINTERACTIVE_SUBCOMMANDS = new Set([\n \"app-server\",\n \"apply\",\n \"cloud\",\n \"completion\",\n \"debug\",\n \"exec\",\n \"features\",\n \"help\",\n \"login\",\n \"logout\",\n \"mcp\",\n \"mcp-server\",\n \"review\",\n \"sandbox\"\n]);\nconst CODEX_OPTIONS_WITH_VALUE = new Set([\n \"-a\",\n \"-c\",\n \"-C\",\n \"-i\",\n \"-m\",\n \"-p\",\n \"-s\",\n \"--add-dir\",\n \"--ask-for-approval\",\n \"--cd\",\n \"--config\",\n \"--disable\",\n \"--enable\",\n \"--image\",\n \"--local-provider\",\n \"--model\",\n \"--profile\",\n \"--remote\",\n \"--remote-auth-token-env\",\n \"--sandbox\"\n]);\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction getBundledStopHookPath(): string {\n return path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"..\", \"hooks\", \"stop-hook.cjs\");\n}\n\nfunction isCodexCommand(command: string): boolean {\n return path.basename(command) === \"codex\";\n}\n\nfunction shouldPrepareInteractiveCodexHooks(commandArgs: readonly string[]): boolean {\n if (commandArgs.includes(\"-h\") || commandArgs.includes(\"--help\") || commandArgs.includes(\"-V\") || commandArgs.includes(\"--version\")) {\n return false;\n }\n\n for (let index = 0; index < commandArgs.length; index += 1) {\n const argument = commandArgs[index];\n\n if (CODEX_OPTIONS_WITH_VALUE.has(argument)) {\n index += 1;\n continue;\n }\n\n if (argument.startsWith(\"-\")) {\n continue;\n }\n\n if (CODEX_NONINTERACTIVE_SUBCOMMANDS.has(argument)) {\n return false;\n }\n\n if (CODEX_INTERACTIVE_SUBCOMMANDS.has(argument)) {\n return true;\n }\n\n return true;\n }\n\n return true;\n}\n\nasync function promptYesNo(question: string, options?: {\n defaultValue?: boolean;\n}): Promise<boolean> {\n const defaultValue = options?.defaultValue ?? true;\n const promptLabel = defaultValue ? \"[Y/n]\" : \"[y/N]\";\n const terminal = readline.createInterface({\n input: process.stdin,\n output: process.stderr\n });\n\n try {\n const answer = (await terminal.question(`[codex-bee] ${question} ${promptLabel} `))\n .trim()\n .toLowerCase();\n\n if (answer.length === 0) {\n return defaultValue;\n }\n\n return answer === \"y\" || answer === \"yes\";\n } finally {\n terminal.close();\n }\n}\n\nasync function inspectCodexHooksFeature(options: {\n command: string;\n commandArgs: readonly string[];\n cwd: string;\n}): Promise<CodexHooksFeatureInspection> {\n const profile = resolveCodexProfile(options.commandArgs);\n const configPath = getGlobalCodexConfigPath();\n\n try {\n const { stdout } = await execFileAsync(options.command, [\n ...collectCodexFeatureProbeArgs(options.commandArgs),\n \"features\",\n \"list\"\n ], {\n cwd: options.cwd,\n encoding: \"utf8\"\n });\n\n return inspectCodexHooksFeatureListOutput({\n configPath,\n output: stdout,\n profile\n });\n } catch (error) {\n return {\n configPath,\n enabled: null,\n health: \"unknown\",\n message: `Unable to determine the effective codex_hooks feature state before launch: ${toErrorMessage(error)}`,\n profile\n };\n }\n}\n\nfunction buildLaunchBlockerMessage(options: {\n featureInspection: CodexHooksFeatureInspection;\n hookSetup: HookSetupInspection;\n}): string {\n const issues: string[] = [];\n\n if (options.featureInspection.health === \"disabled\") {\n issues.push(options.featureInspection.message);\n } else if (options.featureInspection.health === \"unknown\") {\n issues.push(options.featureInspection.message);\n }\n\n if (options.hookSetup.status !== \"ready\") {\n issues.push(options.hookSetup.message);\n }\n\n if (issues.length === 0) {\n return \"Codex hook bootstrap is ready.\";\n }\n\n return issues.join(\" \");\n}\n\nasync function ensureInteractiveCodexHooks(options: {\n command: string;\n commandArgs: readonly string[];\n cwd: string;\n hookScriptPath: string;\n log: (eventType: string, data?: Record<string, unknown>) => void;\n}): Promise<{\n featureInspection: CodexHooksFeatureInspection;\n hookSetup: HookSetupInspection;\n}> {\n let hookSetup = inspectCodexHookSetup({\n cwd: options.cwd,\n hookScriptPath: options.hookScriptPath\n });\n let featureInspection = await inspectCodexHooksFeature({\n command: options.command,\n commandArgs: options.commandArgs,\n cwd: options.cwd\n });\n\n options.log(\"hook_bootstrap_inspected\", {\n featureHealth: featureInspection.health,\n featureProfile: featureInspection.profile,\n hookConfigPath: hookSetup.activeConfig?.path ?? hookSetup.globalPath,\n hookStatus: hookSetup.status\n });\n\n if (featureInspection.health === \"disabled\") {\n const featureTargetDescription = featureInspection.profile\n ? `${featureInspection.configPath} for profile \"${featureInspection.profile}\"`\n : featureInspection.configPath;\n const shouldEnableFeature = await promptYesNo(\n `Enable codex_hooks in ${featureTargetDescription} so codex-bee can receive Stop events?`\n );\n\n options.log(\"hook_bootstrap_feature_prompted\", {\n accepted: shouldEnableFeature,\n profile: featureInspection.profile\n });\n\n if (!shouldEnableFeature) {\n throw new Error(buildLaunchBlockerMessage({\n featureInspection,\n hookSetup\n }));\n }\n\n const existingConfigText = fs.existsSync(featureInspection.configPath)\n ? fs.readFileSync(featureInspection.configPath, \"utf8\")\n : null;\n\n writeCodexConfigFile(\n featureInspection.configPath,\n upsertCodexHooksFeatureConfigText(existingConfigText, featureInspection.profile)\n );\n\n featureInspection = await inspectCodexHooksFeature({\n command: options.command,\n commandArgs: options.commandArgs,\n cwd: options.cwd\n });\n options.log(\"hook_bootstrap_feature_updated\", {\n health: featureInspection.health,\n profile: featureInspection.profile\n });\n }\n\n if (hookSetup.status === \"missing\") {\n const shouldCreateHooksFile = await promptYesNo(\n `Create ${hookSetup.globalPath} with the codex-bee Stop hook?`\n );\n\n options.log(\"hook_bootstrap_hooks_prompted\", {\n accepted: shouldCreateHooksFile,\n action: \"create-global\",\n path: hookSetup.globalPath\n });\n\n if (!shouldCreateHooksFile) {\n throw new Error(buildLaunchBlockerMessage({\n featureInspection,\n hookSetup\n }));\n }\n\n writeHookConfigFile(\n hookSetup.globalPath,\n upsertStopHookConfigText(null, options.hookScriptPath)\n );\n\n hookSetup = inspectCodexHookSetup({\n cwd: options.cwd,\n hookScriptPath: options.hookScriptPath\n });\n options.log(\"hook_bootstrap_hooks_updated\", {\n path: hookSetup.globalPath,\n status: hookSetup.status\n });\n } else if (hookSetup.status === \"missing-stop-hook\" || hookSetup.status === \"stale-stop-hook\") {\n const targetConfig = hookSetup.activeConfig ?? hookSetup.globalConfig;\n const shouldUpdateHooksFile = await promptYesNo(\n `Update ${targetConfig.path} so it points at the current codex-bee Stop hook script?`\n );\n\n options.log(\"hook_bootstrap_hooks_prompted\", {\n accepted: shouldUpdateHooksFile,\n action: \"update-existing\",\n path: targetConfig.path\n });\n\n if (!shouldUpdateHooksFile) {\n throw new Error(buildLaunchBlockerMessage({\n featureInspection,\n hookSetup\n }));\n }\n\n const existingHooksText = fs.existsSync(targetConfig.path)\n ? fs.readFileSync(targetConfig.path, \"utf8\")\n : null;\n\n writeHookConfigFile(\n targetConfig.path,\n upsertStopHookConfigText(existingHooksText, options.hookScriptPath)\n );\n\n hookSetup = inspectCodexHookSetup({\n cwd: options.cwd,\n hookScriptPath: options.hookScriptPath\n });\n options.log(\"hook_bootstrap_hooks_updated\", {\n path: targetConfig.path,\n status: hookSetup.status\n });\n }\n\n if (featureInspection.health === \"disabled\" || hookSetup.status !== \"ready\") {\n throw new Error(buildLaunchBlockerMessage({\n featureInspection,\n hookSetup\n }));\n }\n\n return {\n featureInspection,\n hookSetup\n };\n}\n\nasync function main(): Promise<void> {\n const options = parseWrapperOptions(process.argv.slice(2));\n\n if (options.showHelp || (!options.showVersion && options.command === null)) {\n console.log(HELP_TEXT.trim());\n return;\n }\n\n if (options.showVersion) {\n console.log(CLI_VERSION);\n return;\n }\n\n const wrappedCommand = options.command;\n\n if (wrappedCommand === null) {\n console.log(HELP_TEXT.trim());\n return;\n }\n\n const runId = randomUUID();\n const runStartedAt = Date.now();\n const executionMode = resolveExecutionMode({\n hasContinuation: false,\n stdinIsTTY: process.stdin.isTTY,\n stdoutIsTTY: process.stdout.isTTY\n });\n\n if (executionMode === \"passthrough\") {\n process.exitCode = await runPassthroughCommand({\n args: options.commandArgs,\n command: wrappedCommand,\n cwd: process.cwd(),\n env: process.env\n });\n return;\n }\n\n const logger = createRuntimeEventLogger(process.cwd(), {\n runId\n });\n logger.log(\"wrapper_started\", {\n command: wrappedCommand,\n commandArgs: options.commandArgs,\n runId\n });\n const hookScriptPath = getBundledStopHookPath();\n let startupAnnouncement: string | null = null;\n let initialConnectionState: UiConnectionState = \"connected\";\n\n if (isCodexCommand(wrappedCommand) && shouldPrepareInteractiveCodexHooks(options.commandArgs)) {\n const { featureInspection, hookSetup } = await ensureInteractiveCodexHooks({\n command: wrappedCommand,\n commandArgs: options.commandArgs,\n cwd: process.cwd(),\n hookScriptPath,\n log: (eventType, data) => logger.log(eventType, data)\n });\n\n startupAnnouncement = featureInspection.health === \"unknown\"\n ? `${hookSetup.message} ${featureInspection.message}`\n : hookSetup.message;\n initialConnectionState = \"ready\";\n logger.log(\"hook_bootstrap_ready\", {\n announcement: startupAnnouncement,\n configPath: hookSetup.activeConfig?.path ?? hookSetup.globalPath\n });\n }\n\n let runtimeHost: LiveUiRuntimeHost | null = null;\n const proxy = new PtyProxy({\n command: wrappedCommand,\n commandArgs: options.commandArgs,\n env: {\n ...process.env,\n CODEX_BEE_CAPTURE_ROOT: process.cwd(),\n CODEX_BEE_RUN_ID: runId\n },\n onOutputActivity: ({ timestamp }) => {\n runtimeHost?.recordPtyOutputActivity(timestamp);\n }\n });\n const continuation = new ContinuationController({\n cwd: process.cwd()\n });\n runtimeHost = new LiveUiRuntimeHost({\n beeVersion: CLI_VERSION,\n codexCommand: wrappedCommand,\n continuation,\n cwd: process.cwd(),\n initialAnnouncementMessage: startupAnnouncement,\n initialConnectionState,\n promptProxy: proxy\n });\n const controller = new UiController(runtimeHost);\n const watcherAbortController = new AbortController();\n const overlay = new LiveInkOverlayManager({\n controller,\n onQuitRequested: () => {\n logger.log(\"wrapper_exit_requested_from_ui\");\n watcherAbortController.abort();\n proxy.setInputInterceptor(null);\n proxy.setOutputMuted(false);\n void proxy.stop();\n },\n proxy,\n title: \"codex-bee\"\n });\n\n await controller.initialize();\n void runtimeHost.refreshEnvironmentMetadata().catch((error: unknown) => {\n logger.log(\"ui_runtime_metadata_refresh_failed\", {\n message: error instanceof Error ? error.message : String(error)\n });\n });\n\n await proxy.start();\n proxy.setInputInterceptor((chunk) => overlay.handleInput(chunk));\n\n if (initialConnectionState === \"ready\") {\n void runHookEventWatcher({\n cwd: process.cwd(),\n eventNames: [\"SessionStart\", \"UserPromptSubmit\"],\n logger,\n onEvent: (capture) => {\n runtimeHost.recordAuxiliaryHookEvent(capture);\n },\n runId,\n runStartedAt,\n signal: watcherAbortController.signal\n }).catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.log(\"hook_event_watcher_stopped\", {\n message\n });\n console.error(`[codex-bee] Hook event watcher stopped: ${message}`);\n });\n }\n\n void runContinuationWatcher({\n generateBeeAgentPrompt: (capture, source) => generateBeeAgentPrompt({\n capture,\n cwd: process.cwd(),\n logger,\n runId,\n source\n }),\n continuation,\n cwd: process.cwd(),\n getVerificationCommand: () => runtimeHost.getVerificationCommand(),\n injectDelayMs: 0,\n logger,\n onPromptInjected: (event) => {\n runtimeHost.recordContinuationPromptInjected(event);\n },\n onStopCaptureHandled: (event) => {\n runtimeHost.recordStopCaptureHandled(event);\n },\n proxy,\n runId,\n runStartedAt,\n runVerificationCommand,\n signal: watcherAbortController.signal,\n verificationCommand: null\n }).catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.log(\"continuation_watcher_stopped\", {\n message\n });\n console.error(`[codex-bee] Continuation watcher stopped: ${message}`);\n });\n\n process.exitCode = await proxy.waitForExit();\n watcherAbortController.abort();\n overlay.dispose();\n runtimeHost.markDisconnected();\n}\n\ntry {\n await main();\n} catch (error) {\n console.error(`[codex-bee] ${toErrorMessage(error)}`);\n process.exitCode = 1;\n}\n","import { mkdirSync, readFileSync, writeFileSync, appendFileSync, existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport process from \"node:process\";\nimport { summarizeTranscriptFile, type TranscriptMessage, type TranscriptSummary } from \"./transcript.js\";\nimport type { BeeAgentSource } from \"./continuation-source.js\";\nimport type { StopCapture } from \"./hook-server.js\";\nimport type { RuntimeEventLogger } from \"./runtime-log.js\";\n\nconst BEE_AGENT_RESULT_SCHEMA = {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n additionalProperties: false,\n properties: {\n next_prompt: {\n minLength: 1,\n type: \"string\"\n },\n note: {\n type: [\"string\", \"null\"]\n }\n },\n required: [\"next_prompt\", \"note\"],\n type: \"object\"\n} as const;\n\nconst DEFAULT_BEE_AGENT_MODEL = \"gpt-5.4\";\nconst DEFAULT_MAX_LAST_ASSISTANT_CHARS = 4000;\nconst DEFAULT_MAX_NOTE_CHARS = 4000;\nconst DEFAULT_MAX_OBJECTIVE_CHARS = 1500;\nconst DEFAULT_MAX_RECENT_MESSAGES = 6;\n\nexport interface BeeAgentConfig {\n maxLastAssistantChars: number;\n maxNoteChars: number;\n maxObjectiveChars: number;\n maxRecentMessages: number;\n model: string | null;\n profile: string | null;\n sessionPrompt: string;\n systemPrompt: string;\n}\n\nexport interface BeeAgentContext {\n beeNotes: string;\n capturedAt: string;\n cwd: string;\n lastAssistantMessage: string;\n model: string | null;\n permissionMode: string | null;\n recentMessages: TranscriptMessage[];\n sessionId: string;\n sessionObjective: string | null;\n transcriptPath: string | null;\n wrapperRunId: string;\n}\n\nexport interface BeeAgentGenerationResult {\n context: BeeAgentContext;\n nextPrompt: string;\n note: string | null;\n sessionStateDirectory: string;\n}\n\nexport interface BeeAgentExecRequest {\n args: string[];\n cwd: string;\n outputPath: string;\n prompt: string;\n stderrPath: string;\n stdoutPath: string;\n}\n\nexport interface BeeAgentExecResult {\n code: number;\n stderr: string;\n stdout: string;\n}\n\nexport type BeeAgentExecRunner = (request: BeeAgentExecRequest) => Promise<BeeAgentExecResult>;\n\ninterface BeeAgentRawConfig {\n maxLastAssistantChars?: unknown;\n maxNoteChars?: unknown;\n maxObjectiveChars?: unknown;\n maxRecentMessages?: unknown;\n model?: unknown;\n profile?: unknown;\n sessionPromptPath?: unknown;\n systemPromptPath?: unknown;\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction clampText(value: string, maxChars: number): string {\n if (value.length <= maxChars) {\n return value;\n }\n\n return value.slice(0, maxChars).trimEnd();\n}\n\nfunction readJsonFile(filePath: string): unknown {\n return JSON.parse(readFileSync(filePath, \"utf8\"));\n}\n\nfunction readNonEmptyTextFile(filePath: string, label: string): string {\n const value = readFileSync(filePath, \"utf8\").replace(/\\r\\n?/g, \"\\n\").trim();\n\n if (!value) {\n throw new Error(`${label} is empty: ${filePath}`);\n }\n\n return value;\n}\n\nfunction readPositiveInteger(value: unknown, label: string, fallback: number): number {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 1) {\n throw new Error(`${label} must be a positive integer.`);\n }\n\n return value;\n}\n\nfunction readOptionalString(value: unknown, label: string): string | null {\n if (value === undefined || value === null || value === \"\") {\n return null;\n }\n\n if (typeof value !== \"string\") {\n throw new Error(`${label} must be a string.`);\n }\n\n return value;\n}\n\nfunction sanitizePathSegment(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n}\n\nfunction getSessionStateDirectory(cwd: string, sessionId: string): string {\n return path.join(cwd, \".codex\", \"tmp\", \"bee-agent\", sanitizePathSegment(sessionId));\n}\n\nfunction getCurrentTimestampSlug(): string {\n return new Date().toISOString().replace(/[:.]/g, \"-\");\n}\n\nfunction readNotesFile(filePath: string, maxChars: number): string {\n if (!existsSync(filePath)) {\n return \"\";\n }\n\n const content = readFileSync(filePath, \"utf8\");\n\n if (content.length <= maxChars) {\n return content.trim();\n }\n\n return content.slice(-maxChars).trim();\n}\n\nfunction appendSessionNote(notesPath: string, note: string, capturedAt: string): void {\n mkdirSync(path.dirname(notesPath), {\n recursive: true\n });\n appendFileSync(\n notesPath,\n [\n `## ${capturedAt}`,\n note.trim(),\n \"\"\n ].join(\"\\n\"),\n \"utf8\"\n );\n}\n\nfunction buildTranscriptSummary(capture: StopCapture, maxRecentMessages: number): TranscriptSummary | null {\n const transcriptPath = capture.payload?.transcript_path;\n\n if (!transcriptPath) {\n return null;\n }\n\n try {\n return summarizeTranscriptFile(transcriptPath, {\n maxRecentMessages\n });\n } catch {\n return null;\n }\n}\n\nfunction buildGeneratorPrompt(config: BeeAgentConfig, context: BeeAgentContext): string {\n return [\n \"# Bee-Agent System Prompt\",\n config.systemPrompt,\n \"\",\n \"# Bee-Agent Session Prompt\",\n config.sessionPrompt,\n \"\",\n \"# Output Contract\",\n \"Return a JSON object with exactly these keys:\",\n '- `next_prompt`: a non-empty string that can be sent to the main Codex session as the next input',\n '- `note`: either `null` or a short persistent note for future bee-agent iterations',\n \"\",\n \"# Main Session Context\",\n \"```json\",\n JSON.stringify(context, null, 2),\n \"```\"\n ].join(\"\\n\");\n}\n\nfunction readParsedResult(outputPath: string): {\n next_prompt: string;\n note: string | null;\n} {\n const output = readFileSync(outputPath, \"utf8\").trim();\n\n if (!output) {\n throw new Error(\"Bee-agent output file is empty.\");\n }\n\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(output);\n } catch (error) {\n throw new Error(`Bee-agent output is not valid JSON: ${toErrorMessage(error)}`);\n }\n\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new Error(\"Bee-agent output is not an object.\");\n }\n\n const nextPrompt = (parsed as {\n next_prompt?: unknown;\n }).next_prompt;\n const note = (parsed as {\n note?: unknown;\n }).note;\n\n if (typeof nextPrompt !== \"string\" || !nextPrompt.trim()) {\n throw new Error(\"Bee-agent output field `next_prompt` must be a non-empty string.\");\n }\n\n if (note !== null && note !== undefined && typeof note !== \"string\") {\n throw new Error(\"Bee-agent output field `note` must be a string or null.\");\n }\n\n return {\n next_prompt: nextPrompt.trim(),\n note: note === undefined ? null : note\n };\n}\n\nasync function runBeeAgentExec(request: BeeAgentExecRequest): Promise<BeeAgentExecResult> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"codex\", [...request.args, request.prompt], {\n cwd: request.cwd,\n env: process.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"]\n });\n let stdout = \"\";\n let stderr = \"\";\n\n child.stdout.setEncoding(\"utf8\");\n child.stderr.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk;\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk;\n });\n child.once(\"error\", reject);\n child.once(\"exit\", (code) => {\n writeFileSync(request.stdoutPath, stdout, \"utf8\");\n writeFileSync(request.stderrPath, stderr, \"utf8\");\n resolve({\n code: code ?? 1,\n stderr,\n stdout\n });\n });\n });\n}\n\nexport function describeBeeAgentSource(source: BeeAgentSource): string {\n return `bee-agent config ${source.path}`;\n}\n\nexport function readBeeAgentConfig(source: BeeAgentSource, options?: {\n cwd?: string;\n}): BeeAgentConfig {\n const cwd = options?.cwd ?? process.cwd();\n const resolvedConfigPath = path.resolve(cwd, source.path);\n const configDirectory = path.dirname(resolvedConfigPath);\n const rawConfig = readJsonFile(resolvedConfigPath) as BeeAgentRawConfig;\n\n if (!rawConfig || typeof rawConfig !== \"object\") {\n throw new Error(`Bee-agent config must be an object: ${source.path}`);\n }\n\n if (typeof rawConfig.systemPromptPath !== \"string\" || !rawConfig.systemPromptPath.trim()) {\n throw new Error(`Bee-agent config is missing \\`systemPromptPath\\`: ${source.path}`);\n }\n\n if (typeof rawConfig.sessionPromptPath !== \"string\" || !rawConfig.sessionPromptPath.trim()) {\n throw new Error(`Bee-agent config is missing \\`sessionPromptPath\\`: ${source.path}`);\n }\n\n return {\n maxLastAssistantChars: readPositiveInteger(\n rawConfig.maxLastAssistantChars,\n \"Bee-agent config field `maxLastAssistantChars`\",\n DEFAULT_MAX_LAST_ASSISTANT_CHARS\n ),\n maxNoteChars: readPositiveInteger(\n rawConfig.maxNoteChars,\n \"Bee-agent config field `maxNoteChars`\",\n DEFAULT_MAX_NOTE_CHARS\n ),\n maxObjectiveChars: readPositiveInteger(\n rawConfig.maxObjectiveChars,\n \"Bee-agent config field `maxObjectiveChars`\",\n DEFAULT_MAX_OBJECTIVE_CHARS\n ),\n maxRecentMessages: readPositiveInteger(\n rawConfig.maxRecentMessages,\n \"Bee-agent config field `maxRecentMessages`\",\n DEFAULT_MAX_RECENT_MESSAGES\n ),\n model: readOptionalString(rawConfig.model, \"Bee-agent config field `model`\") ?? DEFAULT_BEE_AGENT_MODEL,\n profile: readOptionalString(rawConfig.profile, \"Bee-agent config field `profile`\"),\n sessionPrompt: readNonEmptyTextFile(\n path.resolve(configDirectory, rawConfig.sessionPromptPath),\n \"Bee-agent session prompt\"\n ),\n systemPrompt: readNonEmptyTextFile(\n path.resolve(configDirectory, rawConfig.systemPromptPath),\n \"Bee-agent system prompt\"\n )\n };\n}\n\nexport function buildBeeAgentContext(capture: StopCapture, config: BeeAgentConfig, options: {\n cwd: string;\n runId: string;\n}): BeeAgentContext {\n const sessionId = capture.payload?.session_id;\n\n if (!sessionId) {\n throw new Error(\"Bee-agent generation requires `session_id` in the matched Stop capture.\");\n }\n\n const transcriptSummary = buildTranscriptSummary(capture, config.maxRecentMessages);\n const sessionStateDirectory = getSessionStateDirectory(options.cwd, sessionId);\n const notesPath = path.join(sessionStateDirectory, \"notes.md\");\n\n return {\n beeNotes: readNotesFile(notesPath, config.maxNoteChars),\n capturedAt: capture.capturedAt ?? new Date().toISOString(),\n cwd: capture.payload?.cwd ?? capture.cwd ?? options.cwd,\n lastAssistantMessage: clampText(\n String(capture.payload?.last_assistant_message ?? \"\"),\n config.maxLastAssistantChars\n ),\n model: typeof capture.payload?.model === \"string\" ? capture.payload.model : null,\n permissionMode: typeof capture.payload?.permission_mode === \"string\" ? capture.payload.permission_mode : null,\n recentMessages: transcriptSummary?.recentMessages ?? [],\n sessionId,\n sessionObjective: transcriptSummary?.sessionObjective\n ? clampText(transcriptSummary.sessionObjective, config.maxObjectiveChars)\n : null,\n transcriptPath: transcriptSummary?.path ?? null,\n wrapperRunId: options.runId\n };\n}\n\nexport async function generateBeeAgentPrompt(options: {\n capture: StopCapture;\n cwd: string;\n logger: RuntimeEventLogger;\n runId: string;\n runner?: BeeAgentExecRunner;\n source: BeeAgentSource;\n}): Promise<BeeAgentGenerationResult> {\n const config = readBeeAgentConfig(options.source, {\n cwd: options.cwd\n });\n const context = buildBeeAgentContext(options.capture, config, {\n cwd: options.cwd,\n runId: options.runId\n });\n const sessionStateDirectory = getSessionStateDirectory(options.cwd, context.sessionId);\n const runDirectory = path.join(sessionStateDirectory, \"runs\", getCurrentTimestampSlug());\n const outputPath = path.join(runDirectory, \"output.json\");\n const stderrPath = path.join(runDirectory, \"stderr.log\");\n const stdoutPath = path.join(runDirectory, \"stdout.log\");\n const schemaPath = path.join(runDirectory, \"result.schema.json\");\n const contextPath = path.join(runDirectory, \"context.json\");\n const promptPath = path.join(runDirectory, \"generator-prompt.md\");\n const resultPath = path.join(runDirectory, \"result.json\");\n const notesPath = path.join(sessionStateDirectory, \"notes.md\");\n const prompt = buildGeneratorPrompt(config, context);\n const runner = options.runner ?? runBeeAgentExec;\n const args = [\n \"exec\",\n \"--color\",\n \"never\",\n \"--disable\",\n \"codex_hooks\",\n \"--skip-git-repo-check\",\n \"--ephemeral\",\n \"-C\",\n runDirectory,\n \"--output-schema\",\n schemaPath,\n \"-o\",\n outputPath\n ];\n\n if (config.profile) {\n args.push(\"--profile\", config.profile);\n }\n\n if (config.model) {\n args.push(\"--model\", config.model);\n }\n\n mkdirSync(runDirectory, {\n recursive: true\n });\n writeFileSync(schemaPath, `${JSON.stringify(BEE_AGENT_RESULT_SCHEMA, null, 2)}\\n`, \"utf8\");\n writeFileSync(contextPath, `${JSON.stringify(context, null, 2)}\\n`, \"utf8\");\n writeFileSync(promptPath, prompt, \"utf8\");\n\n options.logger.log(\"bee_agent_generation_started\", {\n configPath: options.source.path,\n sessionId: context.sessionId\n });\n\n const execResult = await runner({\n args,\n cwd: runDirectory,\n outputPath,\n prompt,\n stderrPath,\n stdoutPath\n });\n\n if (execResult.code !== 0) {\n throw new Error(\n `Bee-agent generator exited with code ${execResult.code}. See ${stdoutPath} and ${stderrPath}.`\n );\n }\n\n const parsedResult = readParsedResult(outputPath);\n\n if (parsedResult.note && parsedResult.note.trim()) {\n appendSessionNote(notesPath, parsedResult.note, options.capture.capturedAt ?? new Date().toISOString());\n }\n\n writeFileSync(\n resultPath,\n `${JSON.stringify({\n nextPrompt: parsedResult.next_prompt,\n note: parsedResult.note\n }, null, 2)}\\n`,\n \"utf8\"\n );\n\n options.logger.log(\"bee_agent_generation_completed\", {\n nextPromptLength: parsedResult.next_prompt.length,\n noteLength: parsedResult.note?.length ?? 0,\n sessionId: context.sessionId\n });\n\n return {\n context,\n nextPrompt: parsedResult.next_prompt,\n note: parsedResult.note,\n sessionStateDirectory\n };\n}\n","import { readFileSync } from \"node:fs\";\n\nexport interface TranscriptMessage {\n role: \"assistant\" | \"user\";\n text: string;\n}\n\nexport interface TranscriptTokenUsage {\n cachedInputTokens: number;\n inputTokens: number;\n outputTokens: number;\n reasoningOutputTokens: number;\n totalTokens: number;\n}\n\nexport interface TranscriptTokenCountSnapshot {\n lastTokenUsage: TranscriptTokenUsage | null;\n modelContextWindow: number | null;\n timestamp: string | null;\n totalTokenUsage: TranscriptTokenUsage | null;\n}\n\nexport interface TranscriptSummary {\n path: string;\n recentMessages: TranscriptMessage[];\n sessionObjective: string | null;\n totalMessages: number;\n}\n\nfunction readMessageText(payload: {\n content?: unknown;\n}): string {\n if (!Array.isArray(payload.content)) {\n return \"\";\n }\n\n const textParts = payload.content\n .filter((item): item is {\n text?: unknown;\n type?: unknown;\n } => typeof item === \"object\" && item !== null)\n .filter((item) => item.type === \"input_text\" || item.type === \"output_text\")\n .map((item) => typeof item.text === \"string\" ? item.text : \"\")\n .filter(Boolean);\n\n return textParts.join(\"\\n\").trim();\n}\n\nfunction readTokenUsage(value: unknown): TranscriptTokenUsage | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n\n const usage = value as {\n cached_input_tokens?: unknown;\n input_tokens?: unknown;\n output_tokens?: unknown;\n reasoning_output_tokens?: unknown;\n total_tokens?: unknown;\n };\n\n if (\n typeof usage.input_tokens !== \"number\"\n || typeof usage.cached_input_tokens !== \"number\"\n || typeof usage.output_tokens !== \"number\"\n || typeof usage.reasoning_output_tokens !== \"number\"\n || typeof usage.total_tokens !== \"number\"\n ) {\n return null;\n }\n\n return {\n cachedInputTokens: usage.cached_input_tokens,\n inputTokens: usage.input_tokens,\n outputTokens: usage.output_tokens,\n reasoningOutputTokens: usage.reasoning_output_tokens,\n totalTokens: usage.total_tokens\n };\n}\n\nexport function parseTranscriptMessages(content: string): TranscriptMessage[] {\n const eventMessages: TranscriptMessage[] = [];\n const responseMessages: TranscriptMessage[] = [];\n\n for (const line of content.split(/\\r?\\n/u)) {\n if (!line.trim()) {\n continue;\n }\n\n let item: unknown;\n\n try {\n item = JSON.parse(line);\n } catch {\n continue;\n }\n\n if (typeof item !== \"object\" || item === null) {\n continue;\n }\n\n const typedItem = item as {\n payload?: {\n content?: unknown;\n last_agent_message?: unknown;\n message?: unknown;\n role?: unknown;\n type?: unknown;\n };\n type?: unknown;\n };\n\n if (typedItem.type === \"event_msg\") {\n if (typedItem.payload?.type === \"user_message\" && typeof typedItem.payload.message === \"string\") {\n const text = typedItem.payload.message.trim();\n\n if (text) {\n eventMessages.push({\n role: \"user\",\n text\n });\n }\n }\n\n if (typedItem.payload?.type === \"task_complete\" && typeof typedItem.payload.last_agent_message === \"string\") {\n const text = typedItem.payload.last_agent_message.trim();\n\n if (text) {\n eventMessages.push({\n role: \"assistant\",\n text\n });\n }\n }\n\n continue;\n }\n\n if (typedItem.type !== \"response_item\" || typedItem.payload?.type !== \"message\") {\n continue;\n }\n\n if (typedItem.payload.role !== \"assistant\" && typedItem.payload.role !== \"user\") {\n continue;\n }\n\n const text = readMessageText(typedItem.payload);\n\n if (!text) {\n continue;\n }\n\n responseMessages.push({\n role: typedItem.payload.role,\n text\n });\n }\n\n return eventMessages.length > 0 ? eventMessages : responseMessages;\n}\n\nexport function parseTranscriptTokenCounts(content: string): TranscriptTokenCountSnapshot[] {\n const snapshots: TranscriptTokenCountSnapshot[] = [];\n\n for (const line of content.split(/\\r?\\n/u)) {\n if (!line.trim()) {\n continue;\n }\n\n let item: unknown;\n\n try {\n item = JSON.parse(line);\n } catch {\n continue;\n }\n\n if (typeof item !== \"object\" || item === null) {\n continue;\n }\n\n const typedItem = item as {\n payload?: {\n info?: {\n last_token_usage?: unknown;\n model_context_window?: unknown;\n total_token_usage?: unknown;\n };\n type?: unknown;\n };\n timestamp?: unknown;\n type?: unknown;\n };\n\n if (typedItem.type !== \"event_msg\" || typedItem.payload?.type !== \"token_count\") {\n continue;\n }\n\n const info = typedItem.payload.info;\n\n snapshots.push({\n lastTokenUsage: readTokenUsage(info?.last_token_usage),\n modelContextWindow: typeof info?.model_context_window === \"number\"\n ? info.model_context_window\n : null,\n timestamp: typeof typedItem.timestamp === \"string\" ? typedItem.timestamp : null,\n totalTokenUsage: readTokenUsage(info?.total_token_usage)\n });\n }\n\n return snapshots;\n}\n\nexport function summarizeTranscriptFile(transcriptPath: string, options?: {\n maxRecentMessages?: number;\n}): TranscriptSummary {\n const maxRecentMessages = options?.maxRecentMessages ?? 6;\n const content = readFileSync(transcriptPath, \"utf8\");\n const messages = parseTranscriptMessages(content);\n const sessionObjective = messages.find((message) => message.role === \"user\")?.text ?? null;\n\n return {\n path: transcriptPath,\n recentMessages: messages.slice(-maxRecentMessages),\n sessionObjective,\n totalMessages: messages.length\n };\n}\n","import type { ContinuationTemplateSource } from \"./continuation.js\";\n\nexport interface BeeAgentSource {\n kind: \"bee-agent\";\n path: string;\n}\n\nexport type ContinuationSource = BeeAgentSource | ContinuationTemplateSource;\n\nexport function isBeeAgentSource(source: ContinuationSource): source is BeeAgentSource {\n return source.kind === \"bee-agent\";\n}\n\nexport function isContinuationTemplateSource(source: ContinuationSource): source is ContinuationTemplateSource {\n return source.kind === \"file\" || source.kind === \"inline\";\n}\n","import { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { StopCapture } from \"./hook-server.js\";\n\nconst SUPPORTED_PLACEHOLDERS = [\n \"captured_at\",\n \"cwd\",\n \"hook_event_name\",\n \"last_assistant_message_excerpt\",\n \"last_assistant_message_json\",\n \"last_assistant_message_single_line\",\n \"last_assistant_message\",\n \"model\",\n \"permission_mode\",\n \"run_id\",\n \"session_id\",\n \"stop_hook_active\",\n \"transcript_path\"\n] as const;\n\nconst PLACEHOLDER_PATTERN = /{{\\s*([a-z0-9_]+)\\s*}}/gi;\nconst SINGLE_LINE_WHITESPACE_PATTERN = /\\s+/g;\nconst LAST_ASSISTANT_MESSAGE_EXCERPT_LENGTH = 280;\nconst WINDOWS_LINE_ENDING_PATTERN = /\\r\\n?/g;\n\ntype ContinuationPlaceholder = (typeof SUPPORTED_PLACEHOLDERS)[number];\n\nexport type ContinuationTemplateSource =\n | {\n kind: \"file\";\n path: string;\n }\n | {\n kind: \"inline\";\n template: string;\n };\n\nexport interface RenderedContinuationPrompt {\n prompt: string;\n unknownPlaceholders: string[];\n usedPlaceholders: string[];\n}\n\nfunction stringifyTemplateValue(value: boolean | null | string | undefined): string {\n if (value === null || value === undefined) {\n return \"\";\n }\n\n return String(value);\n}\n\nfunction toSingleLine(value: string): string {\n return value.replace(SINGLE_LINE_WHITESPACE_PATTERN, \" \").trim();\n}\n\nfunction toExcerpt(value: string): string {\n const singleLineValue = toSingleLine(value);\n\n if (singleLineValue.length <= LAST_ASSISTANT_MESSAGE_EXCERPT_LENGTH) {\n return singleLineValue;\n }\n\n return `${singleLineValue.slice(0, LAST_ASSISTANT_MESSAGE_EXCERPT_LENGTH - 3).trimEnd()}...`;\n}\n\nfunction normalizeTemplateContent(value: string): string {\n const normalizedLineEndings = value.replace(WINDOWS_LINE_ENDING_PATTERN, \"\\n\");\n\n return normalizedLineEndings.endsWith(\"\\n\")\n ? normalizedLineEndings.slice(0, -1)\n : normalizedLineEndings;\n}\n\nfunction buildPlaceholderValues(capture: StopCapture): Record<ContinuationPlaceholder, string> {\n const payload = capture.payload ?? {};\n const lastAssistantMessage = stringifyTemplateValue(payload.last_assistant_message);\n\n return {\n captured_at: stringifyTemplateValue(capture.capturedAt),\n cwd: stringifyTemplateValue(payload.cwd ?? capture.cwd),\n hook_event_name: stringifyTemplateValue(payload.hook_event_name),\n last_assistant_message_excerpt: toExcerpt(lastAssistantMessage),\n last_assistant_message_json: JSON.stringify(lastAssistantMessage),\n last_assistant_message_single_line: toSingleLine(lastAssistantMessage),\n last_assistant_message: lastAssistantMessage,\n model: stringifyTemplateValue(payload.model),\n permission_mode: stringifyTemplateValue(payload.permission_mode),\n run_id: stringifyTemplateValue(capture.env?.CODEX_BEE_RUN_ID),\n session_id: stringifyTemplateValue(payload.session_id),\n stop_hook_active: stringifyTemplateValue(payload.stop_hook_active),\n transcript_path: stringifyTemplateValue(payload.transcript_path)\n };\n}\n\nexport function listSupportedContinuationPlaceholders(): string[] {\n return [...SUPPORTED_PLACEHOLDERS];\n}\n\nexport function describeContinuationTemplateSource(source: ContinuationTemplateSource): string {\n return source.kind === \"file\"\n ? `file ${source.path}`\n : \"inline prompt\";\n}\n\nexport function readContinuationTemplate(\n source: ContinuationTemplateSource,\n options?: {\n cwd?: string;\n }\n): string {\n if (source.kind === \"inline\") {\n return source.template;\n }\n\n const cwd = options?.cwd ?? process.cwd();\n const resolvedPath = resolve(cwd, source.path);\n\n let rawTemplate: string;\n\n try {\n rawTemplate = readFileSync(resolvedPath, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Unable to read continuation template file ${source.path}: ${message}`);\n }\n\n const template = normalizeTemplateContent(rawTemplate);\n\n if (!template.trim()) {\n throw new Error(`Continuation template file is empty: ${source.path}`);\n }\n\n return template;\n}\n\nexport function renderContinuationPrompt(\n promptTemplate: string,\n capture: StopCapture\n): RenderedContinuationPrompt {\n const placeholderValues = buildPlaceholderValues(capture);\n const unknownPlaceholders = new Set<string>();\n const usedPlaceholders = new Set<string>();\n const prompt = promptTemplate.replace(PLACEHOLDER_PATTERN, (match, rawPlaceholderName: string) => {\n const placeholderName = rawPlaceholderName.toLowerCase();\n\n if (!Object.hasOwn(placeholderValues, placeholderName)) {\n unknownPlaceholders.add(rawPlaceholderName);\n return match;\n }\n\n usedPlaceholders.add(placeholderName);\n return placeholderValues[placeholderName as ContinuationPlaceholder];\n });\n\n return {\n prompt,\n unknownPlaceholders: [...unknownPlaceholders],\n usedPlaceholders: [...usedPlaceholders]\n };\n}\n","import { describeBeeAgentSource, readBeeAgentConfig } from \"./bee-agent.js\";\nimport {\n isBeeAgentSource,\n isContinuationTemplateSource,\n type BeeAgentSource,\n type ContinuationSource\n} from \"./continuation-source.js\";\nimport {\n describeContinuationTemplateSource,\n readContinuationTemplate,\n renderContinuationPrompt,\n} from \"./continuation.js\";\nimport type { StopCapture } from \"./hook-server.js\";\n\nexport interface InteractiveContinuationDraft {\n maxContinues: number;\n maxDurationMs: number | null;\n prompt: string;\n}\n\nexport interface ContinuationSnapshot {\n enabled: boolean;\n injectionsUsed: number;\n maxContinues: number;\n maxDurationMs: number | null;\n promptSource: ContinuationSource;\n promptSourceLabel: string;\n promptText: string;\n remainingContinues: number;\n remainingDurationMs: number | null;\n startedAt: number | null;\n}\n\nexport interface ContinuationDecision {\n kind: \"disabled\" | \"empty-prompt\" | \"error\" | \"expired\" | \"generate\" | \"guardrail\" | \"inject\";\n guardrailReached?: boolean;\n injectionNumber?: number;\n maxContinues?: number;\n message?: string;\n prompt?: string;\n source?: BeeAgentSource;\n sourceLabel?: string;\n unknownPlaceholders?: string[];\n usedPlaceholders?: string[];\n}\n\nconst DURATION_INPUT_PATTERN = /^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/i;\nconst PROMPT_PREVIEW_LENGTH = 96;\nconst SINGLE_LINE_WHITESPACE_PATTERN = /\\s+/g;\n\nexport const DEFAULT_CONTINUATION_PROMPT = \"continue\";\nexport const DEFAULT_MAX_CONTINUES = 3;\nexport const UNBOUNDED_MAX_CONTINUES = Number.POSITIVE_INFINITY;\n\nfunction toSingleLine(value: string): string {\n return value.replace(SINGLE_LINE_WHITESPACE_PATTERN, \" \").trim();\n}\n\nfunction toPromptPreview(value: string): string {\n const singleLine = toSingleLine(value);\n\n if (!singleLine) {\n return \"(empty prompt)\";\n }\n\n if (singleLine.length <= PROMPT_PREVIEW_LENGTH) {\n return singleLine;\n }\n\n return `${singleLine.slice(0, PROMPT_PREVIEW_LENGTH - 3).trimEnd()}...`;\n}\n\nfunction describeContinuationSource(source: ContinuationSource): string {\n return isBeeAgentSource(source)\n ? describeBeeAgentSource(source)\n : describeContinuationTemplateSource(source);\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function parseDurationInput(value: string, options?: {\n allowEmpty?: boolean;\n}): number | null {\n const trimmedValue = value.trim();\n\n if (!trimmedValue || /^off$/i.test(trimmedValue)) {\n if (options?.allowEmpty ?? true) {\n return null;\n }\n\n throw new Error(\"Duration is required.\");\n }\n\n const match = trimmedValue.match(DURATION_INPUT_PATTERN);\n\n if (!match) {\n throw new Error(`Unsupported duration value: ${value}`);\n }\n\n const amount = Number.parseFloat(match[1]);\n const unit = (match[2] ?? \"m\").toLowerCase();\n\n if (!Number.isFinite(amount) || amount <= 0) {\n throw new Error(`Unsupported duration value: ${value}`);\n }\n\n const multiplier = {\n h: 60 * 60 * 1000,\n m: 60 * 1000,\n ms: 1,\n s: 1000\n }[unit];\n\n if (multiplier === undefined) {\n throw new Error(`Unsupported duration value: ${value}`);\n }\n\n const durationMs = Math.round(amount * multiplier);\n\n if (durationMs <= 0) {\n throw new Error(`Unsupported duration value: ${value}`);\n }\n\n return durationMs;\n}\n\nexport function formatDurationMs(value: number | null): string {\n if (value === null) {\n return \"off\";\n }\n\n if (value % (60 * 60 * 1000) === 0) {\n return `${value / (60 * 60 * 1000)}h`;\n }\n\n if (value % (60 * 1000) === 0) {\n return `${value / (60 * 1000)}m`;\n }\n\n if (value % 1000 === 0) {\n return `${value / 1000}s`;\n }\n\n return `${value}ms`;\n}\n\nexport class ContinuationController {\n #cwd: string;\n #enabled = false;\n #injectionsUsed = 0;\n #maxContinues = UNBOUNDED_MAX_CONTINUES;\n #maxDurationMs: number | null = null;\n #promptSource: ContinuationSource = {\n kind: \"inline\",\n template: DEFAULT_CONTINUATION_PROMPT\n };\n #startedAt: number | null = null;\n #warnedUnknownPlaceholders = new Set<string>();\n\n constructor(options: {\n cwd: string;\n initial?: {\n enabled: boolean;\n maxContinues: number;\n maxDurationMs: number | null;\n promptSource: ContinuationSource;\n };\n }) {\n this.#cwd = options.cwd;\n\n if (options.initial) {\n this.#enabled = options.initial.enabled;\n this.#maxContinues = options.initial.maxContinues;\n this.#maxDurationMs = options.initial.maxDurationMs;\n this.#promptSource = options.initial.promptSource;\n this.#startedAt = options.initial.enabled ? Date.now() : null;\n }\n }\n\n armWithPromptSource(options: {\n maxContinues: number;\n maxDurationMs: number | null;\n promptSource: ContinuationSource;\n }): ContinuationSnapshot {\n this.#enabled = true;\n this.#injectionsUsed = 0;\n this.#maxContinues = options.maxContinues;\n this.#maxDurationMs = options.maxDurationMs;\n this.#promptSource = options.promptSource;\n this.#startedAt = Date.now();\n this.#warnedUnknownPlaceholders.clear();\n\n return this.getSnapshot();\n }\n\n applyInteractiveDraft(draft: InteractiveContinuationDraft): ContinuationSnapshot {\n return this.updateInteractiveDraft(draft, {\n enable: true\n });\n }\n\n updateInteractiveDraft(\n draft: InteractiveContinuationDraft,\n options?: {\n enable?: boolean;\n }\n ): ContinuationSnapshot {\n const shouldEnable = options?.enable ?? this.#enabled;\n const previousDurationMs = this.#maxDurationMs;\n const wasEnabled = this.#enabled;\n const nextPromptSource: ContinuationSource = {\n kind: \"inline\",\n template: draft.prompt\n };\n\n this.#maxContinues = draft.maxContinues;\n this.#maxDurationMs = draft.maxDurationMs;\n this.#promptSource = nextPromptSource;\n this.#warnedUnknownPlaceholders.clear();\n\n if (shouldEnable) {\n if (!wasEnabled) {\n this.#injectionsUsed = 0;\n\n if (draft.maxDurationMs === null) {\n this.#startedAt = null;\n } else {\n this.#startedAt = this.#startedAt ?? Date.now();\n }\n }\n\n this.#enabled = true;\n } else {\n this.#enabled = false;\n\n if (draft.maxDurationMs === null) {\n this.#startedAt = null;\n } else if (this.#startedAt === null || previousDurationMs !== draft.maxDurationMs) {\n this.#startedAt = Date.now();\n }\n }\n\n return this.getSnapshot();\n }\n\n disable(): ContinuationSnapshot {\n this.#enabled = false;\n this.#startedAt = null;\n\n return this.getSnapshot();\n }\n\n getSnapshot(): ContinuationSnapshot {\n const promptText = this.#readPromptText();\n const remainingDurationMs = this.#getRemainingDurationMs();\n\n return {\n enabled: this.#enabled,\n injectionsUsed: this.#injectionsUsed,\n maxContinues: this.#maxContinues,\n maxDurationMs: this.#maxDurationMs,\n promptSource: this.#promptSource,\n promptSourceLabel: describeContinuationSource(this.#promptSource),\n promptText,\n remainingContinues: Number.isFinite(this.#maxContinues)\n ? Math.max(this.#maxContinues - this.#injectionsUsed, 0)\n : Number.POSITIVE_INFINITY,\n remainingDurationMs,\n startedAt: this.#startedAt\n };\n }\n\n getPromptPreview(): string {\n return toPromptPreview(this.#readPromptText());\n }\n\n handleStop(capture: StopCapture): ContinuationDecision {\n if (!this.#enabled) {\n return {\n kind: \"disabled\"\n };\n }\n\n const remainingDurationMs = this.#getRemainingDurationMs();\n\n if (remainingDurationMs !== null && remainingDurationMs <= 0) {\n this.disable();\n\n return {\n kind: \"expired\",\n message: `[codex-bee] Auto-continue session duration limit reached (${formatDurationMs(this.#maxDurationMs)}).`\n };\n }\n\n if (Number.isFinite(this.#maxContinues) && this.#injectionsUsed >= this.#maxContinues) {\n this.disable();\n\n return {\n kind: \"guardrail\",\n message: `[codex-bee] Auto-continue guardrail reached (${this.#maxContinues} injections). No further prompts will be sent.`\n };\n }\n\n if (isBeeAgentSource(this.#promptSource)) {\n this.#injectionsUsed += 1;\n\n const guardrailReached = Number.isFinite(this.#maxContinues)\n ? this.#injectionsUsed >= this.#maxContinues\n : false;\n\n if (guardrailReached) {\n this.#enabled = false;\n this.#startedAt = null;\n }\n\n return {\n guardrailReached,\n injectionNumber: this.#injectionsUsed,\n kind: \"generate\",\n maxContinues: this.#maxContinues,\n source: this.#promptSource,\n sourceLabel: describeContinuationSource(this.#promptSource)\n };\n }\n\n let promptTemplate: string;\n\n try {\n promptTemplate = readContinuationTemplate(this.#promptSource, {\n cwd: this.#cwd\n });\n } catch (error) {\n this.disable();\n\n return {\n kind: \"error\",\n message: `[codex-bee] ${toErrorMessage(error)}`\n };\n }\n\n const renderedPrompt = renderContinuationPrompt(promptTemplate, capture);\n const unknownPlaceholders = renderedPrompt.unknownPlaceholders.filter((placeholder) => {\n if (this.#warnedUnknownPlaceholders.has(placeholder)) {\n return false;\n }\n\n this.#warnedUnknownPlaceholders.add(placeholder);\n return true;\n });\n\n if (!renderedPrompt.prompt.trim()) {\n this.disable();\n\n return {\n kind: \"empty-prompt\",\n message: \"[codex-bee] Continuation template rendered to an empty prompt. Auto-continue will stop.\"\n };\n }\n\n this.#injectionsUsed += 1;\n\n const guardrailReached = Number.isFinite(this.#maxContinues)\n ? this.#injectionsUsed >= this.#maxContinues\n : false;\n\n if (guardrailReached) {\n this.#enabled = false;\n this.#startedAt = null;\n }\n\n return {\n guardrailReached,\n injectionNumber: this.#injectionsUsed,\n kind: \"inject\",\n maxContinues: this.#maxContinues,\n prompt: renderedPrompt.prompt,\n sourceLabel: describeContinuationSource(this.#promptSource),\n unknownPlaceholders,\n usedPlaceholders: renderedPrompt.usedPlaceholders\n };\n }\n\n #getRemainingDurationMs(): number | null {\n if (this.#maxDurationMs === null || this.#startedAt === null) {\n return null;\n }\n\n return this.#maxDurationMs - (Date.now() - this.#startedAt);\n }\n\n #readPromptText(): string {\n try {\n if (isBeeAgentSource(this.#promptSource)) {\n const config = readBeeAgentConfig(this.#promptSource, {\n cwd: this.#cwd\n });\n\n return `[bee-agent] ${toPromptPreview(config.sessionPrompt)}`;\n }\n\n return readContinuationTemplate(this.#promptSource, {\n cwd: this.#cwd\n });\n } catch {\n if (isContinuationTemplateSource(this.#promptSource) && this.#promptSource.kind === \"inline\") {\n return this.#promptSource.template;\n }\n\n return \"\";\n }\n }\n}\n","export const HELP_TEXT = `\nbee\n\nAutonomous wrapper around Codex CLI.\n\nUsage:\n bee [bee options] <command> [commandArgs]\n bee [bee options] -- <command> [commandArgs]\n\nBee options:\n -h, --help Show help\n --version Show version\n\nAll remaining arguments are passed through to the wrapped command unchanged.\nContinuation prompts, guardrails, and verification settings are configured from the in-session UI.\n`;\n\nexport interface ParsedWrapperOptions {\n command: string | null;\n commandArgs: string[];\n showHelp: boolean;\n showVersion: boolean;\n}\n\nconst WRAPPER_FLAGS = new Set([\n \"-h\",\n \"--help\",\n \"--version\"\n]);\n\nfunction parseCommandInvocation(wrapperArgs: string[], commandInvocation: string[]): {\n command: string | null;\n commandArgs: string[];\n wrapperArgs: string[];\n} {\n return {\n command: commandInvocation[0] ?? null,\n commandArgs: commandInvocation.slice(1),\n wrapperArgs\n };\n}\n\nexport function parseCliArguments(rawArgs: string[]): {\n command: string | null;\n commandArgs: string[];\n wrapperArgs: string[];\n} {\n const separatorIndex = rawArgs.indexOf(\"--\");\n\n if (separatorIndex >= 0) {\n return parseCommandInvocation(\n rawArgs.slice(0, separatorIndex),\n rawArgs.slice(separatorIndex + 1)\n );\n }\n\n const wrapperArgs: string[] = [];\n\n for (let index = 0; index < rawArgs.length; index += 1) {\n const argument = rawArgs[index];\n\n if (WRAPPER_FLAGS.has(argument)) {\n wrapperArgs.push(argument);\n continue;\n }\n\n if (argument.startsWith(\"-\")) {\n return {\n command: null,\n commandArgs: [],\n wrapperArgs: rawArgs\n };\n }\n\n return {\n command: argument,\n commandArgs: rawArgs.slice(index + 1),\n wrapperArgs\n };\n }\n\n return {\n command: null,\n commandArgs: [],\n wrapperArgs\n };\n}\n\nexport function parseWrapperOptions(rawArgs: string[]): ParsedWrapperOptions {\n const { command, commandArgs, wrapperArgs } = parseCliArguments(rawArgs);\n let showHelp = false;\n let showVersion = false;\n\n for (const argument of wrapperArgs) {\n if (argument === \"-h\" || argument === \"--help\") {\n showHelp = true;\n continue;\n }\n\n if (argument === \"--version\") {\n showVersion = true;\n continue;\n }\n\n if (argument.startsWith(\"-\")) {\n throw new Error(\n `Unknown bee option: ${argument}. Continuation, guardrails, and verification are configured from the UI after launch.`\n );\n }\n\n throw new Error(`Unexpected bee argument before the wrapped command: ${argument}`);\n }\n\n return {\n command,\n commandArgs,\n showHelp,\n showVersion\n };\n}\n","import { setTimeout as delay } from \"node:timers/promises\";\nimport process from \"node:process\";\nimport { ContinuationController, type ContinuationDecision } from \"./auto-continue.js\";\nimport type { BeeAgentGenerationResult } from \"./bee-agent.js\";\nimport type { BeeAgentSource } from \"./continuation-source.js\";\nimport { waitForMatchingStopCapture } from \"./hook-server.js\";\nimport type { StopCapture } from \"./hook-server.js\";\nimport type { RuntimeEventLogger } from \"./runtime-log.js\";\nimport {\n formatVerificationFailurePrompt,\n runVerificationCommand as runVerificationCommandDefault,\n type VerificationCommandResult\n} from \"./verification.js\";\n\nexport interface ContinuationPromptProxy {\n injectPrompt(prompt: string): Promise<void>;\n}\n\nexport interface ContinuationWatcherOptions {\n continuation: ContinuationController;\n cwd: string;\n generateBeeAgentPrompt?: (capture: StopCapture, source: BeeAgentSource) => Promise<BeeAgentGenerationResult>;\n getVerificationCommand?: () => string | null;\n injectDelayMs: number;\n logger: RuntimeEventLogger;\n onPromptInjected?: (event: {\n capture: StopCapture;\n decision: ContinuationDecision;\n prompt: string;\n sessionId: string;\n }) => Promise<void> | void;\n onStopCaptureHandled?: (event: {\n capture: StopCapture;\n decision: ContinuationDecision;\n sessionId: string;\n verificationCommand: string | null;\n verificationErrorMessage: string | null;\n verificationResult: VerificationCommandResult | null;\n willInject: boolean;\n }) => Promise<void> | void;\n proxy: ContinuationPromptProxy;\n runVerificationCommand?: (options: {\n command: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n }) => Promise<VerificationCommandResult>;\n runId: string;\n runStartedAt: number;\n signal?: AbortSignal;\n verificationCommand?: string | null;\n waitTimeoutMs?: number | null;\n unrefTimers?: boolean;\n}\n\nfunction isTimeoutError(error: unknown): boolean {\n return error instanceof Error && error.message.startsWith(\"Timed out waiting for \");\n}\n\nfunction appendVerificationBlock(prompt: string, verificationFailurePrompt: string | null): string {\n if (!verificationFailurePrompt) {\n return prompt;\n }\n\n return `${prompt.trimEnd()}\\n\\n${verificationFailurePrompt}`.trim();\n}\n\nexport async function runContinuationWatcher(options: ContinuationWatcherOptions): Promise<void> {\n const seenFilePaths = new Set<string>();\n options.logger.log(\"continuation_watcher_started\", {\n runId: options.runId\n });\n\n while (!options.signal?.aborted) {\n let capture;\n\n try {\n capture = await waitForMatchingStopCapture({\n afterTimeMs: options.runStartedAt,\n cwd: options.cwd,\n runId: options.runId,\n seenFilePaths,\n timeoutMs: options.waitTimeoutMs ?? null,\n unrefTimers: options.unrefTimers\n });\n } catch (error) {\n if (options.signal?.aborted && isTimeoutError(error)) {\n break;\n }\n\n if (options.waitTimeoutMs !== undefined && options.waitTimeoutMs !== null && isTimeoutError(error)) {\n continue;\n }\n\n throw error;\n }\n\n const decision = options.continuation.handleStop(capture);\n const sessionId = capture.payload?.session_id ?? \"unknown\";\n options.logger.log(\"stop_capture_matched\", {\n decisionKind: decision.kind,\n sessionId,\n turnId: capture.payload?.turn_id ?? null\n });\n\n if (decision.kind === \"disabled\") {\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand: null,\n verificationErrorMessage: null,\n verificationResult: null,\n willInject: false\n });\n continue;\n }\n\n if (decision.kind === \"guardrail\" || decision.kind === \"expired\" || decision.kind === \"empty-prompt\" || decision.kind === \"error\") {\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand: null,\n verificationErrorMessage: null,\n verificationResult: null,\n willInject: false\n });\n\n if (decision.message) {\n console.error(decision.message);\n }\n\n continue;\n }\n\n const verificationCommand = options.getVerificationCommand?.() ?? options.verificationCommand ?? null;\n let verificationFailurePrompt: string | null = null;\n let verificationErrorMessage: string | null = null;\n let verificationResult: VerificationCommandResult | null = null;\n\n if (verificationCommand) {\n const runVerificationCommand = options.runVerificationCommand ?? runVerificationCommandDefault;\n\n options.logger.log(\"verification_command_started\", {\n command: verificationCommand,\n sessionId\n });\n\n try {\n verificationResult = await runVerificationCommand({\n command: verificationCommand,\n cwd: options.cwd,\n env: process.env\n });\n\n if (verificationResult.succeeded) {\n options.continuation.disable();\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage: null,\n verificationResult,\n willInject: false\n });\n options.logger.log(\"verification_command_succeeded\", {\n code: verificationResult.code,\n command: verificationResult.command,\n sessionId\n });\n console.error(\n `[codex-bee] Verification command succeeded (exit ${verificationResult.code}) for session ${sessionId}. Auto-continue will stop.`\n );\n continue;\n }\n\n verificationFailurePrompt = formatVerificationFailurePrompt(verificationResult);\n options.logger.log(\"verification_command_failed\", {\n code: verificationResult.code,\n command: verificationResult.command,\n sessionId,\n stderrLength: verificationResult.stderr.length,\n stdoutLength: verificationResult.stdout.length\n });\n console.error(\n `[codex-bee] Verification command failed (exit ${verificationResult.code}) for session ${sessionId}. Auto-continue will keep going.`\n );\n } catch (error) {\n options.continuation.disable();\n verificationErrorMessage = error instanceof Error ? error.message : String(error);\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage,\n verificationResult: null,\n willInject: false\n });\n options.logger.log(\"verification_command_error\", {\n command: verificationCommand,\n message: verificationErrorMessage,\n sessionId\n });\n console.error(\n `[codex-bee] Verification command failed to run: ${verificationErrorMessage}`\n );\n continue;\n }\n }\n\n if (decision.kind === \"generate\") {\n if (!decision.source) {\n options.continuation.disable();\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage: null,\n verificationResult,\n willInject: false\n });\n console.error(\"[codex-bee] Bee-agent continuation source is missing. Auto-continue will stop.\");\n continue;\n }\n\n if (!options.generateBeeAgentPrompt) {\n options.continuation.disable();\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage: null,\n verificationResult,\n willInject: false\n });\n console.error(\"[codex-bee] Bee-agent continuation runner is not configured. Auto-continue will stop.\");\n continue;\n }\n\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage: null,\n verificationResult,\n willInject: true\n });\n\n console.error(\n `[codex-bee] Stop capture matched for bee-agent generation in session ${sessionId} (${decision.injectionNumber}/${decision.maxContinues}).`\n );\n\n try {\n const generation = await options.generateBeeAgentPrompt(capture, decision.source);\n\n if (options.injectDelayMs > 0) {\n await delay(options.injectDelayMs);\n }\n\n const prompt = appendVerificationBlock(generation.nextPrompt, verificationFailurePrompt);\n\n await options.proxy.injectPrompt(prompt);\n options.logger.log(\"continuation_prompt_injected\", {\n injectionNumber: decision.injectionNumber,\n maxContinues: decision.maxContinues,\n noteLength: generation.note?.length ?? 0,\n promptLength: prompt.length,\n sessionId,\n sourceLabel: decision.sourceLabel ?? null\n });\n console.error(\n `[codex-bee] Bee-agent prompt injected (${decision.injectionNumber}/${decision.maxContinues}) with ${decision.sourceLabel}.`\n );\n await options.onPromptInjected?.({\n capture,\n decision,\n prompt,\n sessionId\n });\n\n if (generation.note) {\n console.error(\"[codex-bee] Bee-agent note persisted for this session.\");\n }\n } catch (error) {\n options.continuation.disable();\n options.logger.log(\"bee_agent_generation_failed\", {\n message: error instanceof Error ? error.message : String(error),\n sessionId,\n sourceLabel: decision.sourceLabel ?? null\n });\n console.error(\n `[codex-bee] Bee-agent generation failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n if (decision.guardrailReached) {\n console.error(\n `[codex-bee] Auto-continue guardrail reached (${decision.maxContinues} injections). No further prompts will be sent.`\n );\n }\n\n continue;\n }\n\n await options.onStopCaptureHandled?.({\n capture,\n decision,\n sessionId,\n verificationCommand,\n verificationErrorMessage: null,\n verificationResult,\n willInject: true\n });\n\n console.error(\n `[codex-bee] Stop capture matched for session ${sessionId} (${decision.injectionNumber}/${decision.maxContinues}).`\n );\n\n for (const placeholder of decision.unknownPlaceholders ?? []) {\n console.error(\n `[codex-bee] Continuation template placeholder is not recognized and will be left as-is: {{${placeholder}}}.`\n );\n }\n\n if (options.injectDelayMs > 0) {\n await delay(options.injectDelayMs);\n }\n\n const prompt = appendVerificationBlock(decision.prompt ?? \"\", verificationFailurePrompt);\n\n await options.proxy.injectPrompt(prompt);\n options.logger.log(\"continuation_prompt_injected\", {\n injectionNumber: decision.injectionNumber,\n maxContinues: decision.maxContinues,\n promptLength: prompt.length,\n sessionId,\n sourceLabel: decision.sourceLabel ?? null\n });\n const placeholderSuffix = decision.usedPlaceholders && decision.usedPlaceholders.length > 0\n ? ` using ${decision.usedPlaceholders.map((placeholder) => `{{${placeholder}}}`).join(\", \")}`\n : \"\";\n console.error(\n `[codex-bee] Continuation prompt injected (${decision.injectionNumber}/${decision.maxContinues}) with ${decision.sourceLabel}${placeholderSuffix}.`\n );\n await options.onPromptInjected?.({\n capture,\n decision,\n prompt,\n sessionId\n });\n\n if (decision.guardrailReached) {\n console.error(\n `[codex-bee] Auto-continue guardrail reached (${decision.maxContinues} injections). No further prompts will be sent.`\n );\n }\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\nexport interface HookCapture {\n capturedAt?: string;\n cwd?: string;\n env?: Record<string, string | undefined>;\n payload?: {\n cwd?: string;\n hook_event_name?: string;\n last_assistant_message?: string | null;\n model?: string;\n permission_mode?: string;\n prompt?: string;\n session_id?: string;\n source?: string;\n stop_hook_active?: boolean;\n tool_input?: unknown;\n tool_response?: unknown;\n tool_use_id?: string;\n tool_name?: string;\n transcript_path?: string;\n turn_id?: string;\n };\n transcript?: {\n error?: string;\n exists?: boolean;\n mtimeMs?: number;\n path?: string | null;\n size?: number;\n };\n}\n\nexport type StopCapture = HookCapture;\n\nexport interface HookCaptureWaitOptions {\n afterTimeMs: number;\n cwd: string;\n eventNames?: string[];\n runId: string;\n seenFilePaths?: Set<string>;\n timeoutMs?: number | null;\n unrefTimers?: boolean;\n}\n\nexport type StopCaptureWaitOptions = HookCaptureWaitOptions;\n\nfunction getTempRoot(cwd?: string): string {\n return path.join(cwd ?? process.cwd(), \".codex\", \"tmp\");\n}\n\nfunction getStopCaptureDirectory(cwd?: string): string {\n return path.join(getTempRoot(cwd), \"stop-captures\");\n}\n\nfunction getHookCaptureDirectory(cwd?: string): string {\n return path.join(getTempRoot(cwd), \"hook-captures\");\n}\n\nfunction getLastCapturePath(cwd?: string): string {\n return path.join(getTempRoot(cwd), \"last-stop-capture.json\");\n}\n\nfunction getLastHookCapturePath(cwd?: string): string {\n return path.join(getTempRoot(cwd), \"last-hook-capture.json\");\n}\n\nfunction getCaptureDirectories(options: HookCaptureWaitOptions): string[] {\n const directories = [getHookCaptureDirectory(options.cwd)];\n\n if (options.eventNames?.length === 1 && options.eventNames[0] === \"Stop\") {\n directories.push(getStopCaptureDirectory(options.cwd));\n }\n\n return directories;\n}\n\nfunction readCaptureFile(filePath: string): HookCapture | null {\n try {\n return JSON.parse(fs.readFileSync(filePath, \"utf8\")) as HookCapture;\n } catch {\n return null;\n }\n}\n\nfunction isMatchingCapture(capture: HookCapture | null, options: HookCaptureWaitOptions): boolean {\n if (!capture) {\n return false;\n }\n\n if (capture.cwd !== options.cwd) {\n return false;\n }\n\n const eventName = capture.payload?.hook_event_name;\n\n if (!eventName) {\n return false;\n }\n\n if (options.eventNames && !options.eventNames.includes(eventName)) {\n return false;\n }\n\n const runId = capture.env?.CODEX_BEE_RUN_ID;\n\n if (runId !== options.runId) {\n return false;\n }\n\n const capturedAt = capture.capturedAt ? Date.parse(capture.capturedAt) : Number.NaN;\n\n if (Number.isFinite(capturedAt) && capturedAt < options.afterTimeMs) {\n return false;\n }\n\n return true;\n}\n\nexport function clearStopCaptureArtifacts(cwd?: string): void {\n fs.rmSync(getHookCaptureDirectory(cwd), {\n force: true,\n recursive: true\n });\n fs.rmSync(getLastHookCapturePath(cwd), {\n force: true\n });\n fs.rmSync(getStopCaptureDirectory(cwd), {\n force: true,\n recursive: true\n });\n fs.rmSync(getLastCapturePath(cwd), {\n force: true\n });\n}\n\nexport function waitForMatchingHookCapture(options: HookCaptureWaitOptions): Promise<HookCapture> {\n const timeoutMs = options.timeoutMs ?? null;\n const seenFiles = options.seenFilePaths ?? new Set<string>();\n const unrefTimers = options.unrefTimers ?? true;\n const eventLabel = options.eventNames?.join(\", \") ?? \"hook\";\n\n return new Promise<HookCapture>((resolve, reject) => {\n const timeout = timeoutMs === null\n ? null\n : setTimeout(() => {\n clearInterval(interval);\n reject(new Error(`Timed out waiting for ${eventLabel} capture(s) for run ${options.runId}.`));\n }, timeoutMs);\n\n if (unrefTimers) {\n timeout?.unref();\n }\n\n const interval = setInterval(() => {\n for (const captureDirectory of getCaptureDirectories(options)) {\n if (!fs.existsSync(captureDirectory)) {\n continue;\n }\n\n const entries = fs.readdirSync(captureDirectory).sort();\n\n for (const entry of entries) {\n if (!entry.endsWith(\".json\")) {\n continue;\n }\n\n const filePath = path.join(captureDirectory, entry);\n\n if (seenFiles.has(filePath)) {\n continue;\n }\n\n const capture = readCaptureFile(filePath);\n\n if (!capture) {\n continue;\n }\n\n seenFiles.add(filePath);\n\n if (!isMatchingCapture(capture, options)) {\n continue;\n }\n\n if (timeout) {\n clearTimeout(timeout);\n }\n clearInterval(interval);\n resolve(capture);\n return;\n }\n }\n }, 250);\n\n if (unrefTimers) {\n interval.unref();\n }\n });\n}\n\nexport function waitForMatchingStopCapture(options: StopCaptureWaitOptions): Promise<StopCapture> {\n return waitForMatchingHookCapture({\n ...options,\n eventNames: [\"Stop\"]\n });\n}\n","import { spawn, type ChildProcess, type SpawnOptions } from \"node:child_process\";\n\nconst DEFAULT_MAX_OUTPUT_CHARS = 4000;\nconst MIN_SECTION_OUTPUT_CHARS = 400;\nconst WINDOWS_LINE_ENDING_PATTERN = /\\r\\n?/g;\n\nexport interface VerificationCommandOptions {\n command: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n maxOutputChars?: number;\n spawnImpl?: (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess;\n}\n\nexport interface VerificationCommandResult {\n code: number;\n command: string;\n stderr: string;\n stdout: string;\n succeeded: boolean;\n}\n\nfunction normalizeOutput(value: string): string {\n return value.replace(WINDOWS_LINE_ENDING_PATTERN, \"\\n\").trim();\n}\n\nfunction tailText(value: string, maxChars: number): string {\n if (value.length <= maxChars) {\n return value;\n }\n\n return `...${value.slice(-(maxChars - 3))}`;\n}\n\nfunction getSectionLimit(maxOutputChars: number): number {\n return Math.max(Math.floor(maxOutputChars / 2), MIN_SECTION_OUTPUT_CHARS);\n}\n\nexport async function runVerificationCommand(options: VerificationCommandOptions): Promise<VerificationCommandResult> {\n const spawnImpl = options.spawnImpl ?? spawn;\n const commandText = options.command.trim();\n\n if (!commandText) {\n throw new Error(\"Verification command is empty.\");\n }\n\n return new Promise((resolve) => {\n const child = spawnImpl(\"sh\", [\"-lc\", commandText], {\n cwd: options.cwd,\n env: options.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"]\n });\n let stdout = \"\";\n let stderr = \"\";\n let resolved = false;\n\n child.stdout?.setEncoding(\"utf8\");\n child.stderr?.setEncoding(\"utf8\");\n child.stdout?.on(\"data\", (chunk) => {\n stdout += chunk;\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr += chunk;\n });\n child.once(\"error\", (error) => {\n if (resolved) {\n return;\n }\n\n resolved = true;\n resolve({\n code: 1,\n command: commandText,\n stderr: `Unable to start verification command: ${error instanceof Error ? error.message : String(error)}`,\n stdout: \"\",\n succeeded: false\n });\n });\n child.once(\"exit\", (code, signal) => {\n if (resolved) {\n return;\n }\n\n resolved = true;\n const exitCode = signal ? 1 : code ?? 0;\n const signalMessage = signal\n ? `Verification command exited with signal ${signal}.`\n : \"\";\n const normalizedStdout = normalizeOutput(stdout);\n const normalizedStderr = normalizeOutput(\n signalMessage\n ? [stderr, signalMessage].filter(Boolean).join(\"\\n\")\n : stderr\n );\n\n resolve({\n code: exitCode,\n command: commandText,\n stderr: normalizedStderr,\n stdout: normalizedStdout,\n succeeded: exitCode === 0\n });\n });\n });\n}\n\nexport function formatVerificationFailurePrompt(\n result: VerificationCommandResult,\n options?: {\n maxOutputChars?: number;\n }\n): string {\n const maxOutputChars = options?.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n const sectionLimit = getSectionLimit(maxOutputChars);\n const stdout = tailText(result.stdout, sectionLimit);\n const stderr = tailText(result.stderr, sectionLimit);\n const lines = [\n \"Verification command failed.\",\n `Command: ${result.command}`,\n `Exit code: ${result.code}`\n ];\n\n if (stderr) {\n lines.push(\"\", \"stderr:\", stderr);\n }\n\n if (stdout) {\n lines.push(\"\", \"stdout:\", stdout);\n }\n\n return lines.join(\"\\n\").trim();\n}\n","import { waitForMatchingHookCapture, type HookCapture } from \"./hook-server.js\";\nimport type { RuntimeEventLogger } from \"./runtime-log.js\";\n\nexport interface HookEventWatcherOptions {\n cwd: string;\n eventNames: string[];\n logger: RuntimeEventLogger;\n onEvent?: (capture: HookCapture) => Promise<void> | void;\n runId: string;\n runStartedAt: number;\n signal?: AbortSignal;\n waitTimeoutMs?: number | null;\n unrefTimers?: boolean;\n}\n\nfunction isTimeoutError(error: unknown): boolean {\n return error instanceof Error && error.message.startsWith(\"Timed out waiting for \");\n}\n\nexport async function runHookEventWatcher(options: HookEventWatcherOptions): Promise<void> {\n const seenFilePaths = new Set<string>();\n options.logger.log(\"hook_event_watcher_started\", {\n eventNames: options.eventNames,\n runId: options.runId\n });\n\n while (!options.signal?.aborted) {\n let capture;\n\n try {\n capture = await waitForMatchingHookCapture({\n afterTimeMs: options.runStartedAt,\n cwd: options.cwd,\n eventNames: options.eventNames,\n runId: options.runId,\n seenFilePaths,\n timeoutMs: options.waitTimeoutMs ?? null,\n unrefTimers: options.unrefTimers\n });\n } catch (error) {\n if (options.signal?.aborted && isTimeoutError(error)) {\n break;\n }\n\n if (options.waitTimeoutMs !== undefined && options.waitTimeoutMs !== null && isTimeoutError(error)) {\n continue;\n }\n\n throw error;\n }\n\n options.logger.log(\"hook_event_matched\", {\n eventName: capture.payload?.hook_event_name ?? null,\n sessionId: capture.payload?.session_id ?? null,\n turnId: capture.payload?.turn_id ?? null\n });\n await options.onEvent?.(capture);\n }\n}\n","import fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nexport type CodexHooksScope = \"global\" | \"local\";\nexport type HookConfigHealth =\n | \"invalid\"\n | \"missing\"\n | \"missing-stop-hook\"\n | \"ready\"\n | \"stale-stop-hook\";\nexport type CodexHooksFeatureHealth = \"disabled\" | \"enabled\" | \"unknown\";\n\nexport interface HookConfigInspection {\n configuredHookPath: string | null;\n exists: boolean;\n health: HookConfigHealth;\n hookEvents: string[];\n matchesExpectedScript: boolean;\n missingHookEvents: string[];\n parseError: string | null;\n path: string;\n scope: CodexHooksScope;\n stopHookCommand: string | null;\n targetExists: boolean;\n}\n\nexport interface HookSetupInspection {\n activeConfig: HookConfigInspection | null;\n globalConfig: HookConfigInspection;\n globalPath: string;\n hookCommand: string;\n hookScriptPath: string;\n localConfig: HookConfigInspection;\n localPath: string;\n message: string;\n status: HookConfigHealth;\n}\n\nexport interface CodexHooksFeatureInspection {\n configPath: string;\n enabled: boolean | null;\n health: CodexHooksFeatureHealth;\n message: string;\n profile: string | null;\n}\n\ninterface HookConfigDocument {\n hooks?: Record<string, unknown>;\n}\n\nconst CODEX_FEATURE_FLAGS_WITH_VALUE = new Set([\n \"-c\",\n \"--config\",\n \"--disable\",\n \"--enable\",\n \"-p\",\n \"--profile\",\n \"-C\",\n \"--cd\"\n]);\nconst REQUIRED_HOOK_EVENTS = [\"SessionStart\", \"UserPromptSubmit\", \"Stop\"] as const;\n\nfunction shellEscape(argument: string): string {\n return `'${argument.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction readFileText(filePath: string): string | null {\n try {\n return fs.readFileSync(filePath, \"utf8\");\n } catch {\n return null;\n }\n}\n\nfunction extractStopHookPath(command: string | null): string | null {\n if (!command || !command.includes(\"stop-hook.cjs\")) {\n return null;\n }\n\n const singleQuotedMatch = command.match(/'([^']*stop-hook\\.cjs)'/u);\n\n if (singleQuotedMatch?.[1]) {\n return path.resolve(singleQuotedMatch[1]);\n }\n\n const doubleQuotedMatch = command.match(/\"([^\"]*stop-hook\\.cjs)\"/u);\n\n if (doubleQuotedMatch?.[1]) {\n return path.resolve(doubleQuotedMatch[1]);\n }\n\n const bareMatch = command.match(/(\\S*stop-hook\\.cjs)/u);\n\n if (bareMatch?.[1]) {\n return path.resolve(bareMatch[1]);\n }\n\n return null;\n}\n\nfunction findCodexBeeHookCommand(document: HookConfigDocument, eventName: string): string | null {\n const entries = document.hooks && typeof document.hooks === \"object\"\n ? (document.hooks as Record<string, unknown>)[eventName]\n : null;\n\n if (!Array.isArray(entries)) {\n return null;\n }\n\n for (const entry of entries) {\n if (!entry || typeof entry !== \"object\") {\n continue;\n }\n\n const hooks = (entry as {\n hooks?: unknown;\n }).hooks;\n\n if (!Array.isArray(hooks)) {\n continue;\n }\n\n for (const hook of hooks) {\n if (!hook || typeof hook !== \"object\") {\n continue;\n }\n\n const command = (hook as {\n command?: unknown;\n }).command;\n\n if (typeof command === \"string\" && command.includes(\"stop-hook.cjs\")) {\n return command;\n }\n }\n }\n\n return null;\n}\n\nfunction inspectHookConfigFile(options: {\n expectedHookText: string | null;\n hookCommand: string;\n path: string;\n scope: CodexHooksScope;\n}): HookConfigInspection {\n if (!fs.existsSync(options.path)) {\n return {\n configuredHookPath: null,\n exists: false,\n health: \"missing\",\n hookEvents: [],\n matchesExpectedScript: false,\n missingHookEvents: [...REQUIRED_HOOK_EVENTS],\n parseError: null,\n path: options.path,\n scope: options.scope,\n stopHookCommand: null,\n targetExists: false\n };\n }\n\n const rawText = readFileText(options.path);\n\n if (rawText === null) {\n return {\n configuredHookPath: null,\n exists: true,\n health: \"invalid\",\n hookEvents: [],\n matchesExpectedScript: false,\n missingHookEvents: [...REQUIRED_HOOK_EVENTS],\n parseError: `Unable to read ${options.path}.`,\n path: options.path,\n scope: options.scope,\n stopHookCommand: null,\n targetExists: false\n };\n }\n\n let parsed: HookConfigDocument;\n\n try {\n parsed = JSON.parse(rawText) as HookConfigDocument;\n } catch (error) {\n return {\n configuredHookPath: null,\n exists: true,\n health: \"invalid\",\n hookEvents: [],\n matchesExpectedScript: false,\n missingHookEvents: [...REQUIRED_HOOK_EVENTS],\n parseError: toErrorMessage(error),\n path: options.path,\n scope: options.scope,\n stopHookCommand: null,\n targetExists: false\n };\n }\n\n const hookEvents = REQUIRED_HOOK_EVENTS.filter((eventName) => findCodexBeeHookCommand(parsed, eventName) !== null);\n const missingHookEvents = REQUIRED_HOOK_EVENTS.filter((eventName) => !hookEvents.includes(eventName));\n const stopHookCommand =\n findCodexBeeHookCommand(parsed, \"SessionStart\")\n ?? findCodexBeeHookCommand(parsed, \"UserPromptSubmit\")\n ?? findCodexBeeHookCommand(parsed, \"Stop\");\n\n if (!stopHookCommand || missingHookEvents.length > 0) {\n return {\n configuredHookPath: null,\n exists: true,\n health: \"missing-stop-hook\",\n hookEvents,\n matchesExpectedScript: false,\n missingHookEvents,\n parseError: null,\n path: options.path,\n scope: options.scope,\n stopHookCommand,\n targetExists: false\n };\n }\n\n const configuredHookPath = extractStopHookPath(stopHookCommand);\n const targetExists = configuredHookPath !== null && fs.existsSync(configuredHookPath);\n const targetText = configuredHookPath ? readFileText(configuredHookPath) : null;\n const matchesExpectedScript = Boolean(\n targetExists\n && targetText !== null\n && options.expectedHookText !== null\n && targetText === options.expectedHookText\n );\n\n return {\n configuredHookPath,\n exists: true,\n health: targetExists && matchesExpectedScript\n ? \"ready\"\n : \"stale-stop-hook\",\n hookEvents,\n matchesExpectedScript,\n missingHookEvents,\n parseError: null,\n path: options.path,\n scope: options.scope,\n stopHookCommand,\n targetExists\n };\n}\n\nfunction describeHookStatus(activeConfig: HookConfigInspection | null): string {\n if (!activeConfig) {\n return \"No active Codex hooks config was found. codex-bee cannot receive SessionStart, UserPromptSubmit, or Stop events until its hook entries are installed.\";\n }\n\n const displayPath = activeConfig.path.replace(os.homedir(), \"~\");\n const scopeLabel = activeConfig.scope === \"local\" ? \"project-local\" : \"global\";\n\n switch (activeConfig.health) {\n case \"ready\":\n return `codex-bee hooks are ready via ${scopeLabel} config ${displayPath}. Waiting for SessionStart.`;\n case \"invalid\":\n return `The active ${scopeLabel} hooks config at ${displayPath} is not valid JSON, so codex-bee cannot trust it.`;\n case \"missing-stop-hook\":\n return activeConfig.missingHookEvents.length > 0\n ? `The active ${scopeLabel} hooks config at ${displayPath} is missing required codex-bee hook entries for ${activeConfig.missingHookEvents.join(\", \")}.`\n : `The active ${scopeLabel} hooks config at ${displayPath} does not include the required codex-bee hook entries.`;\n case \"stale-stop-hook\":\n return activeConfig.configuredHookPath && activeConfig.targetExists\n ? `The active ${scopeLabel} hooks config at ${displayPath} points to a stop hook that does not match the current codex-bee script.`\n : `The active ${scopeLabel} hooks config at ${displayPath} points to a missing or unreadable stop-hook.cjs target.`;\n default:\n return `The active ${scopeLabel} hooks config at ${displayPath} is missing.`;\n }\n}\n\nexport function buildStopHookCommand(hookScriptPath: string): string {\n return `node ${shellEscape(hookScriptPath)}`;\n}\n\nexport function getGlobalHooksConfigPath(homeDirectory = os.homedir()): string {\n return path.join(homeDirectory, \".codex\", \"hooks.json\");\n}\n\nexport function getGlobalCodexConfigPath(homeDirectory = os.homedir()): string {\n return path.join(homeDirectory, \".codex\", \"config.toml\");\n}\n\nexport function getLocalHooksConfigPath(cwd: string): string {\n return path.join(cwd, \".codex\", \"hooks.json\");\n}\n\nexport function collectCodexFeatureProbeArgs(commandArgs: readonly string[]): string[] {\n const probeArgs: string[] = [];\n\n for (let index = 0; index < commandArgs.length; index += 1) {\n const argument = commandArgs[index];\n\n if (!CODEX_FEATURE_FLAGS_WITH_VALUE.has(argument)) {\n continue;\n }\n\n const value = commandArgs[index + 1];\n\n if (value === undefined) {\n continue;\n }\n\n probeArgs.push(argument, value);\n index += 1;\n }\n\n return probeArgs;\n}\n\nexport function resolveCodexProfile(commandArgs: readonly string[]): string | null {\n for (let index = commandArgs.length - 1; index >= 0; index -= 1) {\n const argument = commandArgs[index];\n\n if (argument !== \"-p\" && argument !== \"--profile\") {\n continue;\n }\n\n const profile = commandArgs[index + 1];\n\n return profile ?? null;\n }\n\n return null;\n}\n\nfunction getFeatureTableHeader(profile: string | null): string {\n return profile ? `[profiles.${profile}.features]` : \"[features]\";\n}\n\nfunction replaceTomlKeyInTable(existingText: string | null, options: {\n header: string;\n key: string;\n value: string;\n}): string {\n const sourceText = existingText ?? \"\";\n const lines = sourceText.length > 0\n ? sourceText.split(/\\r?\\n/u)\n : [];\n const normalizedKeyPattern = new RegExp(`^\\\\s*${options.key}\\\\s*=`, \"u\");\n let tableStart = -1;\n let tableEnd = lines.length;\n\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index]?.trim();\n\n if (line === options.header) {\n tableStart = index;\n break;\n }\n }\n\n if (tableStart >= 0) {\n for (let index = tableStart + 1; index < lines.length; index += 1) {\n const line = lines[index]?.trim() ?? \"\";\n\n if (line.startsWith(\"[\") && line.endsWith(\"]\")) {\n tableEnd = index;\n break;\n }\n }\n\n for (let index = tableStart + 1; index < tableEnd; index += 1) {\n const line = lines[index];\n\n if (!line || !normalizedKeyPattern.test(line)) {\n continue;\n }\n\n lines[index] = `${options.key} = ${options.value}`;\n\n return `${lines.join(\"\\n\").replace(/\\n*$/u, \"\\n\")}`;\n }\n\n lines.splice(tableEnd, 0, `${options.key} = ${options.value}`);\n\n return `${lines.join(\"\\n\").replace(/\\n*$/u, \"\\n\")}`;\n }\n\n const prefix = sourceText.length > 0 && !sourceText.endsWith(\"\\n\")\n ? `${sourceText}\\n`\n : sourceText;\n const separator = prefix.trim().length > 0 ? \"\\n\" : \"\";\n\n return `${prefix}${separator}${options.header}\\n${options.key} = ${options.value}\\n`;\n}\n\nexport function inspectCodexHooksFeatureListOutput(options: {\n configPath?: string;\n output: string;\n profile?: string | null;\n}): CodexHooksFeatureInspection {\n const featureLine = options.output\n .split(/\\r?\\n/u)\n .map((line) => line.trim())\n .find((line) => line.startsWith(\"codex_hooks \"));\n const configPath = options.configPath ?? getGlobalCodexConfigPath();\n const profile = options.profile ?? null;\n\n if (!featureLine) {\n return {\n configPath,\n enabled: null,\n health: \"unknown\",\n message: \"Unable to determine the effective codex_hooks feature state from `codex features list`.\",\n profile\n };\n }\n\n const enabled = /\\btrue$/u.test(featureLine);\n const targetLabel = profile\n ? `profile \"${profile}\"`\n : \"global Codex config\";\n\n return {\n configPath,\n enabled,\n health: enabled ? \"enabled\" : \"disabled\",\n message: enabled\n ? `codex_hooks is enabled for the ${targetLabel}.`\n : `codex_hooks is disabled for the ${targetLabel}. codex-bee will not receive SessionStart, UserPromptSubmit, or Stop events until it is enabled.`,\n profile\n };\n}\n\nexport function upsertCodexHooksFeatureConfigText(existingText: string | null, profile: string | null): string {\n return replaceTomlKeyInTable(existingText, {\n header: getFeatureTableHeader(profile),\n key: \"codex_hooks\",\n value: \"true\"\n });\n}\n\nexport function inspectCodexHookSetup(options: {\n cwd: string;\n hookScriptPath: string;\n homeDirectory?: string;\n}): HookSetupInspection {\n const homeDirectory = options.homeDirectory ?? os.homedir();\n const localPath = getLocalHooksConfigPath(options.cwd);\n const globalPath = getGlobalHooksConfigPath(homeDirectory);\n const hookCommand = buildStopHookCommand(options.hookScriptPath);\n const expectedHookText = readFileText(options.hookScriptPath);\n const localConfig = inspectHookConfigFile({\n expectedHookText,\n hookCommand,\n path: localPath,\n scope: \"local\"\n });\n const globalConfig = inspectHookConfigFile({\n expectedHookText,\n hookCommand,\n path: globalPath,\n scope: \"global\"\n });\n const activeConfig = localConfig.exists\n ? localConfig\n : globalConfig.exists\n ? globalConfig\n : null;\n const status = activeConfig?.health ?? \"missing\";\n\n return {\n activeConfig,\n globalConfig,\n globalPath,\n hookCommand,\n hookScriptPath: options.hookScriptPath,\n localConfig,\n localPath,\n message: describeHookStatus(activeConfig),\n status\n };\n}\n\nexport function upsertStopHookConfigText(existingText: string | null, hookScriptPath: string): string {\n let document: HookConfigDocument = {};\n\n if (existingText) {\n document = JSON.parse(existingText) as HookConfigDocument;\n }\n\n if (!document || typeof document !== \"object\" || Array.isArray(document)) {\n document = {};\n }\n\n const hooks = document.hooks && typeof document.hooks === \"object\" && !Array.isArray(document.hooks)\n ? { ...(document.hooks as Record<string, unknown>) }\n : {};\n const hookCommand = buildStopHookCommand(hookScriptPath);\n const nextHooks = { ...hooks };\n\n for (const eventName of REQUIRED_HOOK_EVENTS) {\n const eventEntries = Array.isArray(nextHooks[eventName])\n ? [...(nextHooks[eventName] as unknown[])]\n : [];\n let replaced = false;\n\n const nextEntries = eventEntries.map((entry) => {\n if (!entry || typeof entry !== \"object\") {\n return entry;\n }\n\n const hooksList = (entry as {\n hooks?: unknown;\n }).hooks;\n\n if (!Array.isArray(hooksList)) {\n return entry;\n }\n\n const nextHooksList = hooksList.map((hook) => {\n if (!hook || typeof hook !== \"object\") {\n return hook;\n }\n\n const command = (hook as {\n command?: unknown;\n }).command;\n\n if (typeof command !== \"string\" || !command.includes(\"stop-hook.cjs\")) {\n return hook;\n }\n\n replaced = true;\n\n return {\n ...hook,\n command: hookCommand,\n timeout: 30,\n type: \"command\"\n };\n });\n\n return {\n ...entry,\n hooks: nextHooksList\n };\n });\n\n if (!replaced) {\n nextEntries.push({\n hooks: [\n {\n command: hookCommand,\n timeout: 30,\n type: \"command\"\n }\n ]\n });\n }\n\n nextHooks[eventName] = nextEntries;\n }\n\n return `${JSON.stringify({\n ...document,\n hooks: nextHooks\n }, null, 2)}\\n`;\n}\n\nexport function writeHookConfigFile(filePath: string, content: string): void {\n fs.mkdirSync(path.dirname(filePath), {\n recursive: true\n });\n fs.writeFileSync(filePath, content, \"utf8\");\n}\n\nexport function writeCodexConfigFile(filePath: string, content: string): void {\n fs.mkdirSync(path.dirname(filePath), {\n recursive: true\n });\n fs.writeFileSync(filePath, content, \"utf8\");\n}\n","import { spawn, type ChildProcess, type SpawnOptions } from \"node:child_process\";\n\nexport interface PassthroughModeOptions {\n hasContinuation: boolean;\n stdinIsTTY: boolean | undefined;\n stdoutIsTTY: boolean | undefined;\n}\n\nexport interface PassthroughRunOptions {\n args: string[];\n command: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n spawnImpl?: (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess;\n}\n\nexport function resolveExecutionMode(options: PassthroughModeOptions): \"interactive\" | \"passthrough\" {\n if (options.stdinIsTTY && options.stdoutIsTTY) {\n return \"interactive\";\n }\n\n if (options.hasContinuation) {\n throw new Error(\"auto-continue requires both stdin and stdout to be TTYs. Run `bee codex ...` from an interactive terminal.\");\n }\n\n return \"passthrough\";\n}\n\nexport function runPassthroughCommand(options: PassthroughRunOptions): Promise<number> {\n const spawnImpl = options.spawnImpl ?? spawn;\n\n return new Promise<number>((resolve, reject) => {\n const child = spawnImpl(options.command, options.args, {\n cwd: options.cwd,\n env: options.env,\n stdio: \"inherit\"\n }) as ChildProcess;\n\n child.once(\"error\", (error) => {\n reject(error);\n });\n\n child.once(\"exit\", (code, signal) => {\n if (signal) {\n resolve(1);\n return;\n }\n\n resolve(code ?? 0);\n });\n });\n}\n","import { readFile, readlink } from \"node:fs/promises\";\nimport { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport process from \"node:process\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nexport interface PtyProxyOptions {\n command: string;\n commandArgs: string[];\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n onOutputActivity?: (event: {\n bytes: number;\n source: \"stderr\" | \"stdout\";\n timestamp: number;\n }) => void;\n}\n\ntype InputInterceptor = (chunk: Buffer | string) => boolean;\n\ninterface TerminalSize {\n columns: number;\n rows: number;\n}\n\nconst BRACKETED_PASTE_END = \"\\u001b[201~\";\nconst BRACKETED_PASTE_START = \"\\u001b[200~\";\nconst CLEAR_SCROLLBACK_SEQUENCE = \"\\u001b[3J\";\n\nfunction shellEscape(argument: string): string {\n return `'${argument.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nfunction resolveTerminalSize(): TerminalSize {\n const columns = process.stdout.columns && process.stdout.columns > 0\n ? process.stdout.columns\n : 80;\n const rows = process.stdout.rows && process.stdout.rows > 0\n ? process.stdout.rows\n : 24;\n\n return { columns, rows };\n}\n\nfunction buildWrappedProcessCommand(command: string, commandArgs: string[]): string {\n return [command, ...commandArgs].map(shellEscape).join(\" \");\n}\n\nfunction buildWrappedCommand(command: string, commandArgs: string[], terminalSize: TerminalSize): string {\n const wrappedCommand = buildWrappedProcessCommand(command, commandArgs);\n const rows = String(terminalSize.rows);\n const columns = String(terminalSize.columns);\n\n return [\n `stty rows ${rows} cols ${columns} >/dev/null 2>&1`,\n `export LINES=${rows}`,\n `export COLUMNS=${columns}`,\n `exec ${wrappedCommand}`\n ].join(\"; \");\n}\n\nexport function formatBracketedPaste(prompt: string): string {\n return `${BRACKETED_PASTE_START}${prompt}${BRACKETED_PASTE_END}`;\n}\n\nfunction createInteractiveError(message: string): Error {\n return new Error(`codex-bee interactive wrapper error: ${message}`);\n}\n\nfunction sanitizeTerminalOutput(chunk: Buffer): Buffer {\n const text = chunk.toString(\"utf8\");\n\n if (!text.includes(CLEAR_SCROLLBACK_SEQUENCE)) {\n return chunk;\n }\n\n return Buffer.from(text.replaceAll(CLEAR_SCROLLBACK_SEQUENCE, \"\"), \"utf8\");\n}\n\nexport class PtyProxy {\n readonly #options: PtyProxyOptions;\n #bufferedStderrChunks: Buffer[] = [];\n #bufferedStdoutChunks: Buffer[] = [];\n #child: ChildProcessWithoutNullStreams | null = null;\n #exitPromise: Promise<number> | null = null;\n #cleanupCallbacks: Array<() => void> = [];\n #terminalSize: TerminalSize | null = null;\n #childTtyPath: string | null = null;\n #inputInterceptor: InputInterceptor | null = null;\n #outputMuted = false;\n #windowSyncInFlight = false;\n\n constructor(options: PtyProxyOptions) {\n this.#options = options;\n }\n\n async start(): Promise<void> {\n if (this.#child) {\n throw createInteractiveError(\"PTY proxy already started.\");\n }\n\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n throw createInteractiveError(\"interactive mode requires both stdin and stdout to be TTYs.\");\n }\n\n if (process.platform !== \"linux\") {\n throw createInteractiveError(\"the current PTY prototype supports Linux only.\");\n }\n\n this.#terminalSize = resolveTerminalSize();\n\n const command = buildWrappedCommand(this.#options.command, this.#options.commandArgs, this.#terminalSize);\n const child = spawn(\"script\", [\"-qfc\", command, \"/dev/null\"], {\n cwd: this.#options.cwd ?? process.cwd(),\n env: this.#options.env ?? process.env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"]\n });\n\n this.#child = child;\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n const normalizedChunk = sanitizeTerminalOutput(chunk);\n this.#options.onOutputActivity?.({\n bytes: normalizedChunk.length,\n source: \"stdout\",\n timestamp: Date.now()\n });\n\n if (this.#outputMuted) {\n this.#bufferedStdoutChunks.push(Buffer.from(normalizedChunk));\n return;\n }\n\n process.stdout.write(normalizedChunk);\n });\n\n child.stderr.on(\"data\", (chunk: Buffer) => {\n const normalizedChunk = sanitizeTerminalOutput(chunk);\n this.#options.onOutputActivity?.({\n bytes: normalizedChunk.length,\n source: \"stderr\",\n timestamp: Date.now()\n });\n\n if (this.#outputMuted) {\n this.#bufferedStderrChunks.push(Buffer.from(normalizedChunk));\n return;\n }\n\n process.stderr.write(normalizedChunk);\n });\n\n const handleInput = (chunk: Buffer | string) => {\n if (this.#inputInterceptor?.(chunk)) {\n return;\n }\n\n child.stdin.write(chunk);\n };\n\n process.stdin.resume();\n process.stdin.setRawMode(true);\n process.stdin.on(\"data\", handleInput);\n\n this.#cleanupCallbacks.push(() => {\n process.stdin.off(\"data\", handleInput);\n process.stdin.setRawMode(false);\n process.stdin.pause();\n });\n\n const handleResize = () => {\n this.#terminalSize = resolveTerminalSize();\n void this.#syncWindowSize();\n\n if (!child.pid) {\n return;\n }\n\n try {\n process.kill(child.pid, \"SIGWINCH\");\n } catch {\n // Ignore resize propagation failures during shutdown.\n }\n };\n\n process.on(\"SIGWINCH\", handleResize);\n this.#cleanupCallbacks.push(() => {\n process.off(\"SIGWINCH\", handleResize);\n });\n\n void this.#syncWindowSize();\n\n this.#exitPromise = new Promise<number>((resolve, reject) => {\n child.once(\"error\", (error) => {\n this.#cleanup();\n\n if (\"code\" in error && error.code === \"ENOENT\") {\n reject(createInteractiveError(\"`script` command was not found on this machine.\"));\n return;\n }\n\n reject(error);\n });\n\n child.once(\"exit\", (code, signal) => {\n this.#cleanup();\n\n if (signal) {\n resolve(1);\n return;\n }\n\n resolve(code ?? 0);\n });\n });\n }\n\n write(data: string): void {\n if (!this.#child) {\n throw createInteractiveError(\"cannot write before the PTY proxy starts.\");\n }\n\n this.#child.stdin.write(data);\n }\n\n setInputInterceptor(inputInterceptor: InputInterceptor | null): void {\n this.#inputInterceptor = inputInterceptor;\n }\n\n setOutputMuted(muted: boolean): void {\n if (this.#outputMuted === muted) {\n return;\n }\n\n this.#outputMuted = muted;\n\n if (muted) {\n return;\n }\n\n for (const chunk of this.#bufferedStdoutChunks.splice(0, this.#bufferedStdoutChunks.length)) {\n process.stdout.write(chunk);\n }\n\n for (const chunk of this.#bufferedStderrChunks.splice(0, this.#bufferedStderrChunks.length)) {\n process.stderr.write(chunk);\n }\n }\n\n async injectPrompt(prompt: string, options?: {\n submitDelayMs?: number;\n }): Promise<void> {\n const submitDelayMs = options?.submitDelayMs ?? 75;\n\n // Sending the prompt as bracketed paste keeps multiline content intact without early submits.\n this.write(formatBracketedPaste(prompt));\n await delay(submitDelayMs);\n this.write(\"\\r\");\n }\n\n async stop(signal: NodeJS.Signals = \"SIGTERM\"): Promise<void> {\n if (!this.#child || !this.#exitPromise) {\n return;\n }\n\n if (this.#child.exitCode === null && !this.#child.killed) {\n this.#child.kill(signal);\n }\n\n await this.#exitPromise.catch(() => undefined);\n }\n\n requestRedraw(): void {\n if (!this.#child || !this.#child.pid) {\n return;\n }\n\n void this.#syncWindowSize();\n this.write(\"\\f\");\n\n try {\n process.kill(this.#child.pid, \"SIGWINCH\");\n } catch {\n // Ignore redraw propagation failures during shutdown.\n }\n }\n\n waitForExit(): Promise<number> {\n if (!this.#exitPromise) {\n throw createInteractiveError(\"cannot wait for exit before the PTY proxy starts.\");\n }\n\n return this.#exitPromise;\n }\n\n #cleanup(): void {\n const callbacks = this.#cleanupCallbacks.splice(0, this.#cleanupCallbacks.length);\n\n for (const callback of callbacks.reverse()) {\n callback();\n }\n }\n\n async #syncWindowSize(): Promise<void> {\n if (this.#windowSyncInFlight) {\n return;\n }\n\n const childPid = this.#child?.pid;\n const terminalSize = this.#terminalSize;\n\n if (!childPid || !terminalSize) {\n return;\n }\n\n this.#windowSyncInFlight = true;\n\n try {\n const ttyPath = await this.#resolveChildTtyPath(childPid);\n\n if (!ttyPath) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n const resizeProcess = spawn(\n \"stty\",\n [\"-F\", ttyPath, \"rows\", String(terminalSize.rows), \"cols\", String(terminalSize.columns)],\n {\n stdio: \"ignore\"\n }\n );\n\n resizeProcess.once(\"error\", () => {\n resolve();\n });\n\n resizeProcess.once(\"exit\", () => {\n resolve();\n });\n });\n } finally {\n this.#windowSyncInFlight = false;\n }\n }\n\n async #resolveChildTtyPath(rootPid: number): Promise<string | null> {\n if (this.#childTtyPath) {\n return this.#childTtyPath;\n }\n\n const queue = await readProcessChildren(rootPid);\n const seen = new Set<number>(queue);\n\n while (queue.length > 0) {\n const candidatePid = queue.shift();\n\n if (!candidatePid) {\n continue;\n }\n\n const ttyPath = await readProcessTtyPath(candidatePid);\n\n if (ttyPath) {\n this.#childTtyPath = ttyPath;\n return ttyPath;\n }\n\n const children = await readProcessChildren(candidatePid);\n\n for (const childPid of children) {\n if (seen.has(childPid)) {\n continue;\n }\n\n seen.add(childPid);\n queue.push(childPid);\n }\n }\n\n return null;\n }\n}\n\nasync function readProcessChildren(pid: number): Promise<number[]> {\n try {\n const children = await readFile(`/proc/${pid}/task/${pid}/children`, \"utf8\");\n\n return children\n .trim()\n .split(/\\s+/u)\n .filter(Boolean)\n .map((value) => Number.parseInt(value, 10))\n .filter((value) => Number.isInteger(value) && value > 0);\n } catch {\n return [];\n }\n}\n\nasync function readProcessTtyPath(pid: number): Promise<string | null> {\n try {\n const ttyPath = await readlink(`/proc/${pid}/fd/0`);\n\n return ttyPath.startsWith(\"/dev/pts/\") ? ttyPath : null;\n } catch {\n return null;\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface RuntimeEventLogger {\n log(eventType: string, data?: Record<string, unknown>): void;\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function createRuntimeEventLogger(cwd: string, options: {\n runId: string;\n}): RuntimeEventLogger {\n const tempRoot = path.join(cwd, \".codex\", \"tmp\");\n const logPath = path.join(tempRoot, \"bee-events.jsonl\");\n let sequence = 0;\n\n return {\n log(eventType, data) {\n try {\n fs.mkdirSync(tempRoot, {\n recursive: true\n });\n fs.appendFileSync(\n logPath,\n `${JSON.stringify({\n data: data ?? {},\n eventType,\n runId: options.runId,\n sequence: sequence += 1,\n timestamp: new Date().toISOString()\n })}\\n`,\n \"utf8\"\n );\n } catch (error) {\n console.error(`[codex-bee] Failed to write runtime event log: ${toErrorMessage(error)}`);\n }\n }\n };\n}\n","import type { UiCommandId, UiCommandInvocation } from \"./types.js\";\n\nconst SLEEP_INPUT_PATTERN = /^(\\d{1,2}):(\\d{2})$/;\n\nexport interface UiSlashCommandDefinition {\n description: string;\n id: UiCommandId;\n name: string;\n placeholder: string | null;\n}\n\nexport interface UiSlashCommandParseError {\n error: string;\n}\n\nexport const UI_SLASH_COMMANDS: UiSlashCommandDefinition[] = [\n {\n description: \"Set session duration\",\n id: \"duration\",\n name: \"/duration\",\n placeholder: \"<minutes>\"\n },\n {\n description: \"Set absolute stop time\",\n id: \"sleep\",\n name: \"/sleep\",\n placeholder: \"<HH:MM>\"\n },\n {\n description: \"Set max turns count\",\n id: \"steps-count\",\n name: \"/steps-count\",\n placeholder: \"<number>\"\n },\n {\n description: \"Set post-turn hook script\",\n id: \"stop-script\",\n name: \"/stop-script\",\n placeholder: \"<command>\"\n },\n {\n description: \"Clear log output\",\n id: \"clear-log\",\n name: \"/clear-log\",\n placeholder: null\n },\n {\n description: \"Exit codex-bee\",\n id: \"quit\",\n name: \"/quit\",\n placeholder: null\n }\n];\n\nfunction parsePositiveInteger(value: string, label: string): number | UiSlashCommandParseError {\n const parsedValue = Number.parseInt(value.trim(), 10);\n\n if (!Number.isFinite(parsedValue) || parsedValue < 1) {\n return {\n error: `${label} must be a positive integer.`\n };\n }\n\n return parsedValue;\n}\n\nexport function filterSlashCommands(query: string): UiSlashCommandDefinition[] {\n const normalizedQuery = query.trim().toLowerCase();\n\n if (!normalizedQuery) {\n return [...UI_SLASH_COMMANDS];\n }\n\n return UI_SLASH_COMMANDS.filter((command) => command.name.slice(1).startsWith(normalizedQuery));\n}\n\nexport function findSlashCommandById(id: UiCommandId): UiSlashCommandDefinition | undefined {\n return UI_SLASH_COMMANDS.find((command) => command.id === id);\n}\n\nexport function getSlashQuery(composerText: string): string | null {\n if (!composerText.startsWith(\"/\") || composerText.includes(\"\\n\")) {\n return null;\n }\n\n const trailingText = composerText.slice(1);\n\n if (/\\s/.test(trailingText)) {\n return null;\n }\n\n return trailingText.toLowerCase();\n}\n\nexport function isSlashCommandInput(value: string): boolean {\n return value.trimStart().startsWith(\"/\");\n}\n\nexport function parseSlashCommandInput(value: string): UiCommandInvocation | UiSlashCommandParseError {\n const trimmedValue = value.trim();\n\n if (!trimmedValue.startsWith(\"/\")) {\n return {\n error: \"Commands must start with '/'.\"\n };\n }\n\n const [name, ...argumentParts] = trimmedValue.split(/\\s+/);\n const argument = argumentParts.join(\" \").trim();\n\n switch (name) {\n case \"/duration\": {\n if (!argument) {\n return {\n error: \"/duration requires <minutes>.\"\n };\n }\n\n const parsedMinutes = parsePositiveInteger(argument, \"Duration\");\n\n if (typeof parsedMinutes !== \"number\") {\n return parsedMinutes;\n }\n\n return {\n id: \"duration\",\n minutes: parsedMinutes,\n raw: trimmedValue\n };\n }\n case \"/sleep\": {\n if (!argument) {\n return {\n error: \"/sleep requires <HH:MM>.\"\n };\n }\n\n const match = argument.match(SLEEP_INPUT_PATTERN);\n\n if (!match) {\n return {\n error: \"/sleep expects a 24-hour time like 23:15.\"\n };\n }\n\n const hours = Number.parseInt(match[1], 10);\n const minutes = Number.parseInt(match[2], 10);\n\n if (hours > 23 || minutes > 59) {\n return {\n error: \"/sleep expects a 24-hour time like 23:15.\"\n };\n }\n\n return {\n hours,\n id: \"sleep\",\n minutes,\n raw: trimmedValue,\n time: `${String(hours).padStart(2, \"0\")}:${String(minutes).padStart(2, \"0\")}`\n };\n }\n case \"/steps-count\": {\n if (!argument) {\n return {\n error: \"/steps-count requires <number>.\"\n };\n }\n\n const parsedSteps = parsePositiveInteger(argument, \"Steps count\");\n\n if (typeof parsedSteps !== \"number\") {\n return parsedSteps;\n }\n\n return {\n id: \"steps-count\",\n raw: trimmedValue,\n steps: parsedSteps\n };\n }\n case \"/stop-script\":\n if (!argument) {\n return {\n error: \"/stop-script requires <command>.\"\n };\n }\n\n return {\n command: argument,\n id: \"stop-script\",\n raw: trimmedValue\n };\n case \"/clear-log\":\n return {\n id: \"clear-log\",\n raw: trimmedValue\n };\n case \"/quit\":\n return {\n id: \"quit\",\n raw: trimmedValue\n };\n default:\n return {\n error: `Unknown command: ${name}`\n };\n }\n}\n","export type UiMode = \"agent\" | \"off\" | \"static\" | \"thinking\";\nexport type UiVisibleScreen = \"bee\" | \"codex\";\nexport type UiConnectionState = \"connected\" | \"disconnected\" | \"ready\";\nexport type UiRunState = \"idle\" | \"running\";\nexport type UiLogEntryKind = \"hook\" | \"model\" | \"status\" | \"summary\" | \"user\";\nexport type UiNoticeKind = \"error\" | \"info\" | \"warning\";\nexport type UiCommandId = \"clear-log\" | \"duration\" | \"quit\" | \"sleep\" | \"steps-count\" | \"stop-script\";\n\nexport const UI_MODES: UiMode[] = [\"off\", \"static\"];\n\nexport interface UiAnnouncement {\n message: string;\n}\n\nexport interface UiHookStatus {\n code: number;\n ok: boolean;\n}\n\nexport interface UiLogEntry {\n id: string;\n kind: UiLogEntryKind;\n text: string;\n timestamp: number;\n}\n\nexport interface UiTurnGroup {\n durationMs: number | null;\n entries: UiLogEntry[];\n id: string;\n totalTurns: number | null;\n turn: number;\n}\n\nexport interface UiSessionInfo {\n currentTurn: number | null;\n hookStatus: UiHookStatus | null;\n lastCodexOutputAt: number | null;\n stopAt: number | null;\n stopScript: string | null;\n totalTurns: number | null;\n}\n\nexport interface UiWorkspaceInfo {\n ahead: number;\n behind: number;\n cwd: string;\n gitBranch: string;\n}\n\nexport interface UiRuntimeSnapshot {\n activeScenarioId: string | null;\n announcement: UiAnnouncement | null;\n beeVersion: string;\n codexBufferLines: string[];\n codexVersion: string;\n connectionState: UiConnectionState;\n logs: UiTurnGroup[];\n prompts: Record<UiMode, string>;\n runState: UiRunState;\n session: UiSessionInfo;\n workspace: UiWorkspaceInfo;\n}\n\nexport interface UiScenarioOption {\n description: string;\n id: string;\n label: string;\n}\n\nexport interface UiNotice {\n expiresInMs?: number;\n id: number;\n kind: UiNoticeKind;\n message: string;\n}\n\nexport interface UiDropdownState {\n interacted: boolean;\n open: boolean;\n selectedIndex: number;\n}\n\nexport interface UiState {\n activeMode: UiMode;\n composerCursorOffset: number;\n composerText: string;\n currentScreen: UiVisibleScreen;\n dropdown: UiDropdownState;\n exitRequested: boolean;\n isInitialized: boolean;\n notice: UiNotice | null;\n runtime: UiRuntimeSnapshot;\n scenarios: UiScenarioOption[];\n}\n\nexport type UiCommandInvocation =\n | {\n id: \"clear-log\";\n raw: string;\n }\n | {\n id: \"duration\";\n minutes: number;\n raw: string;\n }\n | {\n id: \"quit\";\n raw: string;\n }\n | {\n hours: number;\n id: \"sleep\";\n minutes: number;\n raw: string;\n time: string;\n }\n | {\n id: \"steps-count\";\n raw: string;\n steps: number;\n }\n | {\n command: string;\n id: \"stop-script\";\n raw: string;\n };\n\nexport type UiIntent =\n | {\n text: string;\n type: \"appendInput\";\n }\n | {\n type: \"backspace\";\n }\n | {\n type: \"clearExitRequest\";\n }\n | {\n type: \"closeDropdown\";\n }\n | {\n type: \"cycleMode\";\n }\n | {\n type: \"dismissNotice\";\n }\n | {\n type: \"insertNewline\";\n }\n | {\n offset: number;\n type: \"setComposerCursorOffset\";\n }\n | {\n text: string;\n type: \"pasteInput\";\n }\n | {\n type: \"refreshFromRuntime\";\n }\n | {\n scenarioId: string;\n type: \"selectScenario\";\n }\n | {\n type: \"selectNextCommand\";\n }\n | {\n type: \"selectPreviousCommand\";\n }\n | {\n type: \"showExitHint\";\n }\n | {\n type: \"submitComposer\";\n }\n | {\n type: \"toggleScreen\";\n };\n","import { filterSlashCommands, parseSlashCommandInput, getSlashQuery } from \"./commands.js\";\nimport { UI_MODES } from \"./types.js\";\nimport type {\n UiNotice,\n UiIntent,\n UiMode,\n UiRuntimeSnapshot,\n UiScenarioOption,\n UiState\n} from \"./types.js\";\nimport type { UiHostUpdate, UiRuntimeHost } from \"../runtime/types.js\";\n\ntype Listener = () => void;\n\nfunction clampCodepointOffset(value: string, offset: number): number {\n return Math.max(0, Math.min(offset, Array.from(value).length));\n}\n\nfunction replaceRangeAtCodepointOffset(\n value: string,\n startOffset: number,\n endOffset: number,\n replacement: string\n): {\n nextOffset: number;\n nextValue: string;\n} {\n const codepoints = Array.from(value);\n const replacementCodepoints = Array.from(replacement);\n const clampedStartOffset = clampCodepointOffset(value, startOffset);\n const clampedEndOffset = clampCodepointOffset(value, endOffset);\n const nextValue = [\n ...codepoints.slice(0, clampedStartOffset),\n ...replacementCodepoints,\n ...codepoints.slice(clampedEndOffset)\n ].join(\"\");\n\n return {\n nextOffset: clampedStartOffset + replacementCodepoints.length,\n nextValue\n };\n}\n\nfunction stripTrailingSlashMarkers(value: string): string {\n return value\n .split(\"\\n\")\n .map((line) => line.replace(/\\s*\\/\\s*$/u, \"\"))\n .join(\"\\n\");\n}\n\nfunction createDefaultRuntimeSnapshot(): UiRuntimeSnapshot {\n return {\n activeScenarioId: null,\n announcement: null,\n beeVersion: \"0.1.0\",\n codexBufferLines: [\n \"$ codex mock session booted\",\n \"Waiting for codex-bee to hand control back.\"\n ],\n codexVersion: \"0.118.0\",\n connectionState: \"connected\",\n logs: [],\n prompts: {\n off: \"Off mode is passive. Codex-bee keeps collecting turn stats and logs, but it will not stage or inject prompts.\",\n agent: \"Agent mode placeholder. Dynamic planning will be wired later.\",\n static: \"continue\",\n thinking: \"Thinking mode placeholder. Bee reasoning controls will land later.\"\n },\n runState: \"idle\",\n session: {\n currentTurn: 0,\n hookStatus: {\n code: 0,\n ok: true\n },\n lastCodexOutputAt: null,\n stopAt: null,\n stopScript: \"pnpm test\",\n totalTurns: null\n },\n workspace: {\n ahead: 2,\n behind: 0,\n cwd: \"~/projects/codex-bee\",\n gitBranch: \"main\"\n }\n };\n}\n\nfunction createInitialState(): UiState {\n return {\n activeMode: \"off\",\n composerCursorOffset: 0,\n composerText: \"\",\n currentScreen: \"bee\",\n dropdown: {\n interacted: false,\n open: false,\n selectedIndex: 0\n },\n exitRequested: false,\n isInitialized: false,\n notice: null,\n runtime: createDefaultRuntimeSnapshot(),\n scenarios: []\n };\n}\n\nfunction cloneRuntimeSnapshot(snapshot: UiRuntimeSnapshot): UiRuntimeSnapshot {\n return {\n ...snapshot,\n announcement: snapshot.announcement\n ? {\n ...snapshot.announcement\n }\n : null,\n codexBufferLines: [...snapshot.codexBufferLines],\n logs: snapshot.logs.map((group) => ({\n ...group,\n entries: group.entries.map((entry) => ({\n ...entry\n }))\n })),\n prompts: {\n ...snapshot.prompts\n },\n session: {\n ...snapshot.session,\n hookStatus: snapshot.session.hookStatus\n ? {\n ...snapshot.session.hookStatus\n }\n : null\n },\n workspace: {\n ...snapshot.workspace\n }\n };\n}\n\nexport class UiController {\n readonly #host: UiRuntimeHost;\n readonly #listeners = new Set<Listener>();\n #didInitialize = false;\n #hostUnsubscribe: (() => void) | null = null;\n #noticeCounter = 0;\n #state = createInitialState();\n\n constructor(host: UiRuntimeHost) {\n this.#host = host;\n }\n\n async dispatch(intent: UiIntent): Promise<void> {\n switch (intent.type) {\n case \"appendInput\":\n this.#replaceComposerRange(\n this.#state.composerCursorOffset,\n this.#state.composerCursorOffset,\n intent.text\n );\n return;\n case \"backspace\":\n if (this.#state.currentScreen !== \"bee\" || this.#state.composerCursorOffset === 0) {\n this.#clearNotice();\n return;\n }\n\n this.#replaceComposerRange(\n this.#state.composerCursorOffset - 1,\n this.#state.composerCursorOffset,\n \"\"\n );\n return;\n case \"clearExitRequest\":\n this.#setState({\n exitRequested: false\n });\n return;\n case \"closeDropdown\":\n this.#setState({\n dropdown: {\n interacted: false,\n open: false,\n selectedIndex: 0\n },\n notice: null\n });\n return;\n case \"cycleMode\":\n await this.#cycleMode();\n return;\n case \"dismissNotice\":\n this.#setState({\n notice: null\n });\n return;\n case \"insertNewline\":\n if (this.#state.currentScreen !== \"bee\") {\n this.#clearNotice();\n return;\n }\n\n this.#replaceComposerRange(\n this.#state.composerCursorOffset,\n this.#state.composerCursorOffset,\n \"\\n\"\n );\n return;\n case \"setComposerCursorOffset\":\n if (this.#state.currentScreen !== \"bee\") {\n this.#clearNotice();\n return;\n }\n\n this.#setState({\n composerCursorOffset: clampCodepointOffset(this.#state.composerText, intent.offset),\n notice: null\n });\n return;\n case \"pasteInput\":\n if (this.#state.currentScreen !== \"bee\") {\n this.#clearNotice();\n return;\n }\n\n this.#replaceComposerRange(\n this.#state.composerCursorOffset,\n this.#state.composerCursorOffset,\n intent.text\n );\n return;\n case \"refreshFromRuntime\":\n await this.#refreshState();\n return;\n case \"selectScenario\":\n await this.#selectScenario(intent.scenarioId);\n return;\n case \"selectNextCommand\":\n this.#moveCommandSelection(1);\n return;\n case \"selectPreviousCommand\":\n this.#moveCommandSelection(-1);\n return;\n case \"showExitHint\":\n this.#setState({\n notice: this.#createNotice({\n kind: \"warning\",\n message: \"Ctrl+B to exit\"\n })\n });\n return;\n case \"submitComposer\":\n await this.#submitComposer();\n return;\n case \"toggleScreen\":\n this.#setState({\n currentScreen: this.#state.currentScreen === \"bee\" ? \"codex\" : \"bee\",\n notice: null\n });\n return;\n default:\n return;\n }\n }\n\n getState(): UiState {\n return {\n ...this.#state,\n dropdown: {\n ...this.#state.dropdown\n },\n notice: this.#state.notice\n ? {\n ...this.#state.notice\n }\n : null,\n runtime: cloneRuntimeSnapshot(this.#state.runtime),\n scenarios: this.#state.scenarios.map((scenario) => ({\n ...scenario\n }))\n };\n }\n\n async initialize(): Promise<void> {\n if (this.#didInitialize) {\n return;\n }\n\n this.#didInitialize = true;\n this.#hostUnsubscribe = this.#host.subscribe?.(() => {\n void this.#refreshState();\n }) ?? null;\n await this.#refreshState();\n }\n\n subscribe(listener: Listener): () => void {\n this.#listeners.add(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #applyHostUpdate(update: UiHostUpdate, options?: {\n clearComposer?: boolean;\n }): void {\n this.#state = {\n ...this.#state,\n composerText: options?.clearComposer ? \"\" : this.#state.composerText,\n composerCursorOffset: options?.clearComposer ? 0 : this.#state.composerCursorOffset,\n dropdown: {\n interacted: false,\n open: false,\n selectedIndex: 0\n },\n exitRequested: update.exitRequested ?? this.#state.exitRequested,\n isInitialized: true,\n notice: update.notice ? this.#createNotice(update.notice) : null,\n runtime: cloneRuntimeSnapshot(update.snapshot)\n };\n this.#notify();\n }\n\n #clearNotice(): void {\n if (!this.#state.notice) {\n return;\n }\n\n this.#setState({\n notice: null\n });\n }\n\n #createNotice(notice: Omit<UiNotice, \"id\">): UiNotice {\n this.#noticeCounter += 1;\n\n return {\n ...notice,\n id: this.#noticeCounter\n };\n }\n\n #getNextMode(currentMode: UiMode): UiMode {\n const currentIndex = UI_MODES.indexOf(currentMode);\n const nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % UI_MODES.length;\n\n return UI_MODES[nextIndex] ?? \"off\";\n }\n\n async #cycleMode(): Promise<void> {\n const nextMode = this.#getNextMode(this.#state.activeMode);\n\n if (this.#host.setMode) {\n const update = await this.#host.setMode(nextMode);\n\n this.#state = {\n ...this.#state,\n activeMode: nextMode\n };\n this.#applyHostUpdate(update);\n return;\n }\n\n this.#setState({\n activeMode: nextMode,\n notice: null\n });\n }\n\n #moveCommandSelection(direction: 1 | -1): void {\n if (!this.#state.dropdown.open) {\n return;\n }\n\n const visibleCommands = filterSlashCommands(getSlashQuery(this.#state.composerText) ?? \"\");\n\n if (visibleCommands.length === 0) {\n this.#setState({\n notice: null\n });\n return;\n }\n\n const nextIndex = Math.max(\n 0,\n Math.min(visibleCommands.length - 1, this.#state.dropdown.selectedIndex + direction)\n );\n\n this.#setState({\n dropdown: {\n interacted: true,\n open: true,\n selectedIndex: nextIndex\n },\n notice: null\n });\n }\n\n async #refreshState(options?: {\n notice?: Omit<UiNotice, \"id\"> | null;\n }): Promise<void> {\n const snapshot = await this.#host.getSnapshot();\n const scenarios = this.#host.listScenarios\n ? await this.#host.listScenarios()\n : this.#state.scenarios;\n\n this.#state = {\n ...this.#state,\n isInitialized: true,\n notice: options?.notice ? this.#createNotice(options.notice) : this.#state.notice,\n runtime: cloneRuntimeSnapshot(snapshot),\n scenarios: scenarios.map((scenario) => ({\n ...scenario\n }))\n };\n this.#notify();\n }\n\n async #selectScenario(scenarioId: string): Promise<void> {\n if (!this.#host.selectScenario) {\n this.#setState({\n notice: this.#createNotice({\n kind: \"error\",\n message: \"This runtime host does not support scenario switching.\"\n })\n });\n return;\n }\n\n const snapshot = await this.#host.selectScenario(scenarioId);\n const scenario = this.#state.scenarios.find((candidate) => candidate.id === scenarioId);\n\n this.#state = {\n ...this.#state,\n composerText: \"\",\n composerCursorOffset: 0,\n dropdown: {\n interacted: false,\n open: false,\n selectedIndex: 0\n },\n isInitialized: true,\n notice: this.#createNotice({\n kind: \"info\",\n message: scenario\n ? `Loaded scenario: ${scenario.label}.`\n : `Loaded scenario: ${scenarioId}.`\n }),\n runtime: cloneRuntimeSnapshot(snapshot)\n };\n this.#notify();\n }\n\n #setState(patch: Partial<UiState>): void {\n this.#state = {\n ...this.#state,\n ...patch\n };\n this.#notify();\n }\n\n async #submitComposer(): Promise<void> {\n if (this.#state.currentScreen !== \"bee\") {\n return;\n }\n\n if (this.#state.dropdown.open) {\n const visibleCommands = filterSlashCommands(getSlashQuery(this.#state.composerText) ?? \"\");\n const selectedCommand = visibleCommands[this.#state.dropdown.selectedIndex] ?? null;\n\n if (!selectedCommand) {\n this.#setState({\n notice: this.#createNotice({\n kind: \"error\",\n message: \"No slash commands match the current filter.\"\n })\n });\n return;\n }\n\n this.#updateComposer(`${selectedCommand.name} `, {\n cursorOffset: Array.from(`${selectedCommand.name} `).length\n });\n return;\n }\n\n if (!this.#state.composerText.trim()) {\n return;\n }\n\n if (this.#state.composerText.trimStart().startsWith(\"/\")) {\n const parsedCommand = parseSlashCommandInput(this.#state.composerText);\n\n if (\"error\" in parsedCommand) {\n this.#setState({\n notice: this.#createNotice({\n kind: \"error\",\n message: parsedCommand.error\n })\n });\n return;\n }\n\n const update = await this.#host.executeCommand(parsedCommand);\n this.#applyHostUpdate(update, {\n clearComposer: !update.exitRequested\n });\n return;\n }\n\n if (this.#state.activeMode === \"off\") {\n this.#setState({\n notice: this.#createNotice({\n kind: \"info\",\n message: \"Off mode is passive. Switch to Static to stage the next continuation prompt.\"\n })\n });\n return;\n }\n\n if (this.#state.activeMode !== \"static\") {\n this.#setState({\n notice: this.#createNotice({\n kind: \"warning\",\n message: `${this.#state.activeMode[0]?.toUpperCase() ?? \"\"}${this.#state.activeMode.slice(1)} mode is visual-only in the isolated harness right now.`\n })\n });\n return;\n }\n\n const stagedPrompt = stripTrailingSlashMarkers(this.#state.composerText);\n\n if (!stagedPrompt.trim()) {\n return;\n }\n\n this.#setState({\n notice: null,\n runtime: {\n ...cloneRuntimeSnapshot(this.#state.runtime),\n runState: \"running\"\n }\n });\n\n const update = await this.#host.submitPrompt({\n mode: \"static\",\n text: stagedPrompt\n });\n\n this.#applyHostUpdate(update, {\n clearComposer: true\n });\n }\n\n #replaceComposerRange(startOffset: number, endOffset: number, replacement: string): void {\n const { nextOffset, nextValue } = replaceRangeAtCodepointOffset(\n this.#state.composerText,\n startOffset,\n endOffset,\n replacement\n );\n\n this.#updateComposer(nextValue, {\n cursorOffset: nextOffset\n });\n }\n\n #updateComposer(nextComposerText: string, options?: {\n cursorOffset?: number;\n }): void {\n const query = getSlashQuery(nextComposerText);\n const matchingCommands = query === null ? [] : filterSlashCommands(query);\n const nextCursorOffset = clampCodepointOffset(\n nextComposerText,\n options?.cursorOffset ?? Array.from(nextComposerText).length\n );\n\n this.#state = {\n ...this.#state,\n composerCursorOffset: nextCursorOffset,\n composerText: nextComposerText,\n dropdown: {\n interacted: false,\n open: query !== null,\n selectedIndex: matchingCommands.length === 0\n ? 0\n : Math.min(this.#state.dropdown.selectedIndex, matchingCommands.length - 1)\n },\n notice: null\n };\n this.#notify();\n }\n\n #notify(): void {\n for (const listener of this.#listeners) {\n listener();\n }\n }\n}\n","import process from \"node:process\";\nimport { render } from \"ink\";\nimport React from \"react\";\nimport { PtyProxy } from \"../pty-proxy.js\";\nimport { UiController } from \"./core/controller.js\";\nimport { isCtrlBInput } from \"./input-shortcuts.js\";\nimport { InkControlApp } from \"./renderers/ink/app.js\";\n\nconst ALT_SCREEN_ENTER = \"\\u001b[?1049h\";\nconst ALT_SCREEN_EXIT = \"\\u001b[?1049l\";\nconst CLEAR_VISIBLE_SCREEN = \"\\u001b[2J\\u001b[H\";\nconst DISABLE_MOUSE_TRACKING = \"\\u001b[?1000l\\u001b[?1006l\";\nconst ENABLE_MOUSE_TRACKING = \"\\u001b[?1000h\\u001b[?1006h\";\nconst SHELL_TOGGLE_DEBOUNCE_MS = 200;\nconst SHOW_CURSOR = \"\\u001b[?25h\";\n\nexport interface LiveInkOverlayManagerOptions {\n controller: UiController;\n onQuitRequested: () => void;\n proxy: PtyProxy;\n renderApp?: typeof render;\n title?: string;\n}\n\nexport class LiveInkOverlayManager {\n readonly #controller: UiController;\n readonly #onQuitRequested: () => void;\n readonly #proxy: PtyProxy;\n readonly #renderApp: typeof render;\n readonly #title: string;\n #app: ReturnType<typeof render> | null = null;\n #controllerUnsubscribe: (() => void) | null = null;\n #ignoreShellToggleUntil = 0;\n #quitting = false;\n\n constructor(options: LiveInkOverlayManagerOptions) {\n this.#controller = options.controller;\n this.#onQuitRequested = options.onQuitRequested;\n this.#proxy = options.proxy;\n this.#renderApp = options.renderApp ?? render;\n this.#title = options.title ?? \"codex-bee\";\n }\n\n handleInput(chunk: Buffer | string): boolean {\n const input = typeof chunk === \"string\" ? chunk : chunk.toString(\"utf8\");\n\n if (this.#app) {\n if (isCtrlBInput(input) && Date.now() >= this.#ignoreShellToggleUntil) {\n this.close();\n }\n\n return true;\n }\n\n if (!isCtrlBInput(input)) {\n return false;\n }\n\n this.open();\n return true;\n }\n\n open(): void {\n if (this.#app) {\n return;\n }\n\n this.#proxy.setOutputMuted(true);\n process.stdout.write(`${ALT_SCREEN_ENTER}${ENABLE_MOUSE_TRACKING}${CLEAR_VISIBLE_SCREEN}`);\n this.#ignoreShellToggleUntil = Date.now() + SHELL_TOGGLE_DEBOUNCE_MS;\n void this.#controller.dispatch({\n type: \"refreshFromRuntime\"\n });\n\n this.#controllerUnsubscribe = this.#controller.subscribe(() => {\n const state = this.#controller.getState();\n\n if (!state.exitRequested || this.#quitting) {\n return;\n }\n\n this.#quitting = true;\n void this.#quitWrapper();\n });\n this.#app = this.#renderApp(\n React.createElement(InkControlApp, {\n allowQuit: false,\n controller: this.#controller,\n enableShellToggle: false,\n title: this.#title\n }),\n {\n exitOnCtrlC: false,\n kittyKeyboard: {\n flags: [\"disambiguateEscapeCodes\", \"reportEventTypes\"],\n mode: \"auto\"\n },\n patchConsole: false\n }\n );\n }\n\n close(): void {\n if (!this.#app) {\n return;\n }\n\n this.#controllerUnsubscribe?.();\n this.#controllerUnsubscribe = null;\n this.#app.unmount();\n this.#app = null;\n process.stdout.write(`${SHOW_CURSOR}${DISABLE_MOUSE_TRACKING}${ALT_SCREEN_EXIT}`);\n this.#proxy.setOutputMuted(false);\n\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(true);\n process.stdin.resume();\n }\n }\n\n dispose(): void {\n this.close();\n }\n\n async #quitWrapper(): Promise<void> {\n this.close();\n this.#onQuitRequested();\n }\n}\n","const CTRL_B_PATTERNS = [\n /^\\u0002$/,\n /^\\u001b\\[(?:66|98);5u$/,\n /^\\u001b\\[27;5;(?:66|98)~$/\n];\nconst FOCUS_EVENT_PATTERNS = [\n /^(?:\\u001b)?\\[I$/,\n /^(?:\\u001b)?\\[O$/\n];\nconst MOUSE_SCROLL_DOWN_PATTERN = /^(?:\\u001b)?\\[<65;\\d+;\\d+[Mm]$/;\nconst MOUSE_EVENT_PATTERN = /^(?:\\u001b)?\\[<\\d+;\\d+;\\d+[Mm]$/;\nconst MOUSE_SCROLL_UP_PATTERN = /^(?:\\u001b)?\\[<64;\\d+;\\d+[Mm]$/;\n\nconst SUBMIT_PATTERNS = [\n /^\\r$/,\n /^\\n$/,\n /^\\u001b\\[(?:10|13);(?:2|5|6)u$/,\n /^\\u001b\\[27;(?:2|5|6);(?:10|13)~$/\n];\n\nconst NEWLINE_PATTERNS = [\n /^\\u001b\\[(?:10|13);(?:3|4)u$/,\n /^\\u001b\\[27;(?:3|4);(?:10|13)~$/\n];\n\ninterface InputKeyState {\n ctrl?: boolean;\n return?: boolean;\n shift?: boolean;\n}\n\nexport function isCtrlBInput(input: string): boolean {\n return CTRL_B_PATTERNS.some((pattern) => pattern.test(input));\n}\n\nexport function getMouseScrollDelta(input: string): -1 | 1 | null {\n if (MOUSE_SCROLL_UP_PATTERN.test(input)) {\n return -1;\n }\n\n if (MOUSE_SCROLL_DOWN_PATTERN.test(input)) {\n return 1;\n }\n\n return null;\n}\n\nexport function isIgnorableTerminalInput(input: string): boolean {\n if (FOCUS_EVENT_PATTERNS.some((pattern) => pattern.test(input))) {\n return true;\n }\n\n return MOUSE_EVENT_PATTERN.test(input);\n}\n\nexport function isSubmitComposerInput(input: string, key?: InputKeyState): boolean {\n if (key?.return) {\n return true;\n }\n\n return SUBMIT_PATTERNS.some((pattern) => pattern.test(input));\n}\n\nexport function isInsertNewlineInput(input: string, key?: InputKeyState): boolean {\n return NEWLINE_PATTERNS.some((pattern) => pattern.test(input));\n}\n","import figlet from \"figlet\";\nimport { Box, useApp, useInput, useStdin, useStdout } from \"ink\";\nimport React, { useEffect, useState } from \"react\";\nimport { UiController } from \"../../core/controller.js\";\nimport type { UiMode, UiState } from \"../../core/types.js\";\nimport {\n getMouseScrollDelta,\n isIgnorableTerminalInput,\n isCtrlBInput,\n isInsertNewlineInput,\n isSubmitComposerInput\n} from \"../../input-shortcuts.js\";\nimport {\n getDisplayedRunState,\n formatClockTime,\n formatCompactDuration,\n formatPromptPreview,\n formatSessionInfo,\n formatWorkspaceLine,\n getActivePrompt,\n getModeLabel,\n getModeTone,\n getVisibleSlashCommands,\n getVisibleSlashPlaceholder,\n normalizeLogEntryText\n} from \"../../core/view-model.js\";\nimport {\n measureText,\n renderLine,\n truncateDisplayWidth,\n type InkLineSpec,\n type InkLineSegment,\n wrapAndLimit,\n wrapText\n} from \"./renderer-utils.js\";\n\nexport interface InkControlAppProps {\n allowQuit?: boolean;\n controller: UiController;\n enableShellToggle?: boolean;\n onShellToggle?: () => void;\n title?: string;\n}\n\ninterface InkPalette {\n accent?: string;\n announcementBackground?: string;\n announcementBorder?: string;\n announcementText?: string;\n bodyText?: string;\n error?: string;\n footerBase?: string;\n footerMutedBackground?: string;\n inputBackground?: string;\n logBackground?: string;\n logBorder?: string;\n muted?: string;\n primary?: string;\n promptBackground?: string;\n promptBorder?: string;\n secondary?: string;\n statusBottomBackground?: string;\n statusTopBackground?: string;\n success?: string;\n warning?: string;\n}\n\nconst MAX_CONTENT_WIDTH = 200;\nconst MIN_CONTENT_WIDTH = 80;\nconst LOADER_TICK_MS = 160;\nconst PROMPT_BAR = \"┃\";\nconst TIMESTAMP_WIDTH = 8;\n\nconst LOADER_GLYPHS = [\"■\", \"■\", \"■\", \"■\"];\nconst LOADER_COLOR_FRAMES = [\n [\"#4F3500\", \"#8A5B00\", \"#D89200\", \"#FFD35A\"],\n [\"#8A5B00\", \"#D89200\", \"#FFD35A\", \"#D89200\"],\n [\"#D89200\", \"#FFD35A\", \"#D89200\", \"#8A5B00\"],\n [\"#FFD35A\", \"#D89200\", \"#8A5B00\", \"#4F3500\"]\n];\n\ninterface ComposerVisualLine {\n endOffset: number;\n startOffset: number;\n text: string;\n}\n\nfunction createPalette(stylesEnabled: boolean): InkPalette {\n if (!stylesEnabled) {\n return {};\n }\n\n return {\n accent: \"#4C86FF\",\n announcementBackground: \"#15233A\",\n announcementBorder: \"#4C86FF\",\n announcementText: \"#D9E8FF\",\n bodyText: \"#F5F5F5\",\n error: \"#FF6B6B\",\n footerBase: \"#101317\",\n footerMutedBackground: \"#13171D\",\n inputBackground: \"#202833\",\n logBackground: \"#101113\",\n logBorder: \"#2D3138\",\n muted: \"#9098A4\",\n primary: \"#FFBF00\",\n promptBackground: \"#151A22\",\n promptBorder: \"#38404E\",\n secondary: \"#FF8C00\",\n statusBottomBackground: \"#222B1E\",\n statusTopBackground: \"#1B2633\",\n success: \"#4FD18B\",\n warning: \"#E7C85C\"\n };\n}\n\nfunction createLine(\n key: string,\n segments: InkLineSegment[],\n backgroundColor?: string\n): InkLineSpec {\n return {\n backgroundColor,\n key,\n segments\n };\n}\n\nfunction createTextLine(\n key: string,\n text: string,\n options?: Omit<InkLineSegment, \"text\">\n): InkLineSpec {\n return createLine(key, [\n {\n ...options,\n text\n }\n ], options?.backgroundColor);\n}\n\nfunction createSpacerLine(key: string, backgroundColor?: string): InkLineSpec {\n return createTextLine(key, \"\", {\n backgroundColor\n });\n}\n\nfunction padDisplayWidth(value: string, width: number): string {\n return `${value}${\" \".repeat(Math.max(width - measureText(value), 0))}`;\n}\n\nfunction buildGradientSegments(value: string, palette: InkPalette): InkLineSegment[] {\n if (!palette.primary || !palette.secondary) {\n return [\n {\n bold: true,\n text: value\n }\n ];\n }\n\n const gradientStops = [\"#FFD700\", \"#FFC300\", palette.primary, \"#FFAA00\", \"#FF9800\", palette.secondary];\n const characters = Array.from(value);\n\n return characters.map((character, index) => {\n if (character === \" \") {\n return {\n text: character\n };\n }\n\n const stopIndex = Math.min(\n gradientStops.length - 1,\n Math.floor((index / Math.max(characters.length - 1, 1)) * (gradientStops.length - 1))\n );\n\n return {\n bold: true,\n color: gradientStops[stopIndex],\n text: character\n };\n });\n}\n\nfunction getModeColor(mode: UiMode, palette: InkPalette): string | undefined {\n const tone = getModeTone(mode);\n\n if (tone === \"gray\") {\n return \"#D4D9E2\";\n }\n\n if (tone === \"cyan\") {\n return \"#55D6FF\";\n }\n\n if (tone === \"yellow\") {\n return palette.primary ?? \"yellow\";\n }\n\n return palette.secondary ?? \"#FF8C00\";\n}\n\nfunction getConnectionTokenSpec(\n connectionState: UiState[\"runtime\"][\"connectionState\"],\n palette: InkPalette\n): {\n color: string | undefined;\n compactLabel: string;\n label: string;\n} {\n if (connectionState === \"connected\") {\n return {\n color: palette.success,\n compactLabel: \"Conn\",\n label: \"Connected\"\n };\n }\n\n if (connectionState === \"ready\") {\n return {\n color: palette.warning ?? palette.primary,\n compactLabel: \"Ready\",\n label: \"Hooks ready\"\n };\n }\n\n return {\n color: palette.error,\n compactLabel: \"Disc\",\n label: \"Disconnected\"\n };\n}\n\nfunction buildFigletLines(title: string, maxWidth: number): string[] {\n const fonts = [\"ANSI Shadow\", \"Electronic\"];\n\n for (const font of fonts) {\n try {\n const nextLines = figlet.textSync(title, {\n font,\n horizontalLayout: \"default\"\n }).replace(/\\s+$/gm, \"\").split(\"\\n\");\n\n if (nextLines.every((line) => measureText(line) <= maxWidth)) {\n return nextLines;\n }\n } catch {\n continue;\n }\n }\n\n return [title];\n}\n\nfunction buildAnnouncementPanelLines(\n state: UiState,\n width: number,\n palette: InkPalette\n): InkLineSpec[] {\n if (!state.runtime.announcement || width < 8) {\n return [];\n }\n\n const innerWidth = Math.max(width - 4, 4);\n const contentLines = wrapText(state.runtime.announcement.message, innerWidth);\n const borderColor = palette.announcementBorder ?? palette.accent ?? palette.primary;\n\n return [\n createTextLine(\"announcement-top\", `╭${\"─\".repeat(Math.max(width - 2, 0))}╮`, {\n backgroundColor: palette.announcementBackground,\n color: borderColor\n }),\n ...contentLines.map((line, index) => createLine(`announcement-${index}`, [\n {\n backgroundColor: palette.announcementBackground,\n color: borderColor,\n text: \"│ \"\n },\n {\n backgroundColor: palette.announcementBackground,\n color: palette.announcementText ?? palette.bodyText,\n text: padDisplayWidth(line, innerWidth)\n },\n {\n backgroundColor: palette.announcementBackground,\n color: borderColor,\n text: \" │\"\n }\n ], palette.announcementBackground)),\n createTextLine(\"announcement-bottom\", `╰${\"─\".repeat(Math.max(width - 2, 0))}╯`, {\n backgroundColor: palette.announcementBackground,\n color: borderColor\n })\n ];\n}\n\nfunction buildHeaderColumnLines(\n state: UiState,\n title: string,\n width: number,\n palette: InkPalette\n): InkLineSpec[] {\n const titleLines = buildFigletLines(title.toUpperCase(), Math.max(width, 16));\n\n return [\n ...titleLines.map((line, index) => createLine(`header-${index}`, buildGradientSegments(line, palette))),\n createTextLine(\"versions\", `codex-bee v${state.runtime.beeVersion} • codex v${state.runtime.codexVersion}`, {\n color: palette.muted,\n dimColor: !palette.muted\n })\n ];\n}\n\nfunction buildHeaderLines(\n state: UiState,\n title: string,\n width: number,\n palette: InkPalette\n): InkLineSpec[] {\n return buildHeaderColumnLines(state, title, width, palette);\n}\n\nfunction getLogColor(\n kind: UiState[\"runtime\"][\"logs\"][number][\"entries\"][number][\"kind\"],\n palette: InkPalette\n): string | undefined {\n if (kind === \"user\") {\n return \"#55D6FF\";\n }\n\n if (kind === \"model\") {\n return palette.secondary;\n }\n\n if (kind === \"summary\") {\n return palette.accent;\n }\n\n if (kind === \"hook\") {\n return palette.success;\n }\n\n return palette.muted;\n}\n\nfunction buildDividerLabel(turn: number, totalTurns: number | null, durationMs: number | null, width: number): string {\n const parts = [totalTurns === null ? `turn ${turn}` : `turn ${turn}/${totalTurns}`];\n\n if (durationMs !== null) {\n parts.push(formatCompactDuration(durationMs));\n }\n\n const label = `──── ${parts.join(\" • \")} `;\n const fillWidth = Math.max(width - measureText(label), 0);\n\n return `${label}${\"─\".repeat(fillWidth)}`;\n}\n\nfunction buildComposerVisualLines(value: string, width: number): ComposerVisualLine[] {\n if (width <= 0) {\n return [\n {\n endOffset: 0,\n startOffset: 0,\n text: \"\"\n }\n ];\n }\n\n const codepoints = Array.from(value);\n const lines: ComposerVisualLine[] = [];\n let currentText = \"\";\n let currentStartOffset = 0;\n\n for (let index = 0; index < codepoints.length; index += 1) {\n const character = codepoints[index] ?? \"\";\n\n if (character === \"\\n\") {\n lines.push({\n endOffset: index,\n startOffset: currentStartOffset,\n text: currentText\n });\n currentStartOffset = index + 1;\n currentText = \"\";\n continue;\n }\n\n if (measureText(currentText + character) > width) {\n lines.push({\n endOffset: index,\n startOffset: currentStartOffset,\n text: currentText\n });\n currentStartOffset = index;\n currentText = character;\n continue;\n }\n\n currentText += character;\n }\n\n lines.push({\n endOffset: codepoints.length,\n startOffset: currentStartOffset,\n text: currentText\n });\n\n return lines.length > 0\n ? lines\n : [\n {\n endOffset: 0,\n startOffset: 0,\n text: \"\"\n }\n ];\n}\n\nfunction getComposerCursorLineIndex(lines: ComposerVisualLine[], cursorOffset: number): number {\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index];\n\n if (!line || cursorOffset < line.startOffset || cursorOffset > line.endOffset) {\n continue;\n }\n\n const previousLine = index > 0 ? lines[index - 1] : null;\n const isWrappedBoundary = cursorOffset === line.startOffset && previousLine && previousLine.endOffset === line.startOffset;\n\n if (isWrappedBoundary) {\n continue;\n }\n\n return index;\n }\n\n return Math.max(lines.length - 1, 0);\n}\n\nfunction getComposerCursorColumn(line: ComposerVisualLine, cursorOffset: number): number {\n const relativeOffset = Math.max(0, Math.min(cursorOffset - line.startOffset, Array.from(line.text).length));\n const prefix = Array.from(line.text).slice(0, relativeOffset).join(\"\");\n\n return measureText(prefix);\n}\n\nfunction getOffsetForComposerLineColumn(\n lines: ComposerVisualLine[],\n lineIndex: number,\n targetColumn: number\n): number {\n const line = lines[lineIndex];\n\n if (!line) {\n return 0;\n }\n\n const codepoints = Array.from(line.text);\n let bestOffset = line.startOffset;\n\n for (let index = 0; index <= codepoints.length; index += 1) {\n const prefix = codepoints.slice(0, index).join(\"\");\n const nextColumn = measureText(prefix);\n\n if (nextColumn > targetColumn) {\n break;\n }\n\n bestOffset = line.startOffset + index;\n }\n\n return bestOffset;\n}\n\nfunction buildLogLines(state: UiState, width: number, palette: InkPalette): InkLineSpec[] {\n const logLines: InkLineSpec[] = [\n createTextLine(\"log-top-border\", \"─\".repeat(width), {\n backgroundColor: palette.logBackground,\n color: palette.logBorder ?? palette.muted\n })\n ];\n const contentWidth = Math.max(width - TIMESTAMP_WIDTH - 2, 16);\n\n if (state.runtime.logs.length === 0) {\n return [\n ...logLines,\n createTextLine(\"log-empty\", \"No turns recorded yet. Submit a Static prompt or switch scenarios.\", {\n backgroundColor: palette.logBackground,\n color: palette.muted,\n dimColor: !palette.muted\n }),\n createTextLine(\"log-bottom-border\", \"─\".repeat(width), {\n backgroundColor: palette.logBackground,\n color: palette.logBorder ?? palette.muted\n })\n ];\n }\n\n state.runtime.logs.forEach((group, groupIndex) => {\n if (groupIndex > 0) {\n logLines.push(createSpacerLine(`divider-gap-${group.id}`, palette.logBackground));\n }\n\n logLines.push(createTextLine(`divider-${group.id}`, buildDividerLabel(\n group.turn,\n group.totalTurns,\n group.durationMs,\n width\n ), {\n backgroundColor: palette.logBackground,\n color: palette.muted,\n dimColor: !palette.muted\n }));\n\n group.entries.forEach((entry) => {\n const previewLines = wrapAndLimit(normalizeLogEntryText(entry), contentWidth, 3);\n\n previewLines.forEach((line, lineIndex) => {\n logLines.push(createLine(`${entry.id}-${lineIndex}`, [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: lineIndex === 0\n ? truncateDisplayWidth(formatClockTime(entry.timestamp), TIMESTAMP_WIDTH)\n : \" \".repeat(TIMESTAMP_WIDTH)\n },\n {\n text: \" \"\n },\n {\n color: entry.kind === \"hook\" && entry.text.includes(\"✗\")\n ? palette.error\n : getLogColor(entry.kind, palette),\n text: line\n }\n ], palette.logBackground));\n });\n });\n });\n\n logLines.push(createTextLine(\"log-bottom-border\", \"─\".repeat(width), {\n backgroundColor: palette.logBackground,\n color: palette.logBorder ?? palette.muted\n }));\n\n return logLines;\n}\n\nfunction buildBodyLines(\n state: UiState,\n title: string,\n width: number,\n palette: InkPalette\n): InkLineSpec[] {\n return [\n ...buildHeaderLines(state, title, width, palette),\n createSpacerLine(\"header-gap\"),\n ...buildLogLines(state, width, palette)\n ];\n}\n\nfunction buildLoaderSegments(\n palette: InkPalette,\n animationTick: number,\n isActive: boolean\n): InkLineSegment[] {\n const frame = LOADER_COLOR_FRAMES[animationTick % LOADER_COLOR_FRAMES.length] ?? LOADER_COLOR_FRAMES[0];\n\n return LOADER_GLYPHS.map((glyph, index) => ({\n color: isActive\n ? frame[index] ?? palette.primary\n : [\"#A87400\", \"#BB8500\", \"#CF9600\", \"#E0A700\"][index] ?? palette.primary,\n dimColor: !isActive,\n text: glyph\n }));\n}\n\nfunction measureSegmentsWidth(segments: InkLineSegment[]): number {\n return segments.reduce((total, segment) => total + measureText(segment.text), 0);\n}\n\nfunction buildStatusTokens(\n state: UiState,\n palette: InkPalette,\n animationTick: number,\n now: number,\n width: number\n): InkLineSegment[][] {\n const displayedRunState = getDisplayedRunState(state.runtime, now);\n const loaderToken = buildLoaderSegments(palette, animationTick, displayedRunState === \"running\");\n const connectionSpec = getConnectionTokenSpec(state.runtime.connectionState, palette);\n const connectionToken: InkLineSegment[] = [\n {\n color: connectionSpec.color,\n text: connectionSpec.label\n }\n ];\n const compactConnectionToken: InkLineSegment[] = [\n {\n color: connectionSpec.color,\n text: connectionSpec.compactLabel\n }\n ];\n const runStateToken: InkLineSegment[] = [\n {\n color: displayedRunState === \"running\"\n ? palette.primary\n : displayedRunState === \"quiet\"\n ? palette.warning\n : palette.muted,\n text: displayedRunState === \"running\"\n ? \"Running\"\n : displayedRunState === \"quiet\"\n ? \"Quiet\"\n : \"Idle\"\n }\n ];\n const hotkeyToken: InkLineSegment[] = [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: \"Ctrl+B codex\"\n }\n ];\n const shortHotkeyToken: InkLineSegment[] = [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: \"Ctrl+B\"\n }\n ];\n const commandsToken: InkLineSegment[] = [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: \"/ commands\"\n }\n ];\n const shortCommandsToken: InkLineSegment[] = [\n {\n color: palette.muted,\n dimColor: !palette.muted,\n text: \"/\"\n }\n ];\n const variants: InkLineSegment[][][] = [\n [loaderToken, connectionToken, runStateToken, hotkeyToken, commandsToken],\n [loaderToken, compactConnectionToken, runStateToken, hotkeyToken, commandsToken],\n [loaderToken, compactConnectionToken, runStateToken, shortHotkeyToken, shortCommandsToken]\n ];\n\n for (const variant of variants) {\n const totalWidth = variant.reduce((total, token, index) => {\n const separatorWidth = index === 0 ? 0 : measureText(\" • \");\n\n return total + separatorWidth + measureSegmentsWidth(token);\n }, 0);\n\n if (totalWidth <= width) {\n return variant;\n }\n }\n\n return variants[variants.length - 1] ?? [];\n}\n\nfunction buildStatusBarLine(\n state: UiState,\n palette: InkPalette,\n animationTick: number,\n now: number,\n width: number\n): InkLineSpec {\n const backgroundColor = palette.statusBottomBackground;\n const tokens = buildStatusTokens(state, palette, animationTick, now, width);\n const segments = tokens.flatMap((token, index) => index === 0\n ? token\n : [\n {\n text: \" • \"\n },\n ...token\n ]);\n\n return createLine(\"status-bar\", segments, backgroundColor);\n}\n\nfunction buildModeHintLine(\n state: UiState,\n width: number,\n palette: InkPalette\n): InkLineSpec {\n const prefix = width >= 34 ? \" Shift+Tab mode • \" : \" Tab • \";\n const modeLabel = getModeLabel(state.activeMode);\n const segments: InkLineSegment[] = [\n {\n backgroundColor: palette.promptBackground,\n color: palette.muted,\n dimColor: !palette.muted,\n text: prefix\n },\n {\n backgroundColor: palette.promptBackground,\n color: getModeColor(state.activeMode, palette),\n text: modeLabel\n }\n ];\n const usedWidth = measureSegmentsWidth(segments);\n\n if (usedWidth < width) {\n segments.push({\n backgroundColor: palette.promptBackground,\n text: \" \".repeat(width - usedWidth)\n });\n }\n\n return createLine(\"mode-hint\", segments, palette.promptBackground);\n}\n\nfunction buildDropdownLines(state: UiState, width: number, palette: InkPalette): InkLineSpec[] {\n const commands = getVisibleSlashCommands(state);\n const nameWidth = 16;\n const placeholderWidth = 12;\n const descriptionWidth = Math.max(width - nameWidth - placeholderWidth - 2, 12);\n\n if (commands.length === 0) {\n return [\n createTextLine(\"dropdown-empty\", \"No commands match the current filter.\", {\n backgroundColor: palette.promptBackground,\n color: palette.muted,\n dimColor: !palette.muted\n })\n ];\n }\n\n return commands.map((command, index) => {\n const isSelected = index === state.dropdown.selectedIndex;\n const backgroundColor = isSelected ? palette.inputBackground : palette.promptBackground;\n const description = truncateDisplayWidth(command.description, descriptionWidth);\n const placeholder = command.placeholder\n ? truncateDisplayWidth(command.placeholder, placeholderWidth)\n : \"\";\n\n return createLine(`dropdown-${command.id}`, [\n {\n backgroundColor,\n text: \" \"\n },\n {\n backgroundColor,\n bold: true,\n color: isSelected ? palette.primary : palette.bodyText,\n text: padDisplayWidth(command.name, nameWidth)\n },\n {\n backgroundColor,\n color: palette.muted,\n dimColor: !palette.muted,\n text: padDisplayWidth(description, descriptionWidth)\n },\n {\n backgroundColor,\n color: palette.muted,\n dimColor: !palette.muted,\n italic: true,\n text: padDisplayWidth(placeholder, placeholderWidth)\n }\n ], backgroundColor);\n });\n}\n\nfunction buildPromptPreviewLines(state: UiState, width: number): Array<{\n colorKind: \"body\" | \"muted\";\n text: string;\n}> {\n if (state.activeMode === \"off\") {\n const lengths = [\n Math.max(Math.floor(width * 0.68), 18),\n Math.max(Math.floor(width * 0.52), 14),\n Math.max(Math.floor(width * 0.6), 16)\n ];\n\n return lengths.map((length, index) => ({\n colorKind: \"muted\",\n text: \"░\".repeat(Math.max(Math.min(length - index, width), 8))\n }));\n }\n\n return formatPromptPreview(getActivePrompt(state), 5)\n .flatMap((line) => wrapAndLimit(line, width, 5))\n .slice(0, 5)\n .map((line) => ({\n colorKind: \"body\",\n text: line\n }));\n}\n\nfunction buildPromptFooterLines(\n state: UiState,\n width: number,\n palette: InkPalette,\n cursorVisible: boolean,\n animationTick: number,\n now: number\n): InkLineSpec[] {\n const lines: InkLineSpec[] = [];\n const modeColor = getModeColor(state.activeMode, palette);\n const promptPreviewWidth = Math.max(width - 2, 16);\n const promptLines = buildPromptPreviewLines(state, promptPreviewWidth);\n const inputFieldWidth = Math.max(width - 2, 12);\n const inputContentWidth = Math.max(inputFieldWidth - 1, 8);\n const composerLines = buildComposerVisualLines(state.composerText, inputContentWidth);\n const cursorLineIndex = getComposerCursorLineIndex(composerLines, state.composerCursorOffset);\n const placeholder = getVisibleSlashPlaceholder(state);\n const sessionInfoText = formatSessionInfo(state.runtime, state.activeMode, now);\n\n if (sessionInfoText) {\n lines.push(createTextLine(\"session-info\", sessionInfoText, {\n backgroundColor: palette.statusTopBackground,\n color: state.activeMode === \"off\" ? palette.muted : palette.bodyText,\n dimColor: state.activeMode === \"off\" && !palette.muted\n }));\n lines.push(createSpacerLine(\"session-gap\", palette.footerBase));\n }\n\n lines.push(createTextLine(\"prompt-top-border\", \"─\".repeat(width), {\n backgroundColor: palette.promptBackground,\n color: palette.promptBorder ?? palette.muted\n }));\n lines.push(createSpacerLine(\"prompt-padding-top\", palette.promptBackground));\n\n promptLines.forEach((line, index) => {\n lines.push(createLine(`prompt-${index}`, [\n {\n backgroundColor: palette.promptBackground,\n color: modeColor,\n text: PROMPT_BAR\n },\n {\n backgroundColor: palette.promptBackground,\n text: \" \"\n },\n {\n backgroundColor: palette.promptBackground,\n color: line.colorKind === \"muted\" ? palette.muted : palette.bodyText,\n dimColor: line.colorKind === \"muted\",\n text: padDisplayWidth(line.text, width - 2)\n }\n ], palette.promptBackground));\n });\n\n composerLines.forEach((line, index) => {\n const isCursorLine = index === cursorLineIndex;\n const isLastLine = index === composerLines.length - 1;\n const relativeCursorOffset = Math.max(\n 0,\n Math.min(state.composerCursorOffset - line.startOffset, Array.from(line.text).length)\n );\n const beforeCursor = Array.from(line.text).slice(0, relativeCursorOffset).join(\"\");\n const afterCursor = Array.from(line.text).slice(relativeCursorOffset).join(\"\");\n const fieldSegments: InkLineSegment[] = [\n {\n backgroundColor: palette.inputBackground,\n color: palette.bodyText,\n text: beforeCursor\n }\n ];\n\n if (isCursorLine) {\n fieldSegments.push({\n backgroundColor: palette.inputBackground,\n color: modeColor,\n text: cursorVisible ? \"_\" : \" \"\n });\n }\n\n if (afterCursor) {\n fieldSegments.push({\n backgroundColor: palette.inputBackground,\n color: palette.bodyText,\n text: afterCursor\n });\n }\n\n const usedWidthBeforePlaceholder = fieldSegments.reduce(\n (total, segment) => total + measureText(segment.text),\n 0\n );\n\n if (isLastLine && placeholder && !state.composerText.trimEnd().includes(\" \") && usedWidthBeforePlaceholder < inputFieldWidth) {\n fieldSegments.push({\n backgroundColor: palette.inputBackground,\n color: palette.muted,\n italic: true,\n text: truncateDisplayWidth(placeholder, Math.max(inputFieldWidth - usedWidthBeforePlaceholder, 0))\n });\n }\n\n const usedWidth = fieldSegments.reduce((total, segment) => total + measureText(segment.text), 0);\n\n if (usedWidth < inputFieldWidth) {\n fieldSegments.push({\n backgroundColor: palette.inputBackground,\n text: \" \".repeat(inputFieldWidth - usedWidth)\n });\n }\n\n lines.push(createLine(`input-${index}`, [\n {\n backgroundColor: palette.promptBackground,\n color: modeColor,\n text: index === 0 ? \"❯ \" : \" \"\n },\n ...fieldSegments\n ], palette.promptBackground));\n });\n\n lines.push(buildModeHintLine(state, width, palette));\n\n if (state.dropdown.open) {\n lines.push(...buildDropdownLines(state, width, palette));\n }\n\n lines.push(createSpacerLine(\"prompt-padding-bottom\", palette.promptBackground));\n lines.push(createTextLine(\"prompt-bottom-border\", \"─\".repeat(width), {\n backgroundColor: palette.promptBackground,\n color: palette.promptBorder ?? palette.muted\n }));\n lines.push(createSpacerLine(\"footer-gap\", palette.footerBase));\n lines.push(buildStatusBarLine(state, palette, animationTick, now, width));\n lines.push(createSpacerLine(\"workspace-gap\", palette.footerBase));\n lines.push(createTextLine(\"workspace\", formatWorkspaceLine(state.runtime.workspace), {\n backgroundColor: palette.footerMutedBackground,\n color: palette.muted,\n dimColor: !palette.muted\n }));\n\n return lines;\n}\n\nfunction buildBeeScreenLines(\n state: UiState,\n title: string,\n columns: number,\n cursorVisible: boolean,\n palette: InkPalette,\n animationTick: number,\n now: number\n): InkLineSpec[] {\n const bodyLines = buildBodyLines(state, title, columns, palette);\n const footerLines = buildPromptFooterLines(state, columns, palette, cursorVisible, animationTick, now);\n\n return [...bodyLines, createSpacerLine(\"body-footer-gap\"), ...footerLines];\n}\n\nfunction buildCodexScreenLines(\n state: UiState,\n columns: number,\n palette: InkPalette\n): InkLineSpec[] {\n const bodyLines = state.runtime.codexBufferLines.map((line, index) => createTextLine(`codex-${index}`, line, {\n color: palette.bodyText\n }));\n const footerLines: InkLineSpec[] = [\n createTextLine(\"codex-divider\", \"─\".repeat(columns), {\n color: palette.muted,\n dimColor: !palette.muted\n }),\n createTextLine(\"codex-hint\", \"Mocked Codex buffer • Ctrl+B reopen codex-bee • Ctrl+C shows the exit hint\", {\n backgroundColor: palette.statusBottomBackground,\n color: palette.bodyText\n }),\n createSpacerLine(\"codex-footer-gap\", palette.footerBase),\n createTextLine(\"codex-workspace\", formatWorkspaceLine(state.runtime.workspace), {\n backgroundColor: palette.footerMutedBackground,\n color: palette.muted,\n dimColor: !palette.muted\n })\n ];\n return [...bodyLines, createSpacerLine(\"codex-gap\"), ...footerLines];\n}\n\nfunction buildNarrowScreenLines(columns: number, palette: InkPalette): InkLineSpec[] {\n return [\n createTextLine(\"narrow-title\", \"Terminal too narrow. Minimum 80 columns required.\", {\n bold: true,\n color: palette.warning\n }),\n createTextLine(\"narrow-help\", \"Resize the terminal and codex-bee will redraw the isolated TUI automatically.\", {\n color: palette.muted,\n dimColor: !palette.muted\n }),\n createTextLine(\"narrow-width\", `Current width: ${columns} columns`, {\n color: palette.bodyText\n })\n ];\n}\n\nexport function InkControlApp({\n allowQuit = true,\n controller,\n enableShellToggle = true,\n onShellToggle,\n title = \"codex-bee\"\n}: InkControlAppProps): React.JSX.Element {\n const { exit } = useApp();\n const { isRawModeSupported } = useStdin();\n const { stdout } = useStdout();\n const [state, setState] = useState(() => controller.getState());\n const [isPinnedToBottom, setIsPinnedToBottom] = useState(true);\n const [scrollOffset, setScrollOffset] = useState(0);\n const [clockNow, setClockNow] = useState(() => Date.now());\n const animationTick = Math.floor(clockNow / LOADER_TICK_MS);\n const cursorVisible = true;\n const [viewport] = useState(() => ({\n columns: stdout.columns ?? 100,\n rows: stdout.rows ?? 40\n }));\n\n useEffect(() => {\n const unsubscribe = controller.subscribe(() => {\n setState(controller.getState());\n });\n\n void controller.initialize();\n\n return unsubscribe;\n }, [controller]);\n\n useEffect(() => {\n if (!state.exitRequested) {\n return;\n }\n\n if (allowQuit) {\n exit();\n return;\n }\n\n void controller.dispatch({\n type: \"clearExitRequest\"\n });\n }, [allowQuit, controller, exit, state.exitRequested]);\n\n useEffect(() => {\n setClockNow(Date.now());\n const intervalId = setInterval(() => {\n setClockNow(Date.now());\n }, LOADER_TICK_MS);\n\n return () => {\n clearInterval(intervalId);\n };\n }, []);\n\n const palette = createPalette(stdout.isTTY !== false && !process.env.NO_COLOR && process.env.TERM !== \"dumb\");\n const contentWidth = Math.min(Math.max(viewport.columns, MIN_CONTENT_WIDTH), MAX_CONTENT_WIDTH);\n const renderWidth = viewport.columns < MIN_CONTENT_WIDTH ? viewport.columns : contentWidth;\n const contentLines = viewport.columns < MIN_CONTENT_WIDTH\n ? buildNarrowScreenLines(viewport.columns, palette)\n : (\n state.currentScreen === \"bee\"\n ? buildBeeScreenLines(\n state,\n title,\n contentWidth,\n cursorVisible,\n palette,\n animationTick,\n clockNow\n )\n : buildCodexScreenLines(\n state,\n contentWidth,\n palette\n )\n );\n const maxScrollOffset = Math.max(contentLines.length - viewport.rows, 0);\n\n useEffect(() => {\n setScrollOffset((current) => isPinnedToBottom ? maxScrollOffset : Math.min(current, maxScrollOffset));\n }, [isPinnedToBottom, maxScrollOffset]);\n\n const scrollBy = (deltaLines: number) => {\n if (maxScrollOffset === 0) {\n setScrollOffset(0);\n setIsPinnedToBottom(true);\n return;\n }\n\n setScrollOffset((current) => {\n const next = Math.max(0, Math.min(maxScrollOffset, current + deltaLines));\n\n setIsPinnedToBottom(next >= maxScrollOffset);\n return next;\n });\n };\n const shouldInsertSlashNewlineHack = (input: string, key: {\n ctrl?: boolean;\n return?: boolean;\n shift?: boolean;\n }): boolean => {\n const beforeCursor = Array.from(state.composerText).slice(0, state.composerCursorOffset).join(\"\");\n const currentLineBeforeCursor = beforeCursor.split(\"\\n\").at(-1) ?? \"\";\n\n if (!currentLineBeforeCursor.trimEnd().endsWith(\"/\")) {\n return false;\n }\n\n if (key.return) {\n return !key.shift && !key.ctrl;\n }\n\n return input === \"\\r\" || input === \"\\n\";\n };\n\n useInput((input, key) => {\n if ((key.ctrl && input === \"b\") || isCtrlBInput(input)) {\n if (!enableShellToggle) {\n return;\n }\n\n if (onShellToggle) {\n onShellToggle();\n } else {\n void controller.dispatch({\n type: \"toggleScreen\"\n });\n }\n return;\n }\n\n if (key.ctrl && input === \"c\") {\n void controller.dispatch({\n type: \"showExitHint\"\n });\n return;\n }\n\n const mouseScrollDelta = getMouseScrollDelta(input);\n\n if (mouseScrollDelta !== null) {\n scrollBy(mouseScrollDelta * 3);\n return;\n }\n\n if (isIgnorableTerminalInput(input)) {\n return;\n }\n\n if (state.currentScreen === \"codex\") {\n return;\n }\n\n if (key.pageUp || input === \"\\u001b[5~\") {\n scrollBy(-(viewport.rows - 4));\n return;\n }\n\n if (key.pageDown || input === \"\\u001b[6~\") {\n scrollBy(viewport.rows - 4);\n return;\n }\n\n if (key.home || input === \"\\u001b[H\" || input === \"\\u001b[1~\") {\n setIsPinnedToBottom(false);\n setScrollOffset(0);\n return;\n }\n\n if (key.end || input === \"\\u001b[F\" || input === \"\\u001b[4~\") {\n setIsPinnedToBottom(true);\n setScrollOffset(maxScrollOffset);\n return;\n }\n\n if ((key.tab && key.shift) || input === \"\\u001b[Z\") {\n void controller.dispatch({\n type: \"cycleMode\"\n });\n return;\n }\n\n if (key.escape) {\n void controller.dispatch({\n type: state.dropdown.open ? \"closeDropdown\" : \"dismissNotice\"\n });\n return;\n }\n\n const inputFieldWidth = Math.max(contentWidth - 2, 12);\n const inputContentWidth = Math.max(inputFieldWidth - 1, 8);\n const composerLines = buildComposerVisualLines(state.composerText, inputContentWidth);\n const cursorLineIndex = getComposerCursorLineIndex(composerLines, state.composerCursorOffset);\n const cursorColumn = getComposerCursorColumn(composerLines[cursorLineIndex] ?? composerLines[0] ?? {\n endOffset: 0,\n startOffset: 0,\n text: \"\"\n }, state.composerCursorOffset);\n const shouldUseDropdownNavigation = state.dropdown.open\n && !state.composerText.includes(\"\\n\")\n && state.composerCursorOffset === Array.from(state.composerText).length;\n\n if (shouldUseDropdownNavigation && key.upArrow) {\n void controller.dispatch({\n type: \"selectPreviousCommand\"\n });\n return;\n }\n\n if (shouldUseDropdownNavigation && key.downArrow) {\n void controller.dispatch({\n type: \"selectNextCommand\"\n });\n return;\n }\n\n if (key.leftArrow) {\n void controller.dispatch({\n offset: state.composerCursorOffset - 1,\n type: \"setComposerCursorOffset\"\n });\n return;\n }\n\n if (key.rightArrow) {\n void controller.dispatch({\n offset: state.composerCursorOffset + 1,\n type: \"setComposerCursorOffset\"\n });\n return;\n }\n\n if (key.upArrow) {\n const targetLineIndex = Math.max(cursorLineIndex - 1, 0);\n\n void controller.dispatch({\n offset: getOffsetForComposerLineColumn(composerLines, targetLineIndex, cursorColumn),\n type: \"setComposerCursorOffset\"\n });\n return;\n }\n\n if (key.downArrow) {\n const targetLineIndex = Math.min(cursorLineIndex + 1, composerLines.length - 1);\n\n void controller.dispatch({\n offset: getOffsetForComposerLineColumn(composerLines, targetLineIndex, cursorColumn),\n type: \"setComposerCursorOffset\"\n });\n return;\n }\n\n if (state.dropdown.open && (key.tab || input === \"\\t\" || (state.dropdown.interacted && (key.return || input === \"\\r\" || input === \"\\n\")))) {\n void controller.dispatch({\n type: \"submitComposer\"\n });\n return;\n }\n\n if (shouldInsertSlashNewlineHack(input, key)) {\n void controller.dispatch({\n type: \"insertNewline\"\n });\n return;\n }\n\n if (key.backspace || key.delete) {\n void controller.dispatch({\n type: \"backspace\"\n });\n return;\n }\n\n if (isSubmitComposerInput(input, key)) {\n void controller.dispatch({\n type: \"submitComposer\"\n });\n return;\n }\n\n if (isInsertNewlineInput(input, key)) {\n void controller.dispatch({\n type: \"insertNewline\"\n });\n return;\n }\n\n if (!input) {\n return;\n }\n\n void controller.dispatch({\n text: input,\n type: \"appendInput\"\n });\n }, {\n isActive: isRawModeSupported\n });\n const visibleLines = maxScrollOffset > 0\n ? contentLines.slice(scrollOffset, scrollOffset + viewport.rows)\n : contentLines;\n\n return (\n <Box justifyContent={viewport.columns > MAX_CONTENT_WIDTH ? \"center\" : \"flex-start\"} width=\"100%\">\n <Box flexDirection=\"column\" width={renderWidth}>\n {visibleLines.map((line) => renderLine(line, renderWidth))}\n </Box>\n </Box>\n );\n}\n","import { filterSlashCommands, getSlashQuery } from \"./commands.js\";\nimport type { UiLogEntry, UiMode, UiRuntimeSnapshot, UiState, UiWorkspaceInfo } from \"./types.js\";\n\nexport const CODEX_ACTIVITY_WINDOW_MS = 1_800;\nexport const LOG_ENTRY_LINE_LIMIT = 3;\nexport const PROMPT_PREVIEW_LINE_LIMIT = 5;\n\nconst CODE_BLOCK_PATTERN = /```[\\s\\S]*?```/g;\n\nfunction toSingleLine(value: string): string {\n return value.replace(/\\s+/g, \" \").trim();\n}\n\nexport function formatClockTime(timestamp: number): string {\n return new Date(timestamp).toLocaleTimeString(\"en-GB\", {\n hour12: false\n });\n}\n\nexport function formatCompactDuration(durationMs: number | null): string {\n if (durationMs === null || durationMs <= 0) {\n return \"0s\";\n }\n\n const totalSeconds = Math.max(1, Math.round(durationMs / 1000));\n const minutes = Math.floor(totalSeconds / 60);\n const seconds = totalSeconds % 60;\n\n if (minutes === 0) {\n return `${seconds}s`;\n }\n\n if (minutes < 60) {\n return `${minutes}m ${String(seconds).padStart(2, \"0\")}s`;\n }\n\n const hours = Math.floor(minutes / 60);\n const remainingMinutes = minutes % 60;\n\n return `${hours}h ${String(remainingMinutes).padStart(2, \"0\")}m`;\n}\n\nexport function formatTimeLeft(stopAt: number | null, now = Date.now()): string | null {\n if (stopAt === null) {\n return null;\n }\n\n const remainingMs = Math.max(stopAt - now, 0);\n const totalSeconds = Math.ceil(remainingMs / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n\n return `time left: ${hours}:${String(minutes).padStart(2, \"0\")}:${String(seconds).padStart(2, \"0\")}`;\n}\n\nexport function formatHookStatus(snapshot: UiRuntimeSnapshot): string | null {\n if (!snapshot.session.hookStatus) {\n return snapshot.connectionState === \"ready\"\n ? \"hook: ready\"\n : null;\n }\n\n return `hook: ${snapshot.session.hookStatus.ok ? \"✓\" : \"✗\"} ${snapshot.session.hookStatus.code}`;\n}\n\nexport function hasRecentCodexActivity(snapshot: UiRuntimeSnapshot, now = Date.now()): boolean {\n if (snapshot.connectionState === \"disconnected\") {\n return false;\n }\n\n if (snapshot.session.lastCodexOutputAt === null) {\n return false;\n }\n\n return now - snapshot.session.lastCodexOutputAt <= CODEX_ACTIVITY_WINDOW_MS;\n}\n\nexport function getDisplayedRunState(snapshot: UiRuntimeSnapshot, now = Date.now()): \"idle\" | \"quiet\" | \"running\" {\n if (hasRecentCodexActivity(snapshot, now)) {\n return \"running\";\n }\n\n if (snapshot.runState === \"running\") {\n return \"quiet\";\n }\n\n return \"idle\";\n}\n\nexport function formatSessionInfo(snapshot: UiRuntimeSnapshot, mode: UiMode, now = Date.now()): string {\n if (mode === \"off\") {\n return \"Bee is in Off mode. Codex-bee stays passive and only records session stats and turn history.\";\n }\n\n const parts: string[] = [];\n\n if (snapshot.session.currentTurn !== null && snapshot.session.totalTurns !== null) {\n parts.push(`${snapshot.session.currentTurn}/${snapshot.session.totalTurns} turns`);\n }\n\n const timeLeftLabel = formatTimeLeft(snapshot.session.stopAt, now);\n\n if (timeLeftLabel) {\n parts.push(timeLeftLabel);\n }\n\n const hookStatusLabel = snapshot.session.stopScript\n ? formatHookStatus(snapshot)\n : null;\n\n if (hookStatusLabel) {\n parts.push(hookStatusLabel);\n }\n\n return parts.join(\" • \");\n}\n\nexport function formatWorkspaceLine(workspace: UiWorkspaceInfo): string {\n const parts = [workspace.cwd, workspace.gitBranch];\n const gitParts: string[] = [];\n\n if (workspace.ahead > 0) {\n gitParts.push(`↑${workspace.ahead} ahead`);\n }\n\n if (workspace.behind > 0) {\n gitParts.push(`↓${workspace.behind} behind`);\n }\n\n if (gitParts.length > 0) {\n parts.push(gitParts.join(\" \"));\n }\n\n return parts.join(\" • \");\n}\n\nexport function getActivePrompt(state: UiState): string {\n return state.runtime.prompts[state.activeMode];\n}\n\nexport function getModeLabel(mode: UiMode): string {\n if (mode === \"off\") {\n return \"Off\";\n }\n\n if (mode === \"static\") {\n return \"Static\";\n }\n\n if (mode === \"thinking\") {\n return \"Thinking\";\n }\n\n return \"Agent\";\n}\n\nexport function getModeTone(mode: UiMode): \"cyan\" | \"gray\" | \"orange\" | \"yellow\" {\n if (mode === \"off\") {\n return \"gray\";\n }\n\n if (mode === \"static\") {\n return \"cyan\";\n }\n\n if (mode === \"thinking\") {\n return \"yellow\";\n }\n\n return \"orange\";\n}\n\nexport function getModeUnavailableMessage(mode: UiMode): string | null {\n if (mode === \"off\") {\n return \"Off mode is passive. Codex-bee only records stats and turn logs.\";\n }\n\n if (mode === \"static\") {\n return null;\n }\n\n return `${getModeLabel(mode)} mode is visual-only in the isolated harness right now.`;\n}\n\nexport function getVisibleSlashCommands(state: UiState) {\n const query = getSlashQuery(state.composerText);\n\n if (query === null) {\n return [];\n }\n\n return filterSlashCommands(query);\n}\n\nexport function getVisibleSlashPlaceholder(state: UiState): string | null {\n const trimmedComposer = state.composerText.trimEnd();\n\n for (const command of filterSlashCommands(\"\")) {\n if (trimmedComposer !== command.name) {\n continue;\n }\n\n return command.placeholder;\n }\n\n if (!state.composerText.endsWith(\" \")) {\n return null;\n }\n\n const command = filterSlashCommands(\"\").find((candidate) => state.composerText === `${candidate.name} `);\n\n return command?.placeholder ?? null;\n}\n\nexport function normalizeLogEntryText(entry: UiLogEntry): string {\n if (entry.kind !== \"model\") {\n return entry.text;\n }\n\n return entry.text.replace(CODE_BLOCK_PATTERN, \"[~code block~]\");\n}\n\nexport function splitPreservingEmptyLines(value: string): string[] {\n if (!value) {\n return [\"\"];\n }\n\n return value.split(\"\\n\");\n}\n\nexport function truncateLines(value: string, maxLines: number): string[] {\n const lines = splitPreservingEmptyLines(value);\n\n if (lines.length <= maxLines) {\n return lines;\n }\n\n const visibleLines = lines.slice(0, maxLines);\n const lastLine = visibleLines[maxLines - 1] ?? \"\";\n\n visibleLines[maxLines - 1] = `${lastLine}${lastLine ? \" \" : \"\"}...`;\n\n return visibleLines;\n}\n\nexport function formatPromptPreview(prompt: string, maxLines = PROMPT_PREVIEW_LINE_LIMIT): string[] {\n return truncateLines(prompt, maxLines);\n}\n\nexport function formatLogPreview(entry: UiLogEntry, maxLines = LOG_ENTRY_LINE_LIMIT): string[] {\n return truncateLines(normalizeLogEntryText(entry), maxLines);\n}\n\nexport function formatCodexEcho(prompt: string): string {\n const inlinePrompt = toSingleLine(prompt);\n\n if (!inlinePrompt) {\n return \"Waiting for the next prompt...\";\n }\n\n return inlinePrompt.length <= 72\n ? inlinePrompt\n : `${inlinePrompt.slice(0, 69).trimEnd()}...`;\n}\n\nexport function getPromptSourceLabel(state: UiState): string {\n const modeMessage = getModeUnavailableMessage(state.activeMode);\n\n if (!modeMessage) {\n return \"Static mode will submit the composer text to the mocked Codex runtime.\";\n }\n\n return modeMessage;\n}\n\nexport function getSelectedSlashCommand(state: UiState) {\n const commands = getVisibleSlashCommands(state);\n\n if (commands.length === 0) {\n return null;\n }\n\n const selectedIndex = Math.max(0, Math.min(commands.length - 1, state.dropdown.selectedIndex));\n\n return commands[selectedIndex] ?? null;\n}\n","import { Box, Text } from \"ink\";\nimport React from \"react\";\nimport stringWidth from \"string-width\";\n\nexport interface InkLineSegment {\n backgroundColor?: string;\n bold?: boolean;\n color?: string;\n dimColor?: boolean;\n italic?: boolean;\n text: string;\n}\n\nexport interface InkLineSpec {\n backgroundColor?: string;\n key: string;\n segments: InkLineSegment[];\n}\n\nexport function measureText(value: string): number {\n return stringWidth(value);\n}\n\nexport function takeDisplayWidth(value: string, width: number): string {\n if (width <= 0 || !value) {\n return \"\";\n }\n\n let result = \"\";\n\n for (const character of Array.from(value)) {\n if (measureText(result + character) > width) {\n break;\n }\n\n result += character;\n }\n\n return result;\n}\n\nexport function truncateDisplayWidth(value: string, width: number): string {\n if (measureText(value) <= width) {\n return value;\n }\n\n if (width <= 3) {\n return takeDisplayWidth(value, width);\n }\n\n return `${takeDisplayWidth(value, width - 3)}...`;\n}\n\nfunction wrapSingleLine(value: string, width: number): string[] {\n if (width <= 0) {\n return [\"\"];\n }\n\n if (!value) {\n return [\"\"];\n }\n\n const tokens = value.split(/(\\s+)/);\n const wrappedLines: string[] = [];\n let currentLine = \"\";\n\n for (const token of tokens) {\n if (!token) {\n continue;\n }\n\n if (/^\\s+$/.test(token)) {\n if (!currentLine) {\n continue;\n }\n\n if (measureText(currentLine + token) <= width) {\n currentLine += token;\n } else {\n wrappedLines.push(currentLine.trimEnd());\n currentLine = \"\";\n }\n\n continue;\n }\n\n if (measureText(token) > width) {\n if (currentLine) {\n wrappedLines.push(currentLine.trimEnd());\n currentLine = \"\";\n }\n\n let remaining = token;\n\n while (measureText(remaining) > width) {\n const slice = takeDisplayWidth(remaining, width);\n\n wrappedLines.push(slice);\n remaining = remaining.slice(slice.length);\n }\n\n currentLine = remaining;\n continue;\n }\n\n if (measureText(currentLine + token) <= width) {\n currentLine += token;\n continue;\n }\n\n wrappedLines.push(currentLine.trimEnd());\n currentLine = token;\n }\n\n wrappedLines.push(currentLine.trimEnd());\n\n return wrappedLines.length > 0 ? wrappedLines : [\"\"];\n}\n\nexport function wrapText(value: string, width: number): string[] {\n const sourceLines = value.split(\"\\n\");\n const wrappedLines: string[] = [];\n\n for (const line of sourceLines) {\n const nextLines = wrapSingleLine(line, width);\n\n wrappedLines.push(...nextLines);\n }\n\n return wrappedLines.length > 0 ? wrappedLines : [\"\"];\n}\n\nfunction wrapVerbatimLine(value: string, width: number): string[] {\n if (width <= 0) {\n return [\"\"];\n }\n\n if (!value) {\n return [\"\"];\n }\n\n const wrappedLines: string[] = [];\n let currentLine = \"\";\n\n for (const character of Array.from(value)) {\n if (measureText(currentLine + character) > width) {\n wrappedLines.push(currentLine);\n currentLine = character;\n continue;\n }\n\n currentLine += character;\n }\n\n wrappedLines.push(currentLine);\n\n return wrappedLines.length > 0 ? wrappedLines : [\"\"];\n}\n\nexport function wrapTextVerbatim(value: string, width: number): string[] {\n const sourceLines = value.split(\"\\n\");\n const wrappedLines: string[] = [];\n\n for (const line of sourceLines) {\n wrappedLines.push(...wrapVerbatimLine(line, width));\n }\n\n return wrappedLines.length > 0 ? wrappedLines : [\"\"];\n}\n\nexport function wrapAndLimit(value: string, width: number, maxLines: number): string[] {\n const wrappedLines = wrapText(value, width);\n\n if (wrappedLines.length <= maxLines) {\n return wrappedLines;\n }\n\n const visibleLines = wrappedLines.slice(0, maxLines);\n\n visibleLines[maxLines - 1] = truncateDisplayWidth(\n `${visibleLines[maxLines - 1] ?? \"\"} ...`.trim(),\n width\n );\n\n return visibleLines;\n}\n\nexport function padLine(line: InkLineSpec, width: number): InkLineSpec {\n const lineWidth = line.segments.reduce((total, segment) => total + measureText(segment.text), 0);\n const paddingWidth = Math.max(width - lineWidth, 0);\n\n if (paddingWidth === 0) {\n return line;\n }\n\n return {\n ...line,\n segments: [\n ...line.segments,\n {\n backgroundColor: line.backgroundColor,\n text: \" \".repeat(paddingWidth)\n }\n ]\n };\n}\n\nexport function overlayLines(\n lines: InkLineSpec[],\n overlay: InkLineSpec[],\n startIndex: number\n): InkLineSpec[] {\n if (overlay.length === 0) {\n return lines;\n }\n\n const nextLines = [...lines];\n\n for (let index = 0; index < overlay.length; index += 1) {\n const targetIndex = startIndex + index;\n\n if (targetIndex < 0 || targetIndex >= nextLines.length) {\n continue;\n }\n\n nextLines[targetIndex] = overlay[index];\n }\n\n return nextLines;\n}\n\nexport function renderLine(line: InkLineSpec, width: number): React.JSX.Element {\n const paddedLine = padLine(line, width);\n\n return (\n <Box key={line.key} width={width}>\n {paddedLine.segments.map((segment, index) => (\n <Text\n key={`${line.key}-${index}`}\n backgroundColor={segment.backgroundColor ?? line.backgroundColor}\n bold={segment.bold}\n color={segment.color}\n dimColor={segment.dimColor}\n italic={segment.italic}\n >\n {segment.text}\n </Text>\n ))}\n </Box>\n );\n}\n","import { execFile } from \"node:child_process\";\nimport process from \"node:process\";\nimport { promisify } from \"node:util\";\nimport type {\n ContinuationController,\n ContinuationDecision,\n ContinuationSnapshot\n} from \"../../auto-continue.js\";\nimport type { HookCapture, StopCapture } from \"../../hook-server.js\";\nimport type { ContinuationPromptProxy } from \"../../continuation-watcher.js\";\nimport { summarizeTranscriptFile } from \"../../transcript.js\";\nimport type { VerificationCommandResult } from \"../../verification.js\";\nimport { formatCodexEcho, formatTimeLeft } from \"../core/view-model.js\";\nimport type {\n UiCommandInvocation,\n UiConnectionState,\n UiLogEntry,\n UiLogEntryKind,\n UiRuntimeSnapshot,\n UiTurnGroup,\n UiWorkspaceInfo\n} from \"../core/types.js\";\nimport type { UiHostUpdate, UiRuntimeHost } from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\nconst OUTPUT_ACTIVITY_NOTIFY_INTERVAL_MS = 250;\nconst MAX_EVENT_LINES = 8;\n\ninterface PendingPrompt {\n startedAt: number;\n text: string;\n}\n\nexport interface LiveUiWatcherTurnEvent {\n capture: StopCapture;\n decision: ContinuationDecision;\n sessionId: string;\n verificationCommand: string | null;\n verificationErrorMessage: string | null;\n verificationResult: VerificationCommandResult | null;\n willInject: boolean;\n}\n\nexport interface LiveUiWatcherInjectionEvent {\n capture: StopCapture;\n decision: ContinuationDecision;\n prompt: string;\n sessionId: string;\n}\n\nexport interface LiveUiAuxiliaryHookEvent {\n capture: HookCapture;\n}\n\nexport interface LiveUiRuntimeHostOptions {\n beeVersion: string;\n codexCommand: string;\n codexVersion?: string;\n continuation: ContinuationController;\n cwd: string;\n initialAnnouncementMessage?: string | null;\n initialConnectionState?: UiConnectionState;\n initialVerificationCommand?: string | null;\n promptProxy: ContinuationPromptProxy;\n}\n\nfunction cloneLogEntry(entry: UiLogEntry): UiLogEntry {\n return {\n ...entry\n };\n}\n\nfunction cloneTurnGroup(group: UiTurnGroup): UiTurnGroup {\n return {\n ...group,\n entries: group.entries.map(cloneLogEntry)\n };\n}\n\nfunction cloneSnapshot(snapshot: UiRuntimeSnapshot): UiRuntimeSnapshot {\n return {\n ...snapshot,\n announcement: snapshot.announcement\n ? {\n ...snapshot.announcement\n }\n : null,\n codexBufferLines: [...snapshot.codexBufferLines],\n logs: snapshot.logs.map(cloneTurnGroup),\n prompts: {\n ...snapshot.prompts\n },\n session: {\n ...snapshot.session,\n hookStatus: snapshot.session.hookStatus\n ? {\n ...snapshot.session.hookStatus\n }\n : null\n },\n workspace: {\n ...snapshot.workspace\n }\n };\n}\n\nfunction normalizeAnnouncementMessage(message: string): string {\n return message.replace(/^\\[codex-bee\\]\\s*/i, \"\").trim();\n}\n\nfunction getStopAt(snapshot: ContinuationSnapshot): number | null {\n return snapshot.startedAt !== null && snapshot.maxDurationMs !== null\n ? snapshot.startedAt + snapshot.maxDurationMs\n : null;\n}\n\nfunction toUiTotalTurns(maxContinues: number): number | null {\n return Number.isFinite(maxContinues)\n ? maxContinues\n : null;\n}\n\nfunction createWorkspaceInfo(cwd: string): UiWorkspaceInfo {\n const homeDirectory = process.env.HOME ?? \"\";\n\n return {\n ahead: 0,\n behind: 0,\n cwd: homeDirectory && cwd.startsWith(homeDirectory)\n ? `~${cwd.slice(homeDirectory.length)}`\n : cwd,\n gitBranch: \"unknown\"\n };\n}\n\nfunction createInitialSnapshot(options: LiveUiRuntimeHostOptions): UiRuntimeSnapshot {\n const continuationSnapshot = options.continuation.getSnapshot();\n\n return {\n activeScenarioId: null,\n announcement: options.initialAnnouncementMessage\n ? {\n message: options.initialAnnouncementMessage\n }\n : null,\n beeVersion: options.beeVersion,\n codexBufferLines: [\n \"$ codex live session attached\",\n ...(options.initialAnnouncementMessage ? [options.initialAnnouncementMessage] : []),\n \"Ctrl+B returns to the Codex shell.\"\n ],\n codexVersion: options.codexVersion ?? \"unknown\",\n connectionState: options.initialConnectionState ?? \"ready\",\n logs: [],\n prompts: {\n off: \"Off mode is passive. Codex-bee will keep collecting stats and turn logs without sending prompts.\",\n agent: \"Agent mode is visual-only until the bee-agent runtime is wired into the new UI.\",\n static: continuationSnapshot.promptText,\n thinking: \"Thinking mode is visual-only until live reasoning controls are implemented.\"\n },\n runState: \"idle\",\n session: {\n currentTurn: 0,\n hookStatus: null,\n lastCodexOutputAt: null,\n stopAt: getStopAt(continuationSnapshot),\n stopScript: options.initialVerificationCommand ?? null,\n totalTurns: toUiTotalTurns(continuationSnapshot.maxContinues)\n },\n workspace: createWorkspaceInfo(options.cwd)\n };\n}\n\nfunction getNextSleepTimestamp(hours: number, minutes: number, now = Date.now()): number {\n const nextTarget = new Date(now);\n\n nextTarget.setSeconds(0, 0);\n nextTarget.setHours(hours, minutes, 0, 0);\n\n if (nextTarget.getTime() <= now) {\n nextTarget.setDate(nextTarget.getDate() + 1);\n }\n\n return nextTarget.getTime();\n}\n\nfunction formatTimeLeftSuffix(stopAt: number | null): string {\n const label = formatTimeLeft(stopAt);\n\n if (!label) {\n return \"\";\n }\n\n return ` (${label.replace(/^time left:\\s*/u, \"\")} left)`;\n}\n\nfunction createLogEntry(id: string, kind: UiLogEntryKind, text: string, timestamp: number): UiLogEntry {\n return {\n id,\n kind,\n text,\n timestamp\n };\n}\n\nfunction buildHookSummary(event: LiveUiWatcherTurnEvent): {\n hookStatus: {\n code: number;\n ok: boolean;\n };\n text: string;\n} {\n if (event.verificationErrorMessage) {\n return {\n hookStatus: {\n code: 1,\n ok: false\n },\n text: `Hook: unable to run \"${event.verificationCommand ?? \"verification command\"}\".`\n };\n }\n\n if (event.verificationResult) {\n return {\n hookStatus: {\n code: event.verificationResult.code,\n ok: event.verificationResult.succeeded\n },\n text: event.verificationResult.succeeded\n ? `Hook: \"${event.verificationResult.command}\" succeeded with exit ${event.verificationResult.code}.`\n : `Hook: \"${event.verificationResult.command}\" failed with exit ${event.verificationResult.code}.`\n };\n }\n\n return {\n hookStatus: {\n code: 0,\n ok: true\n },\n text: \"Hook: Stop capture recorded successfully.\"\n };\n}\n\nfunction buildTerminalStatusMessage(event: LiveUiWatcherTurnEvent): string | null {\n if (event.verificationErrorMessage) {\n return \"Verification command failed to run, so auto-continue stopped.\";\n }\n\n if (event.verificationResult?.succeeded) {\n return \"Verification command succeeded, so auto-continue stopped.\";\n }\n\n if (event.decision.kind === \"disabled\") {\n return \"Auto-continue is currently disabled.\";\n }\n\n if (event.decision.kind === \"guardrail\" || event.decision.kind === \"expired\" || event.decision.kind === \"empty-prompt\" || event.decision.kind === \"error\") {\n return normalizeAnnouncementMessage(event.decision.message ?? \"The continuation flow stopped.\");\n }\n\n if (event.verificationResult && !event.verificationResult.succeeded) {\n return \"Verification failed, so codex-bee will keep going.\";\n }\n\n return null;\n}\n\nfunction readUserMessageFromCapture(capture: HookCapture): string | null {\n if (typeof capture.payload?.prompt === \"string\" && capture.payload.prompt.trim().length > 0) {\n return capture.payload.prompt;\n }\n\n const transcriptPath = capture.payload?.transcript_path ?? capture.transcript?.path ?? null;\n\n if (!transcriptPath) {\n return null;\n }\n\n try {\n const summary = summarizeTranscriptFile(transcriptPath, {\n maxRecentMessages: 8\n });\n const latestUserMessage = [...summary.recentMessages]\n .reverse()\n .find((message) => message.role === \"user\");\n\n return latestUserMessage?.text ?? null;\n } catch {\n return null;\n }\n}\n\nasync function readGitWorkspaceInfo(cwd: string): Promise<Partial<UiWorkspaceInfo>> {\n try {\n const [{ stdout: branchStdout }, countsResult] = await Promise.all([\n execFileAsync(\"git\", [\"branch\", \"--show-current\"], {\n cwd,\n encoding: \"utf8\"\n }),\n execFileAsync(\"git\", [\"rev-list\", \"--left-right\", \"--count\", \"@{upstream}...HEAD\"], {\n cwd,\n encoding: \"utf8\"\n }).catch(() => ({\n stdout: \"0\\t0\"\n }))\n ]);\n const [behindValue, aheadValue] = countsResult.stdout.trim().split(/\\s+/);\n const behind = Number.parseInt(behindValue ?? \"0\", 10);\n const ahead = Number.parseInt(aheadValue ?? \"0\", 10);\n\n return {\n ahead: Number.isFinite(ahead) ? ahead : 0,\n behind: Number.isFinite(behind) ? behind : 0,\n gitBranch: branchStdout.trim() || \"detached\"\n };\n } catch {\n return {};\n }\n}\n\nasync function readCodexVersion(command: string): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync(command, [\"--version\"], {\n encoding: \"utf8\"\n });\n const versionMatch = stdout.trim().match(/(\\d+\\.\\d+\\.\\d+)/);\n\n return versionMatch?.[1] ?? null;\n } catch {\n return null;\n }\n}\n\nexport class LiveUiRuntimeHost implements UiRuntimeHost {\n readonly #continuation: ContinuationController;\n readonly #codexCommand: string;\n readonly #cwd: string;\n readonly #listeners = new Set<() => void>();\n readonly #recentEvents: string[] = [];\n #entryCounter = 0;\n #handledStopFingerprints = new Set<string>();\n #lastOutputActivityNotificationAt = 0;\n #pendingPrompts: PendingPrompt[] = [];\n #snapshot: UiRuntimeSnapshot;\n #verificationCommand: string | null;\n\n constructor(options: LiveUiRuntimeHostOptions) {\n this.#continuation = options.continuation;\n this.#codexCommand = options.codexCommand;\n this.#cwd = options.cwd;\n this.#verificationCommand = options.initialVerificationCommand ?? null;\n this.#snapshot = createInitialSnapshot(options);\n }\n\n subscribe(listener: () => void): () => void {\n this.#listeners.add(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n getSnapshot(): UiRuntimeSnapshot {\n return cloneSnapshot(this.#snapshot);\n }\n\n getVerificationCommand(): string | null {\n return this.#verificationCommand;\n }\n\n markDisconnected(): void {\n this.#snapshot = {\n ...this.#snapshot,\n connectionState: \"disconnected\",\n runState: \"idle\"\n };\n this.#pushEventLine(\"Codex session disconnected.\");\n this.#notify();\n }\n\n recordPtyOutputActivity(timestamp = Date.now()): void {\n this.#snapshot = {\n ...this.#snapshot,\n session: {\n ...this.#snapshot.session,\n lastCodexOutputAt: timestamp\n }\n };\n\n if (timestamp - this.#lastOutputActivityNotificationAt < OUTPUT_ACTIVITY_NOTIFY_INTERVAL_MS) {\n return;\n }\n\n this.#lastOutputActivityNotificationAt = timestamp;\n this.#notify();\n }\n\n recordAuxiliaryHookEvent(capture: HookCapture): void {\n const eventName = capture.payload?.hook_event_name ?? null;\n\n if (eventName === \"SessionStart\") {\n const source = capture.payload?.source;\n\n this.#handledStopFingerprints.clear();\n this.#pendingPrompts = [];\n this.#snapshot = {\n ...this.#snapshot,\n connectionState: \"connected\"\n };\n this.#pushEventLine(\n source === \"startup\" || source === \"resume\"\n ? `SessionStart received from ${source}. Hooks are attached to this Codex session.`\n : \"SessionStart received. Hooks are attached to this Codex session.\"\n );\n this.#notify();\n return;\n }\n\n if (eventName === \"UserPromptSubmit\") {\n const submittedAt = Date.now();\n const promptText = readUserMessageFromCapture(capture);\n\n this.#ensureTurnGroupStarted(capture, promptText, submittedAt);\n this.#snapshot = {\n ...this.#snapshot,\n connectionState: \"connected\",\n runState: \"running\",\n session: {\n ...this.#snapshot.session,\n currentTurn: this.#snapshot.logs.length,\n lastCodexOutputAt: submittedAt\n }\n };\n this.#lastOutputActivityNotificationAt = submittedAt;\n this.#pushEventLine(\n promptText\n ? `UserPromptSubmit received. Codex turn is running: ${formatCodexEcho(promptText)}`\n : \"UserPromptSubmit received. Codex turn is running.\"\n );\n this.#notify();\n }\n }\n\n async refreshEnvironmentMetadata(): Promise<void> {\n const [workspaceInfo, codexVersion] = await Promise.all([\n readGitWorkspaceInfo(this.#cwd),\n readCodexVersion(this.#codexCommand)\n ]);\n\n this.#snapshot = {\n ...this.#snapshot,\n codexVersion: codexVersion ?? this.#snapshot.codexVersion,\n workspace: {\n ...this.#snapshot.workspace,\n ...workspaceInfo\n }\n };\n this.#notify();\n }\n\n async executeCommand(command: UiCommandInvocation): Promise<UiHostUpdate> {\n switch (command.id) {\n case \"clear-log\":\n this.#handledStopFingerprints.clear();\n this.#pendingPrompts = [];\n this.#snapshot = {\n ...this.#snapshot,\n logs: [],\n session: {\n ...this.#snapshot.session,\n currentTurn: 0\n }\n };\n this.#pushEventLine(\"Cleared the live turn log.\");\n\n return this.#createUpdate(\"Cleared the live turn log.\");\n case \"duration\": {\n const currentContinuation = this.#continuation.getSnapshot();\n const updatedSnapshot = this.#continuation.updateInteractiveDraft({\n maxContinues: currentContinuation.maxContinues,\n maxDurationMs: command.minutes * 60 * 1000,\n prompt: currentContinuation.promptText\n });\n const stopAt = getStopAt(updatedSnapshot);\n const timeLeftSuffix = formatTimeLeftSuffix(stopAt);\n\n this.#syncContinuationState(updatedSnapshot);\n this.#pushEventLine(`Updated the session duration to ${command.minutes} minute(s)${timeLeftSuffix}.`);\n\n return this.#createUpdate(`Set the live session duration to ${command.minutes} minute(s)${timeLeftSuffix}.`);\n }\n case \"quit\":\n return this.#createUpdate(\"Exiting the current codex-bee session.\", {\n exitRequested: true,\n noticeKind: \"warning\"\n });\n case \"sleep\": {\n const stopAt = getNextSleepTimestamp(command.hours, command.minutes);\n const currentContinuation = this.#continuation.getSnapshot();\n const updatedSnapshot = this.#continuation.updateInteractiveDraft({\n maxContinues: currentContinuation.maxContinues,\n maxDurationMs: Math.max(stopAt - Date.now(), 1_000),\n prompt: currentContinuation.promptText\n });\n const timeLeftSuffix = formatTimeLeftSuffix(getStopAt(updatedSnapshot));\n\n this.#syncContinuationState(updatedSnapshot);\n this.#pushEventLine(`Set the absolute stop time to ${command.time}${timeLeftSuffix}.`);\n\n return this.#createUpdate(`Set the live stop time to ${command.time}${timeLeftSuffix}.`);\n }\n case \"steps-count\": {\n const currentContinuation = this.#continuation.getSnapshot();\n const updatedSnapshot = this.#continuation.updateInteractiveDraft({\n maxContinues: currentContinuation.injectionsUsed + command.steps,\n maxDurationMs: currentContinuation.maxDurationMs,\n prompt: currentContinuation.promptText\n });\n\n this.#syncContinuationState(updatedSnapshot);\n this.#pushEventLine(`Updated the remaining max turns count to ${command.steps}.`);\n\n return this.#createUpdate(`Updated the live remaining max turns count to ${command.steps}.`);\n }\n case \"stop-script\":\n this.#verificationCommand = command.command;\n this.#snapshot = {\n ...this.#snapshot,\n session: {\n ...this.#snapshot.session,\n stopScript: command.command\n }\n };\n this.#pushEventLine(`Stored the stop script: ${command.command}`);\n\n return this.#createUpdate(`Stored the live stop script: ${command.command}`);\n default:\n return this.#createUpdate(\"The live runtime ignored an unknown command.\", {\n noticeKind: \"error\"\n });\n }\n }\n\n setMode(mode: \"agent\" | \"off\" | \"static\" | \"thinking\"): UiHostUpdate {\n if (mode === \"off\") {\n const updatedSnapshot = this.#continuation.disable();\n\n this.#syncContinuationState(updatedSnapshot);\n this.#snapshot = {\n ...this.#snapshot,\n announcement: {\n message: \"Off mode is passive. Codex-bee keeps collecting stats and logs without sending prompts.\"\n },\n runState: \"idle\"\n };\n this.#pushEventLine(\"Switched to Off mode. Auto-continue is disabled.\");\n\n return this.#createUpdate(\"Off mode is passive. Codex-bee will only keep logging turns.\");\n }\n\n this.#snapshot = {\n ...this.#snapshot,\n announcement: null\n };\n\n return this.#createUpdate(\"Static mode is ready to stage the next Stop hook prompt.\");\n }\n\n async submitPrompt(options: {\n mode: \"agent\" | \"off\" | \"static\" | \"thinking\";\n text: string;\n }): Promise<UiHostUpdate> {\n if (options.mode !== \"static\") {\n return this.#createUpdate(`${options.mode} mode is visual-only right now.`, {\n noticeKind: \"warning\"\n });\n }\n\n const continuationSnapshot = this.#continuation.getSnapshot();\n const rearmedSnapshot = this.#continuation.applyInteractiveDraft({\n maxContinues: continuationSnapshot.maxContinues,\n maxDurationMs: continuationSnapshot.maxDurationMs,\n prompt: options.text\n });\n\n this.#syncContinuationState(rearmedSnapshot);\n this.#snapshot = {\n ...this.#snapshot,\n announcement: null\n };\n this.#pushEventLine(`Staged prompt: ${formatCodexEcho(options.text)}`);\n\n return this.#createUpdate(\"Stored the prompt for the next Stop hook.\");\n }\n\n recordContinuationPromptInjected(event: LiveUiWatcherInjectionEvent): void {\n const statusText = event.decision.kind === \"generate\"\n ? `Injected a bee-agent continuation prompt (${event.decision.injectionNumber ?? \"?\"}/${event.decision.maxContinues ?? \"?\"}).`\n : `Injected the next continuation prompt (${event.decision.injectionNumber ?? \"?\"}/${event.decision.maxContinues ?? \"?\"}).`;\n const completedTurnId = event.capture.payload?.turn_id ?? null;\n\n this.#pendingPrompts.push({\n startedAt: Date.now(),\n text: event.prompt\n });\n this.#appendEntryToTurn(completedTurnId, \"status\", statusText);\n\n if (event.decision.guardrailReached) {\n this.#appendEntryToTurn(\n completedTurnId,\n \"status\",\n `Guardrail reached at ${event.decision.maxContinues ?? \"?\"} injections. The next completed turn will stop the loop.`\n );\n this.#snapshot = {\n ...this.#snapshot,\n announcement: {\n message: `Guardrail reached after the latest injection (${event.decision.maxContinues ?? \"?\"} max turns).`\n }\n };\n }\n\n this.#pushEventLine(statusText);\n this.#notify();\n }\n\n recordStopCaptureHandled(event: LiveUiWatcherTurnEvent): void {\n const completedAt = Date.now();\n const terminalStatusMessage = buildTerminalStatusMessage(event);\n const stopFingerprint = this.#buildStopFingerprint(event, terminalStatusMessage);\n\n if (this.#handledStopFingerprints.has(stopFingerprint)) {\n return;\n }\n\n this.#handledStopFingerprints.add(stopFingerprint);\n const pendingPrompt = this.#pendingPrompts.shift() ?? null;\n const transcriptUserMessage = readUserMessageFromCapture(event.capture);\n const existingGroupIndex = event.capture.payload?.turn_id\n ? this.#snapshot.logs.findIndex((group) => group.id === event.capture.payload?.turn_id)\n : -1;\n const existingGroup = existingGroupIndex >= 0\n ? this.#snapshot.logs[existingGroupIndex] ?? null\n : null;\n const turnNumber = existingGroup?.turn ?? (this.#snapshot.logs.length + 1);\n const continuationSnapshot = this.#continuation.getSnapshot();\n const hookSummary = buildHookSummary(event);\n const entries: UiLogEntry[] = existingGroup\n ? [...existingGroup.entries]\n : [];\n\n const userMessageText = pendingPrompt?.text ?? transcriptUserMessage;\n\n if (userMessageText && !entries.some((entry) => entry.kind === \"user\")) {\n entries.push(this.#nextLogEntry(\"user\", userMessageText, pendingPrompt?.startedAt ?? completedAt));\n }\n\n if (event.capture.payload?.last_assistant_message) {\n entries.push(\n this.#nextLogEntry(\n \"model\",\n event.capture.payload.last_assistant_message,\n completedAt\n )\n );\n }\n\n entries.push(this.#nextLogEntry(\"hook\", hookSummary.text, completedAt));\n\n if (terminalStatusMessage) {\n entries.push(this.#nextLogEntry(\"status\", terminalStatusMessage, completedAt));\n }\n\n const groupId = event.capture.payload?.turn_id ?? `turn-${turnNumber}-${completedAt}`;\n const turnStartedAt = existingGroup?.entries.find((entry) => entry.kind === \"user\")?.timestamp\n ?? pendingPrompt?.startedAt\n ?? null;\n const nextGroup: UiTurnGroup = {\n durationMs: turnStartedAt !== null\n ? Math.max(completedAt - turnStartedAt, 0)\n : existingGroup?.durationMs ?? null,\n entries,\n id: groupId,\n totalTurns: null,\n turn: turnNumber\n };\n const nextLogs = existingGroupIndex >= 0\n ? this.#snapshot.logs.map((group, index) => index === existingGroupIndex ? nextGroup : group)\n : [...this.#snapshot.logs, nextGroup];\n const nextTotalTurns = this.#getUiTotalTurns(continuationSnapshot, nextLogs);\n const finalizedLogs = this.#applyTotalTurns(nextLogs, nextTotalTurns);\n\n this.#snapshot = {\n ...this.#snapshot,\n connectionState: \"connected\",\n announcement: this.#buildAnnouncement(event, terminalStatusMessage),\n logs: finalizedLogs,\n runState: \"idle\",\n session: {\n ...this.#snapshot.session,\n currentTurn: finalizedLogs.length,\n hookStatus: hookSummary.hookStatus,\n lastCodexOutputAt: completedAt,\n stopAt: getStopAt(continuationSnapshot),\n stopScript: this.#verificationCommand,\n totalTurns: nextTotalTurns\n }\n };\n this.#pushEventLine(\n event.capture.payload?.last_assistant_message\n ? `Turn ${turnNumber} completed: ${formatCodexEcho(event.capture.payload.last_assistant_message)}`\n : `Turn ${turnNumber} completed without an assistant summary.`\n );\n this.#notify();\n }\n\n #appendEntryToTurn(turnId: string | null, kind: UiLogEntryKind, text: string): void {\n const targetIndex = turnId\n ? this.#snapshot.logs.findIndex((group) => group.id === turnId)\n : this.#snapshot.logs.length - 1;\n\n if (targetIndex < 0) {\n return;\n }\n\n const targetGroup = this.#snapshot.logs[targetIndex];\n\n if (!targetGroup) {\n return;\n }\n\n const updatedGroup: UiTurnGroup = {\n ...targetGroup,\n entries: [\n ...targetGroup.entries,\n this.#nextLogEntry(kind, text, Date.now())\n ]\n };\n const nextLogs = [...this.#snapshot.logs];\n\n nextLogs[targetIndex] = updatedGroup;\n this.#snapshot = {\n ...this.#snapshot,\n logs: nextLogs\n };\n }\n\n #ensureTurnGroupStarted(capture: HookCapture, promptText: string | null, startedAt: number): void {\n const turnId = capture.payload?.turn_id ?? `turn-pending-${startedAt}`;\n const targetIndex = this.#snapshot.logs.findIndex((group) => group.id === turnId);\n\n if (targetIndex >= 0) {\n const targetGroup = this.#snapshot.logs[targetIndex];\n\n if (!targetGroup) {\n return;\n }\n\n if (!promptText || targetGroup.entries.some((entry) => entry.kind === \"user\")) {\n return;\n }\n\n const nextLogs = [...this.#snapshot.logs];\n\n nextLogs[targetIndex] = {\n ...targetGroup,\n entries: [\n this.#nextLogEntry(\"user\", promptText, startedAt),\n ...targetGroup.entries\n ]\n };\n this.#snapshot = {\n ...this.#snapshot,\n logs: this.#applyTotalTurns(\n nextLogs,\n this.#getUiTotalTurns(this.#continuation.getSnapshot(), nextLogs)\n )\n };\n\n return;\n }\n\n if (!promptText) {\n return;\n }\n\n const turnNumber = this.#snapshot.logs.length + 1;\n const nextGroup: UiTurnGroup = {\n durationMs: null,\n entries: [\n this.#nextLogEntry(\"user\", promptText, startedAt)\n ],\n id: turnId,\n totalTurns: null,\n turn: turnNumber\n };\n const nextLogs = [...this.#snapshot.logs, nextGroup];\n const nextTotalTurns = this.#getUiTotalTurns(this.#continuation.getSnapshot(), nextLogs);\n\n this.#snapshot = {\n ...this.#snapshot,\n logs: this.#applyTotalTurns(nextLogs, nextTotalTurns)\n };\n }\n\n #buildAnnouncement(event: LiveUiWatcherTurnEvent, terminalStatusMessage: string | null): {\n message: string;\n } | null {\n if (event.verificationErrorMessage) {\n return {\n message: \"Verification command failed to run, so the loop stopped.\"\n };\n }\n\n if (event.verificationResult && !event.verificationResult.succeeded) {\n return {\n message: \"Verification failed after the latest turn. Codex-bee kept the loop alive.\"\n };\n }\n\n if (event.verificationResult?.succeeded) {\n return {\n message: \"Verification succeeded after the latest turn. Auto-continue stopped.\"\n };\n }\n\n if (!terminalStatusMessage) {\n return null;\n }\n\n return {\n message: terminalStatusMessage\n };\n }\n\n #createUpdate(\n message: string,\n options?: {\n exitRequested?: boolean;\n noticeKind?: \"error\" | \"info\" | \"warning\";\n }\n ): UiHostUpdate {\n return {\n exitRequested: options?.exitRequested,\n notice: {\n kind: options?.noticeKind ?? \"info\",\n message\n },\n snapshot: cloneSnapshot(this.#snapshot)\n };\n }\n\n #nextLogEntry(kind: UiLogEntryKind, text: string, timestamp: number): UiLogEntry {\n this.#entryCounter += 1;\n\n return createLogEntry(`entry-${this.#entryCounter}`, kind, text, timestamp);\n }\n\n #notify(): void {\n for (const listener of this.#listeners) {\n listener();\n }\n }\n\n #pushEventLine(text: string): void {\n this.#recentEvents.push(text);\n\n while (this.#recentEvents.length > MAX_EVENT_LINES) {\n this.#recentEvents.shift();\n }\n\n this.#snapshot = {\n ...this.#snapshot,\n codexBufferLines: [\n \"$ codex live session attached\",\n ...this.#recentEvents\n ]\n };\n }\n\n #syncContinuationState(snapshot: ContinuationSnapshot): void {\n const connectionState: UiConnectionState = this.#snapshot.connectionState;\n const nextTotalTurns = this.#getUiTotalTurns(snapshot, this.#snapshot.logs);\n const nextLogs = this.#applyTotalTurns(this.#snapshot.logs, nextTotalTurns);\n const currentTurn = nextLogs.length;\n\n this.#snapshot = {\n ...this.#snapshot,\n connectionState,\n logs: nextLogs,\n prompts: {\n ...this.#snapshot.prompts,\n static: snapshot.promptText\n },\n runState: this.#snapshot.runState,\n session: {\n ...this.#snapshot.session,\n currentTurn,\n stopAt: getStopAt(snapshot),\n stopScript: this.#verificationCommand,\n totalTurns: nextTotalTurns\n }\n };\n }\n\n #buildStopFingerprint(event: LiveUiWatcherTurnEvent, terminalStatusMessage: string | null): string {\n const turnId = event.capture.payload?.turn_id?.trim();\n\n if (turnId) {\n return `turn:${turnId}`;\n }\n\n return [\n event.capture.payload?.session_id ?? \"session\",\n event.capture.payload?.transcript_path ?? \"\",\n event.capture.payload?.last_assistant_message ?? \"\",\n terminalStatusMessage ?? \"\"\n ].join(\"::\");\n }\n\n #getCompletedTurnCount(logs: UiTurnGroup[] = this.#snapshot.logs): number {\n return logs.filter((group) => group.entries.some((entry) => entry.kind !== \"user\")).length;\n }\n\n #getUiTotalTurns(snapshot: ContinuationSnapshot, logs: UiTurnGroup[] = this.#snapshot.logs): number | null {\n if (!Number.isFinite(snapshot.maxContinues)) {\n return null;\n }\n\n return Math.max(this.#getCompletedTurnCount(logs) - snapshot.injectionsUsed + snapshot.maxContinues, 0);\n }\n\n #applyTotalTurns(logs: UiTurnGroup[], totalTurns: number | null): UiTurnGroup[] {\n return logs.map((group) => ({\n ...group,\n totalTurns\n }));\n }\n}\n"],"mappings":";;;AAEA,SAAS,kBAAkB;AAC3B,SAAS,YAAAA,iBAAgB;AACzB,OAAOC,SAAQ;AACf,SAAS,qBAAqB;AAC9B,OAAOC,WAAU;AACjB,OAAOC,cAAa;AACpB,YAAY,cAAc;AAC1B,SAAS,qBAAqB;AAC9B,SAAS,aAAAC,kBAAiB;;;ACV1B,SAAS,WAAW,gBAAAC,eAAc,eAAe,gBAAgB,kBAAkB;AACnF,OAAO,UAAU;AACjB,SAAS,aAAa;AACtB,OAAOC,cAAa;;;ACHpB,SAAS,oBAAoB;AA6B7B,SAAS,gBAAgB,SAEd;AACT,MAAI,CAAC,MAAM,QAAQ,QAAQ,OAAO,GAAG;AACnC,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,QAAQ,QACvB,OAAO,CAAC,SAGJ,OAAO,SAAS,YAAY,SAAS,I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F,gBAAe,KAAK,CAAC,EAAE;AACpD,EAAAE,SAAQ,WAAW;AACrB;","names":["execFile","fs","path","process","promisify","readFileSync","process","text","readFileSync","resolve","process","readFileSync","readFileSync","SINGLE_LINE_WHITESPACE_PATTERN","toSingleLine","SINGLE_LINE_WHITESPACE_PATTERN","toErrorMessage","guardrailReached","toErrorMessage","process","path","process","resolve","path","spawn","WINDOWS_LINE_ENDING_PATTERN","resolve","runVerificationCommand","process","prompt","isTimeoutError","fs","path","toErrorMessage","spawn","resolve","spawn","process","delay","shellEscape","resolve","fs","path","toErrorMessage","update","process","React","Box","toSingleLine","command","toSingleLine","jsx","jsx","Box","process","React","process","process","nextLogs","require","execFileAsync","promisify","execFile","toErrorMessage","path","process","fs"]}