@agent-native/core 0.66.3 → 0.66.5

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.
@@ -1 +1 @@
1
- {"version":3,"file":"code-agent-executor.d.ts","sourceRoot":"","sources":["../../src/cli/code-agent-executor.ts"],"names":[],"mappings":"AAmCA,OAAO,KAAK,EACV,WAAW,EAEX,aAAa,EAEd,MAAM,0BAA0B,CAAC;AAQlC,OAAO,EAEL,KAAK,eAAe,EACrB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEL,KAAK,qBAAqB,EAC3B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAQL,KAAK,uBAAuB,EAC5B,KAAK,kBAAkB,EACxB,MAAM,sBAAsB,CAAC;AAG9B,MAAM,WAAW,0BAA0B;IACzC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,WAAW,CAAC,EAAE,qBAAqB,EAAE,CAAC;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAsCD,wBAAsB,mBAAmB,CACvC,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CA4ZpC;AA8RD,wBAAsB,2BAA2B,CAC/C,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,IAAI,CAAC,0BAA0B,EAAE,OAAO,CAAM,GACtD,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAEpC;AAED;;;;GAIG;AACH,wBAAsB,qCAAqC,CACzD,KAAK,EAAE,MAAM,EACb,OAAO,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC,cAAc,CAA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odeAgentRun(options) {
89
89
  message: "Agent-Native Code run started.",
90
90
  metadata: { status: "running", phase: "executing" },
91
91
  });
92
- const requestedEngine = normalizeRequestedEngine(metadataString(existing, "engine"));
92
+ // Fall back to AGENT_ENGINE here too, mirroring resolveExecutorEngine below.
93
+ // Without it, `AGENT_ENGINE=codex-cli` skips this Codex branch and is handed
94
+ // to resolveEngine (LLM providers only), which throws `Unknown engine`.
95
+ const requestedEngine = normalizeRequestedEngine(metadataString(existing, "engine") ?? process.env.AGENT_ENGINE);
93
96
  if (requestedEngine === CODEX_CLI_ENGINE_NAME) {
94
97
  return executeCodexCliRun({
95
98
  run: existing,
@@ -1 +1 @@
1
- {"version":3,"file":"code-agent-executor.js","sourceRoot":"","sources":["../../src/cli/code-agent-executor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,wBAAwB,EACxB,sBAAsB,EACtB,gBAAgB,EAChB,kBAAkB,EAClB,oBAAoB,GAErB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EACL,oBAAoB,EACpB,YAAY,GAGb,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,aAAa,EACb,uBAAuB,EACvB,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAQlC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;AACzE,OAAO,EAAE,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AACzE,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E,CAAC,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,YAAY;QAC1D,eAAe,EAAE,CAAC,IAAI,CAAC,eAAe,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,eAAe;QACnE,gBAAgB,EAAE,CAAC,IAAI,CAAC,gBAAgB,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,gBAAgB;KACvE,CAAC;AACJ,CAAC","sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nimport {\n createToolSearchEntry,\n TOOL_SEARCH_ACTION_NAME,\n} from \"../agent/tool-search.js\";\nimport {\n createCodingToolRegistry,\n isReadOnlyShellCommand,\n runCodingCommand,\n truncateBashOutput,\n truncateCodingOutput,\n type StructuredToolMetadata,\n} from \"../coding-tools/index.js\";\nimport {\n buildMergedConfig,\n McpClientManager,\n mcpToolsToActionEntries,\n} from \"../mcp-client/index.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport {\n actionsToEngineTools,\n runAgentLoop,\n type ActionEntry,\n type AgentLoopUsage,\n} from \"../agent/production-agent.js\";\nimport {\n resolveEngine,\n getStoredModelForEngine,\n normalizeModelForEngine,\n registerBuiltinEngines,\n} from \"../agent/engine/index.js\";\nimport type {\n AgentEngine,\n EngineEvent,\n EngineMessage,\n EngineStreamOptions,\n} from \"../agent/engine/types.js\";\nimport type { AgentChatEvent } from \"../agent/types.js\";\nimport { PROVIDER_ENV_VARS } from \"../agent/engine/provider-env-vars.js\";\nimport { DEFAULT_AGENT_MAX_ITERATIONS } from \"../agent/loop-settings.js\";\nimport {\n readAgentsBundleFromFs,\n generateSkillsPromptBlock,\n} from \"../server/agents-bundle.js\";\nimport {\n isReasoningEffort,\n type ReasoningEffort,\n} from \"../shared/reasoning-effort.js\";\nimport {\n formatPromptWithAttachments,\n type AgentPromptAttachment,\n} from \"../code-agents/prompt-attachments.js\";\nimport {\n addCodeAgentCommandToAllowlist,\n appendCodeAgentTranscriptEvent,\n dequeueCodeAgentFollowUp,\n getCodeAgentRunRecord,\n isCodeAgentCommandAllowed,\n listCodeAgentTranscriptEvents,\n updateCodeAgentRunRecord,\n type CodeAgentPermissionMode,\n type CodeAgentRunRecord,\n} from \"./code-agent-runs.js\";\nimport { createCodeAgentOutputSmoother } from \"./code-agent-output-smoother.js\";\n\nexport interface ExecuteCodeAgentRunOptions {\n runId: string;\n prompt?: string;\n appendUserEvent?: boolean;\n engine?: AgentEngine;\n model?: string;\n reasoningEffort?: ReasoningEffort;\n attachments?: AgentPromptAttachment[];\n stdout?: NodeJS.WritableStream;\n signal?: AbortSignal;\n}\n\ninterface PendingCodeAgentApproval {\n id: string;\n tool: \"bash\" | \"run_command\";\n command: string;\n reason: string;\n requestedAt: string;\n permissionMode: CodeAgentPermissionMode;\n}\n\ninterface CodexCliProcessResult {\n exitCode: number | null;\n exitSignal: NodeJS.Signals | null;\n stdout: string;\n stderr: string;\n error?: string;\n}\n\nconst DEFAULT_COMMAND_TIMEOUT_MS = 120_000;\nconst MAX_TOOL_OUTPUT_CHARS = 50_000;\nconst MAX_FILE_READ_CHARS = 120_000;\nconst CODEX_CLI_ENGINE_NAME = \"codex-cli\";\n\n/**\n * Number of most-recent transcript events reconstructed as native\n * EngineMessage objects (with proper tool-call / tool-result pairing).\n * Events older than this cap are summarised into a single compact text\n * preamble so the model retains broad context without token waste.\n */\nconst STRUCTURED_HISTORY_RECENT_EVENTS = 40;\n\n/**\n * Per-tool-result text cap when reconstructing history. Matches the overall\n * tool-output cap so old results don't balloon the context.\n */\nconst STRUCTURED_HISTORY_RESULT_CAP = MAX_TOOL_OUTPUT_CHARS;\n\nexport async function executeCodeAgentRun(\n options: ExecuteCodeAgentRunOptions,\n): Promise<CodeAgentRunRecord | null> {\n const existing = getCodeAgentRunRecord(options.runId);\n if (!existing) return null;\n\n const prompt = options.prompt ?? latestUserPrompt(existing.id);\n const rawAttachments =\n options.attachments ?? latestUserPromptAttachments(existing.id, prompt);\n\n // Split attachments: images (dataUrl) go as engine image parts; text/file\n // attachments are still inlined into the prompt text. This prevents 2 MB\n // images from consuming ~700 K tokens of garbage when treated as plain text.\n const imageAttachments = rawAttachments.filter((a) => a.dataUrl);\n const textOnlyAttachments = rawAttachments.filter((a) => !a.dataUrl);\n const executionPrompt = formatPromptWithAttachments(\n prompt,\n textOnlyAttachments,\n );\n if (!prompt) {\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: \"No prompt was found for this Agent-Native Code run.\",\n metadata: { status: \"errored\", phase: \"missing-prompt\" },\n });\n return updateCodeAgentRunRecord(existing.id, {\n status: \"errored\",\n phase: \"missing-prompt\",\n progress: {\n label: \"Missing prompt\",\n completed: 0,\n total: 1,\n failed: 1,\n percent: 0,\n },\n });\n }\n\n if (options.appendUserEvent !== false) {\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"user\",\n message: prompt,\n metadata: { source: \"execution-prompt\" },\n });\n }\n\n const running = updateCodeAgentRunRecord(existing.id, {\n status: \"running\",\n phase: \"executing\",\n progress: {\n label: \"Running\",\n completed: 0,\n total: 1,\n percent: 10,\n },\n metadata: {\n executionStartedAt: new Date().toISOString(),\n },\n });\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: \"Agent-Native Code run started.\",\n metadata: { status: \"running\", phase: \"executing\" },\n });\n\n const requestedEngine = normalizeRequestedEngine(\n metadataString(existing, \"engine\"),\n );\n if (requestedEngine === CODEX_CLI_ENGINE_NAME) {\n return executeCodexCliRun({\n run: existing,\n prompt: executionPrompt,\n model: options.model ?? metadataString(existing, \"model\"),\n permissionMode: existing.permissionMode ?? \"full-auto\",\n stdout: options.stdout,\n signal: options.signal,\n });\n }\n\n const engine =\n options.engine ?? (await resolveExecutorEngine(requestedEngine));\n if (!engine) {\n const message =\n \"No LLM provider key was found. Set ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY, another supported provider key, or run `codex login` to use Codex CLI.\";\n options.stdout?.write(`${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message,\n metadata: { status: \"paused\", phase: \"missing-credentials\" },\n });\n return updateCodeAgentRunRecord(existing.id, {\n status: \"paused\",\n phase: \"missing-credentials\",\n needsApproval: false,\n progress: {\n label: \"Missing credentials\",\n completed: 0,\n total: 1,\n percent: 0,\n },\n });\n }\n\n const modelCandidate =\n options.model ??\n metadataString(existing, \"model\") ??\n process.env.AGENT_MODEL ??\n (await getStoredModelForEngine(engine).catch(() => undefined)) ??\n engine.defaultModel;\n const model = normalizeModelForEngine(engine, modelCandidate);\n const reasoningEffort =\n options.reasoningEffort ?? metadataReasoningEffort(existing);\n const cwd = existing.cwd || process.cwd();\n const permissionMode = existing.permissionMode ?? \"full-auto\";\n\n // Holds structured metadata emitted by the coding tools side-channel.\n // Keyed by tool name; consumed when the matching tool_start / tool_done fires.\n const pendingToolMeta = new Map<string, StructuredToolMetadata>();\n\n const actions = createLocalCodeAgentActions(\n cwd,\n permissionMode,\n existing.id,\n (toolName, _phase, meta) => {\n // Both \"start\" and \"done\" phases update the map; done has richer data.\n pendingToolMeta.set(toolName, meta);\n },\n (chunk) => {\n // Stream incremental bash output to stdout for the terminal smoother\n options.stdout?.write(chunk);\n },\n );\n const mcpManager = await startCodeAgentMcpManager(existing.id);\n if (mcpManager) {\n Object.assign(actions, mcpToolsToActionEntries(mcpManager));\n }\n actions[TOOL_SEARCH_ACTION_NAME] = createToolSearchEntry(() => actions);\n const tools = actionsToEngineTools(actions);\n const messages = buildCodeAgentMessages(\n existing,\n executionPrompt,\n imageAttachments,\n );\n const controller = new AbortController();\n const abortFromParent = () => controller.abort();\n if (options.signal) {\n if (options.signal.aborted) controller.abort();\n else\n options.signal.addEventListener(\"abort\", abortFromParent, { once: true });\n }\n\n let assistantText = \"\";\n const outputSmoother = createCodeAgentOutputSmoother(options.stdout);\n\n // Accumulate thinking text across deltas so we can persist a single event\n // per reasoning block rather than one event per delta chunk.\n let pendingThinkingText = \"\";\n let thinkingFlushTimer: ReturnType<typeof setTimeout> | undefined;\n\n const runId = existing.id;\n function flushThinkingEvent() {\n thinkingFlushTimer = undefined;\n const text = pendingThinkingText.trim();\n pendingThinkingText = \"\";\n if (!text) return;\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: text,\n metadata: { type: \"thinking\" },\n });\n }\n\n const send = (event: AgentChatEvent) => {\n if (event.type === \"text\") {\n // Flush any buffered thinking when real content arrives.\n if (thinkingFlushTimer !== undefined) {\n clearTimeout(thinkingFlushTimer);\n flushThinkingEvent();\n }\n assistantText += event.text;\n outputSmoother.write(event.text);\n return;\n }\n if (event.type === \"thinking\") {\n pendingThinkingText += event.text;\n // Debounce: flush 300ms after the last delta so rapid chunks are merged.\n if (thinkingFlushTimer !== undefined) clearTimeout(thinkingFlushTimer);\n thinkingFlushTimer = setTimeout(flushThinkingEvent, 300);\n return;\n }\n if (event.type === \"activity\") {\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: event.label,\n metadata: { type: \"activity\", tool: event.tool },\n });\n return;\n }\n if (event.type === \"tool_start\") {\n const startMeta = pendingToolMeta.get(event.tool ?? \"\");\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: `Running ${event.tool}.`,\n metadata: {\n type: \"tool_start\",\n tool: event.tool,\n input: event.input,\n ...(startMeta ? { structuredMeta: startMeta } : {}),\n },\n });\n return;\n }\n if (event.type === \"tool_done\") {\n const pendingMeta = pendingToolMeta.get(event.tool ?? \"\");\n if (pendingMeta) pendingToolMeta.delete(event.tool ?? \"\");\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: `Finished ${event.tool}.`,\n metadata: {\n type: \"tool_done\",\n tool: event.tool,\n result: truncateBashOutput(\n truncateCodingOutput(event.result, MAX_TOOL_OUTPUT_CHARS),\n ),\n ...(event.mcpApp ? { mcpApp: event.mcpApp } : {}),\n ...(pendingMeta ? { structuredMeta: pendingMeta } : {}),\n },\n });\n return;\n }\n if (event.type === \"error\") {\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: event.error,\n metadata: { type: \"error\", errorCode: event.errorCode },\n });\n }\n };\n\n let loopUsage: AgentLoopUsage | null = null;\n try {\n const systemPrompt = await buildCodeAgentSystemPrompt(cwd, permissionMode);\n const usageResult = await runWithOptionalCodeAgentRequestContext(\n existing,\n () =>\n runAgentLoop({\n engine,\n model,\n systemPrompt,\n tools,\n actions,\n messages,\n send,\n signal: controller.signal,\n maxIterations: DEFAULT_AGENT_MAX_ITERATIONS,\n reasoningEffort,\n }),\n );\n loopUsage = usageResult ?? null;\n // Persist cumulative token totals from this turn into the run record so\n // the UI can display per-run usage statistics.\n if (loopUsage) {\n updateCodeAgentRunRecord(existing.id, (record) => ({\n metadata: {\n tokenUsage: accumulateTokenUsage(\n record.metadata?.tokenUsage,\n loopUsage!,\n ),\n },\n }));\n }\n await outputSmoother.flush();\n if (assistantText.trim()) {\n options.stdout?.write(\"\\n\");\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"system\",\n message: assistantText.trim(),\n metadata: {\n role: \"assistant\",\n model,\n engine: engine.name,\n reasoningEffort,\n },\n });\n }\n const approvalPending = getPendingApproval(existing.id);\n if (approvalPending) {\n const message = `Agent-Native Code run paused for approval: ${approvalPending.reason}`;\n options.stdout?.write(`\\n${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message,\n metadata: {\n status: \"needs-approval\",\n phase: \"approval-required\",\n pendingApprovalId: approvalPending.id,\n },\n });\n return updateCodeAgentRunRecord(existing.id, {\n status: \"needs-approval\",\n phase: \"approval-required\",\n needsApproval: true,\n progress: {\n label: \"Approval required\",\n completed: 0,\n total: 1,\n percent: 50,\n },\n });\n }\n\n const pendingFollowUp = dequeueCodeAgentFollowUp(existing.id);\n if (pendingFollowUp) {\n const message =\n pendingFollowUp.mode === \"queued\"\n ? \"Agent-Native Code run completed; running queued follow-up.\"\n : \"Agent-Native Code run completed; applying steering follow-up.\";\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message,\n metadata: {\n status: \"running\",\n phase: \"follow-up\",\n followUpId: pendingFollowUp.id,\n followUpMode: pendingFollowUp.mode,\n },\n });\n if (pendingFollowUp.permissionMode) {\n updateCodeAgentRunRecord(existing.id, {\n permissionMode: pendingFollowUp.permissionMode,\n });\n }\n return executeCodeAgentRun({\n ...options,\n runId: existing.id,\n prompt: pendingFollowUp.prompt,\n attachments:\n pendingFollowUp.attachments ??\n userPromptAttachmentsForEvent(existing.id, pendingFollowUp.eventId),\n appendUserEvent: false,\n });\n }\n\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: \"Agent-Native Code run completed.\",\n metadata: { status: \"completed\", phase: \"complete\" },\n });\n return updateCodeAgentRunRecord(existing.id, {\n status: \"completed\",\n phase: \"complete\",\n needsApproval: false,\n progress: {\n label: \"Complete\",\n completed: 1,\n total: 1,\n percent: 100,\n },\n metadata: {\n executionCompletedAt: new Date().toISOString(),\n engine: engine.name,\n model,\n reasoningEffort,\n permissionMode,\n },\n });\n } catch (err) {\n await outputSmoother.flush().catch(() => undefined);\n const message = err instanceof Error ? err.message : String(err);\n options.stdout?.write(`\\nAgent-Native Code run failed: ${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: `Agent-Native Code run failed: ${message}`,\n metadata: { status: \"errored\", phase: \"error\" },\n });\n return updateCodeAgentRunRecord(existing.id, {\n status: controller.signal.aborted ? \"paused\" : \"errored\",\n phase: controller.signal.aborted ? \"paused\" : \"error\",\n progress: {\n label: controller.signal.aborted ? \"Paused\" : \"Error\",\n completed: 0,\n total: 1,\n failed: controller.signal.aborted ? 0 : 1,\n percent: 0,\n },\n metadata: {\n executionError: message,\n executionErroredAt: new Date().toISOString(),\n },\n });\n } finally {\n if (thinkingFlushTimer !== undefined) {\n clearTimeout(thinkingFlushTimer);\n flushThinkingEvent();\n }\n outputSmoother.cancel();\n options.signal?.removeEventListener(\"abort\", abortFromParent);\n await mcpManager?.stop().catch(() => undefined);\n void running;\n }\n}\n\nasync function executeCodexCliRun(options: {\n run: CodeAgentRunRecord;\n prompt: string;\n model?: string;\n permissionMode: CodeAgentPermissionMode;\n stdout?: NodeJS.WritableStream;\n signal?: AbortSignal;\n}): Promise<CodeAgentRunRecord | null> {\n const cwd = options.run.cwd || process.cwd();\n const outputDir = fs.mkdtempSync(\n path.join(os.tmpdir(), \"agent-native-code-codex-\"),\n );\n const outputPath = path.join(outputDir, \"last-message.txt\");\n const model = normalizeCodexCliModel(options.model);\n const args = [\n \"exec\",\n \"--cd\",\n cwd,\n \"--color\",\n \"never\",\n \"--skip-git-repo-check\",\n \"--sandbox\",\n codexSandboxForPermissionMode(options.permissionMode),\n \"--ask-for-approval\",\n \"never\",\n \"--output-last-message\",\n outputPath,\n ];\n if (model) args.push(\"--model\", model);\n args.push(\"-\");\n\n appendCodeAgentTranscriptEvent({\n runId: options.run.id,\n kind: \"status\",\n message: \"Starting Codex CLI with local Codex authentication.\",\n metadata: {\n status: \"running\",\n phase: \"executing\",\n engine: CODEX_CLI_ENGINE_NAME,\n },\n });\n\n try {\n const result = await runCodexCliProcess({\n args,\n cwd,\n prompt: buildCodexCliPrompt(options.run, options.prompt),\n stdout: options.stdout,\n signal: options.signal,\n });\n\n if (result.exitCode !== 0) {\n const message =\n result.error ??\n result.stderr.trim() ??\n `Codex CLI exited with ${result.exitSignal ?? result.exitCode}.`;\n options.stdout?.write(`\\nCodex CLI run failed: ${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId: options.run.id,\n kind: \"status\",\n message: `Codex CLI run failed: ${message}`,\n metadata: {\n status: \"errored\",\n phase: \"error\",\n engine: CODEX_CLI_ENGINE_NAME,\n exitCode: result.exitCode,\n exitSignal: result.exitSignal,\n },\n });\n return updateCodeAgentRunRecord(options.run.id, {\n status: options.signal?.aborted ? \"paused\" : \"errored\",\n phase: options.signal?.aborted ? \"paused\" : \"error\",\n progress: {\n label: options.signal?.aborted ? \"Paused\" : \"Error\",\n completed: 0,\n total: 1,\n failed: options.signal?.aborted ? 0 : 1,\n percent: 0,\n },\n metadata: {\n executionError: message,\n executionErroredAt: new Date().toISOString(),\n engine: CODEX_CLI_ENGINE_NAME,\n model: model ?? \"codex-default\",\n },\n });\n }\n\n const finalMessage =\n readCodexLastMessage(outputPath) ||\n result.stdout.trim() ||\n \"Codex CLI run completed.\";\n appendCodeAgentTranscriptEvent({\n runId: options.run.id,\n kind: \"system\",\n message: finalMessage,\n metadata: {\n role: \"assistant\",\n engine: CODEX_CLI_ENGINE_NAME,\n model: model ?? \"codex-default\",\n },\n });\n\n const pendingFollowUp = dequeueCodeAgentFollowUp(options.run.id);\n if (pendingFollowUp) {\n const message =\n pendingFollowUp.mode === \"queued\"\n ? \"Codex CLI run completed; running queued follow-up.\"\n : \"Codex CLI run completed; applying steering follow-up.\";\n appendCodeAgentTranscriptEvent({\n runId: options.run.id,\n kind: \"status\",\n message,\n metadata: {\n status: \"running\",\n phase: \"follow-up\",\n followUpId: pendingFollowUp.id,\n followUpMode: pendingFollowUp.mode,\n engine: CODEX_CLI_ENGINE_NAME,\n },\n });\n if (pendingFollowUp.permissionMode) {\n updateCodeAgentRunRecord(options.run.id, {\n permissionMode: pendingFollowUp.permissionMode,\n });\n }\n return executeCodeAgentRun({\n runId: options.run.id,\n prompt: pendingFollowUp.prompt,\n attachments:\n pendingFollowUp.attachments ??\n userPromptAttachmentsForEvent(\n options.run.id,\n pendingFollowUp.eventId,\n ),\n appendUserEvent: false,\n stdout: options.stdout,\n signal: options.signal,\n });\n }\n\n appendCodeAgentTranscriptEvent({\n runId: options.run.id,\n kind: \"status\",\n message: \"Codex CLI run completed.\",\n metadata: {\n status: \"completed\",\n phase: \"complete\",\n engine: CODEX_CLI_ENGINE_NAME,\n },\n });\n return updateCodeAgentRunRecord(options.run.id, {\n status: \"completed\",\n phase: \"complete\",\n needsApproval: false,\n progress: {\n label: \"Complete\",\n completed: 1,\n total: 1,\n percent: 100,\n },\n metadata: {\n executionCompletedAt: new Date().toISOString(),\n engine: CODEX_CLI_ENGINE_NAME,\n model: model ?? \"codex-default\",\n permissionMode: options.permissionMode,\n },\n });\n } finally {\n fs.rmSync(outputDir, { recursive: true, force: true });\n }\n}\n\nfunction runCodexCliProcess(options: {\n args: string[];\n cwd: string;\n prompt: string;\n stdout?: NodeJS.WritableStream;\n signal?: AbortSignal;\n}): Promise<CodexCliProcessResult> {\n return new Promise((resolve) => {\n let stdout = \"\";\n let stderr = \"\";\n let settled = false;\n const child = spawn(\"codex\", options.args, {\n cwd: options.cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: process.env,\n });\n const finish = (\n result: Omit<CodexCliProcessResult, \"stdout\" | \"stderr\">,\n ) => {\n if (settled) return;\n settled = true;\n options.signal?.removeEventListener(\"abort\", onAbort);\n resolve({ ...result, stdout, stderr });\n };\n const onAbort = () => {\n child.kill(\"SIGTERM\");\n };\n if (options.signal) {\n if (options.signal.aborted) onAbort();\n else options.signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n child.stdout?.on(\"data\", (chunk) => {\n const text = chunk.toString();\n stdout += text;\n options.stdout?.write(text);\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr += chunk.toString();\n });\n child.on(\"error\", (err) => {\n finish({\n exitCode: 1,\n exitSignal: null,\n error:\n (err as NodeJS.ErrnoException).code === \"ENOENT\"\n ? \"Codex CLI was not found. Install Codex and run `codex login`.\"\n : err instanceof Error\n ? err.message\n : String(err),\n });\n });\n child.on(\"exit\", (exitCode, exitSignal) => {\n finish({ exitCode, exitSignal });\n });\n child.stdin?.end(options.prompt);\n });\n}\n\nfunction buildCodexCliPrompt(run: CodeAgentRunRecord, prompt: string): string {\n const permissionMode = run.permissionMode ?? \"full-auto\";\n const mode =\n permissionMode === \"read-only\" || permissionMode === \"ask-before-edit\"\n ? \"Plan\"\n : \"Auto\";\n const modeInstruction =\n mode === \"Plan\"\n ? \"Inspect and explain only. Do not edit files or run mutating commands.\"\n : \"Edit and verify as needed. Do not create, switch, reset, rebase, or stash git branches.\";\n return [\n `You are running from Agent-Native Code in ${run.cwd || process.cwd()}.`,\n \"Follow the repository AGENTS.md and any relevant skill instructions.\",\n `Run mode: ${mode} (${permissionMode}). ${modeInstruction}`,\n \"\",\n \"# User request\",\n prompt,\n ].join(\"\\n\");\n}\n\nfunction codexSandboxForPermissionMode(\n permissionMode: CodeAgentPermissionMode,\n): \"read-only\" | \"workspace-write\" {\n return permissionMode === \"read-only\" || permissionMode === \"ask-before-edit\"\n ? \"read-only\"\n : \"workspace-write\";\n}\n\nfunction normalizeCodexCliModel(model: string | undefined): string | undefined {\n const trimmed = model?.trim();\n if (!trimmed || trimmed === \"auto\" || trimmed === CODEX_CLI_ENGINE_NAME) {\n return undefined;\n }\n return trimmed;\n}\n\nfunction normalizeRequestedEngine(\n engine: string | undefined,\n): string | undefined {\n const trimmed = engine?.trim();\n if (!trimmed || trimmed === \"auto\") return undefined;\n return trimmed;\n}\n\nfunction readCodexLastMessage(filePath: string): string | null {\n try {\n const text = fs.readFileSync(filePath, \"utf-8\").trim();\n return text || null;\n } catch {\n return null;\n }\n}\n\nexport async function executeExistingCodeAgentRun(\n runId: string,\n options: Omit<ExecuteCodeAgentRunOptions, \"runId\"> = {},\n): Promise<CodeAgentRunRecord | null> {\n return executeCodeAgentRun({ ...options, runId, appendUserEvent: false });\n}\n\n/**\n * Add the pending approval command to the per-project allowlist, then approve\n * and auto-resume. Future occurrences of this exact command will bypass the\n * approval gate without prompting.\n */\nexport async function executeApproveAlwaysCodeAgentApproval(\n runId: string,\n options: { stdout?: NodeJS.WritableStream } = {},\n): Promise<CodeAgentRunRecord | null> {\n const approval = getPendingApproval(runId);\n if (approval?.command) {\n addCodeAgentCommandToAllowlist(approval.command);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `Command added to allowlist: ${approval.command}`,\n metadata: { type: \"allowlist-added\", command: approval.command },\n });\n }\n return executePendingCodeAgentApproval(runId, options);\n}\n\nexport async function executePendingCodeAgentApproval(\n runId: string,\n options: { stdout?: NodeJS.WritableStream } = {},\n): Promise<CodeAgentRunRecord | null> {\n const record = getCodeAgentRunRecord(runId);\n if (!record) return null;\n const approval = getPendingApproval(runId);\n if (!approval) {\n options.stdout?.write(\"No pending approval was found for this run.\\n\");\n return record;\n }\n\n const permission = classifyCodeAgentCommandPermission(approval.command);\n if (permission.kind === \"forbidden\") {\n const message = `Approval cannot run forbidden command: ${permission.reason}`;\n options.stdout?.write(`${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message,\n metadata: {\n status: \"needs-approval\",\n phase: \"approval-forbidden\",\n approvalId: approval.id,\n },\n });\n return updateCodeAgentRunRecord(runId, {\n status: \"needs-approval\",\n phase: \"approval-forbidden\",\n needsApproval: true,\n });\n }\n\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `Approved command ${approval.id}; running now.`,\n metadata: {\n status: \"running\",\n phase: \"approval-running\",\n approvalId: approval.id,\n command: approval.command,\n },\n });\n const result = await runCodingCommand(\n approval.command,\n record.cwd || process.cwd(),\n DEFAULT_COMMAND_TIMEOUT_MS,\n );\n const summary = truncateCodingOutput(\n [\n `Approved command finished with exit code ${result.code}.`,\n result.timedOut ? \"Timed out: true\" : \"\",\n result.stdout ? `stdout:\\n${result.stdout}` : \"\",\n result.stderr ? `stderr:\\n${result.stderr}` : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\\n\"),\n MAX_TOOL_OUTPUT_CHARS,\n );\n options.stdout?.write(`${summary}\\n`);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: summary,\n metadata: {\n status: \"running\",\n phase: \"approval-complete\",\n approvalId: approval.id,\n exitCode: result.code,\n timedOut: result.timedOut,\n },\n });\n // Clear the pending approval and immediately auto-resume so the model sees\n // the command result and can continue — no manual \"Resume\" click needed.\n updateCodeAgentRunRecord(runId, {\n status: \"running\",\n phase: \"approval-resuming\",\n needsApproval: false,\n metadata: {\n pendingApproval: undefined,\n lastApproval: {\n ...approval,\n completedAt: new Date().toISOString(),\n exitCode: result.code,\n },\n },\n });\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: \"Resuming run after approval.\",\n metadata: { status: \"running\", phase: \"approval-resuming\" },\n });\n return executeExistingCodeAgentRun(runId, { stdout: options.stdout });\n}\n\n/**\n * Deny a pending approval: record the denial, feed it back to the model as a\n * \"command denied by user\" result, and immediately resume the run so the model\n * can adapt its plan without leaving the run dangling.\n */\nexport async function executeDenyCodeAgentApproval(\n runId: string,\n options: { stdout?: NodeJS.WritableStream } = {},\n): Promise<CodeAgentRunRecord | null> {\n const record = getCodeAgentRunRecord(runId);\n if (!record) return null;\n const approval = getPendingApproval(runId);\n if (!approval) {\n options.stdout?.write(\"No pending approval was found for this run.\\n\");\n return record;\n }\n\n const message = `User denied command: ${approval.command} (${approval.reason})`;\n options.stdout?.write(`${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message,\n metadata: {\n status: \"running\",\n phase: \"approval-denied\",\n approvalId: approval.id,\n command: approval.command,\n },\n });\n updateCodeAgentRunRecord(runId, {\n status: \"running\",\n phase: \"approval-denied-resuming\",\n needsApproval: false,\n metadata: {\n pendingApproval: undefined,\n lastApproval: {\n ...approval,\n deniedAt: new Date().toISOString(),\n denied: true,\n },\n },\n });\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: \"Resuming run after denial — model will adapt its plan.\",\n metadata: { status: \"running\", phase: \"approval-denied-resuming\" },\n });\n return executeExistingCodeAgentRun(runId, { stdout: options.stdout });\n}\n\nfunction latestUserPrompt(runId: string): string {\n const events = listCodeAgentTranscriptEvents(runId);\n for (let i = events.length - 1; i >= 0; i--) {\n const event = events[i];\n if (event.kind === \"user\" && event.message.trim()) return event.message;\n }\n return \"\";\n}\n\nfunction latestUserPromptAttachments(\n runId: string,\n prompt: string,\n): AgentPromptAttachment[] {\n const events = listCodeAgentTranscriptEvents(runId);\n const normalizedPrompt = prompt.trim();\n for (let i = events.length - 1; i >= 0; i--) {\n const event = events[i];\n if (event.kind !== \"user\" || !event.message.trim()) continue;\n if (\n !normalizedPrompt ||\n event.message.trim() === normalizedPrompt ||\n i === events.length - 1\n ) {\n return promptAttachmentsFromMetadata(event.metadata?.attachments);\n }\n }\n return [];\n}\n\nfunction userPromptAttachmentsForEvent(\n runId: string,\n eventId: string | undefined,\n): AgentPromptAttachment[] {\n if (!eventId) return [];\n const event = listCodeAgentTranscriptEvents(runId).find(\n (item) => item.id === eventId && item.kind === \"user\",\n );\n return promptAttachmentsFromMetadata(event?.metadata?.attachments);\n}\n\nfunction promptAttachmentsFromMetadata(\n value: unknown,\n): AgentPromptAttachment[] {\n if (!Array.isArray(value)) return [];\n return value\n .filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === \"object\" && !Array.isArray(item)),\n )\n .map((item) => ({\n name: typeof item.name === \"string\" && item.name ? item.name : \"file\",\n ...(typeof item.type === \"string\" ? { type: item.type } : {}),\n ...(typeof item.size === \"number\" ? { size: item.size } : {}),\n ...(typeof item.text === \"string\" ? { text: item.text } : {}),\n ...(typeof item.dataUrl === \"string\" ? { dataUrl: item.dataUrl } : {}),\n }));\n}\n\nfunction metadataString(\n run: CodeAgentRunRecord,\n key: string,\n): string | undefined {\n const value = run.metadata?.[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nasync function startCodeAgentMcpManager(\n runId: string,\n): Promise<McpClientManager | null> {\n const config = await buildMergedConfig().catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `MCP tools unavailable: ${message}`,\n metadata: { type: \"mcp-config-error\" },\n });\n return null;\n });\n if (!config || Object.keys(config.servers ?? {}).length === 0) return null;\n\n const manager = new McpClientManager(config);\n await manager.start().catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `MCP tools failed to start: ${message}`,\n metadata: { type: \"mcp-start-error\" },\n });\n });\n const status = manager.getStatus();\n if (status.totalTools === 0) {\n await manager.stop().catch(() => undefined);\n return null;\n }\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `Connected ${status.totalTools} MCP tool${status.totalTools === 1 ? \"\" : \"s\"} for this run.`,\n metadata: {\n type: \"mcp-tools-connected\",\n servers: status.connectedServers,\n toolCount: status.totalTools,\n },\n });\n return manager;\n}\n\nfunction runWithOptionalCodeAgentRequestContext<T>(\n run: CodeAgentRunRecord,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n const userEmail =\n metadataString(run, \"ownerEmail\") ??\n metadataString(run, \"userEmail\") ??\n process.env.AGENT_USER_EMAIL;\n const orgId = metadataString(run, \"orgId\") ?? process.env.AGENT_ORG_ID;\n if (!userEmail && !orgId) return fn();\n return runWithRequestContext({ userEmail, orgId }, fn);\n}\n\nfunction metadataReasoningEffort(\n run: CodeAgentRunRecord,\n): ReasoningEffort | undefined {\n const value = run.metadata?.reasoningEffort ?? run.metadata?.effort;\n return isReasoningEffort(value) && value !== \"auto\" ? value : undefined;\n}\n\nasync function resolveExecutorEngine(\n requestedEngine?: string,\n): Promise<AgentEngine | null> {\n const fakeText = process.env.AGENT_NATIVE_CODE_AGENT_FAKE_RESPONSE;\n if (fakeText !== undefined) {\n return createFakeCodeAgentEngine(fakeText || \"Done.\");\n }\n registerBuiltinEngines();\n if (!hasAnyProviderCredential()) return null;\n return resolveEngine({\n engineOption: requestedEngine ?? process.env.AGENT_ENGINE,\n });\n}\n\nfunction hasAnyProviderCredential(): boolean {\n if (process.env.AGENT_ENGINE) return true;\n if (PROVIDER_ENV_VARS.some((key) => Boolean(process.env[key]))) return true;\n return Boolean(\n process.env.BUILDER_PRIVATE_KEY && process.env.BUILDER_PUBLIC_KEY,\n );\n}\n\nfunction createFakeCodeAgentEngine(text: string): AgentEngine {\n return {\n name: \"fake-code-agent\",\n label: \"Fake Agent-Native Code\",\n defaultModel: \"fake-code-agent\",\n supportedModels: [\"fake-code-agent\"],\n capabilities: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: false,\n },\n async *stream(_opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n yield { type: \"text-delta\", text };\n yield {\n type: \"assistant-content\",\n parts: [{ type: \"text\", text }],\n };\n yield {\n type: \"usage\",\n inputTokens: 1,\n outputTokens: 1,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n };\n yield { type: \"stop\", reason: \"end_turn\" };\n },\n };\n}\n\nconst SUPPORTED_IMAGE_MEDIA_TYPES = new Set([\n \"image/jpeg\",\n \"image/jpg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n]);\n\nfunction buildCodeAgentMessages(\n run: CodeAgentRunRecord,\n prompt: string,\n attachments?: AgentPromptAttachment[],\n): EngineMessage[] {\n const allEvents = listCodeAgentTranscriptEvents(run.id);\n\n // Split events into an \"older\" prefix (summarised) and a \"recent\" tail\n // (reconstructed as native structured messages).\n const splitAt = Math.max(\n 0,\n allEvents.length - STRUCTURED_HISTORY_RECENT_EVENTS,\n );\n const olderEvents = allEvents.slice(0, splitAt);\n const recentEvents = allEvents.slice(splitAt);\n\n // Build a compact text preamble from any events that pre-date the recent\n // window. Reuses the old flat-text approach so the model still has broad\n // context without paying for full token cost on every old tool result.\n let preamble = \"\";\n if (olderEvents.length > 0) {\n const summaryLines = olderEvents\n .filter(\n (e) =>\n e.kind === \"user\" ||\n (e.kind === \"system\" && e.metadata?.role === \"assistant\") ||\n (e.kind === \"status\" &&\n (e.metadata?.type === \"tool_done\" ||\n e.metadata?.role === \"assistant\")),\n )\n .map((e) => {\n if (e.kind === \"user\") return `User: ${e.message}`;\n if (e.metadata?.role === \"assistant\") return `Assistant: ${e.message}`;\n if (e.metadata?.type === \"tool_done\") {\n const tool = e.metadata?.tool;\n const result = e.metadata?.result;\n const resultText =\n typeof result === \"string\"\n ? truncateCodingOutput(result, 500)\n : result != null\n ? truncateCodingOutput(String(result), 500)\n : \"\";\n return tool ? `Tool[${tool}]: ${resultText}` : `Tool: ${resultText}`;\n }\n return null;\n })\n .filter((line): line is string => line !== null);\n if (summaryLines.length > 0) {\n preamble = `Earlier conversation summary:\\n${summaryLines.join(\"\\n\")}`;\n }\n }\n\n // Reconstruct the recent events as native EngineMessage objects.\n // We build up a sequence of user/assistant messages, pairing tool-call\n // events (from tool_start metadata) with their matching tool-result events\n // (from tool_done metadata), and accumulating assistant text from system\n // events with role=assistant.\n const structuredMessages = buildStructuredMessagesFromEvents(recentEvents);\n\n // Separate image attachments from text attachments. Images are passed as\n // proper EngineImagePart entries rather than inlined base64 text (which\n // would consume ~700K tokens per megabyte of image data).\n const imageParts: import(\"../agent/engine/types.js\").EngineImagePart[] = [];\n const unsupportedImageNotes: string[] = [];\n\n for (const att of attachments ?? []) {\n if (!att.dataUrl) continue;\n const match = att.dataUrl.match(/^data:(image\\/[^;]+);base64,(.+)$/);\n if (!match) continue;\n const mime = match[1].toLowerCase();\n if (SUPPORTED_IMAGE_MEDIA_TYPES.has(mime)) {\n imageParts.push({\n type: \"image\",\n data: match[2],\n mediaType:\n mime as import(\"../agent/engine/types.js\").EngineImagePart[\"mediaType\"],\n });\n } else {\n // Unsupported format — inject a note so the model understands what happened.\n const label = att.name ? `\"${att.name}\"` : \"An image\";\n unsupportedImageNotes.push(\n `[${label} could not be processed — unsupported image format (${mime}). ` +\n `Only JPEG, PNG, GIF, and WebP are supported.]`,\n );\n }\n }\n\n const notesBlock =\n unsupportedImageNotes.length > 0\n ? `\\n\\n${unsupportedImageNotes.join(\"\\n\")}`\n : \"\";\n\n // The current prompt (plus optional preamble) becomes the final user message.\n const promptText = [preamble, prompt, notesBlock]\n .filter(Boolean)\n .join(\"\\n\\n\");\n\n const promptContent: import(\"../agent/engine/types.js\").EngineContentPart[] =\n [...imageParts, { type: \"text\", text: promptText }];\n\n // If there are structured messages from the recent window and the last one\n // is a user message that already contains the current prompt (happens when\n // appendUserEvent added a \"user\" event that got included), de-duplicate by\n // using the structured messages as-is but replacing the last user message's\n // content with the enriched content (images + prompt).\n if (structuredMessages.length > 0) {\n const lastMsg = structuredMessages[structuredMessages.length - 1];\n if (lastMsg.role === \"user\") {\n // Replace last user message content with the enriched prompt content.\n structuredMessages[structuredMessages.length - 1] = {\n role: \"user\",\n content: promptContent,\n };\n return structuredMessages;\n }\n // Last message is assistant — append a new user message.\n return [...structuredMessages, { role: \"user\", content: promptContent }];\n }\n\n return [{ role: \"user\", content: promptContent }];\n}\n\n/**\n * Reconstruct a sequence of EngineMessage objects from transcript events,\n * preserving the native tool-call / tool-result pair structure that models\n * expect when replaying multi-turn conversations.\n *\n * Event mapping:\n * kind=user → user message with text content\n * kind=system, role=assistant → assistant message with text content\n * kind=status, type=tool_start → assistant message with a tool-call part\n * (grouped with any preceding assistant text)\n * kind=status, type=tool_done → user message with a tool-result part\n * kind=status, type=thinking → excluded (ephemeral reasoning)\n * everything else → excluded from model history\n *\n * Each tool_start generates a synthetic toolCallId derived from the event id so\n * that the matching tool_done can reference it. Old events that lack tool/input\n * metadata fall back gracefully to text content.\n */\n/** @internal exported for unit tests */\nexport function buildStructuredMessagesFromEvents(\n events: readonly import(\"./code-agent-runs.js\").CodeAgentTranscriptEvent[],\n): EngineMessage[] {\n // We accumulate into a flat list and then merge adjacent same-role messages.\n type PendingMessage =\n | {\n role: \"user\";\n content: import(\"../agent/engine/types.js\").EngineContentPart[];\n }\n | {\n role: \"assistant\";\n content: import(\"../agent/engine/types.js\").EngineContentPart[];\n };\n\n const pending: PendingMessage[] = [];\n\n // Track in-flight tool-call IDs keyed by event id so tool_done can\n // reference the corresponding call.\n const toolCallIdByEventOrder = new Map<string, string>();\n\n for (const event of events) {\n // Exclude thinking — ephemeral reasoning, never replayed to model.\n if (event.kind === \"status\" && event.metadata?.type === \"thinking\") {\n continue;\n }\n\n if (event.kind === \"user\") {\n const text = event.message.trim();\n if (!text) continue;\n appendOrMerge(pending, \"user\", { type: \"text\", text });\n continue;\n }\n\n // Assistant text (persisted after a turn completes).\n if (event.kind === \"system\" && event.metadata?.role === \"assistant\") {\n const text = event.message.trim();\n if (!text) continue;\n appendOrMerge(pending, \"assistant\", { type: \"text\", text });\n continue;\n }\n\n // Tool call start — emit an assistant tool-call part.\n if (event.kind === \"status\" && event.metadata?.type === \"tool_start\") {\n const tool =\n typeof event.metadata?.tool === \"string\" && event.metadata.tool\n ? event.metadata.tool\n : null;\n if (!tool) continue;\n\n // Generate a stable ID from the event id so tool_done can reference it.\n const toolCallId = `tc-${event.id}`;\n toolCallIdByEventOrder.set(event.id, toolCallId);\n\n const input: unknown =\n event.metadata?.input != null ? event.metadata.input : {};\n\n appendOrMerge(pending, \"assistant\", {\n type: \"tool-call\",\n id: toolCallId,\n name: tool,\n input,\n });\n continue;\n }\n\n // Tool result — emit a user tool-result part paired with the last\n // unmatched tool_start for the same tool name.\n if (event.kind === \"status\" && event.metadata?.type === \"tool_done\") {\n const tool =\n typeof event.metadata?.tool === \"string\" && event.metadata.tool\n ? event.metadata.tool\n : null;\n if (!tool) continue;\n\n // Find the most recent tool_start event id for this tool.\n const matchedCallId = findMatchingToolCallId(\n toolCallIdByEventOrder,\n events,\n event,\n tool,\n );\n\n const rawResult = event.metadata?.result;\n const resultText = truncateCodingOutput(\n typeof rawResult === \"string\"\n ? rawResult\n : rawResult != null\n ? String(rawResult)\n : \"(no output)\",\n STRUCTURED_HISTORY_RESULT_CAP,\n );\n\n if (matchedCallId) {\n const toolInput =\n event.metadata?.input != null\n ? safeJsonStringify(event.metadata.input)\n : \"{}\";\n appendOrMerge(pending, \"user\", {\n type: \"tool-result\",\n toolCallId: matchedCallId,\n toolName: tool,\n toolInput,\n content: resultText,\n });\n } else {\n // Orphaned tool result (no matching call in the recent window) — fall\n // back to plain text so the model still sees the output.\n appendOrMerge(pending, \"user\", {\n type: \"text\",\n text: `[Tool result for ${tool}]: ${resultText}`,\n });\n }\n continue;\n }\n }\n\n return pending;\n}\n\n/**\n * Append a content part to the last message if it has the same role, or\n * start a new message otherwise.\n */\nfunction appendOrMerge(\n pending: Array<{\n role: \"user\" | \"assistant\";\n content: import(\"../agent/engine/types.js\").EngineContentPart[];\n }>,\n role: \"user\" | \"assistant\",\n part: import(\"../agent/engine/types.js\").EngineContentPart,\n): void {\n const last = pending[pending.length - 1];\n if (last && last.role === role) {\n last.content.push(part);\n } else {\n pending.push({ role, content: [part] });\n }\n}\n\n/**\n * Find the toolCallId generated for the most recent tool_start event that\n * matches the given tool name and precedes the current tool_done event.\n * Returns null if no match exists in the recent window.\n */\nfunction findMatchingToolCallId(\n toolCallIdByEventOrder: Map<string, string>,\n events: readonly import(\"./code-agent-runs.js\").CodeAgentTranscriptEvent[],\n doneEvent: import(\"./code-agent-runs.js\").CodeAgentTranscriptEvent,\n toolName: string,\n): string | null {\n // Walk backwards from doneEvent's position to find the nearest unmatched start.\n const doneIndex = events.indexOf(doneEvent);\n for (let i = doneIndex - 1; i >= 0; i--) {\n const e = events[i];\n if (\n e.kind === \"status\" &&\n e.metadata?.type === \"tool_start\" &&\n e.metadata?.tool === toolName\n ) {\n const id = toolCallIdByEventOrder.get(e.id);\n if (id) {\n // Consume it so a second done for the same tool gets the next start.\n toolCallIdByEventOrder.delete(e.id);\n return id;\n }\n }\n }\n return null;\n}\n\nfunction safeJsonStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? \"{}\";\n } catch {\n return \"{}\";\n }\n}\n\n/**\n * Maximum character length for inlined AGENTS.md content in the system prompt.\n * Content beyond this cap is truncated with a note so the model knows more exists.\n */\nconst AGENTS_MD_INLINE_CAP = 16_000;\n\n/**\n * Build the coding agent system prompt, inlining AGENTS.md (or CLAUDE.md as\n * fallback) and a skills index from .agents/skills/ into the prompt so the\n * coding agent has the same repo-context awareness that Claude Code / Codex\n * provide when running locally.\n *\n * The bundle is read synchronously from the filesystem via `readAgentsBundleFromFs`\n * (same function used by the Vite build-time plugin) so there is no async I/O\n * on the hot path — the call is cheap and the result is used once per run leg.\n */\n/** @internal exported for unit tests */\nexport async function buildCodeAgentSystemPrompt(\n cwd: string,\n permissionMode: CodeAgentPermissionMode,\n): Promise<string> {\n const bundle = readAgentsBundleFromFs(cwd);\n\n // If the bundle has no AGENTS.md, try CLAUDE.md as a fallback — many repos\n // use that name for agent instructions (e.g. Claude Code projects).\n let agentsMdContent = bundle.agentsMd;\n if (!agentsMdContent.trim()) {\n try {\n const fs = await import(\"node:fs\");\n const path = await import(\"node:path\");\n const claudeMdPath = path.join(cwd, \"CLAUDE.md\");\n if (fs.existsSync(claudeMdPath)) {\n agentsMdContent = fs.readFileSync(claudeMdPath, \"utf-8\");\n }\n } catch {\n // Not readable — skip\n }\n }\n\n const repoInstructionsBlock = buildRepoInstructionsBlock(agentsMdContent);\n const skillsBlock = generateSkillsPromptBlock(bundle);\n\n return codeAgentSystemPrompt(\n cwd,\n permissionMode,\n repoInstructionsBlock,\n skillsBlock,\n );\n}\n\n/** @internal exported for unit tests */\nexport function buildRepoInstructionsBlock(agentsMdContent: string): string {\n if (!agentsMdContent.trim()) return \"\";\n\n const needsTruncation = agentsMdContent.length > AGENTS_MD_INLINE_CAP;\n const truncated = needsTruncation\n ? agentsMdContent.slice(0, AGENTS_MD_INLINE_CAP)\n : agentsMdContent;\n const truncationNote = needsTruncation\n ? `\\n\\n[Note: AGENTS.md was truncated to ${AGENTS_MD_INLINE_CAP} characters. Read the full file for complete instructions.]`\n : \"\";\n\n return `## Repository instructions\n\n${truncated}${truncationNote}`;\n}\n\n/** @internal exported for unit tests */\nexport function codeAgentSystemPrompt(\n cwd: string,\n permissionMode: CodeAgentPermissionMode,\n repoInstructionsBlock = \"\",\n skillsBlock = \"\",\n): string {\n const mode = permissionMode === \"read-only\" ? \"Plan\" : \"Auto\";\n const repoSection = repoInstructionsBlock\n ? `\\n\\n${repoInstructionsBlock}`\n : \"\";\n const skillsSection = skillsBlock ? `\\n\\n${skillsBlock}` : \"\";\n return `You are Agent-Native Code, a coding agent running in ${cwd}. You and the user share one workspace, and your job is to collaborate with them until their goal is genuinely handled.\n\n# General\n\nYou bring a senior engineer's judgment to the work, but you let it arrive through attention rather than premature certainty. Read the codebase first, resist easy assumptions, and let the shape of the existing system teach you how to move.\n\n- When you search for text or files, reach first for \\`rg\\` or \\`rg --files\\`; they are much faster than \\`grep\\` or \\`find\\`. If \\`rg\\` is unavailable, use the next best tool without fuss.\n- Parallelize independent read-only work (file reads, searches) so you gather context quickly. Keep mutating steps ordered.\n- Read relevant files before editing them. Do not edit a file you have not actually read.\n\n# Engineering judgment\n\nWhen the user leaves implementation details open, choose conservatively and in sympathy with the codebase already in front of you:\n\n- Prefer the repo's existing patterns, frameworks, and local helper APIs over inventing a new abstraction.\n- For structured data, use structured APIs or parsers instead of ad hoc string manipulation when the toolchain gives you a reasonable option.\n- Keep edits closely scoped to what the request and surrounding code imply. Leave unrelated refactors and metadata churn alone unless they are truly needed to finish safely.\n- Add an abstraction only when it removes real complexity, reduces meaningful duplication, or clearly matches an established local pattern.\n- Let test coverage scale with risk and blast radius: focused for narrow changes, broader when you touch shared behavior or cross-module contracts.\n\n# Run mode\n\nCurrent run mode: ${mode} mode (${permissionMode}).\n- In Plan mode, inspect and explain only — do not edit files or run mutating commands.\n- In Auto mode, edit files and run ordinary project commands without pausing. Pause only for genuinely destructive operations: recursive deletes, package publishing, privileged commands, destructive database operations, or forbidden git branch/reset/stash/rebase operations.\n\n# Editing constraints\n\n- Use the shared coding tools: \\`bash\\` for search/list/test/build/git-status commands, \\`read\\` for file reads, \\`edit\\` for exact-match replacements, and \\`write\\` only for new files or an intentional full rewrite. Prefer \\`edit\\` over \\`write\\` for existing files.\n- Default to ASCII when editing or creating files; introduce non-ASCII only when the file already uses it or there is a clear reason.\n- Add succinct comments only where the code is not self-explanatory. Avoid empty narration like \"assign the value\"; a short orienting comment before a complex block is fine, used sparingly.\n- You may be in a dirty git worktree. NEVER revert or overwrite changes you did not make — assume they came from the user or another concurrent agent. If unrelated changes exist, ignore them; if they touch your task, work *with* them rather than undoing them. Only stop and ask if they make the task impossible.\n- If you notice unexpected changes appearing mid-task that you did not make, STOP and ask the user how to proceed rather than guessing.\n- Do not create, switch, delete, reset, rebase, or stash git branches. Never run destructive git commands (\\`git reset --hard\\`, \\`git checkout --\\`, \\`git clean\\`) unless the user explicitly asked for that exact operation.\n\n# Autonomy and verification\n\n- Stay with the work until the task is handled end to end within this turn whenever feasible. Don't stop at analysis or a proposal — implement the fix, and work through blockers yourself before handing them back. The exception is Plan mode, where you propose only.\n- Done means verified, not generated. After code changes (not docs-only), run the repo's checks before reporting success: \\`pnpm run prep\\` (format + typecheck + test + guards), or a focused subset like \\`pnpm typecheck\\` or a single package's tests for a small change. Fix all errors before you call it done.\n- Do not claim a change works, tests pass, or a build succeeds unless you actually ran it and saw the result. If you could not verify something, say exactly what is unverified and why.\n\n# Tools beyond the basics\n\n- Use \\`tool-search\\` when you need a capability that may come from MCP, including browser automation or computer control.\n- Prefer Playwright MCP for deterministic browser testing; prefer Chrome DevTools MCP when the user needs their live logged-in Chrome session.\n- Only use computer-control MCP tools when they are explicitly available and the request warrants controlling the local computer.\n\n# Final answer\n\n- Keep it concise and high-signal — plain, idiomatic engineering prose, not a mechanical report. Lead with the outcome. For a small change, one or two short paragraphs plus a verification line is usually right; reserve bullet lists for genuinely multi-part results.\n- Reference files as clickable paths (e.g. \\`packages/core/src/foo.ts\\`), with a line number when it helps. Do not paste large file contents back — the user shares this machine and can open them.\n- State what you changed, and show evidence you verified it: name the check you ran (e.g. \\`pnpm typecheck\\`) and its key result, not just a claim that it passed. If you could not run something, say so plainly.\n- No emojis or em dashes unless the user used them first.\n- AGENTS.md files take precedence over these defaults on conflict. More deeply nested AGENTS.md files take precedence over shallower ones — check for them in directories you work in.${repoSection}${skillsSection}`;\n}\n\nfunction createLocalCodeAgentActions(\n cwd: string,\n permissionMode: CodeAgentPermissionMode,\n runId: string,\n onToolMetadata?: (\n toolName: string,\n phase: \"start\" | \"done\",\n meta: StructuredToolMetadata,\n ) => void,\n onBashOutputChunk?: (chunk: string) => void,\n): Record<string, ActionEntry> {\n const actions = createCodingToolRegistry({\n cwd,\n restrictToCwd: true,\n commandTimeoutMs: DEFAULT_COMMAND_TIMEOUT_MS,\n maxOutputChars: MAX_TOOL_OUTPUT_CHARS,\n maxFileReadChars: MAX_FILE_READ_CHARS,\n canWrite: (toolName) => permissionErrorForWrite(permissionMode, toolName),\n onToolMetadata,\n onBashOutputChunk,\n beforeBash: ({ command }) => {\n const permission = classifyCodeAgentCommandPermission(command);\n if (permission.kind === \"forbidden\") {\n return `Error: command is blocked by Agent-Native Code policy: ${permission.reason}`;\n }\n if (permission.kind !== \"read\") {\n const permissionError = permissionErrorForWrite(permissionMode, \"bash\");\n if (permissionError) return permissionError;\n }\n if (permission.kind === \"approval-required\") {\n // Skip the approval gate when the user has allowlisted this command.\n if (isCodeAgentCommandAllowed(command)) return null;\n const approval = requestCodeAgentApproval(runId, {\n tool: \"bash\",\n command,\n reason: permission.reason,\n permissionMode,\n });\n return [\n `Approval required before running this command: ${permission.reason}.`,\n `Approval id: ${approval.id}`,\n `Command: ${command}`,\n \"The run is paused; approve from the Agent-Native Code UI/CLI if this command is intentional.\",\n ].join(\"\\n\");\n }\n return null;\n },\n });\n if (permissionMode === \"read-only\") {\n return {\n bash: actions.bash,\n read: actions.read,\n };\n }\n return actions;\n}\n\nexport type CodeAgentCommandPermission =\n | { kind: \"read\" }\n | { kind: \"write\" }\n | { kind: \"approval-required\"; reason: string }\n | { kind: \"forbidden\"; reason: string };\n\nexport function classifyCodeAgentCommandPermission(\n command: string,\n): CodeAgentCommandPermission {\n const normalized = command.trim().toLowerCase();\n if (!normalized) return { kind: \"read\" };\n\n const blockedPatterns: Array<[RegExp, string]> = [\n [\n /\\bgit\\s+(checkout|switch|reset|rebase|stash|clean|worktree)\\b/,\n \"forbidden git branch/reset/stash/rebase operation\",\n ],\n [\n /\\bgit\\s+branch\\b(?!\\s+--show-current\\b)/,\n \"forbidden git branch operation\",\n ],\n [/\\bdrizzle-kit\\s+push\\b/, \"drizzle-kit push is not allowed\"],\n ];\n for (const [pattern, reason] of blockedPatterns) {\n if (pattern.test(normalized)) return { kind: \"forbidden\", reason };\n }\n\n const approvalPatterns: Array<[RegExp, string]> = [\n [/\\brm\\s+-rf\\b/, \"destructive recursive delete\"],\n [/\\bsudo\\b/, \"privileged command\"],\n [/\\bkill\\s+-9\\b/, \"force-kill command\"],\n [/\\bcurl\\b.*\\|\\s*(sh|bash|zsh)\\b/, \"remote script execution\"],\n [/\\b(wget|fetch)\\b.*\\|\\s*(sh|bash|zsh)\\b/, \"remote script execution\"],\n [/\\bnpm\\s+publish\\b/, \"package publish\"],\n [/\\bpnpm\\s+publish\\b/, \"package publish\"],\n [/\\btruncate\\b/, \"destructive data command\"],\n [/\\bdrop\\s+(table|column|database)\\b/, \"destructive database command\"],\n [/\\bdelete\\s+from\\b(?![\\s\\S]*\\bwhere\\b)/, \"unscoped delete command\"],\n ];\n for (const [pattern, reason] of approvalPatterns) {\n if (pattern.test(normalized)) {\n return { kind: \"approval-required\", reason };\n }\n }\n\n if (isReadOnlyShellCommand(command)) {\n return { kind: \"read\" };\n }\n\n const writePatterns = [\n /(^|[^>])>(?!>)/,\n />>/,\n /\\btee\\b/,\n /\\bapply_patch\\b/,\n /\\b(write|touch|mkdir|cp|mv|rm|chmod|chown)\\b/,\n /\\bpnpm\\s+(add|install|remove|dlx)\\b/,\n /\\bnpm\\s+(install|i|add|remove|uninstall)\\b/,\n ];\n if (writePatterns.some((pattern) => pattern.test(normalized))) {\n return { kind: \"write\" };\n }\n\n return { kind: \"write\" };\n}\n\nfunction permissionErrorForWrite(\n permissionMode: CodeAgentPermissionMode,\n toolName: string,\n): string | null {\n if (\n permissionMode === \"ask-before-edit\" ||\n permissionMode === \"auto-edit\" ||\n permissionMode === \"full-auto\"\n ) {\n return null;\n }\n if (permissionMode === \"read-only\") {\n return `Error: ${toolName} is unavailable in read-only mode.`;\n }\n return `Error: ${toolName} is blocked by the current run mode.`;\n}\n\nfunction requestCodeAgentApproval(\n runId: string,\n input: Omit<PendingCodeAgentApproval, \"id\" | \"requestedAt\">,\n): PendingCodeAgentApproval {\n const requestedAt = new Date().toISOString();\n const approval: PendingCodeAgentApproval = {\n id: `approval-${requestedAt.replace(/\\D/g, \"\").slice(0, 14)}`,\n requestedAt,\n ...input,\n };\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `Approval required: ${approval.reason}`,\n metadata: {\n status: \"needs-approval\",\n phase: \"approval-required\",\n pendingApproval: approval,\n },\n });\n updateCodeAgentRunRecord(runId, {\n status: \"needs-approval\",\n phase: \"approval-required\",\n needsApproval: true,\n progress: {\n label: \"Approval required\",\n completed: 0,\n total: 1,\n percent: 50,\n },\n metadata: {\n pendingApproval: approval,\n },\n });\n return approval;\n}\n\nfunction getPendingApproval(runId: string): PendingCodeAgentApproval | null {\n const record = getCodeAgentRunRecord(runId);\n const approval = record?.metadata?.pendingApproval;\n if (!approval || typeof approval !== \"object\") return null;\n const candidate = approval as Record<string, unknown>;\n const tool =\n candidate.tool === \"bash\" || candidate.tool === \"run_command\"\n ? candidate.tool\n : null;\n if (\n !tool ||\n typeof candidate.command !== \"string\" ||\n typeof candidate.reason !== \"string\" ||\n typeof candidate.id !== \"string\" ||\n typeof candidate.requestedAt !== \"string\"\n ) {\n return null;\n }\n return {\n id: candidate.id,\n tool,\n command: candidate.command,\n reason: candidate.reason,\n requestedAt: candidate.requestedAt,\n permissionMode:\n candidate.permissionMode === \"read-only\" ||\n candidate.permissionMode === \"ask-before-edit\" ||\n candidate.permissionMode === \"auto-edit\" ||\n candidate.permissionMode === \"full-auto\"\n ? candidate.permissionMode\n : \"full-auto\",\n };\n}\n\n// --------------- Token usage accumulator ---------------\n\ninterface StoredTokenUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n}\n\nfunction accumulateTokenUsage(\n existing: unknown,\n next: AgentLoopUsage,\n): StoredTokenUsage {\n const prev =\n existing && typeof existing === \"object\" && !Array.isArray(existing)\n ? (existing as Partial<StoredTokenUsage>)\n : {};\n return {\n inputTokens: (prev.inputTokens ?? 0) + next.inputTokens,\n outputTokens: (prev.outputTokens ?? 0) + next.outputTokens,\n cacheReadTokens: (prev.cacheReadTokens ?? 0) + next.cacheReadTokens,\n cacheWriteTokens: (prev.cacheWriteTokens ?? 0) + next.cacheWriteTokens,\n };\n}\n"]}
1
+ {"version":3,"file":"code-agent-executor.js","sourceRoot":"","sources":["../../src/cli/code-agent-executor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,wBAAwB,EACxB,sBAAsB,EACtB,gBAAgB,EAChB,kBAAkB,EAClB,oBAAoB,GAErB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EACL,oBAAoB,EACpB,YAAY,GAGb,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,aAAa,EACb,uBAAuB,EACvB,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAQlC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;AACzE,OAAO,EAAE,4BAA4B,EAAE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;IACT,OAAO;QACL,WAAW,EAAE,CAAC,IAAI,CAAC,WAAW,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,WAAW;QACvD,YAAY,EAAE,CAAC,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,YAAY;QAC1D,eAAe,EAAE,CAAC,IAAI,CAAC,eAAe,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,eAAe;QACnE,gBAAgB,EAAE,CAAC,IAAI,CAAC,gBAAgB,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,gBAAgB;KACvE,CAAC;AACJ,CAAC","sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nimport {\n createToolSearchEntry,\n TOOL_SEARCH_ACTION_NAME,\n} from \"../agent/tool-search.js\";\nimport {\n createCodingToolRegistry,\n isReadOnlyShellCommand,\n runCodingCommand,\n truncateBashOutput,\n truncateCodingOutput,\n type StructuredToolMetadata,\n} from \"../coding-tools/index.js\";\nimport {\n buildMergedConfig,\n McpClientManager,\n mcpToolsToActionEntries,\n} from \"../mcp-client/index.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport {\n actionsToEngineTools,\n runAgentLoop,\n type ActionEntry,\n type AgentLoopUsage,\n} from \"../agent/production-agent.js\";\nimport {\n resolveEngine,\n getStoredModelForEngine,\n normalizeModelForEngine,\n registerBuiltinEngines,\n} from \"../agent/engine/index.js\";\nimport type {\n AgentEngine,\n EngineEvent,\n EngineMessage,\n EngineStreamOptions,\n} from \"../agent/engine/types.js\";\nimport type { AgentChatEvent } from \"../agent/types.js\";\nimport { PROVIDER_ENV_VARS } from \"../agent/engine/provider-env-vars.js\";\nimport { DEFAULT_AGENT_MAX_ITERATIONS } from \"../agent/loop-settings.js\";\nimport {\n readAgentsBundleFromFs,\n generateSkillsPromptBlock,\n} from \"../server/agents-bundle.js\";\nimport {\n isReasoningEffort,\n type ReasoningEffort,\n} from \"../shared/reasoning-effort.js\";\nimport {\n formatPromptWithAttachments,\n type AgentPromptAttachment,\n} from \"../code-agents/prompt-attachments.js\";\nimport {\n addCodeAgentCommandToAllowlist,\n appendCodeAgentTranscriptEvent,\n dequeueCodeAgentFollowUp,\n getCodeAgentRunRecord,\n isCodeAgentCommandAllowed,\n listCodeAgentTranscriptEvents,\n updateCodeAgentRunRecord,\n type CodeAgentPermissionMode,\n type CodeAgentRunRecord,\n} from \"./code-agent-runs.js\";\nimport { createCodeAgentOutputSmoother } from \"./code-agent-output-smoother.js\";\n\nexport interface ExecuteCodeAgentRunOptions {\n runId: string;\n prompt?: string;\n appendUserEvent?: boolean;\n engine?: AgentEngine;\n model?: string;\n reasoningEffort?: ReasoningEffort;\n attachments?: AgentPromptAttachment[];\n stdout?: NodeJS.WritableStream;\n signal?: AbortSignal;\n}\n\ninterface PendingCodeAgentApproval {\n id: string;\n tool: \"bash\" | \"run_command\";\n command: string;\n reason: string;\n requestedAt: string;\n permissionMode: CodeAgentPermissionMode;\n}\n\ninterface CodexCliProcessResult {\n exitCode: number | null;\n exitSignal: NodeJS.Signals | null;\n stdout: string;\n stderr: string;\n error?: string;\n}\n\nconst DEFAULT_COMMAND_TIMEOUT_MS = 120_000;\nconst MAX_TOOL_OUTPUT_CHARS = 50_000;\nconst MAX_FILE_READ_CHARS = 120_000;\nconst CODEX_CLI_ENGINE_NAME = \"codex-cli\";\n\n/**\n * Number of most-recent transcript events reconstructed as native\n * EngineMessage objects (with proper tool-call / tool-result pairing).\n * Events older than this cap are summarised into a single compact text\n * preamble so the model retains broad context without token waste.\n */\nconst STRUCTURED_HISTORY_RECENT_EVENTS = 40;\n\n/**\n * Per-tool-result text cap when reconstructing history. Matches the overall\n * tool-output cap so old results don't balloon the context.\n */\nconst STRUCTURED_HISTORY_RESULT_CAP = MAX_TOOL_OUTPUT_CHARS;\n\nexport async function executeCodeAgentRun(\n options: ExecuteCodeAgentRunOptions,\n): Promise<CodeAgentRunRecord | null> {\n const existing = getCodeAgentRunRecord(options.runId);\n if (!existing) return null;\n\n const prompt = options.prompt ?? latestUserPrompt(existing.id);\n const rawAttachments =\n options.attachments ?? latestUserPromptAttachments(existing.id, prompt);\n\n // Split attachments: images (dataUrl) go as engine image parts; text/file\n // attachments are still inlined into the prompt text. This prevents 2 MB\n // images from consuming ~700 K tokens of garbage when treated as plain text.\n const imageAttachments = rawAttachments.filter((a) => a.dataUrl);\n const textOnlyAttachments = rawAttachments.filter((a) => !a.dataUrl);\n const executionPrompt = formatPromptWithAttachments(\n prompt,\n textOnlyAttachments,\n );\n if (!prompt) {\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: \"No prompt was found for this Agent-Native Code run.\",\n metadata: { status: \"errored\", phase: \"missing-prompt\" },\n });\n return updateCodeAgentRunRecord(existing.id, {\n status: \"errored\",\n phase: \"missing-prompt\",\n progress: {\n label: \"Missing prompt\",\n completed: 0,\n total: 1,\n failed: 1,\n percent: 0,\n },\n });\n }\n\n if (options.appendUserEvent !== false) {\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"user\",\n message: prompt,\n metadata: { source: \"execution-prompt\" },\n });\n }\n\n const running = updateCodeAgentRunRecord(existing.id, {\n status: \"running\",\n phase: \"executing\",\n progress: {\n label: \"Running\",\n completed: 0,\n total: 1,\n percent: 10,\n },\n metadata: {\n executionStartedAt: new Date().toISOString(),\n },\n });\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: \"Agent-Native Code run started.\",\n metadata: { status: \"running\", phase: \"executing\" },\n });\n\n // Fall back to AGENT_ENGINE here too, mirroring resolveExecutorEngine below.\n // Without it, `AGENT_ENGINE=codex-cli` skips this Codex branch and is handed\n // to resolveEngine (LLM providers only), which throws `Unknown engine`.\n const requestedEngine = normalizeRequestedEngine(\n metadataString(existing, \"engine\") ?? process.env.AGENT_ENGINE,\n );\n if (requestedEngine === CODEX_CLI_ENGINE_NAME) {\n return executeCodexCliRun({\n run: existing,\n prompt: executionPrompt,\n model: options.model ?? metadataString(existing, \"model\"),\n permissionMode: existing.permissionMode ?? \"full-auto\",\n stdout: options.stdout,\n signal: options.signal,\n });\n }\n\n const engine =\n options.engine ?? (await resolveExecutorEngine(requestedEngine));\n if (!engine) {\n const message =\n \"No LLM provider key was found. Set ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY, another supported provider key, or run `codex login` to use Codex CLI.\";\n options.stdout?.write(`${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message,\n metadata: { status: \"paused\", phase: \"missing-credentials\" },\n });\n return updateCodeAgentRunRecord(existing.id, {\n status: \"paused\",\n phase: \"missing-credentials\",\n needsApproval: false,\n progress: {\n label: \"Missing credentials\",\n completed: 0,\n total: 1,\n percent: 0,\n },\n });\n }\n\n const modelCandidate =\n options.model ??\n metadataString(existing, \"model\") ??\n process.env.AGENT_MODEL ??\n (await getStoredModelForEngine(engine).catch(() => undefined)) ??\n engine.defaultModel;\n const model = normalizeModelForEngine(engine, modelCandidate);\n const reasoningEffort =\n options.reasoningEffort ?? metadataReasoningEffort(existing);\n const cwd = existing.cwd || process.cwd();\n const permissionMode = existing.permissionMode ?? \"full-auto\";\n\n // Holds structured metadata emitted by the coding tools side-channel.\n // Keyed by tool name; consumed when the matching tool_start / tool_done fires.\n const pendingToolMeta = new Map<string, StructuredToolMetadata>();\n\n const actions = createLocalCodeAgentActions(\n cwd,\n permissionMode,\n existing.id,\n (toolName, _phase, meta) => {\n // Both \"start\" and \"done\" phases update the map; done has richer data.\n pendingToolMeta.set(toolName, meta);\n },\n (chunk) => {\n // Stream incremental bash output to stdout for the terminal smoother\n options.stdout?.write(chunk);\n },\n );\n const mcpManager = await startCodeAgentMcpManager(existing.id);\n if (mcpManager) {\n Object.assign(actions, mcpToolsToActionEntries(mcpManager));\n }\n actions[TOOL_SEARCH_ACTION_NAME] = createToolSearchEntry(() => actions);\n const tools = actionsToEngineTools(actions);\n const messages = buildCodeAgentMessages(\n existing,\n executionPrompt,\n imageAttachments,\n );\n const controller = new AbortController();\n const abortFromParent = () => controller.abort();\n if (options.signal) {\n if (options.signal.aborted) controller.abort();\n else\n options.signal.addEventListener(\"abort\", abortFromParent, { once: true });\n }\n\n let assistantText = \"\";\n const outputSmoother = createCodeAgentOutputSmoother(options.stdout);\n\n // Accumulate thinking text across deltas so we can persist a single event\n // per reasoning block rather than one event per delta chunk.\n let pendingThinkingText = \"\";\n let thinkingFlushTimer: ReturnType<typeof setTimeout> | undefined;\n\n const runId = existing.id;\n function flushThinkingEvent() {\n thinkingFlushTimer = undefined;\n const text = pendingThinkingText.trim();\n pendingThinkingText = \"\";\n if (!text) return;\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: text,\n metadata: { type: \"thinking\" },\n });\n }\n\n const send = (event: AgentChatEvent) => {\n if (event.type === \"text\") {\n // Flush any buffered thinking when real content arrives.\n if (thinkingFlushTimer !== undefined) {\n clearTimeout(thinkingFlushTimer);\n flushThinkingEvent();\n }\n assistantText += event.text;\n outputSmoother.write(event.text);\n return;\n }\n if (event.type === \"thinking\") {\n pendingThinkingText += event.text;\n // Debounce: flush 300ms after the last delta so rapid chunks are merged.\n if (thinkingFlushTimer !== undefined) clearTimeout(thinkingFlushTimer);\n thinkingFlushTimer = setTimeout(flushThinkingEvent, 300);\n return;\n }\n if (event.type === \"activity\") {\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: event.label,\n metadata: { type: \"activity\", tool: event.tool },\n });\n return;\n }\n if (event.type === \"tool_start\") {\n const startMeta = pendingToolMeta.get(event.tool ?? \"\");\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: `Running ${event.tool}.`,\n metadata: {\n type: \"tool_start\",\n tool: event.tool,\n input: event.input,\n ...(startMeta ? { structuredMeta: startMeta } : {}),\n },\n });\n return;\n }\n if (event.type === \"tool_done\") {\n const pendingMeta = pendingToolMeta.get(event.tool ?? \"\");\n if (pendingMeta) pendingToolMeta.delete(event.tool ?? \"\");\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: `Finished ${event.tool}.`,\n metadata: {\n type: \"tool_done\",\n tool: event.tool,\n result: truncateBashOutput(\n truncateCodingOutput(event.result, MAX_TOOL_OUTPUT_CHARS),\n ),\n ...(event.mcpApp ? { mcpApp: event.mcpApp } : {}),\n ...(pendingMeta ? { structuredMeta: pendingMeta } : {}),\n },\n });\n return;\n }\n if (event.type === \"error\") {\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: event.error,\n metadata: { type: \"error\", errorCode: event.errorCode },\n });\n }\n };\n\n let loopUsage: AgentLoopUsage | null = null;\n try {\n const systemPrompt = await buildCodeAgentSystemPrompt(cwd, permissionMode);\n const usageResult = await runWithOptionalCodeAgentRequestContext(\n existing,\n () =>\n runAgentLoop({\n engine,\n model,\n systemPrompt,\n tools,\n actions,\n messages,\n send,\n signal: controller.signal,\n maxIterations: DEFAULT_AGENT_MAX_ITERATIONS,\n reasoningEffort,\n }),\n );\n loopUsage = usageResult ?? null;\n // Persist cumulative token totals from this turn into the run record so\n // the UI can display per-run usage statistics.\n if (loopUsage) {\n updateCodeAgentRunRecord(existing.id, (record) => ({\n metadata: {\n tokenUsage: accumulateTokenUsage(\n record.metadata?.tokenUsage,\n loopUsage!,\n ),\n },\n }));\n }\n await outputSmoother.flush();\n if (assistantText.trim()) {\n options.stdout?.write(\"\\n\");\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"system\",\n message: assistantText.trim(),\n metadata: {\n role: \"assistant\",\n model,\n engine: engine.name,\n reasoningEffort,\n },\n });\n }\n const approvalPending = getPendingApproval(existing.id);\n if (approvalPending) {\n const message = `Agent-Native Code run paused for approval: ${approvalPending.reason}`;\n options.stdout?.write(`\\n${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message,\n metadata: {\n status: \"needs-approval\",\n phase: \"approval-required\",\n pendingApprovalId: approvalPending.id,\n },\n });\n return updateCodeAgentRunRecord(existing.id, {\n status: \"needs-approval\",\n phase: \"approval-required\",\n needsApproval: true,\n progress: {\n label: \"Approval required\",\n completed: 0,\n total: 1,\n percent: 50,\n },\n });\n }\n\n const pendingFollowUp = dequeueCodeAgentFollowUp(existing.id);\n if (pendingFollowUp) {\n const message =\n pendingFollowUp.mode === \"queued\"\n ? \"Agent-Native Code run completed; running queued follow-up.\"\n : \"Agent-Native Code run completed; applying steering follow-up.\";\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message,\n metadata: {\n status: \"running\",\n phase: \"follow-up\",\n followUpId: pendingFollowUp.id,\n followUpMode: pendingFollowUp.mode,\n },\n });\n if (pendingFollowUp.permissionMode) {\n updateCodeAgentRunRecord(existing.id, {\n permissionMode: pendingFollowUp.permissionMode,\n });\n }\n return executeCodeAgentRun({\n ...options,\n runId: existing.id,\n prompt: pendingFollowUp.prompt,\n attachments:\n pendingFollowUp.attachments ??\n userPromptAttachmentsForEvent(existing.id, pendingFollowUp.eventId),\n appendUserEvent: false,\n });\n }\n\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: \"Agent-Native Code run completed.\",\n metadata: { status: \"completed\", phase: \"complete\" },\n });\n return updateCodeAgentRunRecord(existing.id, {\n status: \"completed\",\n phase: \"complete\",\n needsApproval: false,\n progress: {\n label: \"Complete\",\n completed: 1,\n total: 1,\n percent: 100,\n },\n metadata: {\n executionCompletedAt: new Date().toISOString(),\n engine: engine.name,\n model,\n reasoningEffort,\n permissionMode,\n },\n });\n } catch (err) {\n await outputSmoother.flush().catch(() => undefined);\n const message = err instanceof Error ? err.message : String(err);\n options.stdout?.write(`\\nAgent-Native Code run failed: ${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId: existing.id,\n kind: \"status\",\n message: `Agent-Native Code run failed: ${message}`,\n metadata: { status: \"errored\", phase: \"error\" },\n });\n return updateCodeAgentRunRecord(existing.id, {\n status: controller.signal.aborted ? \"paused\" : \"errored\",\n phase: controller.signal.aborted ? \"paused\" : \"error\",\n progress: {\n label: controller.signal.aborted ? \"Paused\" : \"Error\",\n completed: 0,\n total: 1,\n failed: controller.signal.aborted ? 0 : 1,\n percent: 0,\n },\n metadata: {\n executionError: message,\n executionErroredAt: new Date().toISOString(),\n },\n });\n } finally {\n if (thinkingFlushTimer !== undefined) {\n clearTimeout(thinkingFlushTimer);\n flushThinkingEvent();\n }\n outputSmoother.cancel();\n options.signal?.removeEventListener(\"abort\", abortFromParent);\n await mcpManager?.stop().catch(() => undefined);\n void running;\n }\n}\n\nasync function executeCodexCliRun(options: {\n run: CodeAgentRunRecord;\n prompt: string;\n model?: string;\n permissionMode: CodeAgentPermissionMode;\n stdout?: NodeJS.WritableStream;\n signal?: AbortSignal;\n}): Promise<CodeAgentRunRecord | null> {\n const cwd = options.run.cwd || process.cwd();\n const outputDir = fs.mkdtempSync(\n path.join(os.tmpdir(), \"agent-native-code-codex-\"),\n );\n const outputPath = path.join(outputDir, \"last-message.txt\");\n const model = normalizeCodexCliModel(options.model);\n const args = [\n \"exec\",\n \"--cd\",\n cwd,\n \"--color\",\n \"never\",\n \"--skip-git-repo-check\",\n \"--sandbox\",\n codexSandboxForPermissionMode(options.permissionMode),\n \"--ask-for-approval\",\n \"never\",\n \"--output-last-message\",\n outputPath,\n ];\n if (model) args.push(\"--model\", model);\n args.push(\"-\");\n\n appendCodeAgentTranscriptEvent({\n runId: options.run.id,\n kind: \"status\",\n message: \"Starting Codex CLI with local Codex authentication.\",\n metadata: {\n status: \"running\",\n phase: \"executing\",\n engine: CODEX_CLI_ENGINE_NAME,\n },\n });\n\n try {\n const result = await runCodexCliProcess({\n args,\n cwd,\n prompt: buildCodexCliPrompt(options.run, options.prompt),\n stdout: options.stdout,\n signal: options.signal,\n });\n\n if (result.exitCode !== 0) {\n const message =\n result.error ??\n result.stderr.trim() ??\n `Codex CLI exited with ${result.exitSignal ?? result.exitCode}.`;\n options.stdout?.write(`\\nCodex CLI run failed: ${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId: options.run.id,\n kind: \"status\",\n message: `Codex CLI run failed: ${message}`,\n metadata: {\n status: \"errored\",\n phase: \"error\",\n engine: CODEX_CLI_ENGINE_NAME,\n exitCode: result.exitCode,\n exitSignal: result.exitSignal,\n },\n });\n return updateCodeAgentRunRecord(options.run.id, {\n status: options.signal?.aborted ? \"paused\" : \"errored\",\n phase: options.signal?.aborted ? \"paused\" : \"error\",\n progress: {\n label: options.signal?.aborted ? \"Paused\" : \"Error\",\n completed: 0,\n total: 1,\n failed: options.signal?.aborted ? 0 : 1,\n percent: 0,\n },\n metadata: {\n executionError: message,\n executionErroredAt: new Date().toISOString(),\n engine: CODEX_CLI_ENGINE_NAME,\n model: model ?? \"codex-default\",\n },\n });\n }\n\n const finalMessage =\n readCodexLastMessage(outputPath) ||\n result.stdout.trim() ||\n \"Codex CLI run completed.\";\n appendCodeAgentTranscriptEvent({\n runId: options.run.id,\n kind: \"system\",\n message: finalMessage,\n metadata: {\n role: \"assistant\",\n engine: CODEX_CLI_ENGINE_NAME,\n model: model ?? \"codex-default\",\n },\n });\n\n const pendingFollowUp = dequeueCodeAgentFollowUp(options.run.id);\n if (pendingFollowUp) {\n const message =\n pendingFollowUp.mode === \"queued\"\n ? \"Codex CLI run completed; running queued follow-up.\"\n : \"Codex CLI run completed; applying steering follow-up.\";\n appendCodeAgentTranscriptEvent({\n runId: options.run.id,\n kind: \"status\",\n message,\n metadata: {\n status: \"running\",\n phase: \"follow-up\",\n followUpId: pendingFollowUp.id,\n followUpMode: pendingFollowUp.mode,\n engine: CODEX_CLI_ENGINE_NAME,\n },\n });\n if (pendingFollowUp.permissionMode) {\n updateCodeAgentRunRecord(options.run.id, {\n permissionMode: pendingFollowUp.permissionMode,\n });\n }\n return executeCodeAgentRun({\n runId: options.run.id,\n prompt: pendingFollowUp.prompt,\n attachments:\n pendingFollowUp.attachments ??\n userPromptAttachmentsForEvent(\n options.run.id,\n pendingFollowUp.eventId,\n ),\n appendUserEvent: false,\n stdout: options.stdout,\n signal: options.signal,\n });\n }\n\n appendCodeAgentTranscriptEvent({\n runId: options.run.id,\n kind: \"status\",\n message: \"Codex CLI run completed.\",\n metadata: {\n status: \"completed\",\n phase: \"complete\",\n engine: CODEX_CLI_ENGINE_NAME,\n },\n });\n return updateCodeAgentRunRecord(options.run.id, {\n status: \"completed\",\n phase: \"complete\",\n needsApproval: false,\n progress: {\n label: \"Complete\",\n completed: 1,\n total: 1,\n percent: 100,\n },\n metadata: {\n executionCompletedAt: new Date().toISOString(),\n engine: CODEX_CLI_ENGINE_NAME,\n model: model ?? \"codex-default\",\n permissionMode: options.permissionMode,\n },\n });\n } finally {\n fs.rmSync(outputDir, { recursive: true, force: true });\n }\n}\n\nfunction runCodexCliProcess(options: {\n args: string[];\n cwd: string;\n prompt: string;\n stdout?: NodeJS.WritableStream;\n signal?: AbortSignal;\n}): Promise<CodexCliProcessResult> {\n return new Promise((resolve) => {\n let stdout = \"\";\n let stderr = \"\";\n let settled = false;\n const child = spawn(\"codex\", options.args, {\n cwd: options.cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: process.env,\n });\n const finish = (\n result: Omit<CodexCliProcessResult, \"stdout\" | \"stderr\">,\n ) => {\n if (settled) return;\n settled = true;\n options.signal?.removeEventListener(\"abort\", onAbort);\n resolve({ ...result, stdout, stderr });\n };\n const onAbort = () => {\n child.kill(\"SIGTERM\");\n };\n if (options.signal) {\n if (options.signal.aborted) onAbort();\n else options.signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n child.stdout?.on(\"data\", (chunk) => {\n const text = chunk.toString();\n stdout += text;\n options.stdout?.write(text);\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr += chunk.toString();\n });\n child.on(\"error\", (err) => {\n finish({\n exitCode: 1,\n exitSignal: null,\n error:\n (err as NodeJS.ErrnoException).code === \"ENOENT\"\n ? \"Codex CLI was not found. Install Codex and run `codex login`.\"\n : err instanceof Error\n ? err.message\n : String(err),\n });\n });\n child.on(\"exit\", (exitCode, exitSignal) => {\n finish({ exitCode, exitSignal });\n });\n child.stdin?.end(options.prompt);\n });\n}\n\nfunction buildCodexCliPrompt(run: CodeAgentRunRecord, prompt: string): string {\n const permissionMode = run.permissionMode ?? \"full-auto\";\n const mode =\n permissionMode === \"read-only\" || permissionMode === \"ask-before-edit\"\n ? \"Plan\"\n : \"Auto\";\n const modeInstruction =\n mode === \"Plan\"\n ? \"Inspect and explain only. Do not edit files or run mutating commands.\"\n : \"Edit and verify as needed. Do not create, switch, reset, rebase, or stash git branches.\";\n return [\n `You are running from Agent-Native Code in ${run.cwd || process.cwd()}.`,\n \"Follow the repository AGENTS.md and any relevant skill instructions.\",\n `Run mode: ${mode} (${permissionMode}). ${modeInstruction}`,\n \"\",\n \"# User request\",\n prompt,\n ].join(\"\\n\");\n}\n\nfunction codexSandboxForPermissionMode(\n permissionMode: CodeAgentPermissionMode,\n): \"read-only\" | \"workspace-write\" {\n return permissionMode === \"read-only\" || permissionMode === \"ask-before-edit\"\n ? \"read-only\"\n : \"workspace-write\";\n}\n\nfunction normalizeCodexCliModel(model: string | undefined): string | undefined {\n const trimmed = model?.trim();\n if (!trimmed || trimmed === \"auto\" || trimmed === CODEX_CLI_ENGINE_NAME) {\n return undefined;\n }\n return trimmed;\n}\n\nfunction normalizeRequestedEngine(\n engine: string | undefined,\n): string | undefined {\n const trimmed = engine?.trim();\n if (!trimmed || trimmed === \"auto\") return undefined;\n return trimmed;\n}\n\nfunction readCodexLastMessage(filePath: string): string | null {\n try {\n const text = fs.readFileSync(filePath, \"utf-8\").trim();\n return text || null;\n } catch {\n return null;\n }\n}\n\nexport async function executeExistingCodeAgentRun(\n runId: string,\n options: Omit<ExecuteCodeAgentRunOptions, \"runId\"> = {},\n): Promise<CodeAgentRunRecord | null> {\n return executeCodeAgentRun({ ...options, runId, appendUserEvent: false });\n}\n\n/**\n * Add the pending approval command to the per-project allowlist, then approve\n * and auto-resume. Future occurrences of this exact command will bypass the\n * approval gate without prompting.\n */\nexport async function executeApproveAlwaysCodeAgentApproval(\n runId: string,\n options: { stdout?: NodeJS.WritableStream } = {},\n): Promise<CodeAgentRunRecord | null> {\n const approval = getPendingApproval(runId);\n if (approval?.command) {\n addCodeAgentCommandToAllowlist(approval.command);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `Command added to allowlist: ${approval.command}`,\n metadata: { type: \"allowlist-added\", command: approval.command },\n });\n }\n return executePendingCodeAgentApproval(runId, options);\n}\n\nexport async function executePendingCodeAgentApproval(\n runId: string,\n options: { stdout?: NodeJS.WritableStream } = {},\n): Promise<CodeAgentRunRecord | null> {\n const record = getCodeAgentRunRecord(runId);\n if (!record) return null;\n const approval = getPendingApproval(runId);\n if (!approval) {\n options.stdout?.write(\"No pending approval was found for this run.\\n\");\n return record;\n }\n\n const permission = classifyCodeAgentCommandPermission(approval.command);\n if (permission.kind === \"forbidden\") {\n const message = `Approval cannot run forbidden command: ${permission.reason}`;\n options.stdout?.write(`${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message,\n metadata: {\n status: \"needs-approval\",\n phase: \"approval-forbidden\",\n approvalId: approval.id,\n },\n });\n return updateCodeAgentRunRecord(runId, {\n status: \"needs-approval\",\n phase: \"approval-forbidden\",\n needsApproval: true,\n });\n }\n\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `Approved command ${approval.id}; running now.`,\n metadata: {\n status: \"running\",\n phase: \"approval-running\",\n approvalId: approval.id,\n command: approval.command,\n },\n });\n const result = await runCodingCommand(\n approval.command,\n record.cwd || process.cwd(),\n DEFAULT_COMMAND_TIMEOUT_MS,\n );\n const summary = truncateCodingOutput(\n [\n `Approved command finished with exit code ${result.code}.`,\n result.timedOut ? \"Timed out: true\" : \"\",\n result.stdout ? `stdout:\\n${result.stdout}` : \"\",\n result.stderr ? `stderr:\\n${result.stderr}` : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\\n\"),\n MAX_TOOL_OUTPUT_CHARS,\n );\n options.stdout?.write(`${summary}\\n`);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: summary,\n metadata: {\n status: \"running\",\n phase: \"approval-complete\",\n approvalId: approval.id,\n exitCode: result.code,\n timedOut: result.timedOut,\n },\n });\n // Clear the pending approval and immediately auto-resume so the model sees\n // the command result and can continue — no manual \"Resume\" click needed.\n updateCodeAgentRunRecord(runId, {\n status: \"running\",\n phase: \"approval-resuming\",\n needsApproval: false,\n metadata: {\n pendingApproval: undefined,\n lastApproval: {\n ...approval,\n completedAt: new Date().toISOString(),\n exitCode: result.code,\n },\n },\n });\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: \"Resuming run after approval.\",\n metadata: { status: \"running\", phase: \"approval-resuming\" },\n });\n return executeExistingCodeAgentRun(runId, { stdout: options.stdout });\n}\n\n/**\n * Deny a pending approval: record the denial, feed it back to the model as a\n * \"command denied by user\" result, and immediately resume the run so the model\n * can adapt its plan without leaving the run dangling.\n */\nexport async function executeDenyCodeAgentApproval(\n runId: string,\n options: { stdout?: NodeJS.WritableStream } = {},\n): Promise<CodeAgentRunRecord | null> {\n const record = getCodeAgentRunRecord(runId);\n if (!record) return null;\n const approval = getPendingApproval(runId);\n if (!approval) {\n options.stdout?.write(\"No pending approval was found for this run.\\n\");\n return record;\n }\n\n const message = `User denied command: ${approval.command} (${approval.reason})`;\n options.stdout?.write(`${message}\\n`);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message,\n metadata: {\n status: \"running\",\n phase: \"approval-denied\",\n approvalId: approval.id,\n command: approval.command,\n },\n });\n updateCodeAgentRunRecord(runId, {\n status: \"running\",\n phase: \"approval-denied-resuming\",\n needsApproval: false,\n metadata: {\n pendingApproval: undefined,\n lastApproval: {\n ...approval,\n deniedAt: new Date().toISOString(),\n denied: true,\n },\n },\n });\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: \"Resuming run after denial — model will adapt its plan.\",\n metadata: { status: \"running\", phase: \"approval-denied-resuming\" },\n });\n return executeExistingCodeAgentRun(runId, { stdout: options.stdout });\n}\n\nfunction latestUserPrompt(runId: string): string {\n const events = listCodeAgentTranscriptEvents(runId);\n for (let i = events.length - 1; i >= 0; i--) {\n const event = events[i];\n if (event.kind === \"user\" && event.message.trim()) return event.message;\n }\n return \"\";\n}\n\nfunction latestUserPromptAttachments(\n runId: string,\n prompt: string,\n): AgentPromptAttachment[] {\n const events = listCodeAgentTranscriptEvents(runId);\n const normalizedPrompt = prompt.trim();\n for (let i = events.length - 1; i >= 0; i--) {\n const event = events[i];\n if (event.kind !== \"user\" || !event.message.trim()) continue;\n if (\n !normalizedPrompt ||\n event.message.trim() === normalizedPrompt ||\n i === events.length - 1\n ) {\n return promptAttachmentsFromMetadata(event.metadata?.attachments);\n }\n }\n return [];\n}\n\nfunction userPromptAttachmentsForEvent(\n runId: string,\n eventId: string | undefined,\n): AgentPromptAttachment[] {\n if (!eventId) return [];\n const event = listCodeAgentTranscriptEvents(runId).find(\n (item) => item.id === eventId && item.kind === \"user\",\n );\n return promptAttachmentsFromMetadata(event?.metadata?.attachments);\n}\n\nfunction promptAttachmentsFromMetadata(\n value: unknown,\n): AgentPromptAttachment[] {\n if (!Array.isArray(value)) return [];\n return value\n .filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === \"object\" && !Array.isArray(item)),\n )\n .map((item) => ({\n name: typeof item.name === \"string\" && item.name ? item.name : \"file\",\n ...(typeof item.type === \"string\" ? { type: item.type } : {}),\n ...(typeof item.size === \"number\" ? { size: item.size } : {}),\n ...(typeof item.text === \"string\" ? { text: item.text } : {}),\n ...(typeof item.dataUrl === \"string\" ? { dataUrl: item.dataUrl } : {}),\n }));\n}\n\nfunction metadataString(\n run: CodeAgentRunRecord,\n key: string,\n): string | undefined {\n const value = run.metadata?.[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nasync function startCodeAgentMcpManager(\n runId: string,\n): Promise<McpClientManager | null> {\n const config = await buildMergedConfig().catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `MCP tools unavailable: ${message}`,\n metadata: { type: \"mcp-config-error\" },\n });\n return null;\n });\n if (!config || Object.keys(config.servers ?? {}).length === 0) return null;\n\n const manager = new McpClientManager(config);\n await manager.start().catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `MCP tools failed to start: ${message}`,\n metadata: { type: \"mcp-start-error\" },\n });\n });\n const status = manager.getStatus();\n if (status.totalTools === 0) {\n await manager.stop().catch(() => undefined);\n return null;\n }\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `Connected ${status.totalTools} MCP tool${status.totalTools === 1 ? \"\" : \"s\"} for this run.`,\n metadata: {\n type: \"mcp-tools-connected\",\n servers: status.connectedServers,\n toolCount: status.totalTools,\n },\n });\n return manager;\n}\n\nfunction runWithOptionalCodeAgentRequestContext<T>(\n run: CodeAgentRunRecord,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n const userEmail =\n metadataString(run, \"ownerEmail\") ??\n metadataString(run, \"userEmail\") ??\n process.env.AGENT_USER_EMAIL;\n const orgId = metadataString(run, \"orgId\") ?? process.env.AGENT_ORG_ID;\n if (!userEmail && !orgId) return fn();\n return runWithRequestContext({ userEmail, orgId }, fn);\n}\n\nfunction metadataReasoningEffort(\n run: CodeAgentRunRecord,\n): ReasoningEffort | undefined {\n const value = run.metadata?.reasoningEffort ?? run.metadata?.effort;\n return isReasoningEffort(value) && value !== \"auto\" ? value : undefined;\n}\n\nasync function resolveExecutorEngine(\n requestedEngine?: string,\n): Promise<AgentEngine | null> {\n const fakeText = process.env.AGENT_NATIVE_CODE_AGENT_FAKE_RESPONSE;\n if (fakeText !== undefined) {\n return createFakeCodeAgentEngine(fakeText || \"Done.\");\n }\n registerBuiltinEngines();\n if (!hasAnyProviderCredential()) return null;\n return resolveEngine({\n engineOption: requestedEngine ?? process.env.AGENT_ENGINE,\n });\n}\n\nfunction hasAnyProviderCredential(): boolean {\n if (process.env.AGENT_ENGINE) return true;\n if (PROVIDER_ENV_VARS.some((key) => Boolean(process.env[key]))) return true;\n return Boolean(\n process.env.BUILDER_PRIVATE_KEY && process.env.BUILDER_PUBLIC_KEY,\n );\n}\n\nfunction createFakeCodeAgentEngine(text: string): AgentEngine {\n return {\n name: \"fake-code-agent\",\n label: \"Fake Agent-Native Code\",\n defaultModel: \"fake-code-agent\",\n supportedModels: [\"fake-code-agent\"],\n capabilities: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: false,\n },\n async *stream(_opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n yield { type: \"text-delta\", text };\n yield {\n type: \"assistant-content\",\n parts: [{ type: \"text\", text }],\n };\n yield {\n type: \"usage\",\n inputTokens: 1,\n outputTokens: 1,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n };\n yield { type: \"stop\", reason: \"end_turn\" };\n },\n };\n}\n\nconst SUPPORTED_IMAGE_MEDIA_TYPES = new Set([\n \"image/jpeg\",\n \"image/jpg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n]);\n\nfunction buildCodeAgentMessages(\n run: CodeAgentRunRecord,\n prompt: string,\n attachments?: AgentPromptAttachment[],\n): EngineMessage[] {\n const allEvents = listCodeAgentTranscriptEvents(run.id);\n\n // Split events into an \"older\" prefix (summarised) and a \"recent\" tail\n // (reconstructed as native structured messages).\n const splitAt = Math.max(\n 0,\n allEvents.length - STRUCTURED_HISTORY_RECENT_EVENTS,\n );\n const olderEvents = allEvents.slice(0, splitAt);\n const recentEvents = allEvents.slice(splitAt);\n\n // Build a compact text preamble from any events that pre-date the recent\n // window. Reuses the old flat-text approach so the model still has broad\n // context without paying for full token cost on every old tool result.\n let preamble = \"\";\n if (olderEvents.length > 0) {\n const summaryLines = olderEvents\n .filter(\n (e) =>\n e.kind === \"user\" ||\n (e.kind === \"system\" && e.metadata?.role === \"assistant\") ||\n (e.kind === \"status\" &&\n (e.metadata?.type === \"tool_done\" ||\n e.metadata?.role === \"assistant\")),\n )\n .map((e) => {\n if (e.kind === \"user\") return `User: ${e.message}`;\n if (e.metadata?.role === \"assistant\") return `Assistant: ${e.message}`;\n if (e.metadata?.type === \"tool_done\") {\n const tool = e.metadata?.tool;\n const result = e.metadata?.result;\n const resultText =\n typeof result === \"string\"\n ? truncateCodingOutput(result, 500)\n : result != null\n ? truncateCodingOutput(String(result), 500)\n : \"\";\n return tool ? `Tool[${tool}]: ${resultText}` : `Tool: ${resultText}`;\n }\n return null;\n })\n .filter((line): line is string => line !== null);\n if (summaryLines.length > 0) {\n preamble = `Earlier conversation summary:\\n${summaryLines.join(\"\\n\")}`;\n }\n }\n\n // Reconstruct the recent events as native EngineMessage objects.\n // We build up a sequence of user/assistant messages, pairing tool-call\n // events (from tool_start metadata) with their matching tool-result events\n // (from tool_done metadata), and accumulating assistant text from system\n // events with role=assistant.\n const structuredMessages = buildStructuredMessagesFromEvents(recentEvents);\n\n // Separate image attachments from text attachments. Images are passed as\n // proper EngineImagePart entries rather than inlined base64 text (which\n // would consume ~700K tokens per megabyte of image data).\n const imageParts: import(\"../agent/engine/types.js\").EngineImagePart[] = [];\n const unsupportedImageNotes: string[] = [];\n\n for (const att of attachments ?? []) {\n if (!att.dataUrl) continue;\n const match = att.dataUrl.match(/^data:(image\\/[^;]+);base64,(.+)$/);\n if (!match) continue;\n const mime = match[1].toLowerCase();\n if (SUPPORTED_IMAGE_MEDIA_TYPES.has(mime)) {\n imageParts.push({\n type: \"image\",\n data: match[2],\n mediaType:\n mime as import(\"../agent/engine/types.js\").EngineImagePart[\"mediaType\"],\n });\n } else {\n // Unsupported format — inject a note so the model understands what happened.\n const label = att.name ? `\"${att.name}\"` : \"An image\";\n unsupportedImageNotes.push(\n `[${label} could not be processed — unsupported image format (${mime}). ` +\n `Only JPEG, PNG, GIF, and WebP are supported.]`,\n );\n }\n }\n\n const notesBlock =\n unsupportedImageNotes.length > 0\n ? `\\n\\n${unsupportedImageNotes.join(\"\\n\")}`\n : \"\";\n\n // The current prompt (plus optional preamble) becomes the final user message.\n const promptText = [preamble, prompt, notesBlock]\n .filter(Boolean)\n .join(\"\\n\\n\");\n\n const promptContent: import(\"../agent/engine/types.js\").EngineContentPart[] =\n [...imageParts, { type: \"text\", text: promptText }];\n\n // If there are structured messages from the recent window and the last one\n // is a user message that already contains the current prompt (happens when\n // appendUserEvent added a \"user\" event that got included), de-duplicate by\n // using the structured messages as-is but replacing the last user message's\n // content with the enriched content (images + prompt).\n if (structuredMessages.length > 0) {\n const lastMsg = structuredMessages[structuredMessages.length - 1];\n if (lastMsg.role === \"user\") {\n // Replace last user message content with the enriched prompt content.\n structuredMessages[structuredMessages.length - 1] = {\n role: \"user\",\n content: promptContent,\n };\n return structuredMessages;\n }\n // Last message is assistant — append a new user message.\n return [...structuredMessages, { role: \"user\", content: promptContent }];\n }\n\n return [{ role: \"user\", content: promptContent }];\n}\n\n/**\n * Reconstruct a sequence of EngineMessage objects from transcript events,\n * preserving the native tool-call / tool-result pair structure that models\n * expect when replaying multi-turn conversations.\n *\n * Event mapping:\n * kind=user → user message with text content\n * kind=system, role=assistant → assistant message with text content\n * kind=status, type=tool_start → assistant message with a tool-call part\n * (grouped with any preceding assistant text)\n * kind=status, type=tool_done → user message with a tool-result part\n * kind=status, type=thinking → excluded (ephemeral reasoning)\n * everything else → excluded from model history\n *\n * Each tool_start generates a synthetic toolCallId derived from the event id so\n * that the matching tool_done can reference it. Old events that lack tool/input\n * metadata fall back gracefully to text content.\n */\n/** @internal exported for unit tests */\nexport function buildStructuredMessagesFromEvents(\n events: readonly import(\"./code-agent-runs.js\").CodeAgentTranscriptEvent[],\n): EngineMessage[] {\n // We accumulate into a flat list and then merge adjacent same-role messages.\n type PendingMessage =\n | {\n role: \"user\";\n content: import(\"../agent/engine/types.js\").EngineContentPart[];\n }\n | {\n role: \"assistant\";\n content: import(\"../agent/engine/types.js\").EngineContentPart[];\n };\n\n const pending: PendingMessage[] = [];\n\n // Track in-flight tool-call IDs keyed by event id so tool_done can\n // reference the corresponding call.\n const toolCallIdByEventOrder = new Map<string, string>();\n\n for (const event of events) {\n // Exclude thinking — ephemeral reasoning, never replayed to model.\n if (event.kind === \"status\" && event.metadata?.type === \"thinking\") {\n continue;\n }\n\n if (event.kind === \"user\") {\n const text = event.message.trim();\n if (!text) continue;\n appendOrMerge(pending, \"user\", { type: \"text\", text });\n continue;\n }\n\n // Assistant text (persisted after a turn completes).\n if (event.kind === \"system\" && event.metadata?.role === \"assistant\") {\n const text = event.message.trim();\n if (!text) continue;\n appendOrMerge(pending, \"assistant\", { type: \"text\", text });\n continue;\n }\n\n // Tool call start — emit an assistant tool-call part.\n if (event.kind === \"status\" && event.metadata?.type === \"tool_start\") {\n const tool =\n typeof event.metadata?.tool === \"string\" && event.metadata.tool\n ? event.metadata.tool\n : null;\n if (!tool) continue;\n\n // Generate a stable ID from the event id so tool_done can reference it.\n const toolCallId = `tc-${event.id}`;\n toolCallIdByEventOrder.set(event.id, toolCallId);\n\n const input: unknown =\n event.metadata?.input != null ? event.metadata.input : {};\n\n appendOrMerge(pending, \"assistant\", {\n type: \"tool-call\",\n id: toolCallId,\n name: tool,\n input,\n });\n continue;\n }\n\n // Tool result — emit a user tool-result part paired with the last\n // unmatched tool_start for the same tool name.\n if (event.kind === \"status\" && event.metadata?.type === \"tool_done\") {\n const tool =\n typeof event.metadata?.tool === \"string\" && event.metadata.tool\n ? event.metadata.tool\n : null;\n if (!tool) continue;\n\n // Find the most recent tool_start event id for this tool.\n const matchedCallId = findMatchingToolCallId(\n toolCallIdByEventOrder,\n events,\n event,\n tool,\n );\n\n const rawResult = event.metadata?.result;\n const resultText = truncateCodingOutput(\n typeof rawResult === \"string\"\n ? rawResult\n : rawResult != null\n ? String(rawResult)\n : \"(no output)\",\n STRUCTURED_HISTORY_RESULT_CAP,\n );\n\n if (matchedCallId) {\n const toolInput =\n event.metadata?.input != null\n ? safeJsonStringify(event.metadata.input)\n : \"{}\";\n appendOrMerge(pending, \"user\", {\n type: \"tool-result\",\n toolCallId: matchedCallId,\n toolName: tool,\n toolInput,\n content: resultText,\n });\n } else {\n // Orphaned tool result (no matching call in the recent window) — fall\n // back to plain text so the model still sees the output.\n appendOrMerge(pending, \"user\", {\n type: \"text\",\n text: `[Tool result for ${tool}]: ${resultText}`,\n });\n }\n continue;\n }\n }\n\n return pending;\n}\n\n/**\n * Append a content part to the last message if it has the same role, or\n * start a new message otherwise.\n */\nfunction appendOrMerge(\n pending: Array<{\n role: \"user\" | \"assistant\";\n content: import(\"../agent/engine/types.js\").EngineContentPart[];\n }>,\n role: \"user\" | \"assistant\",\n part: import(\"../agent/engine/types.js\").EngineContentPart,\n): void {\n const last = pending[pending.length - 1];\n if (last && last.role === role) {\n last.content.push(part);\n } else {\n pending.push({ role, content: [part] });\n }\n}\n\n/**\n * Find the toolCallId generated for the most recent tool_start event that\n * matches the given tool name and precedes the current tool_done event.\n * Returns null if no match exists in the recent window.\n */\nfunction findMatchingToolCallId(\n toolCallIdByEventOrder: Map<string, string>,\n events: readonly import(\"./code-agent-runs.js\").CodeAgentTranscriptEvent[],\n doneEvent: import(\"./code-agent-runs.js\").CodeAgentTranscriptEvent,\n toolName: string,\n): string | null {\n // Walk backwards from doneEvent's position to find the nearest unmatched start.\n const doneIndex = events.indexOf(doneEvent);\n for (let i = doneIndex - 1; i >= 0; i--) {\n const e = events[i];\n if (\n e.kind === \"status\" &&\n e.metadata?.type === \"tool_start\" &&\n e.metadata?.tool === toolName\n ) {\n const id = toolCallIdByEventOrder.get(e.id);\n if (id) {\n // Consume it so a second done for the same tool gets the next start.\n toolCallIdByEventOrder.delete(e.id);\n return id;\n }\n }\n }\n return null;\n}\n\nfunction safeJsonStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? \"{}\";\n } catch {\n return \"{}\";\n }\n}\n\n/**\n * Maximum character length for inlined AGENTS.md content in the system prompt.\n * Content beyond this cap is truncated with a note so the model knows more exists.\n */\nconst AGENTS_MD_INLINE_CAP = 16_000;\n\n/**\n * Build the coding agent system prompt, inlining AGENTS.md (or CLAUDE.md as\n * fallback) and a skills index from .agents/skills/ into the prompt so the\n * coding agent has the same repo-context awareness that Claude Code / Codex\n * provide when running locally.\n *\n * The bundle is read synchronously from the filesystem via `readAgentsBundleFromFs`\n * (same function used by the Vite build-time plugin) so there is no async I/O\n * on the hot path — the call is cheap and the result is used once per run leg.\n */\n/** @internal exported for unit tests */\nexport async function buildCodeAgentSystemPrompt(\n cwd: string,\n permissionMode: CodeAgentPermissionMode,\n): Promise<string> {\n const bundle = readAgentsBundleFromFs(cwd);\n\n // If the bundle has no AGENTS.md, try CLAUDE.md as a fallback — many repos\n // use that name for agent instructions (e.g. Claude Code projects).\n let agentsMdContent = bundle.agentsMd;\n if (!agentsMdContent.trim()) {\n try {\n const fs = await import(\"node:fs\");\n const path = await import(\"node:path\");\n const claudeMdPath = path.join(cwd, \"CLAUDE.md\");\n if (fs.existsSync(claudeMdPath)) {\n agentsMdContent = fs.readFileSync(claudeMdPath, \"utf-8\");\n }\n } catch {\n // Not readable — skip\n }\n }\n\n const repoInstructionsBlock = buildRepoInstructionsBlock(agentsMdContent);\n const skillsBlock = generateSkillsPromptBlock(bundle);\n\n return codeAgentSystemPrompt(\n cwd,\n permissionMode,\n repoInstructionsBlock,\n skillsBlock,\n );\n}\n\n/** @internal exported for unit tests */\nexport function buildRepoInstructionsBlock(agentsMdContent: string): string {\n if (!agentsMdContent.trim()) return \"\";\n\n const needsTruncation = agentsMdContent.length > AGENTS_MD_INLINE_CAP;\n const truncated = needsTruncation\n ? agentsMdContent.slice(0, AGENTS_MD_INLINE_CAP)\n : agentsMdContent;\n const truncationNote = needsTruncation\n ? `\\n\\n[Note: AGENTS.md was truncated to ${AGENTS_MD_INLINE_CAP} characters. Read the full file for complete instructions.]`\n : \"\";\n\n return `## Repository instructions\n\n${truncated}${truncationNote}`;\n}\n\n/** @internal exported for unit tests */\nexport function codeAgentSystemPrompt(\n cwd: string,\n permissionMode: CodeAgentPermissionMode,\n repoInstructionsBlock = \"\",\n skillsBlock = \"\",\n): string {\n const mode = permissionMode === \"read-only\" ? \"Plan\" : \"Auto\";\n const repoSection = repoInstructionsBlock\n ? `\\n\\n${repoInstructionsBlock}`\n : \"\";\n const skillsSection = skillsBlock ? `\\n\\n${skillsBlock}` : \"\";\n return `You are Agent-Native Code, a coding agent running in ${cwd}. You and the user share one workspace, and your job is to collaborate with them until their goal is genuinely handled.\n\n# General\n\nYou bring a senior engineer's judgment to the work, but you let it arrive through attention rather than premature certainty. Read the codebase first, resist easy assumptions, and let the shape of the existing system teach you how to move.\n\n- When you search for text or files, reach first for \\`rg\\` or \\`rg --files\\`; they are much faster than \\`grep\\` or \\`find\\`. If \\`rg\\` is unavailable, use the next best tool without fuss.\n- Parallelize independent read-only work (file reads, searches) so you gather context quickly. Keep mutating steps ordered.\n- Read relevant files before editing them. Do not edit a file you have not actually read.\n\n# Engineering judgment\n\nWhen the user leaves implementation details open, choose conservatively and in sympathy with the codebase already in front of you:\n\n- Prefer the repo's existing patterns, frameworks, and local helper APIs over inventing a new abstraction.\n- For structured data, use structured APIs or parsers instead of ad hoc string manipulation when the toolchain gives you a reasonable option.\n- Keep edits closely scoped to what the request and surrounding code imply. Leave unrelated refactors and metadata churn alone unless they are truly needed to finish safely.\n- Add an abstraction only when it removes real complexity, reduces meaningful duplication, or clearly matches an established local pattern.\n- Let test coverage scale with risk and blast radius: focused for narrow changes, broader when you touch shared behavior or cross-module contracts.\n\n# Run mode\n\nCurrent run mode: ${mode} mode (${permissionMode}).\n- In Plan mode, inspect and explain only — do not edit files or run mutating commands.\n- In Auto mode, edit files and run ordinary project commands without pausing. Pause only for genuinely destructive operations: recursive deletes, package publishing, privileged commands, destructive database operations, or forbidden git branch/reset/stash/rebase operations.\n\n# Editing constraints\n\n- Use the shared coding tools: \\`bash\\` for search/list/test/build/git-status commands, \\`read\\` for file reads, \\`edit\\` for exact-match replacements, and \\`write\\` only for new files or an intentional full rewrite. Prefer \\`edit\\` over \\`write\\` for existing files.\n- Default to ASCII when editing or creating files; introduce non-ASCII only when the file already uses it or there is a clear reason.\n- Add succinct comments only where the code is not self-explanatory. Avoid empty narration like \"assign the value\"; a short orienting comment before a complex block is fine, used sparingly.\n- You may be in a dirty git worktree. NEVER revert or overwrite changes you did not make — assume they came from the user or another concurrent agent. If unrelated changes exist, ignore them; if they touch your task, work *with* them rather than undoing them. Only stop and ask if they make the task impossible.\n- If you notice unexpected changes appearing mid-task that you did not make, STOP and ask the user how to proceed rather than guessing.\n- Do not create, switch, delete, reset, rebase, or stash git branches. Never run destructive git commands (\\`git reset --hard\\`, \\`git checkout --\\`, \\`git clean\\`) unless the user explicitly asked for that exact operation.\n\n# Autonomy and verification\n\n- Stay with the work until the task is handled end to end within this turn whenever feasible. Don't stop at analysis or a proposal — implement the fix, and work through blockers yourself before handing them back. The exception is Plan mode, where you propose only.\n- Done means verified, not generated. After code changes (not docs-only), run the repo's checks before reporting success: \\`pnpm run prep\\` (format + typecheck + test + guards), or a focused subset like \\`pnpm typecheck\\` or a single package's tests for a small change. Fix all errors before you call it done.\n- Do not claim a change works, tests pass, or a build succeeds unless you actually ran it and saw the result. If you could not verify something, say exactly what is unverified and why.\n\n# Tools beyond the basics\n\n- Use \\`tool-search\\` when you need a capability that may come from MCP, including browser automation or computer control.\n- Prefer Playwright MCP for deterministic browser testing; prefer Chrome DevTools MCP when the user needs their live logged-in Chrome session.\n- Only use computer-control MCP tools when they are explicitly available and the request warrants controlling the local computer.\n\n# Final answer\n\n- Keep it concise and high-signal — plain, idiomatic engineering prose, not a mechanical report. Lead with the outcome. For a small change, one or two short paragraphs plus a verification line is usually right; reserve bullet lists for genuinely multi-part results.\n- Reference files as clickable paths (e.g. \\`packages/core/src/foo.ts\\`), with a line number when it helps. Do not paste large file contents back — the user shares this machine and can open them.\n- State what you changed, and show evidence you verified it: name the check you ran (e.g. \\`pnpm typecheck\\`) and its key result, not just a claim that it passed. If you could not run something, say so plainly.\n- No emojis or em dashes unless the user used them first.\n- AGENTS.md files take precedence over these defaults on conflict. More deeply nested AGENTS.md files take precedence over shallower ones — check for them in directories you work in.${repoSection}${skillsSection}`;\n}\n\nfunction createLocalCodeAgentActions(\n cwd: string,\n permissionMode: CodeAgentPermissionMode,\n runId: string,\n onToolMetadata?: (\n toolName: string,\n phase: \"start\" | \"done\",\n meta: StructuredToolMetadata,\n ) => void,\n onBashOutputChunk?: (chunk: string) => void,\n): Record<string, ActionEntry> {\n const actions = createCodingToolRegistry({\n cwd,\n restrictToCwd: true,\n commandTimeoutMs: DEFAULT_COMMAND_TIMEOUT_MS,\n maxOutputChars: MAX_TOOL_OUTPUT_CHARS,\n maxFileReadChars: MAX_FILE_READ_CHARS,\n canWrite: (toolName) => permissionErrorForWrite(permissionMode, toolName),\n onToolMetadata,\n onBashOutputChunk,\n beforeBash: ({ command }) => {\n const permission = classifyCodeAgentCommandPermission(command);\n if (permission.kind === \"forbidden\") {\n return `Error: command is blocked by Agent-Native Code policy: ${permission.reason}`;\n }\n if (permission.kind !== \"read\") {\n const permissionError = permissionErrorForWrite(permissionMode, \"bash\");\n if (permissionError) return permissionError;\n }\n if (permission.kind === \"approval-required\") {\n // Skip the approval gate when the user has allowlisted this command.\n if (isCodeAgentCommandAllowed(command)) return null;\n const approval = requestCodeAgentApproval(runId, {\n tool: \"bash\",\n command,\n reason: permission.reason,\n permissionMode,\n });\n return [\n `Approval required before running this command: ${permission.reason}.`,\n `Approval id: ${approval.id}`,\n `Command: ${command}`,\n \"The run is paused; approve from the Agent-Native Code UI/CLI if this command is intentional.\",\n ].join(\"\\n\");\n }\n return null;\n },\n });\n if (permissionMode === \"read-only\") {\n return {\n bash: actions.bash,\n read: actions.read,\n };\n }\n return actions;\n}\n\nexport type CodeAgentCommandPermission =\n | { kind: \"read\" }\n | { kind: \"write\" }\n | { kind: \"approval-required\"; reason: string }\n | { kind: \"forbidden\"; reason: string };\n\nexport function classifyCodeAgentCommandPermission(\n command: string,\n): CodeAgentCommandPermission {\n const normalized = command.trim().toLowerCase();\n if (!normalized) return { kind: \"read\" };\n\n const blockedPatterns: Array<[RegExp, string]> = [\n [\n /\\bgit\\s+(checkout|switch|reset|rebase|stash|clean|worktree)\\b/,\n \"forbidden git branch/reset/stash/rebase operation\",\n ],\n [\n /\\bgit\\s+branch\\b(?!\\s+--show-current\\b)/,\n \"forbidden git branch operation\",\n ],\n [/\\bdrizzle-kit\\s+push\\b/, \"drizzle-kit push is not allowed\"],\n ];\n for (const [pattern, reason] of blockedPatterns) {\n if (pattern.test(normalized)) return { kind: \"forbidden\", reason };\n }\n\n const approvalPatterns: Array<[RegExp, string]> = [\n [/\\brm\\s+-rf\\b/, \"destructive recursive delete\"],\n [/\\bsudo\\b/, \"privileged command\"],\n [/\\bkill\\s+-9\\b/, \"force-kill command\"],\n [/\\bcurl\\b.*\\|\\s*(sh|bash|zsh)\\b/, \"remote script execution\"],\n [/\\b(wget|fetch)\\b.*\\|\\s*(sh|bash|zsh)\\b/, \"remote script execution\"],\n [/\\bnpm\\s+publish\\b/, \"package publish\"],\n [/\\bpnpm\\s+publish\\b/, \"package publish\"],\n [/\\btruncate\\b/, \"destructive data command\"],\n [/\\bdrop\\s+(table|column|database)\\b/, \"destructive database command\"],\n [/\\bdelete\\s+from\\b(?![\\s\\S]*\\bwhere\\b)/, \"unscoped delete command\"],\n ];\n for (const [pattern, reason] of approvalPatterns) {\n if (pattern.test(normalized)) {\n return { kind: \"approval-required\", reason };\n }\n }\n\n if (isReadOnlyShellCommand(command)) {\n return { kind: \"read\" };\n }\n\n const writePatterns = [\n /(^|[^>])>(?!>)/,\n />>/,\n /\\btee\\b/,\n /\\bapply_patch\\b/,\n /\\b(write|touch|mkdir|cp|mv|rm|chmod|chown)\\b/,\n /\\bpnpm\\s+(add|install|remove|dlx)\\b/,\n /\\bnpm\\s+(install|i|add|remove|uninstall)\\b/,\n ];\n if (writePatterns.some((pattern) => pattern.test(normalized))) {\n return { kind: \"write\" };\n }\n\n return { kind: \"write\" };\n}\n\nfunction permissionErrorForWrite(\n permissionMode: CodeAgentPermissionMode,\n toolName: string,\n): string | null {\n if (\n permissionMode === \"ask-before-edit\" ||\n permissionMode === \"auto-edit\" ||\n permissionMode === \"full-auto\"\n ) {\n return null;\n }\n if (permissionMode === \"read-only\") {\n return `Error: ${toolName} is unavailable in read-only mode.`;\n }\n return `Error: ${toolName} is blocked by the current run mode.`;\n}\n\nfunction requestCodeAgentApproval(\n runId: string,\n input: Omit<PendingCodeAgentApproval, \"id\" | \"requestedAt\">,\n): PendingCodeAgentApproval {\n const requestedAt = new Date().toISOString();\n const approval: PendingCodeAgentApproval = {\n id: `approval-${requestedAt.replace(/\\D/g, \"\").slice(0, 14)}`,\n requestedAt,\n ...input,\n };\n appendCodeAgentTranscriptEvent({\n runId,\n kind: \"status\",\n message: `Approval required: ${approval.reason}`,\n metadata: {\n status: \"needs-approval\",\n phase: \"approval-required\",\n pendingApproval: approval,\n },\n });\n updateCodeAgentRunRecord(runId, {\n status: \"needs-approval\",\n phase: \"approval-required\",\n needsApproval: true,\n progress: {\n label: \"Approval required\",\n completed: 0,\n total: 1,\n percent: 50,\n },\n metadata: {\n pendingApproval: approval,\n },\n });\n return approval;\n}\n\nfunction getPendingApproval(runId: string): PendingCodeAgentApproval | null {\n const record = getCodeAgentRunRecord(runId);\n const approval = record?.metadata?.pendingApproval;\n if (!approval || typeof approval !== \"object\") return null;\n const candidate = approval as Record<string, unknown>;\n const tool =\n candidate.tool === \"bash\" || candidate.tool === \"run_command\"\n ? candidate.tool\n : null;\n if (\n !tool ||\n typeof candidate.command !== \"string\" ||\n typeof candidate.reason !== \"string\" ||\n typeof candidate.id !== \"string\" ||\n typeof candidate.requestedAt !== \"string\"\n ) {\n return null;\n }\n return {\n id: candidate.id,\n tool,\n command: candidate.command,\n reason: candidate.reason,\n requestedAt: candidate.requestedAt,\n permissionMode:\n candidate.permissionMode === \"read-only\" ||\n candidate.permissionMode === \"ask-before-edit\" ||\n candidate.permissionMode === \"auto-edit\" ||\n candidate.permissionMode === \"full-auto\"\n ? candidate.permissionMode\n : \"full-auto\",\n };\n}\n\n// --------------- Token usage accumulator ---------------\n\ninterface StoredTokenUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n}\n\nfunction accumulateTokenUsage(\n existing: unknown,\n next: AgentLoopUsage,\n): StoredTokenUsage {\n const prev =\n existing && typeof existing === \"object\" && !Array.isArray(existing)\n ? (existing as Partial<StoredTokenUsage>)\n : {};\n return {\n inputTokens: (prev.inputTokens ?? 0) + next.inputTokens,\n outputTokens: (prev.outputTokens ?? 0) + next.outputTokens,\n cacheReadTokens: (prev.cacheReadTokens ?? 0) + next.cacheReadTokens,\n cacheWriteTokens: (prev.cacheWriteTokens ?? 0) + next.cacheWriteTokens,\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"google-oauth.d.ts","sourceRoot":"","sources":["../../src/server/google-oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAKL,KAAK,OAAO,EACb,MAAM,IAAI,CAAC;AA0DZ;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAElD;AAED,2DAA2D;AAC3D,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAEhD;AA8HD;;;;;;;;;;;GAWG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAgChD;AAED,uEAAuE;AACvE,wBAAgB,cAAc,IAAI,MAAM,CAEvC;AAED,sEAAsE;AACtE,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,EAA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AAY,CAAC,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,GACA,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC,CAuGpE;AAED;;;kEAGkE;AAClE,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ,CAMxD;AAED,wBAAgB,wBAAwB,CACtC,OAAO,SAA4B,GAClC,QAAQ,CAKV"}
@@ -542,10 +542,14 @@ export function oauthCallbackResponse(event, email, opts) {
542
542
  const callbackState = typeof query.state === "string" && query.state.length > 0
543
543
  ? query.state
544
544
  : undefined;
545
- // Mobile: deep link back to native app
545
+ // Mobile: deep link back to the native app. `isMobile` is UA-only, so this
546
+ // also fires for a plain mobile web browser with no app to handle the deep
547
+ // link — there it no-ops, so the fallback must return to the post-login URL,
548
+ // not the app root (else signed-out visitors land on the homepage).
546
549
  if (mobile) {
547
550
  const deepLink = buildOAuthCompleteDeepLink(opts.sessionToken, callbackState);
548
- return htmlResponse(`<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><title>Connected</title></head><body style="background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0"><p>Connected! Returning to app…</p><script>window.location.href=${JSON.stringify(deepLink)};setTimeout(function(){window.location.href="/"},1500)</script></body></html>`);
551
+ const webFallback = appendSessionToOAuthReturnUrl(opts.returnUrl, opts.sessionToken);
552
+ return htmlResponse(`<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><title>Connected</title></head><body style="background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0"><p>Connected! Returning to app…</p><script>window.location.href=${JSON.stringify(deepLink)};setTimeout(function(){window.location.href=${JSON.stringify(webFallback)}},1500)</script></body></html>`);
549
553
  }
550
554
  // Desktop add-account: close-tab page (must come before general desktop check
551
555
  // to ensure no deep link fires and the existing session is never switched).
@@ -1 +1 @@
1
- {"version":3,"file":"google-oauth.js","sourceRoot":"","sources":["../../src/server/google-oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,SAAS,EACT,QAAQ,EACR,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,IAAI,CAAC;AACZ,OAAO,EACL,UAAU,EACV,UAAU,EACV,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,+EAA+E;AAE/E;;oDAEoD;AACpD,SAAS,YAAY,CAAC,IAAY,EAAE,MAAM,GAAG,GAAG;IAC9C,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;QACxB,MAAM;QACN,OAAO,EAAE,EAAE,cAAc,EAAE,0BAA0B,EAAE;KACxD,CAAC,CAAC;AACL,CAAC;AAED;;;gCAGgC;AAChC,SAAS,gBAAgB,CAAC,MAAe;IACvC,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAChD,CAAC;AAED,SAAS,wBAAwB,CAC/B,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SAAS,0BAA0B,CACjC,YAAqB,EACrB,KAAc;IAEd,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;IACrC,IAAI,YAAY;QAAE,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;IACpD,IAAI,KAAK;QAAE,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACtC,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;IACjC,OAAO,MAAM;QACX,CAAC,CAAC,gCAAgC,MAAM,EAAE;QAC1C,CAAC,CAAC,8BAA8B,CAAC;AACrC,CAAC;AAED,SAAS,kBAAkB,CACzB,MAAe,EACf,KAAc,EACd,YAAqB,EACrB,KAAc;IAEd,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACjD,MAAM,GAAG,GAAG,SAAS,CAAC,CAAC,CAAC,aAAa,SAAS,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC;IACjE,IAAI,YAAY,EAAE,CAAC;QACjB,MAAM,QAAQ,GAAG,0BAA0B,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;QACjE,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QAC9C,wEAAwE;QACxE,yEAAyE;QACzE,qEAAqE;QACrE,qEAAqE;QACrE,yEAAyE;QACzE,OAAO,YAAY,CACjB,isBAAisB,GAAG,2FAA2F,YAAY,2bAA2b,YAAY,4KAA4K,CAC/5C,CAAC;IACJ,CAAC;IACD,OAAO,YAAY,CACjB,wBAAwB,CACtB,GAAG,EACH,oDAAoD,CACrD,CACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared Google OAuth utilities for all templates.\n *\n * Handles platform detection (desktop/mobile), state encoding,\n * session token creation, and deep-link responses — the logic\n * that was previously copy-pasted across every template's\n * google-auth.ts handler.\n */\n\nimport crypto from \"node:crypto\";\nimport {\n getHeader,\n getQuery,\n setResponseStatus,\n setResponseHeader,\n type H3Event,\n} from \"h3\";\nimport {\n addSession,\n getSession,\n getSessionMaxAge,\n setFrameworkSessionCookie,\n} from \"./auth.js\";\nimport { getAppName } from \"./app-name.js\";\nimport { getWorkspaceA2ADerivedSecret } from \"./derived-secret.js\";\nimport { writeDesktopSso } from \"./desktop-sso.js\";\nimport { appendSessionToOAuthReturnUrl } from \"./oauth-return-url.js\";\nimport { getConfiguredAppBasePath } from \"./app-base-path.js\";\n\n// ─── Platform Detection ─────────────────────────────────────────────────────\n\n/** Return an HTML response with the correct Content-Type.\n * Uses a web-standard Response to ensure the header survives\n * Nitro dev mode's mock-node-response pipeline. */\nfunction htmlResponse(html: string, status = 200): Response {\n return new Response(html, {\n status,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Shared markup for OAuth success \"close this tab\" pages. Renders a green\n * check icon above the message, with a little breathing room between the\n * headline and secondary line. Used by every template that goes through the\n * shared Google OAuth flow. */\nfunction oauthDebugFlowId(flowId?: string): string | undefined {\n return flowId ? flowId.slice(-10) : undefined;\n}\n\nfunction oauthSuccessCloseTabHtml(\n headline: string,\n footnote: string,\n debugFlowId?: string,\n): string {\n const debug = debugFlowId\n ? `<p style=\"font-size:11px;color:#555;margin:12px 0 0 0\">Debug flow: ${escapeHtml(debugFlowId)}</p>`\n : \"\";\n return `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#22c55e\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M9 12l2 2l4 -4\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0\">${headline}</p><p style=\"font-size:13px;color:#888;margin:0\">${footnote}</p>${debug}<script>console.info(\"[agent-native][google-oauth] success page loaded\",{flow:${JSON.stringify(debugFlowId || null)}});setTimeout(function(){try{window.close()}catch(e){}},250)</script></body></html>`;\n}\n\n/**\n * HTML escape — minimal but covers the cases that matter when interpolating\n * user-controlled values into our OAuth callback HTML. Mirrors the helper in\n * email-template.ts; kept inline here to avoid a circular import.\n */\nfunction escapeHtml(s: string): string {\n return String(s ?? \"\")\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/**\n * Detect requests from the Agent Native desktop app specifically.\n *\n * The desktop app appends `AgentNativeDesktop/<version>` to its user-agent\n * (see `packages/desktop-app/src/main/index.ts`). We check for that marker\n * rather than matching generic `Electron`, which would also match other\n * Electron-based webviews like Builder.io's Fusion, Slack desktop, Discord,\n * etc. Falsely treating those as \"the desktop app\" sends users to the\n * `agentnative://oauth-complete` deep-link success page after Google sign-in,\n * where the protocol handler can't fire and the \"Open Agent Native\" button\n * does nothing.\n *\n * Kept exported as `isElectron` for backwards compatibility with consumers.\n */\nexport function isElectron(event: H3Event): boolean {\n return /AgentNativeDesktop/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/** Detect requests from a mobile browser (iOS/Android). */\nexport function isMobile(event: H3Event): boolean {\n return /iPhone|iPad|iPod|Android/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/**\n * Build the static allowlist of origins we trust for `getOrigin`. Reads\n * deployment-known public URLs. Each entry is normalised to\n * `${proto}://${host}` (no path). Duplicates collapse, invalid entries are\n * dropped silently.\n */\nconst EXPLICIT_PUBLIC_ORIGIN_ENV_KEYS = [\n \"WORKSPACE_OAUTH_ORIGIN\",\n \"VITE_WORKSPACE_OAUTH_ORIGIN\",\n \"APP_URL\",\n \"VITE_APP_URL\",\n \"BETTER_AUTH_URL\",\n \"VITE_BETTER_AUTH_URL\",\n \"URL\",\n \"DEPLOY_URL\",\n] as const;\n\nconst WORKSPACE_GATEWAY_ORIGIN_ENV_KEYS = [\n \"WORKSPACE_GATEWAY_URL\",\n \"VITE_WORKSPACE_GATEWAY_URL\",\n] as const;\n\nfunction normalizeOrigin(raw: string | undefined): string | undefined {\n if (!raw) return undefined;\n try {\n const u = new URL(raw);\n return `${u.protocol}//${u.host}`;\n } catch {\n return undefined;\n }\n}\n\nfunction addNormalizedOrigin(\n out: Set<string>,\n raw: string | undefined,\n options: { allowLoopback: boolean },\n): void {\n const origin = normalizeOrigin(raw);\n if (!origin) return;\n if (!options.allowLoopback && isLoopbackOrigin(origin)) return;\n out.add(origin);\n}\n\nfunction firstOriginFromEnv(\n keys: readonly string[],\n options: { allowLoopback: boolean },\n): string | undefined {\n for (const key of keys) {\n const origin = normalizeOrigin(process.env[key]);\n if (!origin) continue;\n if (!options.allowLoopback && isLoopbackOrigin(origin)) continue;\n return origin;\n }\n return undefined;\n}\n\nfunction getConfiguredOriginAllowlist(): Set<string> {\n const out = new Set<string>();\n for (const key of EXPLICIT_PUBLIC_ORIGIN_ENV_KEYS) {\n addNormalizedOrigin(out, process.env[key], { allowLoopback: true });\n }\n for (const key of WORKSPACE_GATEWAY_ORIGIN_ENV_KEYS) {\n addNormalizedOrigin(out, process.env[key], { allowLoopback: false });\n }\n return out;\n}\n\nfunction getWorkspaceCallbackOrigin(): string | undefined {\n const publicAuthOrigin = firstOriginFromEnv(EXPLICIT_PUBLIC_ORIGIN_ENV_KEYS, {\n allowLoopback: true,\n });\n if (publicAuthOrigin) return publicAuthOrigin;\n\n return firstOriginFromEnv(WORKSPACE_GATEWAY_ORIGIN_ENV_KEYS, {\n allowLoopback: false,\n });\n}\n\nfunction isLoopbackHost(host: string | undefined): boolean {\n if (!host) return false;\n try {\n const parsed = new URL(`http://${host}`);\n return (\n parsed.hostname === \"localhost\" ||\n parsed.hostname === \"127.0.0.1\" ||\n parsed.hostname === \"::1\" ||\n parsed.hostname === \"[::1]\"\n );\n } catch {\n return false;\n }\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n return isLoopbackHost(new URL(origin).host);\n } catch {\n return false;\n }\n}\n\nfunction isBuilderPreviewHost(host: string | undefined): boolean {\n if (!host) return false;\n try {\n const parsed = new URL(`http://${host}`);\n const hostname = parsed.hostname.toLowerCase();\n return (\n hostname === \"builderio.xyz\" ||\n hostname.endsWith(\".builderio.xyz\") ||\n hostname === \"builderio.dev\" ||\n hostname.endsWith(\".builderio.dev\") ||\n hostname === \"builder.codes\" ||\n hostname.endsWith(\".builder.codes\") ||\n hostname === \"builder.io\" ||\n hostname.endsWith(\".builder.io\") ||\n hostname === \"builder.my\" ||\n hostname.endsWith(\".builder.my\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Get the origin from forwarded headers or Host.\n *\n * Defends against Host-header injection: in production we require the resolved\n * origin to match `APP_URL` / `BETTER_AUTH_URL` / `WORKSPACE_GATEWAY_URL`,\n * falling back to those values when inbound headers are missing or don't match.\n * In dev we accept inbound `Host` so localhost / ngrok / preview hosts keep\n * working without configuration, except workspace OAuth requests from loopback\n * or Builder preview hosts use the configured gateway origin when one exists.\n * The protocol defaults to `https` in production (so a TLS-terminating proxy\n * that drops `x-forwarded-proto` doesn't downgrade us to plain HTTP).\n */\nexport function getOrigin(event: H3Event): string {\n const headerHost =\n getHeader(event, \"x-forwarded-host\") || getHeader(event, \"host\");\n const isProd = process.env.NODE_ENV === \"production\";\n const headerProto =\n getHeader(event, \"x-forwarded-proto\") || (isProd ? \"https\" : \"http\");\n const workspaceCallbackOrigin = isWorkspaceOAuthCallbackRelayEnabled()\n ? getWorkspaceCallbackOrigin()\n : undefined;\n\n if (\n workspaceCallbackOrigin &&\n (isLoopbackHost(headerHost) || isBuilderPreviewHost(headerHost))\n ) {\n return workspaceCallbackOrigin;\n }\n\n if (isProd) {\n const allow = getConfiguredOriginAllowlist();\n // If the deploy declares its public URL, prefer it over inbound headers.\n if (allow.size > 0) {\n const inbound = headerHost ? `${headerProto}://${headerHost}` : \"\";\n if (inbound && allow.has(inbound)) return inbound;\n // Inbound didn't match — fall back to the first configured origin.\n return [...allow][0];\n }\n // No allowlist configured: still default to https, but accept the\n // inbound Host (best we can do without a configured base URL).\n return `${headerProto}://${headerHost ?? \"\"}`;\n }\n\n return `${headerProto}://${headerHost ?? \"localhost\"}`;\n}\n\n/** App mount prefix, if the template is served under APP_BASE_PATH. */\nexport function getAppBasePath(): string {\n return getConfiguredAppBasePath();\n}\n\n/** Build an absolute same-origin URL that preserves APP_BASE_PATH. */\nexport function getAppUrl(event: H3Event, path = \"/\"): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${getOrigin(event)}${getAppBasePath()}${cleanPath}`;\n}\n\nfunction isWorkspaceOAuthCallbackRelayEnabled(): boolean {\n return (\n process.env.AGENT_NATIVE_WORKSPACE === \"1\" ||\n process.env.VITE_AGENT_NATIVE_WORKSPACE === \"1\"\n );\n}\n\nfunction isFrameworkOAuthCallbackPath(pathname: string): boolean {\n return (\n pathname.startsWith(\"/_agent-native/\") &&\n (pathname.endsWith(\"/callback\") || pathname.includes(\"/callback/\"))\n );\n}\n\nfunction getOriginalRequestPath(event: H3Event): string {\n const mountedPathname = (event as any).context?._mountedPathname;\n if (typeof mountedPathname === \"string\" && mountedPathname) {\n return mountedPathname;\n }\n\n const urlPathname = (event as any).url?.pathname;\n if (typeof urlPathname === \"string\" && urlPathname) return urlPathname;\n\n const nodeUrl = event.node?.req?.url;\n if (typeof nodeUrl === \"string\" && nodeUrl) {\n const queryStart = nodeUrl.indexOf(\"?\");\n return queryStart >= 0 ? nodeUrl.slice(0, queryStart) : nodeUrl;\n }\n\n const eventPath = (event as any).path;\n if (typeof eventPath === \"string\" && eventPath) {\n const queryStart = eventPath.indexOf(\"?\");\n return queryStart >= 0 ? eventPath.slice(0, queryStart) : eventPath;\n }\n\n return \"/\";\n}\n\nfunction isRequestUnderAppBasePath(event: H3Event): boolean {\n const basePath = getAppBasePath();\n if (!basePath) return false;\n const requestPath = getOriginalRequestPath(event);\n return (\n requestPath === `${basePath}/_agent-native` ||\n requestPath.startsWith(`${basePath}/_agent-native/`)\n );\n}\n\nfunction getDefaultOAuthRedirectUrl(event: H3Event, path: string): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n if (\n isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(cleanPath)\n ) {\n return `${getOrigin(event)}${cleanPath}`;\n }\n const basePath = isRequestUnderAppBasePath(event) ? getAppBasePath() : \"\";\n return `${getOrigin(event)}${basePath}${cleanPath}`;\n}\n\n// ─── redirect_uri Allowlist ──────────────────────────────────────────────────\n\n/**\n * Validate a user-supplied `redirect_uri` for OAuth flows.\n *\n * Defends against authorization-code interception (RFC 6819 §4.4.1.7):\n * even though the upstream provider (Google/Atlassian/Zoom) refuses\n * unregistered redirect URIs, prefix-style registrations and side\n * registrations on the same host let a malicious caller swap in an\n * attacker-controlled URI that the provider still accepts. We reject any\n * candidate that isn't on this server's own origin AND under the\n * framework's `/_agent-native/` namespace. Returns the validated URI on\n * success, or `undefined` on rejection — callers must treat `undefined`\n * as a 400.\n *\n * The intentional shape is exact-prefix:\n * - Origin must equal `getOrigin(event)` — no Host-header injection\n * reusing somebody else's registered redirect URI.\n * - Path must start with `${appBasePath}/_agent-native/` so we never\n * hand auth codes to a public marketing or open-redirect endpoint\n * on the same registered host.\n *\n * For desktop / native flows that need ephemeral `http://127.0.0.1:<port>`\n * loopback URIs, callers should validate those at the template level\n * with a dedicated allowlist — this helper rejects them by design.\n */\nexport function isAllowedOAuthRedirectUri(\n candidate: string,\n event: H3Event,\n): boolean {\n if (typeof candidate !== \"string\" || candidate.length === 0) return false;\n let url: URL;\n try {\n url = new URL(candidate);\n } catch {\n return false;\n }\n // Must be same origin as our server.\n const expectedOrigin = getOrigin(event);\n let expectedUrl: URL;\n try {\n expectedUrl = new URL(expectedOrigin);\n } catch {\n return false;\n }\n if (url.protocol !== expectedUrl.protocol) return false;\n if (url.host !== expectedUrl.host) return false;\n // Must live under the framework's namespace. Workspace deploys can route\n // root /_agent-native/* to Dispatch even when Dispatch itself is mounted at\n // /dispatch, but app-prefixed requests should not be able to swap their\n // callback to that root namespace.\n const basePath = getAppBasePath();\n const allowedPrefixes =\n basePath && isRequestUnderAppBasePath(event)\n ? [\n `${basePath}/_agent-native/`,\n ...(isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(url.pathname)\n ? [\"/_agent-native/\"]\n : []),\n ]\n : [\"/_agent-native/\"];\n if (!allowedPrefixes.some((prefix) => url.pathname.startsWith(prefix))) {\n return false;\n }\n return true;\n}\n\n/**\n * Resolve the `redirect_uri` for an outbound OAuth `auth-url` request.\n *\n * Reads `?redirect_uri=` from the query and validates it via\n * `isAllowedOAuthRedirectUri`. Returns:\n * - the validated URI when supplied and allowed, OR\n * - the framework default when no override was supplied, OR\n * - `null` when an override was supplied but rejected — callers must\n * respond with 400 in that case.\n *\n * Templates that need a non-default redirect path can pass it via\n * `defaultPath` (e.g. `\"/_agent-native/google/desktop-callback\"` for\n * desktop flows).\n */\nexport function resolveOAuthRedirectUri(\n event: H3Event,\n defaultPath = \"/_agent-native/google/callback\",\n): string | null {\n const supplied = getQuery(event).redirect_uri;\n if (typeof supplied === \"string\" && supplied.length > 0) {\n return isAllowedOAuthRedirectUri(supplied, event) ? supplied : null;\n }\n return getDefaultOAuthRedirectUrl(event, defaultPath);\n}\n\n// ─── OAuth State ─────────────────────────────────────────────────────────────\n\nexport interface OAuthStatePayload {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n /**\n * Same-origin path to redirect to after a successful web-flow sign-in.\n * Threaded through the (HMAC-signed) state so it survives the round trip\n * to Google. Validated again on decode via safeReturnPath as defence in\n * depth. Has no effect on desktop / mobile / add-account flows, which\n * use their own deep-link / close-tab handling.\n */\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Ephemeral in-memory state-signing key for development. Generated lazily\n * on first read so dev sessions don't depend on filesystem writability or\n * env-var configuration. Sessions reset on each restart, which is fine\n * for dev — no real users / production data are involved.\n */\nlet _devStateSigningKey: string | undefined;\n\n/**\n * Derive a server-only signing key for HMAC verification of OAuth state.\n *\n * Uses a dedicated secret — never an OAuth client secret. Reusing a\n * client_secret (which is shared with Google / GitHub / Atlassian) as our\n * own HMAC key conflates two trust domains: rotating the client secret\n * silently invalidates every in-flight OAuth state, and any leak of the\n * client secret also lets an attacker forge our state envelopes.\n *\n * Resolution order:\n * 1. OAUTH_STATE_SECRET (preferred — dedicated to this purpose)\n * 2. BETTER_AUTH_SECRET (already used by Better Auth as a server secret)\n * 3. Hosted workspace deploys derive a per-purpose key from A2A_SECRET\n * 4. In dev only, an ephemeral random key (per-process)\n *\n * In production, throws if no usable server secret is set.\n */\nfunction getStateSigningKey(): string {\n const secret =\n process.env.OAUTH_STATE_SECRET ||\n process.env.BETTER_AUTH_SECRET ||\n getWorkspaceA2ADerivedSecret(\"oauth-state\");\n if (secret) return secret;\n\n const isProd = process.env.NODE_ENV === \"production\";\n if (isProd) {\n throw new Error(\n \"OAuth state signing requires a server secret. \" +\n \"Set OAUTH_STATE_SECRET, BETTER_AUTH_SECRET, or A2A_SECRET in production workspace deploys.\",\n );\n }\n\n if (!_devStateSigningKey) {\n _devStateSigningKey = crypto.randomBytes(32).toString(\"hex\");\n }\n return _devStateSigningKey;\n}\n\n/**\n * Options for the named-argument form of {@link encodeOAuthState}.\n * Prefer this form — the positional overload is easy to misuse (the mail\n * and calendar templates historically passed `flowId` in the `returnUrl`\n * slot, smuggling state into a defence-in-depth path).\n */\nexport interface EncodeOAuthStateOptions {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Encode OAuth state into a signed base64url string.\n * The state is HMAC-signed so the callback can verify it wasn't forged,\n * preventing CSRF attacks on the OAuth flow.\n *\n * Two call shapes are supported:\n * - Recommended: pass an options object — clear, mismatch-proof.\n * `encodeOAuthState({ redirectUri, owner, desktop, ... })`\n * - Legacy positional form (kept working for backward compatibility):\n * `encodeOAuthState(redirectUri, owner, desktop, addAccount, app, returnUrl, flowId)`.\n * Callers should migrate to the options form — see the audit on\n * templates/mail and templates/calendar where the positional shape\n * led to `flowId` being smuggled in via the `returnUrl` slot.\n */\nexport function encodeOAuthState(opts: EncodeOAuthStateOptions): string;\nexport function encodeOAuthState(\n redirectUri: string,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string;\nexport function encodeOAuthState(\n redirectUriOrOpts: string | EncodeOAuthStateOptions,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string {\n const opts: EncodeOAuthStateOptions =\n typeof redirectUriOrOpts === \"string\"\n ? {\n redirectUri: redirectUriOrOpts,\n owner,\n desktop,\n addAccount,\n app,\n returnUrl,\n flowId,\n }\n : redirectUriOrOpts;\n\n const nonce = crypto.randomBytes(8).toString(\"hex\");\n const payload: Record<string, string | boolean> = {\n n: nonce,\n r: opts.redirectUri,\n };\n if (opts.owner) payload.o = opts.owner;\n if (opts.desktop) payload.d = true;\n if (opts.addAccount) payload.a = true;\n if (opts.app) payload.app = opts.app;\n if (opts.returnUrl) payload.r2 = opts.returnUrl;\n if (opts.flowId) payload.f = opts.flowId;\n const data = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n const sig = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n return `${data}.${sig}`;\n}\n\n/**\n * Decode and verify OAuth state from the callback's state query parameter.\n * Rejects forged or tampered state by checking the HMAC signature.\n * Falls back to the provided URI if decoding or verification fails.\n */\nexport function decodeOAuthState(\n stateParam: string | undefined,\n fallbackUri: string,\n): OAuthStatePayload {\n if (stateParam) {\n try {\n const dotIdx = stateParam.lastIndexOf(\".\");\n if (dotIdx === -1) return { redirectUri: fallbackUri };\n\n const data = stateParam.slice(0, dotIdx);\n const sig = stateParam.slice(dotIdx + 1);\n const expected = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n\n if (\n sig.length !== expected.length ||\n !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))\n ) {\n return { redirectUri: fallbackUri };\n }\n\n const parsed = JSON.parse(Buffer.from(data, \"base64url\").toString());\n return {\n redirectUri: parsed.r || fallbackUri,\n owner: parsed.o || undefined,\n desktop: !!parsed.d,\n addAccount: !!parsed.a,\n app: typeof parsed.app === \"string\" ? parsed.app : undefined,\n // Pass returnUrl through as-is — same-origin validation runs at the\n // consumer (oauthCallbackResponse → safeReturnPath). The state is\n // HMAC-signed, but we still validate at consumption as defence in\n // depth in case the signing key ever leaks.\n returnUrl: typeof parsed.r2 === \"string\" ? parsed.r2 : undefined,\n flowId: parsed.f || undefined,\n };\n } catch {}\n }\n return { redirectUri: fallbackUri };\n}\n\n// ─── Session Creation ────────────────────────────────────────────────────────\n\nexport interface OAuthOwnerResult {\n owner: string | undefined;\n hasProductionSession: boolean;\n}\n\n/**\n * Determine the token owner from the current session and OAuth state.\n * Call this BEFORE exchangeCode to get the owner parameter.\n */\nexport async function resolveOAuthOwner(\n event: H3Event,\n stateOwner?: string,\n): Promise<OAuthOwnerResult> {\n const existingSession = await getSession(event);\n const hasProductionSession = !!existingSession?.email;\n const owner = hasProductionSession\n ? existingSession!.email\n : stateOwner || undefined;\n\n return { owner, hasProductionSession };\n}\n\nexport interface OAuthSessionResult {\n sessionToken: string | undefined;\n}\n\n/**\n * Create a session token after a successful OAuth exchange.\n *\n * Desktop and mobile apps have separate cookie jars from the system\n * browser, so they always get a fresh session token (even if the browser\n * already has one). The token is then passed via deep link so the native\n * app can inject it.\n */\nexport async function createOAuthSession(\n event: H3Event,\n email: string,\n opts: {\n hasProductionSession: boolean;\n desktop?: boolean;\n },\n): Promise<OAuthSessionResult> {\n const mobile = isMobile(event);\n const needsDeepLink = opts.desktop || mobile;\n const maxAge = getSessionMaxAge();\n\n let sessionToken: string | undefined;\n if (!opts.hasProductionSession || needsDeepLink) {\n sessionToken = crypto.randomBytes(32).toString(\"hex\");\n await addSession(sessionToken, email);\n setFrameworkSessionCookie(event, sessionToken);\n // Desktop SSO: record this session in the home-dir broker file so\n // sibling templates (each with its own database) can resolve the\n // same token without a DB row of their own. Only the PRIMARY\n // sign-in writes the broker — if a production session already\n // exists, this is an add-account flow (connecting a secondary\n // Google account for scraping) and must never switch the active\n // user across sibling templates.\n if (opts.desktop && !opts.hasProductionSession) {\n await writeDesktopSso({\n email,\n token: sessionToken,\n expiresAt: Date.now() + maxAge * 1000,\n });\n }\n }\n\n return { sessionToken };\n}\n\n// ─── Callback Responses ──────────────────────────────────────────────────────\n\n/**\n * Return the appropriate response after a successful OAuth callback.\n *\n * Handles mobile deep links, desktop deep links, add-account close-tab\n * pages, and plain web redirects — so templates don't have to.\n */\nexport function oauthCallbackResponse(\n event: H3Event,\n email: string,\n opts: {\n sessionToken?: string;\n desktop?: boolean;\n addAccount?: boolean;\n /**\n * Same-origin path to return the viewer to after a successful web\n * sign-in. Validated via safeReturnPath; falls back to \"/\" for any\n * shape that escapes same-origin. Has no effect on desktop / mobile\n * / add-account flows — those use their own deep-link handling.\n */\n returnUrl?: string;\n flowId?: string;\n appName?: string;\n },\n): Response | string | unknown | Promise<Response | string | unknown> {\n const mobile = isMobile(event);\n const query = getQuery(event);\n const callbackState =\n typeof query.state === \"string\" && query.state.length > 0\n ? query.state\n : undefined;\n\n // Mobile: deep link back to native app\n if (mobile) {\n const deepLink = buildOAuthCompleteDeepLink(\n opts.sessionToken,\n callbackState,\n );\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\"><title>Connected</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p>Connected! Returning to app…</p><script>window.location.href=${JSON.stringify(deepLink)};setTimeout(function(){window.location.href=\"/\"},1500)</script></body></html>`,\n );\n }\n\n // Desktop add-account: close-tab page (must come before general desktop check\n // to ensure no deep link fires and the existing session is never switched).\n if (opts.desktop && opts.addAccount) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n oauthDebugFlowId(opts.flowId),\n ),\n );\n }\n\n // Electron desktop exchange flow: mail/calendar still pass a flow id so the\n // renderer can poll as a fallback, but the main handoff should use the\n // protocol deep link so the popup returns focus to the desktop app.\n if (opts.desktop && opts.flowId && isElectron(event) && opts.sessionToken) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Desktop exchange flow (non-Electron tray app): the tray app polls the\n // desktop-exchange endpoint for the token — no deep link needed.\n if (opts.desktop && opts.flowId) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Signed in as ${safeEmail}!` : \"Signed in!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n oauthDebugFlowId(opts.flowId),\n ),\n );\n }\n\n // Desktop login: deep link back to Electron app — only when the callback\n // request actually carries the AgentNativeDesktop UA marker. Without this\n // check, any client whose OAuth state was minted with `desktop=true` (e.g.\n // a stale link, or an upstream that wrongly set `?desktop=1`) would land\n // on the `agentnative://` page where the deep link can't fire and the\n // \"Open Agent Native\" button does nothing — surfaces inside Builder.io's\n // Fusion webview hit this exact dead-end. Fall through to the web flow\n // for non-Agent-Native-Desktop clients so they get a real redirect.\n if (opts.desktop && isElectron(event)) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Add-account web flow: close-tab page. The email is rendered into the\n // page via DOM `textContent` (safe), but we still JSON-stringify so a\n // payload containing `</script>` can't break out of the script tag —\n // and explicitly assert it's a string so a callbacks like `null` or\n // an object won't end up serialised into the page.\n if (opts.addAccount) {\n const safeEmail = JSON.stringify(typeof email === \"string\" ? email : \"\");\n return htmlResponse(`<!DOCTYPE html><html><body><script>\n window.close();\n var p = document.createElement('p');\n p.style.cssText = 'font-family:system-ui;text-align:center;margin-top:40vh';\n p.textContent = 'Connected ' + ${safeEmail} + '! You can close this tab.';\n document.body.appendChild(p);\n </script></body></html>`);\n }\n\n // Web: redirect to the requested return target. Path-only returns stay\n // same-origin; Builder desktop workspace returns may point back to the\n // local loopback gateway and carry the short-lived `_session` bridge so\n // the local app can promote the newly created hosted OAuth session.\n setResponseStatus(event, 302);\n setResponseHeader(\n event,\n \"Location\",\n appendSessionToOAuthReturnUrl(opts.returnUrl, opts.sessionToken),\n );\n setResponseHeader(event, \"Referrer-Policy\", \"no-referrer\");\n return \"\";\n}\n\n/** HTML error page for OAuth failures. The message is HTML-escaped — most\n * callers pass `error.message` from a token-exchange or userinfo failure,\n * which can echo upstream provider strings (and historically attacker-\n * controlled query params via the `error_description` field). */\nexport function oauthErrorPage(message: string): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connection failed</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;text-align:center\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#ef4444\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M15 9l-6 6\"/><path d=\"M9 9l6 6\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0;color:#ddd\">${safe}</p><p style=\"font-size:13px;color:#888;margin:0\"><a href=\"/\" style=\"color:#888;text-decoration:underline;text-underline-offset:3px\">Back to login</a></p></body></html>`,\n 400,\n );\n}\n\nexport function oauthDesktopExchangePage(\n message = \"Returning to the app...\",\n): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Returning</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p style=\"font-size:14px\">${safe}</p><script>window.close()</script></body></html>`,\n );\n}\n\n// ─── Internal ────────────────────────────────────────────────────────────────\n\nfunction resolveOAuthAppName(explicit?: string): string {\n const raw = explicit || getAppName() || \"Agent Native\";\n if (!/^[a-z0-9_-]+$/.test(raw)) return raw;\n return raw\n .split(/[-_]+/)\n .filter(Boolean)\n .map((word) => word[0].toUpperCase() + word.slice(1))\n .join(\" \");\n}\n\nfunction buildOAuthCompleteDeepLink(\n sessionToken?: string,\n state?: string,\n): string {\n const params = new URLSearchParams();\n if (sessionToken) params.set(\"token\", sessionToken);\n if (state) params.set(\"state\", state);\n const suffix = params.toString();\n return suffix\n ? `agentnative://oauth-complete?${suffix}`\n : \"agentnative://oauth-complete\";\n}\n\nfunction desktopSuccessPage(\n _event: H3Event,\n email?: string,\n sessionToken?: string,\n state?: string,\n): Response {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n if (sessionToken) {\n const deepLink = buildOAuthCompleteDeepLink(sessionToken, state);\n const deepLinkJson = JSON.stringify(deepLink);\n // Defence in depth: if this page somehow gets served to a UA that isn't\n // the Agent Native desktop app (server gate bypassed, stale link, etc.),\n // skip the `agentnative://` deep link entirely and bounce to the app\n // root. The deep link silently fails outside the desktop app and the\n // \"Open Agent Native\" button is a dead end in a generic browser/webview.\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title><style>@keyframes spin{to{transform:rotate(360deg)}}@keyframes fadeIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.spinner{width:28px;height:28px;border:2px solid #333;border-top-color:#fff;border-radius:50%;animation:spin .8s linear infinite}.fallback{display:none;flex-direction:column;align-items:center;gap:8px;animation:fadeIn .2s ease-out}.fallback.show{display:flex}</style></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;gap:16px\"><p style=\"font-size:16px;margin:0\">${msg}</p><div id=\"loading\" class=\"spinner\"></div><div id=\"fallback\" class=\"fallback\"><a href=${deepLinkJson} style=\"display:inline-block;padding:10px 24px;background:#fff;color:#000;border-radius:8px;text-decoration:none;font-size:14px;font-weight:500\">Open Agent Native</a><p style=\"font-size:12px;color:#666;margin:0\">If the app didn\\u2019t open automatically, click the button above.</p></div><script>(function(){var ua=(navigator.userAgent||\"\");if(ua.indexOf(\"AgentNativeDesktop\")===-1){window.location.replace(\"/\");return}window.location.href=${deepLinkJson};setTimeout(function(){document.getElementById(\"loading\").style.display=\"none\";document.getElementById(\"fallback\").classList.add(\"show\")},3000)})()</script></body></html>`,\n );\n }\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n \"You can close this tab and return to Agent Native.\",\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"google-oauth.js","sourceRoot":"","sources":["../../src/server/google-oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,SAAS,EACT,QAAQ,EACR,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,IAAI,CAAC;AACZ,OAAO,EACL,UAAU,EACV,UAAU,EACV,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe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AkB,CACzB,MAAe,EACf,KAAc,EACd,YAAqB,EACrB,KAAc;IAEd,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACjD,MAAM,GAAG,GAAG,SAAS,CAAC,CAAC,CAAC,aAAa,SAAS,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC;IACjE,IAAI,YAAY,EAAE,CAAC;QACjB,MAAM,QAAQ,GAAG,0BAA0B,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;QACjE,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QAC9C,wEAAwE;QACxE,yEAAyE;QACzE,qEAAqE;QACrE,qEAAqE;QACrE,yEAAyE;QACzE,OAAO,YAAY,CACjB,isBAAisB,GAAG,2FAA2F,YAAY,2bAA2b,YAAY,4KAA4K,CAC/5C,CAAC;IACJ,CAAC;IACD,OAAO,YAAY,CACjB,wBAAwB,CACtB,GAAG,EACH,oDAAoD,CACrD,CACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared Google OAuth utilities for all templates.\n *\n * Handles platform detection (desktop/mobile), state encoding,\n * session token creation, and deep-link responses — the logic\n * that was previously copy-pasted across every template's\n * google-auth.ts handler.\n */\n\nimport crypto from \"node:crypto\";\nimport {\n getHeader,\n getQuery,\n setResponseStatus,\n setResponseHeader,\n type H3Event,\n} from \"h3\";\nimport {\n addSession,\n getSession,\n getSessionMaxAge,\n setFrameworkSessionCookie,\n} from \"./auth.js\";\nimport { getAppName } from \"./app-name.js\";\nimport { getWorkspaceA2ADerivedSecret } from \"./derived-secret.js\";\nimport { writeDesktopSso } from \"./desktop-sso.js\";\nimport { appendSessionToOAuthReturnUrl } from \"./oauth-return-url.js\";\nimport { getConfiguredAppBasePath } from \"./app-base-path.js\";\n\n// ─── Platform Detection ─────────────────────────────────────────────────────\n\n/** Return an HTML response with the correct Content-Type.\n * Uses a web-standard Response to ensure the header survives\n * Nitro dev mode's mock-node-response pipeline. */\nfunction htmlResponse(html: string, status = 200): Response {\n return new Response(html, {\n status,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Shared markup for OAuth success \"close this tab\" pages. Renders a green\n * check icon above the message, with a little breathing room between the\n * headline and secondary line. Used by every template that goes through the\n * shared Google OAuth flow. */\nfunction oauthDebugFlowId(flowId?: string): string | undefined {\n return flowId ? flowId.slice(-10) : undefined;\n}\n\nfunction oauthSuccessCloseTabHtml(\n headline: string,\n footnote: string,\n debugFlowId?: string,\n): string {\n const debug = debugFlowId\n ? `<p style=\"font-size:11px;color:#555;margin:12px 0 0 0\">Debug flow: ${escapeHtml(debugFlowId)}</p>`\n : \"\";\n return `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#22c55e\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M9 12l2 2l4 -4\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0\">${headline}</p><p style=\"font-size:13px;color:#888;margin:0\">${footnote}</p>${debug}<script>console.info(\"[agent-native][google-oauth] success page loaded\",{flow:${JSON.stringify(debugFlowId || null)}});setTimeout(function(){try{window.close()}catch(e){}},250)</script></body></html>`;\n}\n\n/**\n * HTML escape — minimal but covers the cases that matter when interpolating\n * user-controlled values into our OAuth callback HTML. Mirrors the helper in\n * email-template.ts; kept inline here to avoid a circular import.\n */\nfunction escapeHtml(s: string): string {\n return String(s ?? \"\")\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/**\n * Detect requests from the Agent Native desktop app specifically.\n *\n * The desktop app appends `AgentNativeDesktop/<version>` to its user-agent\n * (see `packages/desktop-app/src/main/index.ts`). We check for that marker\n * rather than matching generic `Electron`, which would also match other\n * Electron-based webviews like Builder.io's Fusion, Slack desktop, Discord,\n * etc. Falsely treating those as \"the desktop app\" sends users to the\n * `agentnative://oauth-complete` deep-link success page after Google sign-in,\n * where the protocol handler can't fire and the \"Open Agent Native\" button\n * does nothing.\n *\n * Kept exported as `isElectron` for backwards compatibility with consumers.\n */\nexport function isElectron(event: H3Event): boolean {\n return /AgentNativeDesktop/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/** Detect requests from a mobile browser (iOS/Android). */\nexport function isMobile(event: H3Event): boolean {\n return /iPhone|iPad|iPod|Android/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/**\n * Build the static allowlist of origins we trust for `getOrigin`. Reads\n * deployment-known public URLs. Each entry is normalised to\n * `${proto}://${host}` (no path). Duplicates collapse, invalid entries are\n * dropped silently.\n */\nconst EXPLICIT_PUBLIC_ORIGIN_ENV_KEYS = [\n \"WORKSPACE_OAUTH_ORIGIN\",\n \"VITE_WORKSPACE_OAUTH_ORIGIN\",\n \"APP_URL\",\n \"VITE_APP_URL\",\n \"BETTER_AUTH_URL\",\n \"VITE_BETTER_AUTH_URL\",\n \"URL\",\n \"DEPLOY_URL\",\n] as const;\n\nconst WORKSPACE_GATEWAY_ORIGIN_ENV_KEYS = [\n \"WORKSPACE_GATEWAY_URL\",\n \"VITE_WORKSPACE_GATEWAY_URL\",\n] as const;\n\nfunction normalizeOrigin(raw: string | undefined): string | undefined {\n if (!raw) return undefined;\n try {\n const u = new URL(raw);\n return `${u.protocol}//${u.host}`;\n } catch {\n return undefined;\n }\n}\n\nfunction addNormalizedOrigin(\n out: Set<string>,\n raw: string | undefined,\n options: { allowLoopback: boolean },\n): void {\n const origin = normalizeOrigin(raw);\n if (!origin) return;\n if (!options.allowLoopback && isLoopbackOrigin(origin)) return;\n out.add(origin);\n}\n\nfunction firstOriginFromEnv(\n keys: readonly string[],\n options: { allowLoopback: boolean },\n): string | undefined {\n for (const key of keys) {\n const origin = normalizeOrigin(process.env[key]);\n if (!origin) continue;\n if (!options.allowLoopback && isLoopbackOrigin(origin)) continue;\n return origin;\n }\n return undefined;\n}\n\nfunction getConfiguredOriginAllowlist(): Set<string> {\n const out = new Set<string>();\n for (const key of EXPLICIT_PUBLIC_ORIGIN_ENV_KEYS) {\n addNormalizedOrigin(out, process.env[key], { allowLoopback: true });\n }\n for (const key of WORKSPACE_GATEWAY_ORIGIN_ENV_KEYS) {\n addNormalizedOrigin(out, process.env[key], { allowLoopback: false });\n }\n return out;\n}\n\nfunction getWorkspaceCallbackOrigin(): string | undefined {\n const publicAuthOrigin = firstOriginFromEnv(EXPLICIT_PUBLIC_ORIGIN_ENV_KEYS, {\n allowLoopback: true,\n });\n if (publicAuthOrigin) return publicAuthOrigin;\n\n return firstOriginFromEnv(WORKSPACE_GATEWAY_ORIGIN_ENV_KEYS, {\n allowLoopback: false,\n });\n}\n\nfunction isLoopbackHost(host: string | undefined): boolean {\n if (!host) return false;\n try {\n const parsed = new URL(`http://${host}`);\n return (\n parsed.hostname === \"localhost\" ||\n parsed.hostname === \"127.0.0.1\" ||\n parsed.hostname === \"::1\" ||\n parsed.hostname === \"[::1]\"\n );\n } catch {\n return false;\n }\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n return isLoopbackHost(new URL(origin).host);\n } catch {\n return false;\n }\n}\n\nfunction isBuilderPreviewHost(host: string | undefined): boolean {\n if (!host) return false;\n try {\n const parsed = new URL(`http://${host}`);\n const hostname = parsed.hostname.toLowerCase();\n return (\n hostname === \"builderio.xyz\" ||\n hostname.endsWith(\".builderio.xyz\") ||\n hostname === \"builderio.dev\" ||\n hostname.endsWith(\".builderio.dev\") ||\n hostname === \"builder.codes\" ||\n hostname.endsWith(\".builder.codes\") ||\n hostname === \"builder.io\" ||\n hostname.endsWith(\".builder.io\") ||\n hostname === \"builder.my\" ||\n hostname.endsWith(\".builder.my\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Get the origin from forwarded headers or Host.\n *\n * Defends against Host-header injection: in production we require the resolved\n * origin to match `APP_URL` / `BETTER_AUTH_URL` / `WORKSPACE_GATEWAY_URL`,\n * falling back to those values when inbound headers are missing or don't match.\n * In dev we accept inbound `Host` so localhost / ngrok / preview hosts keep\n * working without configuration, except workspace OAuth requests from loopback\n * or Builder preview hosts use the configured gateway origin when one exists.\n * The protocol defaults to `https` in production (so a TLS-terminating proxy\n * that drops `x-forwarded-proto` doesn't downgrade us to plain HTTP).\n */\nexport function getOrigin(event: H3Event): string {\n const headerHost =\n getHeader(event, \"x-forwarded-host\") || getHeader(event, \"host\");\n const isProd = process.env.NODE_ENV === \"production\";\n const headerProto =\n getHeader(event, \"x-forwarded-proto\") || (isProd ? \"https\" : \"http\");\n const workspaceCallbackOrigin = isWorkspaceOAuthCallbackRelayEnabled()\n ? getWorkspaceCallbackOrigin()\n : undefined;\n\n if (\n workspaceCallbackOrigin &&\n (isLoopbackHost(headerHost) || isBuilderPreviewHost(headerHost))\n ) {\n return workspaceCallbackOrigin;\n }\n\n if (isProd) {\n const allow = getConfiguredOriginAllowlist();\n // If the deploy declares its public URL, prefer it over inbound headers.\n if (allow.size > 0) {\n const inbound = headerHost ? `${headerProto}://${headerHost}` : \"\";\n if (inbound && allow.has(inbound)) return inbound;\n // Inbound didn't match — fall back to the first configured origin.\n return [...allow][0];\n }\n // No allowlist configured: still default to https, but accept the\n // inbound Host (best we can do without a configured base URL).\n return `${headerProto}://${headerHost ?? \"\"}`;\n }\n\n return `${headerProto}://${headerHost ?? \"localhost\"}`;\n}\n\n/** App mount prefix, if the template is served under APP_BASE_PATH. */\nexport function getAppBasePath(): string {\n return getConfiguredAppBasePath();\n}\n\n/** Build an absolute same-origin URL that preserves APP_BASE_PATH. */\nexport function getAppUrl(event: H3Event, path = \"/\"): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${getOrigin(event)}${getAppBasePath()}${cleanPath}`;\n}\n\nfunction isWorkspaceOAuthCallbackRelayEnabled(): boolean {\n return (\n process.env.AGENT_NATIVE_WORKSPACE === \"1\" ||\n process.env.VITE_AGENT_NATIVE_WORKSPACE === \"1\"\n );\n}\n\nfunction isFrameworkOAuthCallbackPath(pathname: string): boolean {\n return (\n pathname.startsWith(\"/_agent-native/\") &&\n (pathname.endsWith(\"/callback\") || pathname.includes(\"/callback/\"))\n );\n}\n\nfunction getOriginalRequestPath(event: H3Event): string {\n const mountedPathname = (event as any).context?._mountedPathname;\n if (typeof mountedPathname === \"string\" && mountedPathname) {\n return mountedPathname;\n }\n\n const urlPathname = (event as any).url?.pathname;\n if (typeof urlPathname === \"string\" && urlPathname) return urlPathname;\n\n const nodeUrl = event.node?.req?.url;\n if (typeof nodeUrl === \"string\" && nodeUrl) {\n const queryStart = nodeUrl.indexOf(\"?\");\n return queryStart >= 0 ? nodeUrl.slice(0, queryStart) : nodeUrl;\n }\n\n const eventPath = (event as any).path;\n if (typeof eventPath === \"string\" && eventPath) {\n const queryStart = eventPath.indexOf(\"?\");\n return queryStart >= 0 ? eventPath.slice(0, queryStart) : eventPath;\n }\n\n return \"/\";\n}\n\nfunction isRequestUnderAppBasePath(event: H3Event): boolean {\n const basePath = getAppBasePath();\n if (!basePath) return false;\n const requestPath = getOriginalRequestPath(event);\n return (\n requestPath === `${basePath}/_agent-native` ||\n requestPath.startsWith(`${basePath}/_agent-native/`)\n );\n}\n\nfunction getDefaultOAuthRedirectUrl(event: H3Event, path: string): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n if (\n isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(cleanPath)\n ) {\n return `${getOrigin(event)}${cleanPath}`;\n }\n const basePath = isRequestUnderAppBasePath(event) ? getAppBasePath() : \"\";\n return `${getOrigin(event)}${basePath}${cleanPath}`;\n}\n\n// ─── redirect_uri Allowlist ──────────────────────────────────────────────────\n\n/**\n * Validate a user-supplied `redirect_uri` for OAuth flows.\n *\n * Defends against authorization-code interception (RFC 6819 §4.4.1.7):\n * even though the upstream provider (Google/Atlassian/Zoom) refuses\n * unregistered redirect URIs, prefix-style registrations and side\n * registrations on the same host let a malicious caller swap in an\n * attacker-controlled URI that the provider still accepts. We reject any\n * candidate that isn't on this server's own origin AND under the\n * framework's `/_agent-native/` namespace. Returns the validated URI on\n * success, or `undefined` on rejection — callers must treat `undefined`\n * as a 400.\n *\n * The intentional shape is exact-prefix:\n * - Origin must equal `getOrigin(event)` — no Host-header injection\n * reusing somebody else's registered redirect URI.\n * - Path must start with `${appBasePath}/_agent-native/` so we never\n * hand auth codes to a public marketing or open-redirect endpoint\n * on the same registered host.\n *\n * For desktop / native flows that need ephemeral `http://127.0.0.1:<port>`\n * loopback URIs, callers should validate those at the template level\n * with a dedicated allowlist — this helper rejects them by design.\n */\nexport function isAllowedOAuthRedirectUri(\n candidate: string,\n event: H3Event,\n): boolean {\n if (typeof candidate !== \"string\" || candidate.length === 0) return false;\n let url: URL;\n try {\n url = new URL(candidate);\n } catch {\n return false;\n }\n // Must be same origin as our server.\n const expectedOrigin = getOrigin(event);\n let expectedUrl: URL;\n try {\n expectedUrl = new URL(expectedOrigin);\n } catch {\n return false;\n }\n if (url.protocol !== expectedUrl.protocol) return false;\n if (url.host !== expectedUrl.host) return false;\n // Must live under the framework's namespace. Workspace deploys can route\n // root /_agent-native/* to Dispatch even when Dispatch itself is mounted at\n // /dispatch, but app-prefixed requests should not be able to swap their\n // callback to that root namespace.\n const basePath = getAppBasePath();\n const allowedPrefixes =\n basePath && isRequestUnderAppBasePath(event)\n ? [\n `${basePath}/_agent-native/`,\n ...(isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(url.pathname)\n ? [\"/_agent-native/\"]\n : []),\n ]\n : [\"/_agent-native/\"];\n if (!allowedPrefixes.some((prefix) => url.pathname.startsWith(prefix))) {\n return false;\n }\n return true;\n}\n\n/**\n * Resolve the `redirect_uri` for an outbound OAuth `auth-url` request.\n *\n * Reads `?redirect_uri=` from the query and validates it via\n * `isAllowedOAuthRedirectUri`. Returns:\n * - the validated URI when supplied and allowed, OR\n * - the framework default when no override was supplied, OR\n * - `null` when an override was supplied but rejected — callers must\n * respond with 400 in that case.\n *\n * Templates that need a non-default redirect path can pass it via\n * `defaultPath` (e.g. `\"/_agent-native/google/desktop-callback\"` for\n * desktop flows).\n */\nexport function resolveOAuthRedirectUri(\n event: H3Event,\n defaultPath = \"/_agent-native/google/callback\",\n): string | null {\n const supplied = getQuery(event).redirect_uri;\n if (typeof supplied === \"string\" && supplied.length > 0) {\n return isAllowedOAuthRedirectUri(supplied, event) ? supplied : null;\n }\n return getDefaultOAuthRedirectUrl(event, defaultPath);\n}\n\n// ─── OAuth State ─────────────────────────────────────────────────────────────\n\nexport interface OAuthStatePayload {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n /**\n * Same-origin path to redirect to after a successful web-flow sign-in.\n * Threaded through the (HMAC-signed) state so it survives the round trip\n * to Google. Validated again on decode via safeReturnPath as defence in\n * depth. Has no effect on desktop / mobile / add-account flows, which\n * use their own deep-link / close-tab handling.\n */\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Ephemeral in-memory state-signing key for development. Generated lazily\n * on first read so dev sessions don't depend on filesystem writability or\n * env-var configuration. Sessions reset on each restart, which is fine\n * for dev — no real users / production data are involved.\n */\nlet _devStateSigningKey: string | undefined;\n\n/**\n * Derive a server-only signing key for HMAC verification of OAuth state.\n *\n * Uses a dedicated secret — never an OAuth client secret. Reusing a\n * client_secret (which is shared with Google / GitHub / Atlassian) as our\n * own HMAC key conflates two trust domains: rotating the client secret\n * silently invalidates every in-flight OAuth state, and any leak of the\n * client secret also lets an attacker forge our state envelopes.\n *\n * Resolution order:\n * 1. OAUTH_STATE_SECRET (preferred — dedicated to this purpose)\n * 2. BETTER_AUTH_SECRET (already used by Better Auth as a server secret)\n * 3. Hosted workspace deploys derive a per-purpose key from A2A_SECRET\n * 4. In dev only, an ephemeral random key (per-process)\n *\n * In production, throws if no usable server secret is set.\n */\nfunction getStateSigningKey(): string {\n const secret =\n process.env.OAUTH_STATE_SECRET ||\n process.env.BETTER_AUTH_SECRET ||\n getWorkspaceA2ADerivedSecret(\"oauth-state\");\n if (secret) return secret;\n\n const isProd = process.env.NODE_ENV === \"production\";\n if (isProd) {\n throw new Error(\n \"OAuth state signing requires a server secret. \" +\n \"Set OAUTH_STATE_SECRET, BETTER_AUTH_SECRET, or A2A_SECRET in production workspace deploys.\",\n );\n }\n\n if (!_devStateSigningKey) {\n _devStateSigningKey = crypto.randomBytes(32).toString(\"hex\");\n }\n return _devStateSigningKey;\n}\n\n/**\n * Options for the named-argument form of {@link encodeOAuthState}.\n * Prefer this form — the positional overload is easy to misuse (the mail\n * and calendar templates historically passed `flowId` in the `returnUrl`\n * slot, smuggling state into a defence-in-depth path).\n */\nexport interface EncodeOAuthStateOptions {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Encode OAuth state into a signed base64url string.\n * The state is HMAC-signed so the callback can verify it wasn't forged,\n * preventing CSRF attacks on the OAuth flow.\n *\n * Two call shapes are supported:\n * - Recommended: pass an options object — clear, mismatch-proof.\n * `encodeOAuthState({ redirectUri, owner, desktop, ... })`\n * - Legacy positional form (kept working for backward compatibility):\n * `encodeOAuthState(redirectUri, owner, desktop, addAccount, app, returnUrl, flowId)`.\n * Callers should migrate to the options form — see the audit on\n * templates/mail and templates/calendar where the positional shape\n * led to `flowId` being smuggled in via the `returnUrl` slot.\n */\nexport function encodeOAuthState(opts: EncodeOAuthStateOptions): string;\nexport function encodeOAuthState(\n redirectUri: string,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string;\nexport function encodeOAuthState(\n redirectUriOrOpts: string | EncodeOAuthStateOptions,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string {\n const opts: EncodeOAuthStateOptions =\n typeof redirectUriOrOpts === \"string\"\n ? {\n redirectUri: redirectUriOrOpts,\n owner,\n desktop,\n addAccount,\n app,\n returnUrl,\n flowId,\n }\n : redirectUriOrOpts;\n\n const nonce = crypto.randomBytes(8).toString(\"hex\");\n const payload: Record<string, string | boolean> = {\n n: nonce,\n r: opts.redirectUri,\n };\n if (opts.owner) payload.o = opts.owner;\n if (opts.desktop) payload.d = true;\n if (opts.addAccount) payload.a = true;\n if (opts.app) payload.app = opts.app;\n if (opts.returnUrl) payload.r2 = opts.returnUrl;\n if (opts.flowId) payload.f = opts.flowId;\n const data = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n const sig = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n return `${data}.${sig}`;\n}\n\n/**\n * Decode and verify OAuth state from the callback's state query parameter.\n * Rejects forged or tampered state by checking the HMAC signature.\n * Falls back to the provided URI if decoding or verification fails.\n */\nexport function decodeOAuthState(\n stateParam: string | undefined,\n fallbackUri: string,\n): OAuthStatePayload {\n if (stateParam) {\n try {\n const dotIdx = stateParam.lastIndexOf(\".\");\n if (dotIdx === -1) return { redirectUri: fallbackUri };\n\n const data = stateParam.slice(0, dotIdx);\n const sig = stateParam.slice(dotIdx + 1);\n const expected = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n\n if (\n sig.length !== expected.length ||\n !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))\n ) {\n return { redirectUri: fallbackUri };\n }\n\n const parsed = JSON.parse(Buffer.from(data, \"base64url\").toString());\n return {\n redirectUri: parsed.r || fallbackUri,\n owner: parsed.o || undefined,\n desktop: !!parsed.d,\n addAccount: !!parsed.a,\n app: typeof parsed.app === \"string\" ? parsed.app : undefined,\n // Pass returnUrl through as-is — same-origin validation runs at the\n // consumer (oauthCallbackResponse → safeReturnPath). The state is\n // HMAC-signed, but we still validate at consumption as defence in\n // depth in case the signing key ever leaks.\n returnUrl: typeof parsed.r2 === \"string\" ? parsed.r2 : undefined,\n flowId: parsed.f || undefined,\n };\n } catch {}\n }\n return { redirectUri: fallbackUri };\n}\n\n// ─── Session Creation ────────────────────────────────────────────────────────\n\nexport interface OAuthOwnerResult {\n owner: string | undefined;\n hasProductionSession: boolean;\n}\n\n/**\n * Determine the token owner from the current session and OAuth state.\n * Call this BEFORE exchangeCode to get the owner parameter.\n */\nexport async function resolveOAuthOwner(\n event: H3Event,\n stateOwner?: string,\n): Promise<OAuthOwnerResult> {\n const existingSession = await getSession(event);\n const hasProductionSession = !!existingSession?.email;\n const owner = hasProductionSession\n ? existingSession!.email\n : stateOwner || undefined;\n\n return { owner, hasProductionSession };\n}\n\nexport interface OAuthSessionResult {\n sessionToken: string | undefined;\n}\n\n/**\n * Create a session token after a successful OAuth exchange.\n *\n * Desktop and mobile apps have separate cookie jars from the system\n * browser, so they always get a fresh session token (even if the browser\n * already has one). The token is then passed via deep link so the native\n * app can inject it.\n */\nexport async function createOAuthSession(\n event: H3Event,\n email: string,\n opts: {\n hasProductionSession: boolean;\n desktop?: boolean;\n },\n): Promise<OAuthSessionResult> {\n const mobile = isMobile(event);\n const needsDeepLink = opts.desktop || mobile;\n const maxAge = getSessionMaxAge();\n\n let sessionToken: string | undefined;\n if (!opts.hasProductionSession || needsDeepLink) {\n sessionToken = crypto.randomBytes(32).toString(\"hex\");\n await addSession(sessionToken, email);\n setFrameworkSessionCookie(event, sessionToken);\n // Desktop SSO: record this session in the home-dir broker file so\n // sibling templates (each with its own database) can resolve the\n // same token without a DB row of their own. Only the PRIMARY\n // sign-in writes the broker — if a production session already\n // exists, this is an add-account flow (connecting a secondary\n // Google account for scraping) and must never switch the active\n // user across sibling templates.\n if (opts.desktop && !opts.hasProductionSession) {\n await writeDesktopSso({\n email,\n token: sessionToken,\n expiresAt: Date.now() + maxAge * 1000,\n });\n }\n }\n\n return { sessionToken };\n}\n\n// ─── Callback Responses ──────────────────────────────────────────────────────\n\n/**\n * Return the appropriate response after a successful OAuth callback.\n *\n * Handles mobile deep links, desktop deep links, add-account close-tab\n * pages, and plain web redirects — so templates don't have to.\n */\nexport function oauthCallbackResponse(\n event: H3Event,\n email: string,\n opts: {\n sessionToken?: string;\n desktop?: boolean;\n addAccount?: boolean;\n /**\n * Same-origin path to return the viewer to after a successful web\n * sign-in. Validated via safeReturnPath; falls back to \"/\" for any\n * shape that escapes same-origin. Has no effect on desktop / mobile\n * / add-account flows — those use their own deep-link handling.\n */\n returnUrl?: string;\n flowId?: string;\n appName?: string;\n },\n): Response | string | unknown | Promise<Response | string | unknown> {\n const mobile = isMobile(event);\n const query = getQuery(event);\n const callbackState =\n typeof query.state === \"string\" && query.state.length > 0\n ? query.state\n : undefined;\n\n // Mobile: deep link back to the native app. `isMobile` is UA-only, so this\n // also fires for a plain mobile web browser with no app to handle the deep\n // link — there it no-ops, so the fallback must return to the post-login URL,\n // not the app root (else signed-out visitors land on the homepage).\n if (mobile) {\n const deepLink = buildOAuthCompleteDeepLink(\n opts.sessionToken,\n callbackState,\n );\n const webFallback = appendSessionToOAuthReturnUrl(\n opts.returnUrl,\n opts.sessionToken,\n );\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\"><title>Connected</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p>Connected! Returning to app…</p><script>window.location.href=${JSON.stringify(deepLink)};setTimeout(function(){window.location.href=${JSON.stringify(webFallback)}},1500)</script></body></html>`,\n );\n }\n\n // Desktop add-account: close-tab page (must come before general desktop check\n // to ensure no deep link fires and the existing session is never switched).\n if (opts.desktop && opts.addAccount) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n oauthDebugFlowId(opts.flowId),\n ),\n );\n }\n\n // Electron desktop exchange flow: mail/calendar still pass a flow id so the\n // renderer can poll as a fallback, but the main handoff should use the\n // protocol deep link so the popup returns focus to the desktop app.\n if (opts.desktop && opts.flowId && isElectron(event) && opts.sessionToken) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Desktop exchange flow (non-Electron tray app): the tray app polls the\n // desktop-exchange endpoint for the token — no deep link needed.\n if (opts.desktop && opts.flowId) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Signed in as ${safeEmail}!` : \"Signed in!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n oauthDebugFlowId(opts.flowId),\n ),\n );\n }\n\n // Desktop login: deep link back to Electron app — only when the callback\n // request actually carries the AgentNativeDesktop UA marker. Without this\n // check, any client whose OAuth state was minted with `desktop=true` (e.g.\n // a stale link, or an upstream that wrongly set `?desktop=1`) would land\n // on the `agentnative://` page where the deep link can't fire and the\n // \"Open Agent Native\" button does nothing — surfaces inside Builder.io's\n // Fusion webview hit this exact dead-end. Fall through to the web flow\n // for non-Agent-Native-Desktop clients so they get a real redirect.\n if (opts.desktop && isElectron(event)) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Add-account web flow: close-tab page. The email is rendered into the\n // page via DOM `textContent` (safe), but we still JSON-stringify so a\n // payload containing `</script>` can't break out of the script tag —\n // and explicitly assert it's a string so a callbacks like `null` or\n // an object won't end up serialised into the page.\n if (opts.addAccount) {\n const safeEmail = JSON.stringify(typeof email === \"string\" ? email : \"\");\n return htmlResponse(`<!DOCTYPE html><html><body><script>\n window.close();\n var p = document.createElement('p');\n p.style.cssText = 'font-family:system-ui;text-align:center;margin-top:40vh';\n p.textContent = 'Connected ' + ${safeEmail} + '! You can close this tab.';\n document.body.appendChild(p);\n </script></body></html>`);\n }\n\n // Web: redirect to the requested return target. Path-only returns stay\n // same-origin; Builder desktop workspace returns may point back to the\n // local loopback gateway and carry the short-lived `_session` bridge so\n // the local app can promote the newly created hosted OAuth session.\n setResponseStatus(event, 302);\n setResponseHeader(\n event,\n \"Location\",\n appendSessionToOAuthReturnUrl(opts.returnUrl, opts.sessionToken),\n );\n setResponseHeader(event, \"Referrer-Policy\", \"no-referrer\");\n return \"\";\n}\n\n/** HTML error page for OAuth failures. The message is HTML-escaped — most\n * callers pass `error.message` from a token-exchange or userinfo failure,\n * which can echo upstream provider strings (and historically attacker-\n * controlled query params via the `error_description` field). */\nexport function oauthErrorPage(message: string): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connection failed</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;text-align:center\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#ef4444\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M15 9l-6 6\"/><path d=\"M9 9l6 6\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0;color:#ddd\">${safe}</p><p style=\"font-size:13px;color:#888;margin:0\"><a href=\"/\" style=\"color:#888;text-decoration:underline;text-underline-offset:3px\">Back to login</a></p></body></html>`,\n 400,\n );\n}\n\nexport function oauthDesktopExchangePage(\n message = \"Returning to the app...\",\n): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Returning</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p style=\"font-size:14px\">${safe}</p><script>window.close()</script></body></html>`,\n );\n}\n\n// ─── Internal ────────────────────────────────────────────────────────────────\n\nfunction resolveOAuthAppName(explicit?: string): string {\n const raw = explicit || getAppName() || \"Agent Native\";\n if (!/^[a-z0-9_-]+$/.test(raw)) return raw;\n return raw\n .split(/[-_]+/)\n .filter(Boolean)\n .map((word) => word[0].toUpperCase() + word.slice(1))\n .join(\" \");\n}\n\nfunction buildOAuthCompleteDeepLink(\n sessionToken?: string,\n state?: string,\n): string {\n const params = new URLSearchParams();\n if (sessionToken) params.set(\"token\", sessionToken);\n if (state) params.set(\"state\", state);\n const suffix = params.toString();\n return suffix\n ? `agentnative://oauth-complete?${suffix}`\n : \"agentnative://oauth-complete\";\n}\n\nfunction desktopSuccessPage(\n _event: H3Event,\n email?: string,\n sessionToken?: string,\n state?: string,\n): Response {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n if (sessionToken) {\n const deepLink = buildOAuthCompleteDeepLink(sessionToken, state);\n const deepLinkJson = JSON.stringify(deepLink);\n // Defence in depth: if this page somehow gets served to a UA that isn't\n // the Agent Native desktop app (server gate bypassed, stale link, etc.),\n // skip the `agentnative://` deep link entirely and bounce to the app\n // root. The deep link silently fails outside the desktop app and the\n // \"Open Agent Native\" button is a dead end in a generic browser/webview.\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title><style>@keyframes spin{to{transform:rotate(360deg)}}@keyframes fadeIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.spinner{width:28px;height:28px;border:2px solid #333;border-top-color:#fff;border-radius:50%;animation:spin .8s linear infinite}.fallback{display:none;flex-direction:column;align-items:center;gap:8px;animation:fadeIn .2s ease-out}.fallback.show{display:flex}</style></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;gap:16px\"><p style=\"font-size:16px;margin:0\">${msg}</p><div id=\"loading\" class=\"spinner\"></div><div id=\"fallback\" class=\"fallback\"><a href=${deepLinkJson} style=\"display:inline-block;padding:10px 24px;background:#fff;color:#000;border-radius:8px;text-decoration:none;font-size:14px;font-weight:500\">Open Agent Native</a><p style=\"font-size:12px;color:#666;margin:0\">If the app didn\\u2019t open automatically, click the button above.</p></div><script>(function(){var ua=(navigator.userAgent||\"\");if(ua.indexOf(\"AgentNativeDesktop\")===-1){window.location.replace(\"/\");return}window.location.href=${deepLinkJson};setTimeout(function(){document.getElementById(\"loading\").style.display=\"none\";document.getElementById(\"fallback\").classList.add(\"show\")},3000)})()</script></body></html>`,\n );\n }\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n \"You can close this tab and return to Agent Native.\",\n ),\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.66.3",
3
+ "version": "0.66.5",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22"