@jami-studio/core 0.92.29 → 0.92.31

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":"production-agent.js","sourceRoot":"","sources":["../../src/agent/production-agent.ts"],"names":[],"mappings":"AAAA,OAAO,GAA8B,MAAM,KAAK,CAAC;AACjD,OAAO,EACL,kBAAkB,EAClB,SAAS,EACT,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,GACV,MAAM,IAAI,CAAC;AAGZ,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,MAAM,0CAA0C,CAAC;AAChF,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AACzE,OAAO,EACL,WAAW,IAAI,mBAAmB,EAClC,QAAQ,IAAI,gBAAgB,EAC5B,iBAAiB,GAClB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,wCAAwC,EACxC,gCAAgC,EAChC,uBAAuB,GACxB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EACL,oBAAoB,EACpB,uBAAuB,EACvB,iBAAiB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AE,CAAC;QAChD,CAAC;QAED,iBAAiB,CAAC,KAAK,EAAE,cAAc,EAAE,mBAAmB,CAAC,CAAC;QAC9D,iBAAiB,CAAC,KAAK,EAAE,eAAe,EAAE,UAAU,CAAC,CAAC;QACtD,iBAAiB,CAAC,KAAK,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;QACrD,iBAAiB,CAAC,KAAK,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;QAC5C,iBAAiB,CACf,KAAK,EACL,iBAAiB,EACjB,2BAA2B,CAAC,CAAC,CAAC,uBAAuB,CAAC,CAAC,CAAC,YAAY,CACrE,CAAC;QAEF,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,OAAO,EACL,qBAAqB,EACrB,0BAA0B,EAC1B,MAAM,EACN,QAAQ,EACR,cAAc,GACf,CAAC","sourcesContent":["import Ajv, { type ValidateFunction } from \"ajv\";\r\nimport {\r\n defineEventHandler,\r\n getHeader,\r\n setResponseHeader,\r\n setResponseStatus,\r\n getMethod,\r\n} from \"h3\";\r\nimport type { EventHandler as H3EventHandler } from \"h3\";\r\n\r\nimport { isAgentActionStopError } from \"../action.js\";\r\nimport { readAppState } from \"../application-state/script-helpers.js\";\r\nimport { isReadOnlyShellCommand } from \"../coding-tools/index.js\";\r\nimport { isDemoModeEnabled } from \"../demo/config.js\";\r\nimport { redactDemoData, redactDemoString } from \"../demo/redact.js\";\r\nimport { extensionIdFromPathname } from \"../extensions/path.js\";\r\nimport { preUploadAttachments } from \"../file-upload/pre-upload-attachments.js\";\r\nimport { isMcpActionResult } from \"../mcp-client/app-result.js\";\r\nimport { extractMcpToolResultImages } from \"../mcp-client/index.js\";\r\nimport { isMcpToolAllowedForRequest } from \"../mcp-client/visibility.js\";\r\nimport {\r\n completeRun as completeProgressRun,\r\n startRun as startProgressRun,\r\n updateRunProgress,\r\n} from \"../progress/registry.js\";\r\nimport {\r\n getFrontmatterValue,\r\n parseFrontmatter,\r\n} from \"../resources/metadata.js\";\r\nimport {\r\n canUseDeployCredentialFallbackForRequest,\r\n getProviderCredentialAuthFailure,\r\n readDeployCredentialEnv,\r\n} from \"../server/credential-provider.js\";\r\nimport { readBody } from \"../server/h3-helpers.js\";\r\nimport {\r\n getRequestRunContext,\r\n ensureRequestRunContext,\r\n getRequestContext,\r\n getRequestOrgId,\r\n getRequestUserEmail,\r\n runWithRequestContext,\r\n} from \"../server/request-context.js\";\r\nimport { fireInternalDispatch } from \"../server/self-dispatch.js\";\r\nimport {\r\n isReasoningEffort,\r\n normalizeReasoningEffortForModel,\r\n stepDownReasoningEffort,\r\n type ReasoningEffort,\r\n} from \"../shared/reasoning-effort.js\";\r\nimport { actionPreparationContinuationNote } from \"./action-continuation-guidance.js\";\r\nimport { applyContextDirectives } from \"./context-xray/apply-directives.js\";\r\nimport { loadContextDirectives } from \"./context-xray/directives-store.js\";\r\nimport {\r\n buildManifest,\r\n writeContextManifest,\r\n} from \"./context-xray/manifest.js\";\r\nimport { computeProtectedSegmentIds } from \"./context-xray/segments.js\";\r\nimport {\r\n AGENT_CHAT_BACKGROUND_RUN_FIELD,\r\n AGENT_CHAT_PROCESS_RUN_PATH,\r\n backgroundRuntimeDiagnosticDetail,\r\n dispatchPathTargetsNetlifyBackgroundFunction,\r\n isAgentChatDurableBackgroundEnabled,\r\n isAgentChatForegroundSelfChainEnabled,\r\n resolveAgentChatProcessRunDispatchPath,\r\n shouldUseBackgroundFunctionTimeoutForWorker,\r\n} from \"./durable-background.js\";\r\nimport {\r\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\r\n LLM_MISSING_CREDENTIALS_MESSAGE,\r\n userFacingLlmCredentialError,\r\n} from \"./engine/credential-errors.js\";\r\nimport {\r\n resolveEngine,\r\n registerBuiltinEngines,\r\n getStoredModelForEngine,\r\n normalizeModelForEngine,\r\n isResolvedEngineUsableForRequest,\r\n} from \"./engine/index.js\";\r\nimport {\r\n resolveEmptyResponseRetryMaxOutputTokens,\r\n resolveMainChatMaxOutputTokens,\r\n resolveMaxOutputTokensForEngine,\r\n} from \"./engine/output-tokens.js\";\r\nimport { PROVIDER_TO_ENV } from \"./engine/provider-env-vars.js\";\r\nimport {\r\n backfillEngineMessagesToolResults,\r\n stringifyToolUseInputForGateway,\r\n unmatchedToolResultReplayText,\r\n} from \"./engine/translate-anthropic.js\";\r\nimport type {\r\n AgentEngine,\r\n EngineTool,\r\n EngineMessage,\r\n EngineContentPart,\r\n EngineEvent,\r\n EngineToolResultPart,\r\n} from \"./engine/types.js\";\r\nimport { EngineError } from \"./engine/types.js\";\r\nimport {\r\n type AgentLoopSettings,\r\n getDefaultMaxIterations,\r\n MAX_AGENT_MAX_ITERATIONS,\r\n MIN_AGENT_MAX_ITERATIONS,\r\n normalizeMaxIterations,\r\n readAgentLoopSettings,\r\n} from \"./loop-settings.js\";\r\nimport {\r\n maybeCompactThread,\r\n buildObservationalContext,\r\n hasObservationalMemory,\r\n serializeObservationalMemoryBlock,\r\n} from \"./observational-memory/index.js\";\r\nimport {\r\n ProcessorChain,\r\n TripWire,\r\n toolCallsFromContent,\r\n type Processor,\r\n} from \"./processors.js\";\r\nimport {\r\n startRun,\r\n subscribeToRun,\r\n getActiveRunForThread,\r\n getActiveRunForThreadAsync,\r\n getRun,\r\n abortRun,\r\n tryClaimRunSlot,\r\n} from \"./run-manager.js\";\r\nimport type { ActiveRun } from \"./run-manager.js\";\r\nimport {\r\n writeLedgerEntry,\r\n readLedgerEntry,\r\n clearLedgerForThread,\r\n getCurrentTurnEventsForThread,\r\n insertRun,\r\n updateRunHeartbeat,\r\n updateRunStatusIfRunning,\r\n setRunTerminalReason,\r\n claimBackgroundRun,\r\n readBackgroundRunClaim,\r\n recordRunDiagnostic,\r\n countRunsForTurn,\r\n RUN_DIAG_STAGE,\r\n UNCLAIMED_BACKGROUND_RUN_GRACE_MS,\r\n} from \"./run-store.js\";\r\nimport { buildCurrentTimeUserContext } from \"./runtime-context.js\";\r\nimport {\r\n classifyToolCallJournal,\r\n findCompletedJournalEntry,\r\n type ToolCallJournal,\r\n} from \"./tool-call-journal.js\";\r\nimport {\r\n redactSensitiveFields,\r\n sanitizeToolErrorText,\r\n sanitizeToolErrorValue,\r\n} from \"./tool-error-redaction.js\";\r\nimport {\r\n describeToolResultImages,\r\n extractAgentImagesFromActionResult,\r\n} from \"./tool-result-images.js\";\r\nimport {\r\n createToolSearchEntry,\r\n TOOL_SEARCH_ACTION_NAME,\r\n} from \"./tool-search.js\";\r\nimport type {\r\n ActionTool,\r\n AgentNativeJsonSchema,\r\n AgentChatAttachment,\r\n AgentChatRequest,\r\n AgentChatEvent,\r\n AgentChatReference,\r\n AgentChatStructuredMessage,\r\n} from \"./types.js\";\r\n\r\n// Register built-in engines on first import\r\nregisterBuiltinEngines();\r\n\r\nexport { PROVIDER_TO_ENV };\r\n\r\n/**\r\n * Grace window + poll interval for the foreground circuit-breaker that confirms\r\n * a background worker actually CLAIMED a 202-dispatched run before recovering\r\n * inline. The grace must cover the worker's cold-start + per-request init before\r\n * it reaches `claimBackgroundRun`: light apps win the claim in ~1-2s, but heavy\r\n * apps (e.g. analytics) were observed in prod taking >8s, so an 8s grace made\r\n * their worker lose the race every time and always fall back to inline (adding\r\n * ~8s latency with no background budget). 15s covers the slow apps while staying\r\n * well within the foreground's ~40s soft-timeout.\r\n */\r\nexport const BACKGROUND_CLAIM_GRACE_MS = 15_000;\r\n/**\r\n * Safety margin subtracted from the unclaimed-reaper grace when deciding how\r\n * long the foreground may keep waiting for a slow-but-live worker to claim. The\r\n * foreground recovers the run inline this many ms BEFORE `reapUnclaimedBackgroundRun`\r\n * would error an unclaimed row, so the foreground always wins the race to claim\r\n * and the two never collide — see `resolveBackgroundDispatchOutcome`.\r\n */\r\nexport const BACKGROUND_REAPER_SAFETY_MARGIN_MS = 2_000;\r\nexport const BACKGROUND_CLAIM_POLL_MS = 400;\r\n\r\nexport type BackgroundDispatchOutcome =\r\n | { action: \"stream\" }\r\n | { action: \"subscribe\" }\r\n | {\r\n action: \"inline\";\r\n reason: \"dispatch-failed\" | \"worker-never-claimed\" | \"no-row\";\r\n };\r\n\r\n/**\r\n * `diag_stage` is persisted as a JSON payload (`{ stage, detail?, at }`) by\r\n * `recordRunDiagnostic`. Extract the bare stage name so it can be compared to\r\n * `RUN_DIAG_STAGE` constants. Falls back to the raw value when it is not JSON\r\n * (defensive — legacy rows or tests may store a bare stage).\r\n */\r\nfunction parseRunDiagStage(raw: string | null | undefined): string | null {\r\n if (!raw) return null;\r\n try {\r\n const parsed = JSON.parse(raw) as { stage?: unknown };\r\n if (parsed && typeof parsed.stage === \"string\") return parsed.stage;\r\n } catch {\r\n // Not JSON — treat the raw value as the stage name.\r\n }\r\n return typeof raw === \"string\" ? raw : null;\r\n}\r\n\r\n/**\r\n * Decide what the foreground should do after attempting a durable background\r\n * dispatch. A Netlify async background function returns 202 the instant it\r\n * ENQUEUES the invocation — that is NOT proof the worker executed. If the\r\n * generated wrapper fails to import/hand off to the route, the worker never\r\n * reaches `claimBackgroundRun` and the run is reaped as \"worker never claimed\".\r\n *\r\n * So after a successful dispatch we poll briefly for the worker to CLAIM the run:\r\n * - claimed within grace → \"stream\" (subscribe to the worker)\r\n * - dispatch failed OR no claim → recover inline by atomically claiming the\r\n * run ourselves: if we win → \"inline\"; if a (delayed) worker already won\r\n * it → \"subscribe\" (never double-run).\r\n *\r\n * Pure except for the injected `readClaim`/`claim`/`now`/`sleep` deps, so each\r\n * branch is unit-testable.\r\n */\r\nexport async function resolveBackgroundDispatchOutcome(opts: {\r\n dispatched: boolean;\r\n backgroundRowInserted: boolean;\r\n runId: string;\r\n graceMs: number;\r\n /**\r\n * The unclaimed-run reaper's grace (`UNCLAIMED_BACKGROUND_RUN_GRACE_MS`). When\r\n * provided, the foreground may keep waiting PAST `graceMs` while the worker is\r\n * provably alive and still in setup — but it recovers inline before the run has\r\n * been unclaimed this long (minus the safety margin), so it always claims\r\n * before the reaper can fire. Omit to disable the extension (behaves exactly\r\n * like the base grace).\r\n */\r\n reaperGraceMs?: number;\r\n /** Margin subtracted from `reaperGraceMs` (default `BACKGROUND_REAPER_SAFETY_MARGIN_MS`). */\r\n reaperSafetyMarginMs?: number;\r\n pollIntervalMs: number;\r\n readClaim: (runId: string) => Promise<{\r\n dispatchMode: string | null;\r\n status: string | null;\r\n diagStage?: string | null;\r\n /** COALESCE(heartbeat_at, started_at) — the reaper's liveness basis. */\r\n lastLivenessAt?: number | null;\r\n } | null>;\r\n claim: (runId: string) => Promise<boolean>;\r\n now?: () => number;\r\n sleep?: (ms: number) => Promise<void>;\r\n}): Promise<BackgroundDispatchOutcome> {\r\n const now = opts.now ?? (() => Date.now());\r\n const sleep =\r\n opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\r\n\r\n // Pre-claim diag stages that prove the worker is ALIVE and executing: it\r\n // reached the route, passed HMAC auth, and is grinding through handler setup\r\n // (system prompt build / action loading) on its way to `claimBackgroundRun`.\r\n // A dead handoff — the generated wrapper never reached the route — never\r\n // records these, so it is NOT eligible for the extended grace.\r\n const ALIVE_IN_SETUP: ReadonlySet<string> = new Set([\r\n RUN_DIAG_STAGE.authPassed,\r\n RUN_DIAG_STAGE.workerEntered,\r\n ]);\r\n // Pre-claim diag stages that prove the worker DIED before claiming — stop\r\n // waiting and recover inline immediately instead of burning the rest of the\r\n // grace on a worker that already failed.\r\n const DIED_BEFORE_CLAIM: ReadonlySet<string> = new Set([\r\n RUN_DIAG_STAGE.authFailed,\r\n RUN_DIAG_STAGE.routeThrew,\r\n RUN_DIAG_STAGE.workerThrew,\r\n ]);\r\n\r\n if (opts.dispatched) {\r\n // One now() at entry + one per iteration (so callers/tests that model a\r\n // stepping clock stay deterministic).\r\n const startedAt = now();\r\n const baseDeadline = startedAt + opts.graceMs;\r\n const reaperGraceMs = opts.reaperGraceMs;\r\n const reaperMargin =\r\n opts.reaperSafetyMarginMs ?? BACKGROUND_REAPER_SAFETY_MARGIN_MS;\r\n for (;;) {\r\n const claim = await opts.readClaim(opts.runId).catch(() => null);\r\n if (\r\n claim &&\r\n ((claim.dispatchMode && claim.dispatchMode !== \"background\") ||\r\n (claim.status && claim.status !== \"running\"))\r\n ) {\r\n return { action: \"stream\" };\r\n }\r\n // `diag_stage` is stored as JSON ({stage, detail?, at}); compare on the\r\n // bare stage name, not the raw payload.\r\n const stage = parseRunDiagStage(claim?.diagStage);\r\n // Worker recorded a pre-claim death — no point waiting out the grace.\r\n if (stage && DIED_BEFORE_CLAIM.has(stage)) break;\r\n const elapsedNow = now();\r\n // The unclaimed-reaper errors any still-`background` row once it has been\r\n // unclaimed for `reaperGraceMs`, measured from the row's OWN liveness\r\n // (COALESCE(heartbeat_at, started_at)) — NOT from when we began polling.\r\n // Recover inline just before that point so the foreground claims the run\r\n // first; anchoring to the row's liveness makes this immune to dispatch\r\n // latency between insertRun and the start of polling.\r\n const reaperWillFireSoon =\r\n reaperGraceMs != null &&\r\n claim?.lastLivenessAt != null &&\r\n elapsedNow - claim.lastLivenessAt >= reaperGraceMs - reaperMargin;\r\n if (reaperWillFireSoon) break;\r\n // ADAPTIVE GRACE: past the base window, keep polling ONLY while the worker\r\n // is provably alive and still in setup (heavy cold start). A dead handoff\r\n // never recorded an ALIVE_IN_SETUP stage, so it recovers inline at the base\r\n // grace; the reaper-anchored break above bounds how long a live worker can\r\n // extend. The extension is enabled only when a reaper grace was provided.\r\n const aliveInSetup =\r\n reaperGraceMs != null &&\r\n claim?.status === \"running\" &&\r\n !!stage &&\r\n ALIVE_IN_SETUP.has(stage);\r\n if (elapsedNow >= baseDeadline && !aliveInSetup) break;\r\n await sleep(opts.pollIntervalMs);\r\n }\r\n }\r\n\r\n // Dispatch fast-failed OR no worker claimed within grace → recover inline.\r\n if (!opts.backgroundRowInserted) {\r\n // No row to reconcile (insert failed / non-duplicate) — run a fresh inline\r\n // turn; `startRun` inserts the row.\r\n return { action: \"inline\", reason: \"no-row\" };\r\n }\r\n let claimedInline = false;\r\n try {\r\n claimedInline = await opts.claim(opts.runId);\r\n } catch {\r\n claimedInline = false;\r\n }\r\n if (claimedInline) {\r\n return {\r\n action: \"inline\",\r\n reason: opts.dispatched ? \"worker-never-claimed\" : \"dispatch-failed\",\r\n };\r\n }\r\n // The atomic claim was lost: a (delayed) background worker already owns the\r\n // run — subscribe to it, never run a second copy.\r\n return { action: \"subscribe\" };\r\n}\r\n\r\nconst SAFE_BROWSER_TAB_ID_RE = /^[A-Za-z0-9_-]{1,96}$/;\r\n\r\nfunction normalizeBrowserTabId(value: unknown): string | undefined {\r\n if (typeof value !== \"string\") return undefined;\r\n const trimmed = value.trim();\r\n return SAFE_BROWSER_TAB_ID_RE.test(trimmed) ? trimmed : undefined;\r\n}\r\n\r\nfunction normalizeChatScope(\r\n value: unknown,\r\n): { type: string; id: string; label?: string } | null | undefined {\r\n if (value == null) return null;\r\n if (typeof value !== \"object\") return undefined;\r\n const record = value as Record<string, unknown>;\r\n const type = typeof record.type === \"string\" ? record.type.trim() : \"\";\r\n const id = typeof record.id === \"string\" ? record.id.trim() : \"\";\r\n if (!type || !id || type.length > 64 || id.length > 256) {\r\n return undefined;\r\n }\r\n const label =\r\n typeof record.label === \"string\" && record.label.trim().length > 0\r\n ? record.label.trim().slice(0, 256)\r\n : undefined;\r\n return { type, id, ...(label ? { label } : {}) };\r\n}\r\n\r\nfunction appStateKeyForBrowserTab(key: string, browserTabId?: string): string {\r\n return browserTabId ? `${key}:${browserTabId}` : key;\r\n}\r\n\r\nasync function readAppStateForBrowserTab<T>(\r\n key: string,\r\n browserTabId?: string,\r\n): Promise<T | null> {\r\n const tabKey = appStateKeyForBrowserTab(key, browserTabId);\r\n if (tabKey !== key) {\r\n const scoped = (await readAppState(tabKey).catch(() => null)) as T | null;\r\n if (scoped) return scoped;\r\n }\r\n return (await readAppState(key)) as T | null;\r\n}\r\n\r\n/**\r\n * Look up a user's persisted API key for the given provider. Returns\r\n * `undefined` for unauthenticated callers.\r\n *\r\n * Read order:\r\n * 1. `app_secrets` — encrypted user override, then active org/workspace.\r\n * 2. Legacy `user-api-key:<provider>:<email>` settings row — pre-migration\r\n * data that hasn't been backfilled yet. Surfaced for compat only;\r\n * writes always go to app_secrets now.\r\n */\r\nexport async function getOwnerApiKey(\r\n provider: string,\r\n ownerEmail: string | null | undefined,\r\n): Promise<string | undefined> {\r\n if (!ownerEmail) return undefined;\r\n const secretKey =\r\n PROVIDER_TO_ENV[provider] ?? `${provider.toUpperCase()}_API_KEY`;\r\n try {\r\n const { readAppSecret } = await import(\"../secrets/storage.js\");\r\n const refs: Array<{\r\n scope: \"user\" | \"org\" | \"workspace\";\r\n scopeId: string;\r\n }> = [{ scope: \"user\", scopeId: ownerEmail }];\r\n const orgId = getRequestOrgId();\r\n if (orgId) {\r\n refs.push(\r\n { scope: \"org\", scopeId: orgId },\r\n { scope: \"workspace\", scopeId: orgId },\r\n );\r\n } else {\r\n refs.push({ scope: \"workspace\", scopeId: `solo:${ownerEmail}` });\r\n }\r\n for (const ref of refs) {\r\n const fromSecrets = await readAppSecret({\r\n key: secretKey,\r\n scope: ref.scope,\r\n scopeId: ref.scopeId,\r\n });\r\n if (\r\n fromSecrets?.value &&\r\n !(await getProviderCredentialAuthFailure({\r\n key: secretKey,\r\n value: fromSecrets.value,\r\n }))\r\n ) {\r\n return fromSecrets.value;\r\n }\r\n }\r\n } catch {\r\n // app_secrets table not ready — fall through to legacy lookup.\r\n }\r\n try {\r\n const { getSetting } = await import(\"../settings/store.js\");\r\n const stored = await getSetting(`user-api-key:${provider}:${ownerEmail}`);\r\n const key =\r\n stored && typeof stored.key === \"string\" ? stored.key.trim() : \"\";\r\n if (\r\n key &&\r\n !(await getProviderCredentialAuthFailure({ key: secretKey, value: key }))\r\n ) {\r\n return key;\r\n }\r\n if (provider === \"anthropic\") {\r\n const legacy = await getSetting(`user-anthropic-api-key:${ownerEmail}`);\r\n const legacyKey =\r\n legacy && typeof legacy.key === \"string\" ? legacy.key.trim() : \"\";\r\n if (\r\n legacyKey &&\r\n !(await getProviderCredentialAuthFailure({\r\n key: secretKey,\r\n value: legacyKey,\r\n }))\r\n ) {\r\n return legacyKey;\r\n }\r\n return undefined;\r\n }\r\n return undefined;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/**\r\n * Derive the provider name from the active engine setting.\r\n * \"ai-sdk:openai\" → \"openai\", \"anthropic\" → \"anthropic\"\r\n */\r\nexport function engineToProvider(engineName: string): string {\r\n return engineName.startsWith(\"ai-sdk:\") ? engineName.slice(7) : engineName;\r\n}\r\n\r\n/**\r\n * Resolve the active engine's provider and look up the user's API key for it.\r\n *\r\n * If the owner has no scoped key, fall back to provider keys supplied by the\r\n * hosting environment only when the current request can safely use deploy-level\r\n * credentials. This is a read from process-level config, not a request-scoped\r\n * write to `process.env`.\r\n *\r\n * Callers that layer another deployment-key fallback after this should keep the\r\n * same precedence: scoped key first, host-provided env key second.\r\n */\r\nexport async function getOwnerActiveApiKey(\r\n ownerEmail: string | null | undefined,\r\n): Promise<string | undefined> {\r\n try {\r\n const { getSetting } = await import(\"../settings/store.js\");\r\n const engineSetting = await getSetting(\"agent-engine\");\r\n const activeEngine =\r\n (engineSetting?.engine as string | undefined) ?? \"anthropic\";\r\n const provider = engineToProvider(activeEngine);\r\n const userKey = await getOwnerApiKey(provider, ownerEmail);\r\n if (userKey) return userKey;\r\n const envVar = PROVIDER_TO_ENV[provider];\r\n if (!envVar || !canUseDeployCredentialFallbackForRequest(envVar)) {\r\n return undefined;\r\n }\r\n const envKey = readDeployCredentialEnv(envVar);\r\n if (\r\n envKey &&\r\n !(await getProviderCredentialAuthFailure({ key: envVar, value: envKey }))\r\n ) {\r\n return envKey;\r\n }\r\n return undefined;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/** @deprecated Use getOwnerApiKey(\"anthropic\", ownerEmail) instead */\r\nexport async function getOwnerAnthropicApiKey(\r\n ownerEmail: string | null | undefined,\r\n): Promise<string | undefined> {\r\n return getOwnerApiKey(\"anthropic\", ownerEmail);\r\n}\r\n\r\n/**\r\n * Context passed as the optional second argument to an action's `run`.\r\n * Defined in `../action.js` (cycle-free home) and re-exported here so existing\r\n * importers (e.g. `scripts/call-agent.ts`) keep their import path.\r\n */\r\nexport type { ActionRunContext, ActionCaller } from \"../action.js\";\r\n\r\nexport interface ActionEntry {\r\n tool: ActionTool;\r\n run: (\r\n args: any,\r\n context?: import(\"../action.js\").ActionRunContext,\r\n ) => Promise<any> | any;\r\n /** Standard Schema input validator when declared through defineAction. */\r\n schema?: unknown;\r\n /** HTTP exposure config. `false` = agent-only. Omitted = auto-inferred from name. */\r\n http?: import(\"../action.js\").ActionHttpConfig | false;\r\n /** Whether HTTP/frontend action calls must have an authenticated owner.\r\n * Defaults to true; false lets safe metadata/read actions run with\r\n * `ctx.userEmail` undefined when auth resolution returns 401/403. */\r\n requiresAuth?: boolean;\r\n /** Max HTTP request body in bytes; the route 413s on `Content-Length` before\r\n * parsing. For public, no-auth POST actions. */\r\n maxBodyBytes?: number;\r\n /** Whether the action is exposed to the agent as a callable tool. Only an\r\n * explicit `false` hides it from every agent tool surface (in-app assistant,\r\n * MCP, A2A, job/trigger runners) while leaving it frontend/HTTP-callable.\r\n * Set by `defineAction`'s `agentTool` option. */\r\n agentTool?: boolean;\r\n /** Explicit opt-in metadata for public agent protocols. Public routes never\r\n * imply public tool exposure; MCP/A2A/OpenAPI surfaces must filter for this. */\r\n publicAgent?: import(\"../action.js\").PublicAgentActionConfig;\r\n /** If true, completion does NOT trigger a screen-refresh change event.\r\n * Set automatically by `defineAction` when `http.method === \"GET\"`. */\r\n readOnly?: boolean;\r\n /** False keeps a read-only tool available in Act mode but hides/blocks it in\r\n * Plan mode. Use for tools that perform substantive work even without\r\n * mutating state. */\r\n allowInPlanMode?: boolean;\r\n /** If true, this action can run concurrently with other same-turn\r\n * read-only/parallel-safe tool calls. Only use for actions that handle\r\n * their own write ordering and idempotency. */\r\n parallelSafe?: boolean;\r\n /** Whether this action may be invoked from the tools-iframe bridge.\r\n * **Default-allow opt-out**: only an explicit `false` returns 403.\r\n * - `true` / `undefined` — allow.\r\n * - `false` — explicit deny; the tools bridge returns 403.\r\n * See `defineAction` (`packages/core/src/action.ts`) and audit H5 in\r\n * `security-audit/05-tools-sandbox.md`. */\r\n toolCallable?: boolean;\r\n /** Optional deep-link builder. When set, MCP/A2A surfaces append an\r\n * \"Open in <app> →\" link built from the call's args + result. Pure, sync,\r\n * best-effort. See `defineAction` and the `external-agents` skill. */\r\n link?: import(\"../action.js\").ActionLinkBuilder;\r\n /** Optional MCP Apps UI resource for hosts that support inline interactive\r\n * app iframes. CLI/non-UI hosts still receive the normal tool result and\r\n * any deep link from `link`. */\r\n mcpApp?: import(\"../action.js\").ActionMcpAppConfig;\r\n /** Optional native Agent-Native chat renderer for this action's result. */\r\n chatUI?: import(\"../action-ui.js\").ActionChatUIConfig;\r\n /**\r\n * Per-tool timeout override in milliseconds. When set, the agent loop uses\r\n * this value instead of the global TOOL_TIMEOUT_MS (60 s) for this action.\r\n * Useful for long-running tools such as sandboxed code execution.\r\n */\r\n timeoutMs?: number;\r\n /**\r\n * Per-tool max-result-chars override. When set, the agent loop truncates\r\n * the result to this many characters instead of the global 50 000 cap.\r\n */\r\n maxResultChars?: number;\r\n /**\r\n * Opt-in human-in-the-loop approval gate (default off). When truthy (or a\r\n * predicate that resolves truthy for the call's args), the loop emits\r\n * `approval_required` and stops the turn instead of executing this action,\r\n * until a human approves the specific call. Set by `defineAction`'s\r\n * `needsApproval` option. See `packages/core/docs/content/actions.mdx`.\r\n */\r\n needsApproval?:\r\n | boolean\r\n | ((\r\n args: any,\r\n ctx?: import(\"../action.js\").ActionRunContext,\r\n ) => boolean | Promise<boolean>);\r\n}\r\n\r\n/** @deprecated Use `ActionEntry` instead */\r\nexport type ScriptEntry = ActionEntry;\r\n\r\nexport type AgentExecutionMode = \"act\" | \"plan\";\r\n\r\nexport const PLAN_MODE_SYSTEM_PROMPT = `## Plan Mode Active\r\n\r\nYou are in Plan mode. This turn is for research, clarification, and a proposed approach only.\r\n\r\nHard rules:\r\n- Use only read-only tools. Do not edit files, write resources, run mutating bash commands, mutate SQL rows, navigate the UI, send notifications, create jobs, create tools, call external agents, or change external systems.\r\n- If a needed detail is unclear, ask a concise clarifying question before proposing a plan.\r\n- When ready, present a concrete plan with the files/tools you expect to touch, the intended changes, validation steps, and notable risks.\r\n- Do not treat approval as implicit while Plan mode is still active. Tell the user to switch to Act mode with the mode selector or /act before implementation.`;\r\n\r\nconst PLAN_MODE_BLOCKED_READONLY_TOOLS = new Set([\r\n \"refresh-screen\",\r\n \"set-search-params\",\r\n \"set-url-path\",\r\n]);\r\n\r\nconst PLAN_MODE_ALLOWED_ACTIONS: Record<string, readonly string[]> = {\r\n resources: [\"list\", \"read\"],\r\n \"chat-history\": [\"search\"],\r\n \"agent-teams\": [\"status\", \"read-result\", \"list\"],\r\n \"manage-jobs\": [\"list\"],\r\n \"manage-automations\": [\"list-events\", \"list\"],\r\n \"manage-notifications\": [\"list\"],\r\n \"manage-progress\": [\"list\"],\r\n \"manage-agent-engine\": [\"list\"],\r\n};\r\n\r\nconst PLAN_MODE_WEB_REQUEST_METHODS = new Set([\"GET\", \"HEAD\"]);\r\nconst SOURCE_SWEEP_AGENT_TEAM_ALLOWED_ACTIONS = [\r\n \"status\",\r\n \"read-result\",\r\n \"list\",\r\n] as const;\r\n\r\nfunction getToolAction(name: string, args: unknown): string {\r\n const raw =\r\n args && typeof args === \"object\" && \"action\" in args\r\n ? (args as Record<string, unknown>).action\r\n : undefined;\r\n if (raw == null && name === \"chat-history\") return \"search\";\r\n return String(raw ?? \"\").toLowerCase();\r\n}\r\n\r\nfunction getWebRequestMethod(args: unknown): string {\r\n const raw =\r\n args && typeof args === \"object\" && \"method\" in args\r\n ? (args as Record<string, unknown>).method\r\n : undefined;\r\n return String(raw ?? \"GET\").toUpperCase();\r\n}\r\n\r\nfunction restrictActionEnum(\r\n parameters: ActionTool[\"parameters\"] | undefined,\r\n allowedActions: readonly string[],\r\n): ActionTool[\"parameters\"] | undefined {\r\n if (!parameters) return parameters;\r\n const actionParam = parameters.properties.action;\r\n if (!actionParam) return parameters;\r\n return {\r\n ...parameters,\r\n properties: {\r\n ...parameters.properties,\r\n action: {\r\n ...actionParam,\r\n enum: [...allowedActions],\r\n },\r\n },\r\n };\r\n}\r\n\r\nfunction restrictWebRequestMethods(\r\n parameters: ActionTool[\"parameters\"] | undefined,\r\n): ActionTool[\"parameters\"] | undefined {\r\n if (!parameters) return parameters;\r\n const methodParam = parameters.properties.method;\r\n if (!methodParam) return parameters;\r\n return {\r\n ...parameters,\r\n properties: {\r\n ...parameters.properties,\r\n method: {\r\n ...methodParam,\r\n enum: [...PLAN_MODE_WEB_REQUEST_METHODS],\r\n },\r\n },\r\n };\r\n}\r\n\r\nfunction planModeBlockedMessage(toolName: string, reason?: string): string {\r\n return (\r\n `Plan mode blocked \\`${toolName}\\`` +\r\n (reason ? ` (${reason})` : \"\") +\r\n \". Switch to Act mode after the user approves the plan, then retry the action.\"\r\n );\r\n}\r\n\r\nexport function isPlanModeToolCallAllowed(\r\n name: string,\r\n input: unknown,\r\n entry: ActionEntry,\r\n): boolean {\r\n if (entry.allowInPlanMode === false) return false;\r\n if (PLAN_MODE_BLOCKED_READONLY_TOOLS.has(name)) return false;\r\n\r\n if (name === \"web-request\") {\r\n return PLAN_MODE_WEB_REQUEST_METHODS.has(getWebRequestMethod(input));\r\n }\r\n\r\n if (name === \"bash\") {\r\n return isPlanModeReadOnlyBashCall(input);\r\n }\r\n\r\n const allowedActions = PLAN_MODE_ALLOWED_ACTIONS[name];\r\n if (allowedActions) {\r\n return allowedActions.includes(getToolAction(name, input));\r\n }\r\n\r\n return entry.readOnly === true;\r\n}\r\n\r\nfunction isPlanModeReadOnlyBashCall(input: unknown): boolean {\r\n if (!input || typeof input !== \"object\") return false;\r\n const command = (input as Record<string, unknown>).command;\r\n if (typeof command !== \"string\") return false;\r\n return isReadOnlyShellCommand(command);\r\n}\r\n\r\nfunction createPlanModeGuardedAction(\r\n name: string,\r\n entry: ActionEntry,\r\n allowedActions: readonly string[],\r\n): ActionEntry {\r\n return {\r\n ...entry,\r\n readOnly: true,\r\n tool: {\r\n ...entry.tool,\r\n description:\r\n `${entry.tool.description}\\n\\nPlan mode: only these read-only actions are available: ` +\r\n allowedActions.map((action) => `\"${action}\"`).join(\", \") +\r\n \".\",\r\n parameters: restrictActionEnum(entry.tool.parameters, allowedActions),\r\n },\r\n run: async (args, context) => {\r\n const action = getToolAction(name, args);\r\n if (!allowedActions.includes(action)) {\r\n return planModeBlockedMessage(\r\n name,\r\n `action=\"${action || \"(missing)\"}\"`,\r\n );\r\n }\r\n return entry.run(args, context);\r\n },\r\n };\r\n}\r\n\r\nfunction createPlanModeWebRequestAction(entry: ActionEntry): ActionEntry {\r\n return {\r\n ...entry,\r\n readOnly: true,\r\n tool: {\r\n ...entry.tool,\r\n description: `${entry.tool.description}\\n\\nPlan mode: only GET and HEAD requests are allowed.`,\r\n parameters: restrictWebRequestMethods(entry.tool.parameters),\r\n },\r\n run: async (args, context) => {\r\n const method = getWebRequestMethod(args);\r\n if (!PLAN_MODE_WEB_REQUEST_METHODS.has(method)) {\r\n return planModeBlockedMessage(\"web-request\", `method=\"${method}\"`);\r\n }\r\n return entry.run(args, context);\r\n },\r\n };\r\n}\r\n\r\nfunction createPlanModeBashAction(entry: ActionEntry): ActionEntry {\r\n return {\r\n ...entry,\r\n readOnly: true,\r\n tool: {\r\n ...entry.tool,\r\n description: `${entry.tool.description}\\n\\nPlan mode: only read-only inspection commands such as pwd, ls, find, rg, grep, cat, sed -n, head, tail, wc, and git status/diff/show/log are allowed.`,\r\n },\r\n run: async (args, context) => {\r\n if (!isPlanModeReadOnlyBashCall(args)) {\r\n return planModeBlockedMessage(\"bash\", \"command is not read-only\");\r\n }\r\n return entry.run(args, context);\r\n },\r\n };\r\n}\r\n\r\nfunction createPlanModeBlockedAction(\r\n name: string,\r\n entry: ActionEntry,\r\n reason?: string,\r\n): ActionEntry {\r\n return {\r\n ...entry,\r\n allowInPlanMode: false,\r\n readOnly: true,\r\n tool: {\r\n ...entry.tool,\r\n description: `${entry.tool.description}\\n\\nPlan mode blocked: ${reason ?? \"not available while planning\"}.`,\r\n },\r\n run: async () => planModeBlockedMessage(name, reason),\r\n };\r\n}\r\n\r\nexport function createPlanModeActionRegistry(\r\n actions: Record<string, ActionEntry>,\r\n): Record<string, ActionEntry> {\r\n const filtered: Record<string, ActionEntry> = {};\r\n\r\n for (const [name, entry] of Object.entries(actions)) {\r\n if (name === TOOL_SEARCH_ACTION_NAME) continue;\r\n if (entry.allowInPlanMode === false) {\r\n filtered[name] = createPlanModeBlockedAction(\r\n name,\r\n entry,\r\n \"not available while planning\",\r\n );\r\n continue;\r\n }\r\n if (PLAN_MODE_BLOCKED_READONLY_TOOLS.has(name)) {\r\n filtered[name] = createPlanModeBlockedAction(\r\n name,\r\n entry,\r\n \"not available while planning\",\r\n );\r\n continue;\r\n }\r\n\r\n const allowedActions = PLAN_MODE_ALLOWED_ACTIONS[name];\r\n if (allowedActions) {\r\n filtered[name] = createPlanModeGuardedAction(name, entry, allowedActions);\r\n continue;\r\n }\r\n\r\n if (name === \"web-request\") {\r\n filtered[name] = createPlanModeWebRequestAction(entry);\r\n continue;\r\n }\r\n\r\n if (name === \"bash\") {\r\n filtered[name] = createPlanModeBashAction(entry);\r\n continue;\r\n }\r\n\r\n if (entry.readOnly === true) {\r\n filtered[name] = entry;\r\n } else {\r\n filtered[name] = createPlanModeBlockedAction(\r\n name,\r\n entry,\r\n \"write or side-effecting tool\",\r\n );\r\n }\r\n }\r\n\r\n if (actions[TOOL_SEARCH_ACTION_NAME]) {\r\n filtered[TOOL_SEARCH_ACTION_NAME] = createToolSearchEntry(() => filtered);\r\n }\r\n\r\n return filtered;\r\n}\r\n\r\nexport interface ProductionAgentOptions {\r\n /** Action entries for the agent. Use `actions` (preferred) or `scripts` (deprecated alias). */\r\n actions?: Record<string, ActionEntry>;\r\n /** @deprecated Use `actions` instead */\r\n scripts?: Record<string, ActionEntry>;\r\n /** Static system prompt string, or async function called per-request with the H3 event */\r\n systemPrompt: string | ((event: any) => string | Promise<string>);\r\n /** Falls back to ANTHROPIC_API_KEY env var. Ignored when `engine` is provided. */\r\n apiKey?: string;\r\n /** Agent engine to use. Defaults to the \"anthropic\" engine. */\r\n engine?:\r\n | AgentEngine\r\n | string\r\n | { name: string; config: Record<string, unknown> };\r\n /** Model to use. Defaults to the resolved engine's default model. */\r\n model?: string;\r\n /** App/template id used for org-scoped per-app model defaults. */\r\n appId?: string;\r\n /** Default reasoning effort for requests that do not supply an override. */\r\n reasoningEffort?: ReasoningEffort;\r\n /** Provider-specific options passed through to the engine */\r\n providerOptions?: EngineMessage extends never ? never : any;\r\n /** Called when a run completes (for server-side thread persistence) */\r\n onRunComplete?: (run: ActiveRun, threadId: string | undefined) => void;\r\n /** Called after request validation but before a run is started. */\r\n onRunPrepared?: (details: {\r\n runId: string;\r\n threadId: string | undefined;\r\n message: string;\r\n attachments?: AgentChatAttachment[];\r\n }) => void | Promise<void>;\r\n /**\r\n * Optional per-template request normalizer. Runs after owner resolution and\r\n * before system/context assembly so templates can materialize uploaded chat\r\n * attachments or append app-specific, non-visible instructions.\r\n */\r\n prepareRequest?: (details: {\r\n event: any;\r\n ownerEmail: string | null;\r\n message: string;\r\n displayMessage?: string;\r\n attachments: AgentChatAttachment[];\r\n references: AgentChatReference[];\r\n threadId?: string;\r\n internalContinuation?: boolean;\r\n mode: AgentExecutionMode;\r\n }) =>\r\n | void\r\n | {\r\n message?: string;\r\n displayMessage?: string;\r\n attachments?: AgentChatAttachment[];\r\n }\r\n | Promise<void | {\r\n message?: string;\r\n displayMessage?: string;\r\n attachments?: AgentChatAttachment[];\r\n }>;\r\n /** Optional per-app agent run chunk budget in milliseconds. Defaults to\r\n * AGENT_RUN_SOFT_TIMEOUT_MS when set, otherwise no framework-imposed\r\n * timeout. When reached, the client receives an internal auto-continuation\r\n * signal instead of a user-facing warning. */\r\n runSoftTimeoutMs?: number;\r\n /** Optional no-progress watchdog override for this app's runs. */\r\n runNoProgressTimeoutMs?: number;\r\n /**\r\n * Opt this app into durable Netlify background-function agent-chat runs. This\r\n * is a runtime opt-in layered on top of the hosted-runtime + A2A_SECRET gates;\r\n * single-template Netlify deploys must also enable the deploy-time\r\n * `AGENT_CHAT_DURABLE_BACKGROUND` flag so the background function is emitted.\r\n */\r\n durableBackgroundRuns?: boolean;\r\n /** Called when a run starts, with the send function for emitting events and the threadId */\r\n onRunStart?: (\r\n send: (event: AgentChatEvent) => void,\r\n threadId: string,\r\n ) => void | Promise<void>;\r\n /**\r\n * Called after the engine + model are resolved for this request. Used by\r\n * the plugin layer to thread the parent's choices into sub-agents so\r\n * delegated tasks don't default back to Anthropic + Claude.\r\n */\r\n onEngineResolved?: (engine: AgentEngine, model: string) => void;\r\n /** Resolve the owner email from the H3 event (for usage tracking) */\r\n resolveOwnerEmail?: (event: any) => string | Promise<string>;\r\n /**\r\n * Optional final-answer guard. If it returns a message after a text-only\r\n * assistant turn, the loop clears that draft once and asks the model to\r\n * continue with the returned corrective instruction before allowing a final.\r\n */\r\n finalResponseGuard?: AgentLoopFinalResponseGuard;\r\n /**\r\n * Skip auto-injecting the workspace files/skills/agents inventory on the\r\n * first message of a conversation. Useful for minimal/voice apps where\r\n * the ~2KB inventory of unrelated resources is noise, not signal.\r\n * Default: false (inventory is injected).\r\n */\r\n skipFilesContext?: boolean;\r\n /**\r\n * Optional starter tool catalog. When set, the first model request includes\r\n * only these tool schemas plus `tool-search`; the full action registry remains\r\n * searchable, and matching tool schemas from `tool-search` results are added\r\n * to the next model request. This keeps first-token latency low without\r\n * forcing rarely used capabilities into every prompt. The framework also\r\n * promotes common provider/corpus/code-execution tools when the current\r\n * app/mode registry exposes them, so prompts that teach broad integrations do\r\n * not describe tools that require an extra discovery turn before use.\r\n */\r\n initialToolNames?: string[];\r\n /**\r\n * App-level default tool limits. Each action's own `timeoutMs` /\r\n * `maxResultChars` takes precedence; this sets the fallback for actions\r\n * that don't declare their own limits.\r\n */\r\n toolLimits?: { timeoutMs?: number; maxResultChars?: number };\r\n}\r\n\r\nexport async function resolveAgentOwnerEmail(\r\n options: Pick<ProductionAgentOptions, \"resolveOwnerEmail\">,\r\n event: any,\r\n): Promise<string | null> {\r\n let ownerEmail: string | null = null;\r\n if (options.resolveOwnerEmail) {\r\n try {\r\n ownerEmail = await options.resolveOwnerEmail(event);\r\n } catch {\r\n ownerEmail = null;\r\n }\r\n }\r\n return ownerEmail ?? getRequestUserEmail() ?? null;\r\n}\r\n\r\nconst MAX_RETRIES = 3;\r\n/**\r\n * Retry budget override for `builder_gateway_error` — the no-detail Builder\r\n * gateway fallback. Production data shows this code is almost never\r\n * transient: it's the gateway emitting `{type:\"stop\",reason:\"error\"}` with\r\n * no explanation, which usually means the upstream provider rejected the\r\n * call (model quota, account misconfiguration). Retrying the same request\r\n * synchronously rarely recovers, and each retry emits a `clear` event that\r\n * wipes the user's visible content and re-streams from scratch — three\r\n * cycles of \"regenerate, clear, regenerate\" inside a single run for a\r\n * failure mode where retrying doesn't help. Keep the budget at 1 so we\r\n * cover genuinely transient cases without the visible flicker storm.\r\n */\r\nconst BUILDER_GATEWAY_ERROR_MAX_RETRIES = 1;\r\nconst RETRY_BASE_DELAY_MS = 2000;\r\n\r\nfunction maxRetriesForError(err: unknown): number {\r\n if (err instanceof EngineError) {\r\n const code = (err.errorCode ?? \"\").toLowerCase();\r\n if (code === \"builder_gateway_error\") {\r\n return BUILDER_GATEWAY_ERROR_MAX_RETRIES;\r\n }\r\n }\r\n return MAX_RETRIES;\r\n}\r\nconst TOOL_INPUT_ACTIVITY_INTERVAL_MS = 1500;\r\nconst ACTION_PREPARATION_NO_PROGRESS_TIMEOUT_MS = 90_000;\r\nconst ACTION_PREPARATION_ZERO_BYTE_RESTART_LIMIT = 2;\r\nconst MODEL_STREAM_NO_PROGRESS_TIMEOUT_MS = 90_000;\r\n// Raised from 1 -> 2 now that each retry actually adapts (raises the token\r\n// ceiling and steps reasoning effort down a tier) instead of re-issuing the\r\n// exact same doomed request twice.\r\nconst EMPTY_FINAL_RESPONSE_RETRY_LIMIT = 2;\r\nconst MAIN_CHAT_INTERNAL_CONTINUATION_LIMIT = 6;\r\nconst RUN_BUDGET_EXHAUSTED_ERROR_CODE = \"run_budget_exhausted\";\r\nconst RUN_BUDGET_EXHAUSTED_MESSAGE =\r\n \"I ran out of time before finishing this step. \" +\r\n \"I stopped rather than keep retrying silently. \" +\r\n \"Check any completed tool cards above before retrying, ideally as one smaller follow-up.\";\r\nconst MAX_TEXT_ATTACHMENT_CHARS = 60_000;\r\nconst MAX_SELECTION_CONTEXT_CHARS = 8_000;\r\nconst MAX_RESOURCE_INVENTORY_ITEMS = 40;\r\nconst MAX_RESOURCE_INVENTORY_DESCRIPTION_CHARS = 160;\r\nconst MAX_INLINE_SKILL_REFERENCE_CHARS = 40_000;\r\nconst SOURCE_SWEEP_TOOL_CALL_THRESHOLD = 12;\r\n\r\n/**\r\n * Hard cap on the `<current-screen>` block injected into EVERY user message.\r\n *\r\n * The screen snapshot comes from the template's `view-screen` action, which can\r\n * be unbounded — e.g. a recording/meeting page returns the full transcript +\r\n * every segment. Injected on every turn with no cap, that single block can blow\r\n * past the model's context window and hard-error the chat with\r\n * `context_length_exceeded` (observed: a brand-new \"hi\" message failing because\r\n * an open recording's transcript shipped in `<current-screen>`). Keep this to a\r\n * compact page summary; the agent can call `view-screen` (or a data action like\r\n * `get-recording-player-data`) for full detail on demand.\r\n */\r\nconst MAX_SCREEN_CONTEXT_CHARS = 10_000;\r\n\r\nfunction capScreenContext(text: string): string {\r\n if (text.length <= MAX_SCREEN_CONTEXT_CHARS) return text;\r\n return `${text.slice(0, MAX_SCREEN_CONTEXT_CHARS)}\\n\\n…[current-screen snapshot truncated after ${MAX_SCREEN_CONTEXT_CHARS.toLocaleString()} chars to protect the context window. Call the view-screen action for the full snapshot, or a data action (e.g. get-recording-player-data) for full transcripts.]`;\r\n}\r\n\r\nfunction capSelectionContext(text: string): string {\r\n if (text.length <= MAX_SELECTION_CONTEXT_CHARS) return text;\r\n return `${text.slice(0, MAX_SELECTION_CONTEXT_CHARS)}\\n\\n…[selection truncated after ${MAX_SELECTION_CONTEXT_CHARS.toLocaleString()} chars. Ask the user or use an app data action if the omitted text is required.]`;\r\n}\r\n\r\nfunction compactInventoryDescription(description: string): string {\r\n const oneLine = description.replace(/\\s+/g, \" \").trim();\r\n if (oneLine.length <= MAX_RESOURCE_INVENTORY_DESCRIPTION_CHARS) {\r\n return oneLine;\r\n }\r\n return `${oneLine.slice(0, MAX_RESOURCE_INVENTORY_DESCRIPTION_CHARS - 1)}…`;\r\n}\r\n\r\nfunction limitInventoryLines(lines: string[], label: string): string[] {\r\n if (lines.length <= MAX_RESOURCE_INVENTORY_ITEMS) return lines;\r\n const omitted = lines.length - MAX_RESOURCE_INVENTORY_ITEMS;\r\n return [\r\n ...lines.slice(0, MAX_RESOURCE_INVENTORY_ITEMS),\r\n ` … ${omitted} more ${label} omitted; use the resources tool with action \"list\" or \"read\" for the full inventory.`,\r\n ];\r\n}\r\n\r\nfunction generateRunId(): string {\r\n return `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\r\n}\r\n\r\nfunction toolInputActivityLabel(toolName?: string): string {\r\n return toolName ? `Preparing ${toolName} action` : \"Preparing action input\";\r\n}\r\n\r\n/** Check if an error is transient and should be retried\r\n * @internal exported for unit tests only\r\n */\r\nexport function isContextTooLongError(err: unknown): boolean {\r\n if (!(err instanceof Error)) return false;\r\n const msg = err.message.toLowerCase();\r\n if (\r\n msg.includes(\"context_length_exceeded\") ||\r\n msg.includes(\"input_too_long\") ||\r\n msg.includes(\"too many tokens\") ||\r\n msg.includes(\"prompt is too long\") ||\r\n msg.includes(\"reduce the length\") ||\r\n // Gemini phrasing\r\n msg.includes(\"input token count exceeds\") ||\r\n msg.includes(\"request too large\")\r\n )\r\n return true;\r\n if (err instanceof EngineError) {\r\n const code = (err.errorCode ?? \"\").toLowerCase();\r\n if (code.includes(\"context_length\") || code.includes(\"input_too_long\"))\r\n return true;\r\n }\r\n return false;\r\n}\r\n\r\n/** @internal exported for unit tests only */\r\nexport function isRetryableError(err: unknown): boolean {\r\n if (!(err instanceof Error)) return false;\r\n const msg = err.message.toLowerCase();\r\n const engineErr = err instanceof EngineError ? err : null;\r\n const code = (engineErr?.errorCode ?? \"\").toLowerCase();\r\n\r\n // Hard non-retryable codes — check these first.\r\n if (code === \"builder_gateway_timeout\") return false;\r\n if (\r\n code === \"rate_limit_exceeded\" ||\r\n msg.includes(\"daily gateway request cap\")\r\n )\r\n return false;\r\n\r\n // Prefer structured fields from the engine before falling back to message\r\n // keyword matching — avoids false positives on user-supplied text that\r\n // happens to contain \"rate_limit\" etc.\r\n if (engineErr) {\r\n // Provider explicitly said it is retryable.\r\n if (engineErr.providerRetryable === true) return true;\r\n // HTTP status-code checks (429, 500, 502, 503, 529 = Anthropic overloaded).\r\n const sc = engineErr.statusCode;\r\n if (sc === 429 || sc === 500 || sc === 502 || sc === 503 || sc === 529)\r\n return true;\r\n }\r\n\r\n return (\r\n code === \"builder_gateway_error\" ||\r\n code === \"builder_gateway_network_error\" ||\r\n code === \"provider_network_error\" ||\r\n code === \"http_429\" ||\r\n code === \"http_500\" ||\r\n code === \"http_502\" ||\r\n code === \"http_503\" ||\r\n code === \"http_504\" ||\r\n code === \"timeout\" ||\r\n // Anthropic\r\n msg.includes(\"overloaded\") ||\r\n msg.includes(\"rate_limit\") ||\r\n // Bare provider rate-limit messages that carry no structured status,\r\n // e.g. the Anthropic/AI-SDK \"429 status code (no body)\" format.\r\n /\\b429\\b/.test(msg) ||\r\n msg.includes(\"529\") ||\r\n // OpenAI phrasing\r\n msg.includes(\"rate limit reached\") ||\r\n // Google / Gemini\r\n msg.includes(\"resource_exhausted\") ||\r\n msg.includes(\"quota exceeded\") ||\r\n // Generic HTTP codes\r\n msg.includes(\"502\") ||\r\n msg.includes(\"503\") ||\r\n msg.includes(\"504\") ||\r\n msg.includes(\"gateway error\") ||\r\n msg.includes(\"socket hang up\") ||\r\n msg.includes(\"connection reset\") ||\r\n // Anthropic SDK APIConnectionError default message is exactly\r\n // \"Connection error.\" — Builder gateway often forwards it as a stop\r\n // event with no structured code. Without this match the run fails in\r\n // ~3s and the client recovery loop storms POSTs.\r\n msg.includes(\"connection error\") ||\r\n msg.includes(\"too many requests\") ||\r\n msg.includes(\"timeout\") ||\r\n msg.includes(\"gateway timeout\") ||\r\n msg.includes(\"inactivity timeout\") ||\r\n msg.includes(\"too much time has passed without sending any data\")\r\n );\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Context-window overflow recovery\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Number of recent messages to protect when trimming tool results.\r\n * Messages in the tail of this length are left completely intact; only\r\n * older messages have their tool-result text replaced with a stub.\r\n */\r\nconst CONTEXT_TRIM_KEEP_TAIL = 10;\r\nconst CONTEXT_TRIM_STUB =\r\n \"[result trimmed to save context — re-run the tool if needed]\";\r\n\r\n/**\r\n * Attempt one aggressive trim of old tool-result content to reduce the\r\n * context window usage. Tool-result messages older than the last\r\n * {@link CONTEXT_TRIM_KEEP_TAIL} messages have their text replaced with a\r\n * short stub. All user/assistant text messages and the recent tail are\r\n * preserved exactly.\r\n *\r\n * Returns a new array — the original is not mutated.\r\n * Returns `null` when there are no trimable tool results (so the caller can\r\n * skip the retry).\r\n */\r\nexport function trimOldToolResults(\r\n messages: EngineMessage[],\r\n keepTail = CONTEXT_TRIM_KEEP_TAIL,\r\n): EngineMessage[] | null {\r\n const cutoff = Math.max(0, messages.length - keepTail);\r\n let trimmed = false;\r\n\r\n const result = messages.map((msg, idx): EngineMessage => {\r\n // Keep messages in the protected tail intact\r\n if (idx >= cutoff) return msg;\r\n\r\n // Only touch user messages that contain tool-result parts\r\n if (msg.role !== \"user\") return msg;\r\n\r\n const hasToolResult = msg.content.some((p) => p.type === \"tool-result\");\r\n if (!hasToolResult) return msg;\r\n\r\n const stubbedContent = msg.content.map(\r\n (p): import(\"./engine/types.js\").EngineContentPart => {\r\n if (p.type !== \"tool-result\") return p;\r\n trimmed = true;\r\n return { ...p, content: CONTEXT_TRIM_STUB };\r\n },\r\n );\r\n\r\n return { role: \"user\", content: stubbedContent };\r\n });\r\n\r\n return trimmed ? result : null;\r\n}\r\n\r\n/** Wait with exponential backoff, respecting abort signal */\r\nfunction retryDelay(attempt: number, signal: AbortSignal): Promise<void> {\r\n const baseMs = RETRY_BASE_DELAY_MS * Math.pow(2, attempt);\r\n const jitter = baseMs * 0.1;\r\n const ms = Math.max(0, baseMs + (Math.random() * 2 - 1) * jitter);\r\n return new Promise((resolve, reject) => {\r\n if (signal.aborted) return reject(new Error(\"aborted\"));\r\n const onAbort = () => {\r\n clearTimeout(timer);\r\n reject(new Error(\"aborted\"));\r\n };\r\n const timer = setTimeout(() => {\r\n signal.removeEventListener(\"abort\", onAbort);\r\n resolve();\r\n }, ms);\r\n signal.addEventListener(\"abort\", onAbort, { once: true });\r\n });\r\n}\r\n\r\ntype SupportedImageMediaType =\r\n | \"image/jpeg\"\r\n | \"image/png\"\r\n | \"image/gif\"\r\n | \"image/webp\";\r\n\r\nfunction isSupportedImageMediaType(\r\n mediaType: string,\r\n): mediaType is SupportedImageMediaType {\r\n return (\r\n mediaType === \"image/jpeg\" ||\r\n mediaType === \"image/png\" ||\r\n mediaType === \"image/gif\" ||\r\n mediaType === \"image/webp\"\r\n );\r\n}\r\n\r\nfunction isSvgMediaType(mediaType: string | undefined): boolean {\r\n return mediaType?.split(\";\")[0]?.trim().toLowerCase() === \"image/svg+xml\";\r\n}\r\n\r\nfunction escapeAttachmentAttribute(value: string): string {\r\n return value\r\n .replace(/&/g, \"&amp;\")\r\n .replace(/\"/g, \"&quot;\")\r\n .replace(/</g, \"&lt;\")\r\n .replace(/>/g, \"&gt;\");\r\n}\r\n\r\nfunction unwrapTextAttachmentEnvelope(text: string): string {\r\n const match = text.match(/^<attachment\\b[^>]*>\\n([\\s\\S]*)\\n<\\/attachment>$/);\r\n return match ? match[1] : text;\r\n}\r\n\r\nfunction truncateTextAttachment(text: string, attachmentName?: string): string {\r\n if (text.length <= MAX_TEXT_ATTACHMENT_CHARS) return text;\r\n\r\n const omitted = text.length - MAX_TEXT_ATTACHMENT_CHARS;\r\n const readHint = attachmentName\r\n ? ` Use the \\`read-attachment\\` tool with name=\"${escapeAttachmentAttribute(attachmentName)}\" to read the rest.`\r\n : \"\";\r\n return `${text.slice(0, MAX_TEXT_ATTACHMENT_CHARS)}\\n\\n[Attachment truncated after ${MAX_TEXT_ATTACHMENT_CHARS.toLocaleString()} characters; ${omitted.toLocaleString()} characters omitted.${readHint}]`;\r\n}\r\n\r\nfunction formatTextAttachment(att: AgentChatAttachment): string | null {\r\n if (typeof att.text !== \"string\" || att.text.length === 0) return null;\r\n const text = truncateTextAttachment(\r\n unwrapTextAttachmentEnvelope(att.text),\r\n att.name,\r\n );\r\n\r\n const attrs = [\r\n `name=\"${escapeAttachmentAttribute(att.name || \"attachment\")}\"`,\r\n att.contentType\r\n ? `contentType=\"${escapeAttachmentAttribute(att.contentType)}\"`\r\n : null,\r\n att.type ? `type=\"${escapeAttachmentAttribute(att.type)}\"` : null,\r\n ].filter(Boolean);\r\n\r\n return `<attachment ${attrs.join(\" \")}>\\n${text}\\n</attachment>`;\r\n}\r\n\r\nfunction dataUrlToFilePart(\r\n att: AgentChatAttachment,\r\n): { type: \"file\"; data: string; mediaType: string; filename?: string } | null {\r\n if (att.type !== \"file\" || typeof att.data !== \"string\") return null;\r\n const match = att.data.match(/^data:([^;]+);base64,(.+)$/);\r\n if (!match) return null;\r\n return {\r\n type: \"file\",\r\n data: match[2],\r\n mediaType: att.contentType || match[1],\r\n filename: att.name || undefined,\r\n };\r\n}\r\n\r\nexport function buildUserContentWithAttachments(opts: {\r\n text: string;\r\n attachments?: AgentChatAttachment[];\r\n}): EngineContentPart[] {\r\n const userContent: EngineContentPart[] = [];\r\n const textAttachments: string[] = [];\r\n\r\n for (const att of opts.attachments ?? []) {\r\n const uploadedUrl = (att as any).url as string | undefined;\r\n if ((att as any).referenceOnly === true && uploadedUrl) {\r\n const label = att.name ? `\"${att.name}\"` : \"A file\";\r\n const contentType = att.contentType ? ` (${att.contentType})` : \"\";\r\n textAttachments.push(\r\n `[${label} was uploaded to ${uploadedUrl} as a reference-only file${contentType}. Use the URL for embedding/reference if needed; do not inline raw file contents unless the target app sanitizes it.]`,\r\n );\r\n continue;\r\n }\r\n\r\n if (att.type === \"image\") {\r\n if (!att.data) {\r\n if (uploadedUrl) {\r\n const label = att.name ? `\"${att.name}\"` : \"An image\";\r\n textAttachments.push(\r\n `[${label} was uploaded to ${uploadedUrl}, but was not sent as a vision image because no supported base64 image data was present. Use the URL for embedding/reference if needed.]`,\r\n );\r\n }\r\n continue;\r\n }\r\n const match = att.data.match(/^data:(image\\/[^;]+);base64,(.+)$/);\r\n if (match && isSupportedImageMediaType(match[1])) {\r\n userContent.push({\r\n type: \"image\",\r\n data: match[2],\r\n mediaType: match[1],\r\n });\r\n } else {\r\n // The client sent an image in an unsupported format (HEIC, TIFF, AVIF,\r\n // etc.). Inject a short text placeholder so the model knows the image\r\n // was present but could not be processed, rather than silently omitting\r\n // it and leaving the model confused (\"I don't see an image\").\r\n const mime = match?.[1] ?? att.contentType ?? \"unknown format\";\r\n const label = att.name ? `\"${att.name}\"` : \"An image\";\r\n const uploadedHint = uploadedUrl\r\n ? ` It is available at ${uploadedUrl}; use that URL for embedding/reference if the task does not require vision analysis.`\r\n : \"\";\r\n if (uploadedUrl && isSvgMediaType(mime)) {\r\n textAttachments.push(\r\n `[${label} was uploaded to ${uploadedUrl} as an SVG reference (${mime}). ` +\r\n `It was not sent as a vision image because SVG files are handled as reference-only vector files. ` +\r\n `Use the URL for embedding/reference if needed; ask for a JPEG, PNG, GIF, or WebP export only if rendered-pixel vision analysis is required.]`,\r\n );\r\n continue;\r\n }\r\n textAttachments.push(\r\n `[${label} could not be processed — unsupported image format (${mime}). ` +\r\n uploadedHint +\r\n ` Inform the user that only JPEG, PNG, GIF, and WebP images are supported for vision analysis, ` +\r\n `and ask them to convert the file before attaching.]`,\r\n );\r\n }\r\n continue;\r\n }\r\n\r\n const filePart = dataUrlToFilePart(att);\r\n if (filePart) {\r\n userContent.push(filePart);\r\n continue;\r\n }\r\n\r\n const textAttachment = formatTextAttachment(att);\r\n if (textAttachment) {\r\n textAttachments.push(textAttachment);\r\n }\r\n }\r\n\r\n userContent.push({\r\n type: \"text\",\r\n text:\r\n textAttachments.length > 0\r\n ? `${textAttachments.join(\"\\n\\n\")}\\n\\n${opts.text}`\r\n : opts.text,\r\n });\r\n\r\n return userContent;\r\n}\r\n\r\nfunction coerceStructuredToolResultWire(part: {\r\n toolCallId?: unknown;\r\n content?: unknown;\r\n}): { toolCallId: string; content: string } {\r\n const toolCallId =\r\n typeof part.toolCallId === \"string\"\r\n ? part.toolCallId.trim()\r\n : part.toolCallId === undefined || part.toolCallId === null\r\n ? \"\"\r\n : String(part.toolCallId).trim();\r\n let content = \"\";\r\n if (typeof part.content === \"string\") {\r\n content = part.content;\r\n } else if (part.content !== undefined && part.content !== null) {\r\n try {\r\n content = JSON.stringify(part.content);\r\n } catch {\r\n content = String(part.content);\r\n }\r\n }\r\n return { toolCallId, content };\r\n}\r\n\r\nexport function structuredHistoryToEngineMessages(\r\n history: AgentChatStructuredMessage[] | undefined,\r\n): EngineMessage[] | null {\r\n if (!Array.isArray(history)) return null;\r\n\r\n const toolUseById = new Map<string, { name: string; input: unknown }>();\r\n\r\n const messages: EngineMessage[] = [];\r\n for (const message of history) {\r\n if (\r\n !message ||\r\n (message.role !== \"user\" && message.role !== \"assistant\") ||\r\n !Array.isArray(message.content)\r\n ) {\r\n continue;\r\n }\r\n\r\n const content: EngineContentPart[] = [];\r\n for (const part of message.content) {\r\n if (!part || typeof part !== \"object\") continue;\r\n if (part.type === \"text\" && typeof part.text === \"string\") {\r\n if (part.text.length > 0) {\r\n content.push({ type: \"text\", text: part.text });\r\n }\r\n continue;\r\n }\r\n\r\n if (part.type === \"tool-call\" && message.role === \"assistant\") {\r\n const id =\r\n typeof part.id === \"string\"\r\n ? part.id\r\n : typeof part.toolCallId === \"string\"\r\n ? part.toolCallId\r\n : \"\";\r\n const name =\r\n typeof part.name === \"string\"\r\n ? part.name\r\n : typeof part.toolName === \"string\"\r\n ? part.toolName\r\n : \"\";\r\n if (!id || !name) continue;\r\n const input = part.input ?? part.args ?? {};\r\n toolUseById.set(id, { name, input });\r\n content.push({\r\n type: \"tool-call\",\r\n id,\r\n name,\r\n input,\r\n });\r\n continue;\r\n }\r\n\r\n if (part.type === \"tool-result\" && message.role === \"user\") {\r\n const wire = coerceStructuredToolResultWire(part);\r\n const lookup =\r\n wire.toolCallId.length > 0\r\n ? toolUseById.get(wire.toolCallId)\r\n : undefined;\r\n const toolName =\r\n typeof part.toolName === \"string\" && part.toolName.trim().length > 0\r\n ? part.toolName\r\n : lookup?.name;\r\n if (!toolName?.trim()) {\r\n content.push({\r\n type: \"text\",\r\n text: unmatchedToolResultReplayText({\r\n toolCallId:\r\n wire.toolCallId.length > 0 ? wire.toolCallId : \"(missing)\",\r\n content: wire.content,\r\n isError: part.isError,\r\n }),\r\n });\r\n continue;\r\n }\r\n if (!wire.toolCallId) {\r\n // Named tool but no id — cannot emit a valid paired `tool-result`.\r\n content.push({\r\n type: \"text\",\r\n text: unmatchedToolResultReplayText({\r\n toolCallId: \"(missing)\",\r\n content: wire.content,\r\n isError: part.isError,\r\n }),\r\n });\r\n continue;\r\n }\r\n const toolInput =\r\n typeof part.toolInput === \"string\" && part.toolInput.length > 0\r\n ? part.toolInput\r\n : stringifyToolUseInputForGateway(lookup?.input);\r\n content.push({\r\n type: \"tool-result\",\r\n toolCallId: wire.toolCallId,\r\n toolName,\r\n toolInput,\r\n content: wire.content,\r\n ...(part.isError ? { isError: true } : {}),\r\n });\r\n }\r\n }\r\n\r\n if (content.length > 0) {\r\n messages.push({ role: message.role, content });\r\n }\r\n }\r\n\r\n return messages.length > 0\r\n ? backfillEngineMessagesToolResults(messages)\r\n : null;\r\n}\r\n\r\n/** Build enriched message with file/skill/mention references */\r\nfunction capInlineSkillReferenceContent(text: string): string {\r\n const trimmed = text.trim();\r\n if (trimmed.length <= MAX_INLINE_SKILL_REFERENCE_CHARS) return trimmed;\r\n const omitted = trimmed.length - MAX_INLINE_SKILL_REFERENCE_CHARS;\r\n return `${trimmed.slice(0, MAX_INLINE_SKILL_REFERENCE_CHARS)}\\n\\n[Skill content truncated after ${MAX_INLINE_SKILL_REFERENCE_CHARS.toLocaleString()} chars; ${omitted.toLocaleString()} chars omitted.]`;\r\n}\r\n\r\nfunction escapeReferenceAttribute(value: string): string {\r\n return value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\r\n}\r\n\r\nfunction isRuntimeVisibleSkillContent(content: string): boolean {\r\n const frontmatter = parseFrontmatter(content);\r\n const scope = getFrontmatterValue(frontmatter, \"scope\")?.trim().toLowerCase();\r\n return scope !== \"dev\";\r\n}\r\n\r\nexport async function resolveSkillReferenceContent(\r\n ref: AgentChatReference,\r\n): Promise<string | null> {\r\n if (!ref.path && !ref.name) return null;\r\n\r\n if (ref.source === \"resource\") {\r\n const ownerEmail = getRequestUserEmail();\r\n if (!ownerEmail || !ref.path) return null;\r\n try {\r\n const { resourceEffectiveContext, resourceGet } =\r\n await import(\"../resources/store.js\");\r\n const resourceOptions = {\r\n userEmail: ownerEmail,\r\n orgId: getRequestOrgId() ?? null,\r\n };\r\n const effective = await resourceEffectiveContext(ownerEmail, ref.path, {\r\n ...resourceOptions,\r\n });\r\n if (!effective.effectiveResource) return null;\r\n const full = await resourceGet(effective.effectiveResource.id, {\r\n ...resourceOptions,\r\n });\r\n if (!full?.content || !isRuntimeVisibleSkillContent(full.content)) {\r\n return null;\r\n }\r\n return full.content;\r\n } catch {\r\n return null;\r\n }\r\n }\r\n\r\n try {\r\n const { loadAgentsBundle, getRuntimeSkills } =\r\n await import(\"../server/agents-bundle.js\");\r\n const bundle = await loadAgentsBundle();\r\n const normalizedPath = ref.path?.replace(/\\/+$/g, \"\");\r\n const skill = getRuntimeSkills(bundle).find((candidate) => {\r\n const skillPath = candidate.dir.replace(/\\/+$/g, \"\");\r\n return (\r\n candidate.meta.name === ref.name ||\r\n normalizedPath === skillPath ||\r\n normalizedPath === `${skillPath}/SKILL.md`\r\n );\r\n });\r\n return skill?.content ?? null;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nasync function enrichMessage(\r\n message: string,\r\n references: AgentChatReference[],\r\n): Promise<string> {\r\n if (references.length === 0) return message;\r\n\r\n const fileRefs = references.filter((r) => r.type === \"file\");\r\n const skillRefs = references.filter((r) => r.type === \"skill\");\r\n const customAgentRefs = references.filter((r) => r.type === \"custom-agent\");\r\n const mentionRefs = references.filter((r) => r.type === \"mention\");\r\n\r\n const parts: string[] = [];\r\n if (fileRefs.length > 0) {\r\n parts.push(\r\n \"Referenced files:\\n\" +\r\n fileRefs\r\n .map(\r\n (r) => `- ${r.path}${r.source === \"resource\" ? \" (resource)\" : \"\"}`,\r\n )\r\n .join(\"\\n\"),\r\n );\r\n }\r\n if (skillRefs.length > 0) {\r\n const skillLines = await Promise.all(\r\n skillRefs.map(async (r) => {\r\n const content = await resolveSkillReferenceContent(r);\r\n if (content?.trim()) {\r\n return `- ${r.name} (${r.path})\\n\\n<applied-skill name=\"${escapeReferenceAttribute(r.name)}\" path=\"${escapeReferenceAttribute(r.path)}\" source=\"${escapeReferenceAttribute(r.source)}\">\\n${capInlineSkillReferenceContent(content)}\\n</applied-skill>`;\r\n }\r\n return `- ${r.name} (${r.path})${\r\n r.source === \"resource\"\r\n ? ' — content was not inlined; read with the resources tool (action: \"read\") if needed'\r\n : \" — content was not inlined; read with the read tool if needed\"\r\n }`;\r\n }),\r\n );\r\n parts.push(\r\n \"Applied skills (read and follow before acting):\\n\" +\r\n skillLines.join(\"\\n\"),\r\n );\r\n }\r\n if (customAgentRefs.length > 0) {\r\n parts.push(\r\n \"Requested custom agents:\\n\" +\r\n customAgentRefs\r\n .map(\r\n (r) =>\r\n `- ${r.name}${r.refId ? ` (id: ${r.refId})` : \"\"}${r.path ? ` (path: ${r.path})` : \"\"}`,\r\n )\r\n .join(\"\\n\"),\r\n );\r\n }\r\n if (mentionRefs.length > 0) {\r\n parts.push(\r\n \"Referenced items:\\n\" +\r\n mentionRefs\r\n .map(\r\n (r) =>\r\n `- [${r.refType || \"item\"}] ${r.name}${r.refId ? ` (id: ${r.refId})` : \"\"}${r.path ? ` (path: ${r.path})` : \"\"}`,\r\n )\r\n .join(\"\\n\"),\r\n );\r\n }\r\n\r\n return `${parts.join(\"\\n\\n\")}\\n\\n${message}`;\r\n}\r\n\r\n/** Accumulated token usage from an agent loop run */\r\nexport interface AgentLoopUsage {\r\n inputTokens: number;\r\n outputTokens: number;\r\n cacheReadTokens: number;\r\n cacheWriteTokens: number;\r\n model: string;\r\n}\r\n\r\nexport interface AgentLoopToolCallSummary {\r\n name: string;\r\n input: unknown;\r\n}\r\n\r\nexport interface AgentLoopToolResultSummary {\r\n name: string;\r\n content: string;\r\n isError: boolean;\r\n}\r\n\r\nexport interface AgentLoopFinalResponseGuardContext {\r\n messages: EngineMessage[];\r\n assistantContent: EngineContentPart[];\r\n text: string;\r\n toolCalls: AgentLoopToolCallSummary[];\r\n toolResults: AgentLoopToolResultSummary[];\r\n retryCount: number;\r\n executionMode: AgentExecutionMode;\r\n}\r\n\r\nexport type AgentLoopFinalResponseGuardResult =\r\n | string\r\n | {\r\n retryMessage: string;\r\n fallbackMessage?: string;\r\n };\r\n\r\nexport type AgentLoopFinalResponseGuard = (\r\n context: AgentLoopFinalResponseGuardContext,\r\n) =>\r\n | AgentLoopFinalResponseGuardResult\r\n | null\r\n | undefined\r\n | Promise<AgentLoopFinalResponseGuardResult | null | undefined>;\r\n\r\nfunction collectTextParts(parts: EngineContentPart[]): string {\r\n return parts\r\n .filter(\r\n (part): part is import(\"./engine/types.js\").EngineTextPart =>\r\n part.type === \"text\",\r\n )\r\n .map((part) => part.text)\r\n .join(\"\");\r\n}\r\n\r\nexport const AGENT_INTERNAL_CONTINUE_PROMPT =\r\n \"Continue from where you left off and finish the user's original request. Do not repeat completed work, do not mention internal reconnects, time limits, or step limits, and continue as if this is the same uninterrupted run.\";\r\n\r\nexport type AgentLoopContinuationReason =\r\n | \"run_timeout\"\r\n | \"loop_limit\"\r\n | \"max_tokens\"\r\n | \"stream_ended\"\r\n | \"gateway_timeout\"\r\n | \"network_interrupted\"\r\n | \"no_progress\";\r\n\r\nexport function appendAgentLoopContinuation(\r\n messages: EngineMessage[],\r\n reason: AgentLoopContinuationReason,\r\n options: { actionPreparationTool?: string } = {},\r\n) {\r\n const note =\r\n reason === \"loop_limit\"\r\n ? \"The previous run reached an internal step budget.\"\r\n : reason === \"max_tokens\"\r\n ? \"The previous LLM call reached the model output-token cap before the response finished.\"\r\n : reason === \"stream_ended\"\r\n ? \"The previous stream ended before the agent sent a final completion signal.\"\r\n : reason === \"gateway_timeout\"\r\n ? \"The previous LLM call hit an upstream gateway timeout before the response finished streaming.\"\r\n : reason === \"network_interrupted\"\r\n ? \"The previous LLM call was cut off by a transport-level interruption (socket dropped, connection reset, or stream closed unexpectedly).\"\r\n : reason === \"no_progress\"\r\n ? \"The previous run stopped producing progress events while the connection stayed open.\"\r\n : \"The previous run reached an internal execution budget.\";\r\n const actionInputNote = options.actionPreparationTool\r\n ? actionPreparationContinuationNote(options.actionPreparationTool)\r\n : \"\";\r\n messages.push({\r\n role: \"user\",\r\n content: [\r\n {\r\n type: \"text\",\r\n text: `${AGENT_INTERNAL_CONTINUE_PROMPT}\\n\\nInternal note: ${note}${actionInputNote}`,\r\n },\r\n ],\r\n });\r\n}\r\n\r\nfunction isAgentLoopContinuationReason(\r\n reason: unknown,\r\n): reason is AgentLoopContinuationReason {\r\n return (\r\n reason === \"run_timeout\" ||\r\n reason === \"loop_limit\" ||\r\n reason === \"max_tokens\" ||\r\n reason === \"stream_ended\" ||\r\n reason === \"gateway_timeout\" ||\r\n reason === \"network_interrupted\" ||\r\n reason === \"no_progress\"\r\n );\r\n}\r\n\r\n/**\r\n * True when an error thrown by `runAgentLoop` is a recoverable transport- or\r\n * gateway-level interruption that the agent can resume from rather than a\r\n * terminal failure. The continuation pattern works because the LLM call's\r\n * conversation prefix is preserved on the next attempt — Anthropic's prompt\r\n * cache rescues the latency, and the agent gets a \"you got cut off, continue\"\r\n * nudge so it doesn't redo work it already finished.\r\n *\r\n * Distinct from `isRetryableError` which guides per-engine quick retries:\r\n * `isResumableEngineError` is checked AFTER engine retries are exhausted, at\r\n * the run level. It catches both gateway-reported timeouts (where engine\r\n * retries don't apply because the gateway already gave up) and transport\r\n * errors that survived engine retry budgets.\r\n */\r\nexport function isResumableEngineError(err: unknown): boolean {\r\n if (!(err instanceof Error)) return false;\r\n const code =\r\n err instanceof EngineError ? (err.errorCode ?? \"\").toLowerCase() : \"\";\r\n if (\r\n code === \"builder_gateway_timeout\" ||\r\n code === \"builder_gateway_network_error\" ||\r\n code === \"provider_network_error\"\r\n ) {\r\n return true;\r\n }\r\n if (\r\n code === \"http_502\" ||\r\n code === \"http_503\" ||\r\n code === \"http_504\" ||\r\n code === \"timeout\"\r\n ) {\r\n return true;\r\n }\r\n const text = errorSearchText(err);\r\n return (\r\n text.includes(\"socket hang up\") ||\r\n text.includes(\"econnreset\") ||\r\n text.includes(\"enetreset\") ||\r\n text.includes(\"econnaborted\") ||\r\n text.includes(\"fetch failed\") ||\r\n text.includes(\"network error\") ||\r\n text.includes(\"connection error\") ||\r\n text.includes(\"connection reset\") ||\r\n text.includes(\"connection closed\") ||\r\n text.includes(\"stream closed\") ||\r\n text.includes(\"inactivity timeout\") ||\r\n text.includes(\"gateway timeout\") ||\r\n text.includes(\"upstream timeout\") ||\r\n text.includes(\"function timeout\") ||\r\n text.includes(\"too much time has passed without sending any data\") ||\r\n text.includes(\"terminated\")\r\n );\r\n}\r\n\r\n/**\r\n * Map a resumable error to the most descriptive continuation reason. Used\r\n * when surfacing the resume to the agent and to clients via the\r\n * `auto_continue` event.\r\n */\r\nexport function continuationReasonForResumableError(\r\n err: unknown,\r\n): \"gateway_timeout\" | \"network_interrupted\" {\r\n const code =\r\n err instanceof EngineError ? (err.errorCode ?? \"\").toLowerCase() : \"\";\r\n if (code === \"builder_gateway_timeout\") return \"gateway_timeout\";\r\n const text = err instanceof Error ? err.message.toLowerCase() : \"\";\r\n if (\r\n text.includes(\"gateway timeout\") ||\r\n text.includes(\"upstream timeout\") ||\r\n text.includes(\"function timeout\")\r\n ) {\r\n return \"gateway_timeout\";\r\n }\r\n return \"network_interrupted\";\r\n}\r\n\r\nfunction errorSearchText(err: unknown): string {\r\n const parts: string[] = [];\r\n if (err instanceof Error) {\r\n parts.push(err.name, err.message);\r\n const maybe = err as Error & { code?: unknown; cause?: unknown };\r\n if (typeof maybe.code === \"string\") parts.push(maybe.code);\r\n if (maybe.cause) parts.push(errorSearchText(maybe.cause));\r\n } else {\r\n parts.push(String(err));\r\n }\r\n return parts.join(\" \").toLowerCase();\r\n}\r\n\r\nfunction textFromEngineMessage(message: EngineMessage): string {\r\n return message.content\r\n .filter(\r\n (part): part is import(\"./engine/types.js\").EngineTextPart =>\r\n part.type === \"text\",\r\n )\r\n .map((part) => part.text)\r\n .join(\"\\n\");\r\n}\r\n\r\nfunction isInternalContinuationTurn(messages: EngineMessage[]): boolean {\r\n for (let i = messages.length - 1; i >= 0; i--) {\r\n const message = messages[i];\r\n if (message.role !== \"user\") continue;\r\n return textFromEngineMessage(message).startsWith(\r\n AGENT_INTERNAL_CONTINUE_PROMPT,\r\n );\r\n }\r\n return false;\r\n}\r\n\r\nfunction isToolResultOnlyUserMessage(message: EngineMessage): boolean {\r\n return (\r\n message.role === \"user\" &&\r\n message.content.length > 0 &&\r\n message.content.every((part) => part.type === \"tool-result\")\r\n );\r\n}\r\n\r\n/** Start of the active turn on an internal continuation (real user prompt). */\r\nfunction findCurrentTurnStartForContinuation(\r\n messages: EngineMessage[],\r\n): number {\r\n let i = messages.length - 1;\r\n while (i >= 0) {\r\n const message = messages[i];\r\n if (message.role !== \"user\") {\r\n i--;\r\n continue;\r\n }\r\n const userText = textFromEngineMessage(message);\r\n if (userText.startsWith(AGENT_INTERNAL_CONTINUE_PROMPT)) {\r\n i--;\r\n continue;\r\n }\r\n if (isToolResultOnlyUserMessage(message)) {\r\n i--;\r\n continue;\r\n }\r\n return i;\r\n }\r\n return 0;\r\n}\r\n\r\n/**\r\n * First message index that is safe to start a trimmed window on. A window must\r\n * not begin with a tool-result-only user message — that would orphan it from\r\n * the assistant tool-call turn it answers and break Anthropic's tool_use /\r\n * tool_result pairing. We walk forward from `desiredStart` to the first\r\n * non-orphaned boundary; if none exists we refuse to trim (return -1).\r\n */\r\nfunction findSafeWindowStart(\r\n messages: EngineMessage[],\r\n desiredStart: number,\r\n): number {\r\n for (let i = Math.max(0, desiredStart); i < messages.length; i++) {\r\n if (!isToolResultOnlyUserMessage(messages[i])) return i;\r\n }\r\n return -1;\r\n}\r\n\r\n/**\r\n * Observational Memory consumer (threshold-gated, conservative).\r\n *\r\n * Builds the three-tier OM context for a thread and, ONLY when the thread has\r\n * already crossed the compaction threshold (i.e. it has at least one persisted\r\n * observation/reflection), returns a rewritten message list that:\r\n * - prepends a single system-role \"Observational Memory\" block holding the\r\n * reflections + observations, and\r\n * - replaces the raw older history with just the recent-raw-message window,\r\n * keeping the current user turn and any pending tool results intact.\r\n *\r\n * For threads with NO OM entries (every short thread) it returns the input\r\n * array unchanged by reference, so the common path is byte-for-byte identical.\r\n *\r\n * Best-effort: any failure returns the input unchanged so OM can never break a\r\n * normal turn.\r\n */\r\nasync function applyObservationalMemoryToContext(\r\n messages: EngineMessage[],\r\n opts: {\r\n threadId: string;\r\n ownerEmail?: string | null;\r\n orgId?: string | null;\r\n },\r\n): Promise<EngineMessage[]> {\r\n if (!opts.ownerEmail) return messages;\r\n\r\n try {\r\n const context = await buildObservationalContext({\r\n threadId: opts.threadId,\r\n ownerEmail: opts.ownerEmail,\r\n orgId: opts.orgId ?? null,\r\n messages,\r\n });\r\n\r\n // No compacted memory yet → short thread, leave context untouched.\r\n if (!hasObservationalMemory(context)) return messages;\r\n\r\n const block = serializeObservationalMemoryBlock(context);\r\n if (!block.trim()) return messages;\r\n\r\n // EngineMessage has no \"system\" role; the framework injects auxiliary\r\n // context as leading user messages (same convention as the continuation\r\n // nudge and the resume journal note), and the serialized block is clearly\r\n // self-labeled \"[Observational Memory]\".\r\n const omMessage: EngineMessage = {\r\n role: \"user\",\r\n content: [{ type: \"text\", text: block }],\r\n };\r\n\r\n // Trim the raw prefix to only the recent-raw window. The window is the tail\r\n // of `messages`, so it always contains the latest user turn and any pending\r\n // tool results. Guard the boundary so we never start mid tool_use/result\r\n // pair; if a safe boundary can't be found, additively inject the memory\r\n // block WITHOUT trimming (the conservative fallback) so we never drop a\r\n // pending tool result.\r\n const recentCount = context.recentMessages.length;\r\n if (recentCount === 0 || recentCount >= messages.length) {\r\n return [omMessage, ...messages];\r\n }\r\n const desiredStart = messages.length - recentCount;\r\n const safeStart = findSafeWindowStart(messages, desiredStart);\r\n if (safeStart < 0) {\r\n // Whole tail is tool-result-only (degenerate) — don't trim.\r\n return [omMessage, ...messages];\r\n }\r\n return [omMessage, ...messages.slice(safeStart)];\r\n } catch (err) {\r\n console.warn(\r\n \"[observational-memory] context injection skipped:\",\r\n err instanceof Error ? err.message : String(err),\r\n );\r\n return messages;\r\n }\r\n}\r\n\r\nfunction seedReadOnlyToolResultsFromHistory(\r\n messages: EngineMessage[],\r\n actions: Record<string, ActionEntry>,\r\n): Map<string, string> {\r\n const cache = new Map<string, string>();\r\n if (!isInternalContinuationTurn(messages)) return cache;\r\n\r\n const pendingToolCalls = new Map<string, { name: string; input: unknown }>();\r\n for (const message of messages) {\r\n if (message.role === \"assistant\") {\r\n for (const part of message.content) {\r\n if (part.type !== \"tool-call\") continue;\r\n const entry = actions[part.name];\r\n if (entry?.readOnly !== true) continue;\r\n pendingToolCalls.set(part.id, {\r\n name: part.name,\r\n input: part.input,\r\n });\r\n }\r\n continue;\r\n }\r\n\r\n for (const part of message.content) {\r\n if (part.type !== \"tool-result\") continue;\r\n const call = pendingToolCalls.get(part.toolCallId);\r\n if (!call) continue;\r\n if (!isReusableReadOnlyToolResult(part)) continue;\r\n cache.set(toolCallCacheKey(call.name, call.input), part.content);\r\n }\r\n }\r\n\r\n return cache;\r\n}\r\n\r\nfunction isReusableReadOnlyToolResult(part: EngineToolResultPart): boolean {\r\n if (part.isError) return false;\r\n const lower = part.content.trim().toLowerCase();\r\n if (!lower) return false;\r\n return !(\r\n lower.startsWith(\"invalid action parameters for \") ||\r\n lower.startsWith(\"error running \") ||\r\n lower.includes(\"run aborted\") ||\r\n lower.includes(\"tool call timed out\") ||\r\n lower.includes(\"stale_run\") ||\r\n lower.includes(\"connection_error\")\r\n );\r\n}\r\n\r\n/**\r\n * Counts how many times each write (non-read-only) tool call was interrupted\r\n * before returning a result in the continuation history. When a connection\r\n * drops mid-tool-execution the client sends a placeholder result\r\n * (\"Interrupted before this tool returned a result.\") so the model knows\r\n * what was attempted. If the same write tool is called again with identical\r\n * input in the next continuation, this count prevents infinite retry loops.\r\n */\r\nconst INTERRUPTED_TOOL_RESULT_MARKER =\r\n \"Interrupted before this tool returned a result.\";\r\nconst MAX_WRITE_TOOL_INTERRUPTIONS = 2;\r\nconst MAX_IDENTICAL_TOOL_ERRORS = 3;\r\n\r\nfunction seedWriteToolInterruptionsFromHistory(\r\n messages: EngineMessage[],\r\n actions: Record<string, ActionEntry>,\r\n): Map<string, number> {\r\n const interruptions = new Map<string, number>();\r\n if (!isInternalContinuationTurn(messages)) return interruptions;\r\n\r\n const turnStart = findCurrentTurnStartForContinuation(messages);\r\n const turnMessages = messages.slice(turnStart);\r\n\r\n const pendingToolCalls = new Map<string, { name: string; input: unknown }>();\r\n for (const message of turnMessages) {\r\n if (message.role === \"assistant\") {\r\n for (const part of message.content) {\r\n if (part.type !== \"tool-call\") continue;\r\n const entry = actions[part.name];\r\n if (entry?.readOnly === true) continue;\r\n pendingToolCalls.set(part.id, { name: part.name, input: part.input });\r\n }\r\n continue;\r\n }\r\n\r\n for (const part of message.content) {\r\n if (part.type !== \"tool-result\") continue;\r\n const call = pendingToolCalls.get(part.toolCallId);\r\n if (!call) continue;\r\n if (\r\n typeof part.content === \"string\" &&\r\n part.content.includes(INTERRUPTED_TOOL_RESULT_MARKER)\r\n ) {\r\n const key = toolCallCacheKey(call.name, call.input);\r\n interruptions.set(key, (interruptions.get(key) ?? 0) + 1);\r\n }\r\n }\r\n }\r\n\r\n return interruptions;\r\n}\r\n\r\n/**\r\n * Convert ActionEntry registry to EngineTool array.\r\n */\r\nexport function actionsToEngineTools(\r\n actions: Record<string, ActionEntry>,\r\n): EngineTool[] {\r\n const tools: EngineTool[] = [];\r\n for (const [name, entry] of Object.entries(actions)) {\r\n if (entry.agentTool === false) continue;\r\n const inputSchema = normalizeToolInputSchema(entry.tool.parameters);\r\n if (!inputSchema) {\r\n console.warn(\r\n `[agent] Skipping tool \"${name}\" because its input schema is not an object.`,\r\n );\r\n continue;\r\n }\r\n tools.push({\r\n name,\r\n description: entry.tool.description,\r\n inputSchema,\r\n });\r\n }\r\n return tools;\r\n}\r\n\r\nexport function filterInitialEngineTools(\r\n tools: EngineTool[],\r\n initialToolNames?: string[],\r\n): EngineTool[] {\r\n if (!initialToolNames) return tools;\r\n const names = new Set(initialToolNames);\r\n names.add(TOOL_SEARCH_ACTION_NAME);\r\n for (const tool of tools) {\r\n if (isDefaultLeanInitialToolName(tool.name)) {\r\n names.add(tool.name);\r\n }\r\n }\r\n return tools.filter((tool) => names.has(tool.name));\r\n}\r\n\r\nconst DEFAULT_LEAN_INITIAL_TOOL_NAMES = new Set([\r\n // Broad provider/API/corpus primitives should be callable as soon as the\r\n // prompt teaches them; waiting for a discovery round-trip caused prod runs to\r\n // waste turns on provider work that was described but not loaded.\r\n \"data-source-status\",\r\n \"provider-api-catalog\",\r\n \"provider-api-docs\",\r\n \"provider-api-request\",\r\n \"provider-corpus-job\",\r\n \"provider-corpus-jobs\",\r\n \"query-staged-dataset\",\r\n \"list-staged-datasets\",\r\n \"delete-staged-dataset\",\r\n \"run-code\",\r\n \"get-code-execution\",\r\n \"list-extensions\",\r\n \"get-extension\",\r\n \"update-extension\",\r\n \"list-extension-history\",\r\n \"get-extension-history-version\",\r\n // Common first-class integration shortcuts. These are included only when the\r\n // current app/mode registry actually exposes them.\r\n \"bigquery\",\r\n \"search-bigquery-schema\",\r\n \"bigquery-table-info\",\r\n \"ga4\",\r\n \"amplitude\",\r\n \"prometheus\",\r\n \"grafana\",\r\n \"sentry\",\r\n \"stripe\",\r\n \"account-deep-dive\",\r\n \"slack-messages\",\r\n \"hubspot-deals\",\r\n \"hubspot-records\",\r\n \"hubspot-pipelines\",\r\n \"hubspot-metrics\",\r\n \"gong-calls\",\r\n \"github-repo-files\",\r\n \"jira\",\r\n \"jira-search\",\r\n \"gcloud\",\r\n \"notion-search\",\r\n \"pylon-search\",\r\n]);\r\n\r\nfunction isDefaultLeanInitialToolName(name: string): boolean {\r\n if (DEFAULT_LEAN_INITIAL_TOOL_NAMES.has(name)) return true;\r\n return (\r\n name.startsWith(\"provider-api-\") || name.startsWith(\"provider-corpus-\")\r\n );\r\n}\r\n\r\nfunction extractToolSearchResultNames(value: unknown): string[] {\r\n if (!value || typeof value !== \"object\") return [];\r\n const result = value as { query?: unknown; results?: unknown };\r\n if (typeof result.query !== \"string\" || result.query.trim().length === 0) {\r\n return [];\r\n }\r\n if (!Array.isArray(result.results)) return [];\r\n const names: string[] = [];\r\n for (const item of result.results) {\r\n if (!item || typeof item !== \"object\") continue;\r\n const name = (item as Record<string, unknown>).name;\r\n if (typeof name === \"string\" && name.trim()) names.push(name);\r\n }\r\n return names;\r\n}\r\n\r\nfunction extractToolSearchResultNamesFromMessages(\r\n messages: EngineMessage[],\r\n): string[] {\r\n const names: string[] = [];\r\n for (const message of messages) {\r\n if (message.role !== \"user\") continue;\r\n for (const part of message.content) {\r\n if (\r\n part.type !== \"tool-result\" ||\r\n part.toolName !== TOOL_SEARCH_ACTION_NAME ||\r\n typeof part.content !== \"string\"\r\n ) {\r\n continue;\r\n }\r\n try {\r\n names.push(...extractToolSearchResultNames(JSON.parse(part.content)));\r\n } catch {\r\n // Tool results are best-effort history hints; ignore non-JSON content.\r\n }\r\n }\r\n }\r\n return names;\r\n}\r\n\r\nfunction normalizeToolInputSchema(\r\n schema: ActionTool[\"parameters\"] | undefined,\r\n): EngineTool[\"inputSchema\"] | null {\r\n if (!schema) return { type: \"object\", properties: {} };\r\n if (schema.type !== \"object\") return null;\r\n return {\r\n ...schema,\r\n type: \"object\",\r\n properties:\r\n schema.properties && typeof schema.properties === \"object\"\r\n ? schema.properties\r\n : {},\r\n required: Array.isArray(schema.required) ? schema.required : [],\r\n };\r\n}\r\n\r\nfunction stringifyToolInput(input: unknown): string {\r\n try {\r\n const str = JSON.stringify(redactSensitiveFields(input));\r\n if (!str) return String(input);\r\n return str.length > 500 ? `${str.slice(0, 500)}…` : str;\r\n } catch {\r\n return String(input);\r\n }\r\n}\r\n\r\nfunction stableStringify(value: unknown): string {\r\n if (value === null || typeof value !== \"object\") {\r\n return JSON.stringify(value);\r\n }\r\n if (Array.isArray(value)) {\r\n return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\r\n }\r\n const obj = value as Record<string, unknown>;\r\n return `{${Object.keys(obj)\r\n .sort()\r\n .map((key) => `${JSON.stringify(key)}:${stableStringify(obj[key])}`)\r\n .join(\",\")}}`;\r\n}\r\n\r\nfunction toolCallCacheKey(toolName: string, input: unknown): string {\r\n return `${toolName}:${stableStringify(normalizeToolCallInputForHistory(input))}`;\r\n}\r\n\r\nconst INTERRUPTED_TOOL_LEDGER_POLL_MS =\r\n process.env.NODE_ENV === \"test\" ? 0 : 2_000;\r\n\r\nasync function waitForInterruptedToolLedgerEntry(opts: {\r\n threadId: string;\r\n toolKey: string;\r\n toolName: string;\r\n timeoutMs: number;\r\n signal: AbortSignal;\r\n send: (event: AgentChatEvent) => void;\r\n}): Promise<string | null> {\r\n const pollMs = INTERRUPTED_TOOL_LEDGER_POLL_MS;\r\n // Wait up to the tool's OWN declared timeout — the abandoned zombie can keep\r\n // running that long (e.g. a 12-minute image generation, whose provider keeps\r\n // generating after the run aborts), and giving up early re-runs the same\r\n // write tool while the original is still in flight, duplicating work and\r\n // double-charging. A flat sub-tool-timeout cap (previously 5 min) silently\r\n // truncated long tools. The run's AbortSignal still bounds this to the run's\r\n // remaining budget: when the run is cut off, the poll returns null and the\r\n // re-dispatch hits the already-aborted signal instead of launching a real\r\n // second call, so the wait never outlives the run.\r\n const maxWaitMs =\r\n process.env.NODE_ENV === \"test\" ? 1 : Math.max(0, opts.timeoutMs);\r\n const maxPolls =\r\n process.env.NODE_ENV === \"test\"\r\n ? 3\r\n : Math.max(1, Math.ceil(maxWaitMs / Math.max(1, pollMs)) + 1);\r\n\r\n for (let attempt = 0; attempt < maxPolls; attempt++) {\r\n if (opts.signal.aborted) return null;\r\n const ledgerResult = await readLedgerEntry(opts.threadId, opts.toolKey);\r\n if (ledgerResult !== null) return ledgerResult;\r\n\r\n if (attempt >= maxPolls - 1) break;\r\n opts.send({\r\n type: \"activity\",\r\n tool: opts.toolName,\r\n label: `Waiting for previous ${opts.toolName} result.`,\r\n });\r\n if (pollMs <= 0) continue;\r\n await new Promise<void>((resolve) => {\r\n let settled = false;\r\n const done = () => {\r\n if (settled) return;\r\n settled = true;\r\n clearTimeout(timer);\r\n opts.signal.removeEventListener(\"abort\", done);\r\n resolve();\r\n };\r\n const timer = setTimeout(done, pollMs);\r\n opts.signal.addEventListener(\"abort\", done, { once: true });\r\n });\r\n }\r\n\r\n return null;\r\n}\r\n\r\nfunction normalizeToolErrorForBreaker(error: string): string {\r\n return error.replace(/\\s+/g, \" \").trim();\r\n}\r\n\r\nfunction rateLimitRecoveryHint(message: string): string {\r\n if (\r\n !/\\b(?:429|rate[-\\s]?limit|rate limited|quota exceeded|too many requests|calls limit exceeded)\\b/i.test(\r\n message,\r\n )\r\n ) {\r\n return \"\";\r\n }\r\n return \"\\n\\nProvider rate-limit guidance: stop retrying this provider in this turn. Report the rate limit as a coverage gap, include any evidence already gathered, and ask the user to retry after the provider quota resets if full coverage is required.\";\r\n}\r\n\r\nconst SOURCE_SWEEP_TOOL_NAME =\r\n /\\b(?:api|calls?|deals?|events?|issues?|messages?|metrics?|provider|query|records?|request|search|tickets?|transcripts?)\\b/i;\r\n\r\nconst SOURCE_SWEEP_PROVIDER_TOKEN =\r\n /\\b(?:amplitude|apollo|bigquery|commonroom|data-source|ga4|github|gong|grafana|hubspot|jira|mixpanel|notion|posthog|postgres|postgresql|pylon|sentry|slack|stripe)\\b/i;\r\n\r\nconst SOURCE_SWEEP_EXCLUDED_TOOLS = new Set([\r\n \"chat-history\",\r\n \"list-staged-datasets\",\r\n \"manage-agent-engine\",\r\n \"manage-agent-loop-settings\",\r\n \"manage-automations\",\r\n \"manage-jobs\",\r\n \"manage-notifications\",\r\n \"manage-progress\",\r\n \"read-attachment\",\r\n \"refresh-screen\",\r\n \"resources\",\r\n \"tool-search\",\r\n \"view-screen\",\r\n]);\r\n\r\nfunction normalizeToolNameForHeuristics(name: string): string {\r\n return name.replace(/[_-]+/g, \" \");\r\n}\r\n\r\nfunction isLikelySourceSweepTool(\r\n name: string,\r\n entry: ActionEntry | undefined,\r\n): boolean {\r\n if (!entry || entry.readOnly === false) return false;\r\n const lower = name.toLowerCase();\r\n if (SOURCE_SWEEP_EXCLUDED_TOOLS.has(lower)) return false;\r\n const normalized = normalizeToolNameForHeuristics(lower);\r\n return (\r\n SOURCE_SWEEP_PROVIDER_TOKEN.test(normalized) ||\r\n SOURCE_SWEEP_TOOL_NAME.test(normalized)\r\n );\r\n}\r\n\r\nfunction hasExhaustedSourceSweepBudget(opts: {\r\n priorToolCalls: readonly AgentLoopToolCallSummary[];\r\n actions: Record<string, ActionEntry>;\r\n threshold?: number;\r\n}): boolean {\r\n const threshold = opts.threshold ?? SOURCE_SWEEP_TOOL_CALL_THRESHOLD;\r\n const counts = new Map<string, number>();\r\n for (const call of opts.priorToolCalls) {\r\n if (!isLikelySourceSweepTool(call.name, opts.actions[call.name])) continue;\r\n const next = (counts.get(call.name) ?? 0) + 1;\r\n if (next >= threshold) return true;\r\n counts.set(call.name, next);\r\n }\r\n return false;\r\n}\r\n\r\nfunction sourceSweepDelegationText(input: unknown): string {\r\n if (!input || typeof input !== \"object\") return \"\";\r\n const record = input as Record<string, unknown>;\r\n return [\"task\", \"instructions\", \"message\", \"name\"]\r\n .map((key) => record[key])\r\n .filter((value): value is string => typeof value === \"string\")\r\n .join(\"\\n\");\r\n}\r\n\r\nfunction isLikelySourceSweepDelegation(opts: {\r\n toolName: string;\r\n input: unknown;\r\n}): boolean {\r\n if (opts.toolName !== \"agent-teams\") return false;\r\n const action = getToolAction(opts.toolName, opts.input);\r\n if (![\"spawn\", \"send\"].includes(action)) return false;\r\n const normalized = normalizeToolNameForHeuristics(\r\n sourceSweepDelegationText(opts.input).toLowerCase(),\r\n );\r\n if (!normalized) return false;\r\n return (\r\n SOURCE_SWEEP_PROVIDER_TOKEN.test(normalized) ||\r\n SOURCE_SWEEP_TOOL_NAME.test(normalized)\r\n );\r\n}\r\n\r\nfunction sourceSweepDelegationGuardMessage(action: string): string {\r\n return (\r\n `Skipped agent-teams ${action || \"action\"}: this turn already exhausted ` +\r\n `a read-only source/search convergence budget. Do not move that same ` +\r\n `provider/source sweep into agent teams, background sub-agents, or a ` +\r\n `follow-up thread; delegation is not a bulk mechanism and does not remove ` +\r\n `provider quota, timeout, or cost limits. Continue in the main turn with a ` +\r\n `bulk/code/provider API path if one is available, or answer from gathered ` +\r\n `evidence with explicit coverage gaps.`\r\n );\r\n}\r\n\r\nfunction restrictAgentTeamsAfterSourceSweep(tools: EngineTool[]): EngineTool[] {\r\n return tools.map((tool) => {\r\n if (tool.name !== \"agent-teams\") return tool;\r\n const actionParam = tool.inputSchema.properties?.action;\r\n if (!actionParam || typeof actionParam !== \"object\") return tool;\r\n return {\r\n ...tool,\r\n description:\r\n `${tool.description}\\n\\nSource-sweep budget exhausted: only these ` +\r\n `read-only coordination actions are available: ` +\r\n SOURCE_SWEEP_AGENT_TEAM_ALLOWED_ACTIONS.map(\r\n (action) => `\"${action}\"`,\r\n ).join(\", \") +\r\n \". Do not spawn or message background sub-agents to continue the same provider/source sweep.\",\r\n inputSchema: {\r\n ...tool.inputSchema,\r\n properties: {\r\n ...tool.inputSchema.properties,\r\n action: {\r\n ...actionParam,\r\n enum: [...SOURCE_SWEEP_AGENT_TEAM_ALLOWED_ACTIONS],\r\n },\r\n },\r\n },\r\n };\r\n });\r\n}\r\n\r\nexport function repeatedSourceSweepGuardMessage(opts: {\r\n toolName: string;\r\n priorCalls: number;\r\n threshold?: number;\r\n}): string {\r\n const threshold = opts.threshold ?? SOURCE_SWEEP_TOOL_CALL_THRESHOLD;\r\n return (\r\n `Skipped ${opts.toolName}: this turn already made ${opts.priorCalls} ` +\r\n `call(s) to the same read-only source/search tool, which exceeds the ` +\r\n `${threshold}-call convergence budget. Stop calling ${opts.toolName} ` +\r\n `one item at a time and change strategy before answering. If a broader ` +\r\n `read-only bulk/source mechanism is available, use it now: provider API ` +\r\n `catalog/docs/request tools with pagination or staging, code execution ` +\r\n `against staged/provider data, workspace files, or another batch-capable ` +\r\n `tool that can join, grep, classify, count, or aggregate without flooding ` +\r\n `the chat context. Do not ask the user whether to run the obvious bulk/code ` +\r\n `workflow when it is read-only and needed to satisfy their request; either ` +\r\n `do it in this turn or state exactly why it is unavailable. Do not delegate ` +\r\n `this same one-item-at-a-time source sweep to agent teams, background ` +\r\n `sub-agents, or a follow-up thread; delegation is not a bulk mechanism and ` +\r\n `does not remove provider quota, timeout, or cost limits. Do not leave the ` +\r\n `user with a \"come back later\" answer for this turn. If no broader path ` +\r\n `exists or quota/timeouts block it, answer from the evidence already ` +\r\n `gathered: state the source filters, count what was inspected, list ` +\r\n `confirmed hits, and explicitly name remaining gaps or uninspected records.`\r\n );\r\n}\r\n\r\nexport function shouldGuardRepeatedSourceSweep(opts: {\r\n toolName: string;\r\n entry: ActionEntry | undefined;\r\n priorToolCalls: readonly AgentLoopToolCallSummary[];\r\n threshold?: number;\r\n}): { toolName: string; priorCalls: number; message: string } | null {\r\n if (!isLikelySourceSweepTool(opts.toolName, opts.entry)) return null;\r\n const threshold = opts.threshold ?? SOURCE_SWEEP_TOOL_CALL_THRESHOLD;\r\n const priorCalls = opts.priorToolCalls.filter(\r\n (call) => call.name === opts.toolName,\r\n ).length;\r\n if (priorCalls < threshold) return null;\r\n return {\r\n toolName: opts.toolName,\r\n priorCalls,\r\n message: repeatedSourceSweepGuardMessage({\r\n toolName: opts.toolName,\r\n priorCalls,\r\n threshold,\r\n }),\r\n };\r\n}\r\n\r\nfunction seedSourceSweepToolCallsFromHistory(\r\n messages: EngineMessage[],\r\n actions: Record<string, ActionEntry>,\r\n): AgentLoopToolCallSummary[] {\r\n if (!isInternalContinuationTurn(messages)) return [];\r\n\r\n const seeded: AgentLoopToolCallSummary[] = [];\r\n const turnStart = findCurrentTurnStartForContinuation(messages);\r\n for (const message of messages.slice(turnStart)) {\r\n if (message.role !== \"assistant\") continue;\r\n for (const part of message.content) {\r\n if (part.type !== \"tool-call\") continue;\r\n if (!isLikelySourceSweepTool(part.name, actions[part.name])) continue;\r\n seeded.push({\r\n name: part.name,\r\n input: normalizeToolCallInputForHistory(part.input),\r\n });\r\n }\r\n }\r\n return seeded;\r\n}\r\n\r\nfunction normalizeToolCallInputForHistory(\r\n input: unknown,\r\n): Record<string, unknown> {\r\n if (input && typeof input === \"object\" && !Array.isArray(input)) {\r\n return input as Record<string, unknown>;\r\n }\r\n return { rawInput: input };\r\n}\r\n\r\nfunction toolInputSchemaErrorResult(\r\n toolName: string,\r\n input: unknown,\r\n error: string,\r\n): string {\r\n return (\r\n `Invalid action parameters for ${toolName}: ${sanitizeToolErrorText(error)}. ` +\r\n `Received: ${stringifyToolInput(input)}. ` +\r\n \"The tool was not executed; retry with arguments that match the tool schema.\"\r\n );\r\n}\r\n\r\ntype RawJsonSchema = AgentNativeJsonSchema;\r\n\r\nconst rawToolInputAjv = new Ajv({\r\n strict: false,\r\n allErrors: true,\r\n coerceTypes: true,\r\n useDefaults: false,\r\n removeAdditional: false,\r\n});\r\n\r\nconst rawToolInputValidatorCache = new WeakMap<object, ValidateFunction>();\r\n\r\nfunction getRawToolInputValidator(schema: RawJsonSchema): ValidateFunction {\r\n const cached = rawToolInputValidatorCache.get(schema);\r\n if (cached) return cached;\r\n const validator = rawToolInputAjv.compile(schema);\r\n rawToolInputValidatorCache.set(schema, validator);\r\n return validator;\r\n}\r\n\r\nfunction shouldValidateRawToolParameters(entry: ActionEntry): boolean {\r\n const maybeSchema = entry.schema as\r\n | { \"~standard\"?: unknown }\r\n | null\r\n | undefined;\r\n return !maybeSchema?.[\"~standard\"] && Boolean(entry.tool.parameters);\r\n}\r\n\r\nfunction validateRawToolInput(\r\n entry: ActionEntry,\r\n input: unknown,\r\n): string | null {\r\n if (!shouldValidateRawToolParameters(entry)) return null;\r\n const parameters = entry.tool.parameters;\r\n if (!parameters) return null;\r\n let validator: ValidateFunction;\r\n try {\r\n validator = getRawToolInputValidator(parameters);\r\n } catch (err) {\r\n return `tool schema is invalid: ${sanitizeToolErrorValue(err)}`;\r\n }\r\n if (validator(input === undefined ? {} : input)) return null;\r\n return rawToolInputAjv.errorsText(validator.errors, {\r\n separator: \"; \",\r\n dataVar: \"input\",\r\n });\r\n}\r\n\r\n/**\r\n * The core agent loop — calls the engine iteratively until no more tool calls.\r\n * Decoupled from HTTP transport so it can run in the background.\r\n * Returns accumulated token usage for cost tracking.\r\n */\r\nexport async function runAgentLoop(opts: {\r\n engine: AgentEngine;\r\n model: string;\r\n systemPrompt: string;\r\n tools: EngineTool[];\r\n availableTools?: EngineTool[];\r\n messages: EngineMessage[];\r\n actions: Record<string, ActionEntry>;\r\n send: (event: AgentChatEvent) => void;\r\n signal: AbortSignal;\r\n ownerEmail?: string | null;\r\n orgId?: string | null;\r\n /**\r\n * Attachments submitted with this turn (pasted text, files, images), passed\r\n * through to each tool's `ActionRunContext.attachments` so actions can\r\n * consume a large pasted artifact by reference instead of having the model\r\n * re-emit it as a tool argument. See `create-extension`'s\r\n * `contentFromAttachment`.\r\n */\r\n attachments?: AgentChatAttachment[];\r\n reasoningEffort?: ReasoningEffort;\r\n providerOptions?: any;\r\n maxOutputTokens?: number;\r\n executionMode?: AgentExecutionMode;\r\n maxIterations?: number;\r\n finalResponseGuard?: AgentLoopFinalResponseGuard;\r\n threadId?: string;\r\n turnId?: string;\r\n /**\r\n * App-level default limits applied to every tool call unless the individual\r\n * ActionEntry overrides them with its own timeoutMs / maxResultChars.\r\n */\r\n toolLimits?: { timeoutMs?: number; maxResultChars?: number };\r\n /**\r\n * Stable approval keys granted by a human for actions declared\r\n * `needsApproval`. A call whose key is present here runs even though the\r\n * action requires approval; otherwise the loop pauses with\r\n * `approval_required`. See `AgentChatRequest.approvedToolCalls`.\r\n */\r\n approvedToolCalls?: string[];\r\n /**\r\n * In-loop processor seam (see `processors.ts`). Each processor can observe\r\n * streamed chunks, observe model responses around tool execution, and\r\n * `abort()` the run. Loop-internal config, NOT a tool/authoring surface —\r\n * processors only observe/mutate-stream/abort; they never define app\r\n * behavior or replace actions. When omitted or empty, none of the seam code\r\n * runs and the loop is byte-for-byte unchanged (zero overhead).\r\n */\r\n processors?: Processor[];\r\n}): Promise<AgentLoopUsage> {\r\n const {\r\n engine,\r\n model,\r\n systemPrompt,\r\n tools,\r\n availableTools,\r\n messages,\r\n actions,\r\n send,\r\n signal,\r\n } = opts;\r\n const availableToolMap = new Map(\r\n (availableTools ?? tools).map((tool) => [tool.name, tool]),\r\n );\r\n const activeToolNames = new Set(tools.map((tool) => tool.name));\r\n let activeTools = tools;\r\n\r\n const expandActiveTools = (names: string[]): string[] => {\r\n const added: string[] = [];\r\n for (const name of names) {\r\n if (activeToolNames.has(name)) continue;\r\n const tool = availableToolMap.get(name);\r\n if (!tool) continue;\r\n activeToolNames.add(name);\r\n added.push(name);\r\n }\r\n if (added.length > 0) {\r\n activeTools = (availableTools ?? tools).filter((tool) =>\r\n activeToolNames.has(tool.name),\r\n );\r\n }\r\n return added;\r\n };\r\n\r\n expandActiveTools(extractToolSearchResultNamesFromMessages(messages));\r\n\r\n // Build the processor chain only when at least one processor is supplied so\r\n // the common (no-processors) path is unchanged and carries zero overhead.\r\n const processorChain =\r\n opts.processors && opts.processors.length > 0\r\n ? new ProcessorChain(opts.processors)\r\n : null;\r\n\r\n const usage: AgentLoopUsage = {\r\n inputTokens: 0,\r\n outputTokens: 0,\r\n cacheReadTokens: 0,\r\n cacheWriteTokens: 0,\r\n model,\r\n };\r\n\r\n const maxIterations = normalizeMaxIterations(\r\n opts.maxIterations,\r\n getDefaultMaxIterations(),\r\n );\r\n const toolCallHistory: AgentLoopToolCallSummary[] = [];\r\n const sourceSweepToolCallHistory = seedSourceSweepToolCallsFromHistory(\r\n messages,\r\n actions,\r\n );\r\n let sourceSweepDelegationGuardActive = hasExhaustedSourceSweepBudget({\r\n priorToolCalls: sourceSweepToolCallHistory,\r\n actions,\r\n });\r\n const toolResultHistory: AgentLoopToolResultSummary[] = [];\r\n const runCtx = getRequestRunContext();\r\n if (runCtx) {\r\n runCtx.toolCalls = toolCallHistory;\r\n runCtx.toolResults = toolResultHistory;\r\n }\r\n const readOnlyToolResultCache = seedReadOnlyToolResultsFromHistory(\r\n messages,\r\n actions,\r\n );\r\n const duplicateReadOnlyToolCalls = new Map<string, number>();\r\n const writeToolInterruptions = seedWriteToolInterruptionsFromHistory(\r\n messages,\r\n actions,\r\n );\r\n const repeatedToolErrors = new Map<string, number>();\r\n\r\n // Tool-call journal hard-block (resume safety). Snapshot the per-turn journal\r\n // ONCE here, before any tool runs in this chunk, so it reflects only PRIOR\r\n // run chunks of this logical turn. A write tool whose exact call already\r\n // completed in an earlier interrupted chunk must not re-fire its side effect;\r\n // when matched, runToolCall returns the journaled result instead of executing.\r\n // Loaded eagerly (not lazily mid-loop) so the current chunk's own\r\n // asynchronously-persisted tool_done events can never leak in and make a\r\n // same-chunk call wrongly short-circuit. Best-effort: any ledger failure\r\n // leaves the journal empty and all calls run normally. Fresh first-turn calls\r\n // see an empty journal and are unaffected.\r\n let toolCallJournal: ToolCallJournal | null = null;\r\n const consumedJournalKeys = new Set<string>();\r\n if (opts.threadId) {\r\n try {\r\n const priorEvents = await getCurrentTurnEventsForThread(opts.threadId);\r\n if (priorEvents.length > 0) {\r\n // A logical turn can span multiple background continuation runs. Final\r\n // response guards must see successful reads from earlier chunks, not\r\n // only tools executed after the latest handoff. Otherwise a guard can\r\n // reject a grounded answer (or a successfully-created artifact) after\r\n // the evidence-producing query completed in a predecessor run.\r\n for (const event of priorEvents) {\r\n if (event.type === \"tool_start\") {\r\n toolCallHistory.push({\r\n name: event.tool,\r\n input: event.input,\r\n });\r\n } else if (event.type === \"tool_done\") {\r\n toolResultHistory.push({\r\n name: event.tool,\r\n content: event.result,\r\n isError: event.isError === true,\r\n });\r\n }\r\n }\r\n toolCallJournal = classifyToolCallJournal(priorEvents);\r\n }\r\n } catch {\r\n // Journal is a hardening layer, never a gate — a failed ledger read just\r\n // means no hard-block this turn.\r\n }\r\n }\r\n\r\n let finalGuardRetries = 0;\r\n let emptyFinalResponseRetries = 0;\r\n let iterations = 0;\r\n // Overridden (raised tokens, lowered effort) only after an empty-final-\r\n // response retry below — kept separate from `opts.maxOutputTokens`/\r\n // `opts.reasoningEffort` so the very first attempt is unaffected and later\r\n // tool-loop turns revert to the caller's original request after a success.\r\n let effectiveMaxOutputTokens = opts.maxOutputTokens;\r\n let effectiveReasoningEffort = opts.reasoningEffort;\r\n\r\n // Set when an in-loop processor aborts via `abort()` / throws a `TripWire`.\r\n // The loop emits the `tripwire` event, surfaces the reason as a final\r\n // assistant message, and stops cleanly.\r\n let tripwire: TripWire | null = null;\r\n const emitTripwire = (err: TripWire) => {\r\n tripwire = err;\r\n send({\r\n type: \"tripwire\",\r\n reason: err.message,\r\n ...(err.processor ? { processor: err.processor } : {}),\r\n });\r\n send({ type: \"text\", text: err.message });\r\n messages.push({\r\n role: \"assistant\",\r\n content: [{ type: \"text\", text: err.message }],\r\n });\r\n };\r\n\r\n while (true) {\r\n if (signal.aborted) break;\r\n if (++iterations > maxIterations) {\r\n appendAgentLoopContinuation(messages, \"loop_limit\");\r\n iterations = 1;\r\n }\r\n\r\n let assistantContent: EngineContentPart[] | undefined;\r\n let streamedAssistantText = \"\";\r\n let terminalStopReason:\r\n | Extract<EngineEvent, { type: \"stop\" }>[\"reason\"]\r\n | undefined;\r\n const toolCallErrors = new Map<\r\n string,\r\n { name: string; input: unknown; error: string }\r\n >();\r\n let contextMessages = messages;\r\n\r\n if (opts.threadId) {\r\n try {\r\n const directives = await loadContextDirectives(opts.threadId, {\r\n ownerEmail: opts.ownerEmail ?? null,\r\n });\r\n const protectedSegmentIds = computeProtectedSegmentIds(messages);\r\n const { messages: transformedMessages, appliedStatus } =\r\n applyContextDirectives(messages, directives, {\r\n protectedSegmentIds,\r\n });\r\n const manifest = await buildManifest({\r\n threadId: opts.threadId,\r\n ...(opts.turnId ? { turnId: opts.turnId } : {}),\r\n model,\r\n rawMessages: messages,\r\n sentMessages: transformedMessages,\r\n appliedStatus,\r\n directives,\r\n protectedSegmentIds,\r\n source: \"structured\",\r\n enforceable: true,\r\n });\r\n contextMessages = transformedMessages;\r\n void writeContextManifest(opts.threadId, manifest).catch((err) => {\r\n console.warn(\r\n \"[context-xray] failed to write manifest:\",\r\n err instanceof Error ? err.message : String(err),\r\n );\r\n });\r\n } catch (err) {\r\n console.warn(\r\n \"[context-xray] context transform skipped:\",\r\n err instanceof Error ? err.message : String(err),\r\n );\r\n }\r\n\r\n // Observational Memory (consumer): for long threads that have already been\r\n // compacted, fold the reflections+observations in as a leading context\r\n // block and prefer the recent-raw-message window over the full raw\r\n // history. No-op (returns the same array) for short threads with no OM\r\n // entries, so the common path is unchanged. Runs after the context-xray\r\n // transform so the two compose; best-effort inside the helper. Gated on an\r\n // authenticated owner so anonymous threads never read OM scoped to a\r\n // shared default identity.\r\n if (opts.ownerEmail) {\r\n contextMessages = await applyObservationalMemoryToContext(\r\n contextMessages,\r\n {\r\n threadId: opts.threadId,\r\n ownerEmail: opts.ownerEmail,\r\n orgId: opts.orgId ?? null,\r\n },\r\n );\r\n }\r\n }\r\n\r\n for (let retry = 0; ; retry++) {\r\n assistantContent = undefined;\r\n streamedAssistantText = \"\";\r\n terminalStopReason = undefined;\r\n toolCallErrors.clear();\r\n try {\r\n const streamOpts = {\r\n model,\r\n systemPrompt,\r\n messages: contextMessages,\r\n tools: sourceSweepDelegationGuardActive\r\n ? restrictAgentTeamsAfterSourceSweep(activeTools)\r\n : activeTools,\r\n abortSignal: signal,\r\n maxOutputTokens: resolveMaxOutputTokensForEngine(\r\n engine.name,\r\n effectiveMaxOutputTokens,\r\n model,\r\n ),\r\n reasoningEffort: effectiveReasoningEffort,\r\n providerOptions: opts.providerOptions,\r\n };\r\n\r\n const eventStream = engine.stream(streamOpts);\r\n let thinkingBuffer = \"\";\r\n const toolInputNames = new Map<string, string>();\r\n const toolInputBytes = new Map<string, number>();\r\n let lastToolInputActivityAt = 0;\r\n type ActiveToolInputPreparation = {\r\n id: string;\r\n toolName?: string;\r\n startedAt: number;\r\n lastProgressAt: number;\r\n bytes: number;\r\n };\r\n type ZeroByteToolInputRestart = {\r\n toolName: string;\r\n firstStartedAt: number;\r\n lastStartedAt: number;\r\n count: number;\r\n };\r\n const activeToolInputs = new Map<string, ActiveToolInputPreparation>();\r\n let zeroByteToolInputRestart: ZeroByteToolInputRestart | undefined;\r\n let endedForNoProgress = false;\r\n let lastModelStreamProgressAt = Date.now();\r\n const sendToolInputActivity = (\r\n toolName: string | undefined,\r\n toolInputId?: string,\r\n progressBytes?: number,\r\n force = false,\r\n ) => {\r\n const now = Date.now();\r\n if (\r\n !force &&\r\n now - lastToolInputActivityAt < TOOL_INPUT_ACTIVITY_INTERVAL_MS\r\n ) {\r\n return;\r\n }\r\n lastToolInputActivityAt = now;\r\n send({\r\n type: \"activity\",\r\n label: toolInputActivityLabel(toolName),\r\n ...(toolName ? { tool: toolName } : {}),\r\n ...(toolInputId ? { id: toolInputId } : {}),\r\n ...(typeof progressBytes === \"number\" ? { progressBytes } : {}),\r\n });\r\n };\r\n const actionPreparationDeadlineAt = () => {\r\n let deadlineAt = Number.POSITIVE_INFINITY;\r\n if (zeroByteToolInputRestart) {\r\n deadlineAt = Math.min(\r\n deadlineAt,\r\n zeroByteToolInputRestart.firstStartedAt +\r\n ACTION_PREPARATION_NO_PROGRESS_TIMEOUT_MS,\r\n );\r\n }\r\n let earliestStartedAt = Number.POSITIVE_INFINITY;\r\n let latestPositiveProgressAt = 0;\r\n for (const active of activeToolInputs.values()) {\r\n if (active.startedAt < earliestStartedAt) {\r\n earliestStartedAt = active.startedAt;\r\n }\r\n if (\r\n active.bytes > 0 &&\r\n active.lastProgressAt > latestPositiveProgressAt\r\n ) {\r\n latestPositiveProgressAt = active.lastProgressAt;\r\n }\r\n }\r\n const progressAt =\r\n latestPositiveProgressAt > 0\r\n ? latestPositiveProgressAt\r\n : earliestStartedAt;\r\n if (Number.isFinite(progressAt)) {\r\n deadlineAt = Math.min(\r\n deadlineAt,\r\n progressAt + ACTION_PREPARATION_NO_PROGRESS_TIMEOUT_MS,\r\n );\r\n }\r\n return Number.isFinite(deadlineAt) ? deadlineAt : undefined;\r\n };\r\n const modelStreamNoProgressDeadlineAt = () =>\r\n lastModelStreamProgressAt + MODEL_STREAM_NO_PROGRESS_TIMEOUT_MS;\r\n const noProgressDeadlineAt = () => {\r\n const actionDeadlineAt = actionPreparationDeadlineAt();\r\n const modelDeadlineAt = modelStreamNoProgressDeadlineAt();\r\n return actionDeadlineAt === undefined\r\n ? modelDeadlineAt\r\n : Math.min(actionDeadlineAt, modelDeadlineAt);\r\n };\r\n const hasNoProgressStalled = () => Date.now() >= noProgressDeadlineAt();\r\n const checkpointNoProgress = () => {\r\n if (endedForNoProgress) return;\r\n send({\r\n type: \"auto_continue\",\r\n reason: \"no_progress\",\r\n });\r\n endedForNoProgress = true;\r\n };\r\n let eventIteratorReturnRequested = false;\r\n const requestEventIteratorReturn = (\r\n iterator: AsyncIterator<EngineEvent>,\r\n awaitReturn: boolean,\r\n ) => {\r\n if (eventIteratorReturnRequested) return;\r\n eventIteratorReturnRequested = true;\r\n let returnPromise:\r\n | ReturnType<NonNullable<typeof iterator.return>>\r\n | undefined;\r\n try {\r\n returnPromise = iterator.return?.();\r\n } catch {\r\n return;\r\n }\r\n if (!returnPromise) return;\r\n if (awaitReturn) return returnPromise.catch(() => undefined);\r\n void returnPromise.catch(() => undefined);\r\n };\r\n const nextEngineEventWithNoProgressTimeout = async (\r\n iterator: AsyncIterator<EngineEvent>,\r\n ): Promise<IteratorResult<EngineEvent>> => {\r\n const deadlineAt = noProgressDeadlineAt();\r\n const timeoutMs = Math.max(0, deadlineAt - Date.now());\r\n if (timeoutMs <= 0) {\r\n checkpointNoProgress();\r\n requestEventIteratorReturn(iterator, false);\r\n return { done: true, value: undefined };\r\n }\r\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\r\n const next = iterator.next();\r\n void next.catch(() => undefined);\r\n const timeout = new Promise<\"timeout\">((resolve) => {\r\n timeoutId = setTimeout(() => resolve(\"timeout\"), timeoutMs);\r\n });\r\n try {\r\n const result = await Promise.race([next, timeout]);\r\n if (result === \"timeout\") {\r\n checkpointNoProgress();\r\n requestEventIteratorReturn(iterator, false);\r\n return { done: true, value: undefined };\r\n }\r\n return result;\r\n } finally {\r\n if (timeoutId) clearTimeout(timeoutId);\r\n }\r\n };\r\n const trackActiveToolInput = (\r\n key: string,\r\n toolName: string | undefined,\r\n bytes: number,\r\n ) => {\r\n const now = Date.now();\r\n const previous = activeToolInputs.get(key);\r\n const resolvedToolName = toolName ?? previous?.toolName;\r\n activeToolInputs.set(key, {\r\n id: key,\r\n ...(resolvedToolName ? { toolName: resolvedToolName } : {}),\r\n startedAt: previous?.startedAt ?? now,\r\n lastProgressAt: now,\r\n bytes,\r\n });\r\n };\r\n const resetZeroByteToolInputRestart = (toolName?: string) => {\r\n if (!zeroByteToolInputRestart) return;\r\n if (!toolName || zeroByteToolInputRestart.toolName === toolName) {\r\n zeroByteToolInputRestart = undefined;\r\n }\r\n };\r\n const noteZeroByteToolInputStart = (toolName?: string) => {\r\n if (!toolName) return false;\r\n const now = Date.now();\r\n if (zeroByteToolInputRestart?.toolName === toolName) {\r\n zeroByteToolInputRestart = {\r\n ...zeroByteToolInputRestart,\r\n lastStartedAt: now,\r\n count: zeroByteToolInputRestart.count + 1,\r\n };\r\n } else {\r\n zeroByteToolInputRestart = {\r\n toolName,\r\n firstStartedAt: now,\r\n lastStartedAt: now,\r\n count: 1,\r\n };\r\n }\r\n return (\r\n zeroByteToolInputRestart.count >=\r\n ACTION_PREPARATION_ZERO_BYTE_RESTART_LIMIT &&\r\n now - zeroByteToolInputRestart.firstStartedAt >=\r\n ACTION_PREPARATION_NO_PROGRESS_TIMEOUT_MS\r\n );\r\n };\r\n const eventIterator = eventStream[Symbol.asyncIterator]();\r\n let eventIteratorDone = false;\r\n try {\r\n while (true) {\r\n const nextEvent =\r\n await nextEngineEventWithNoProgressTimeout(eventIterator);\r\n if (nextEvent.done) {\r\n eventIteratorDone = true;\r\n break;\r\n }\r\n const event = nextEvent.value;\r\n if (hasNoProgressStalled()) {\r\n checkpointNoProgress();\r\n break;\r\n }\r\n if (event.type !== \"gateway-heartbeat\") {\r\n lastModelStreamProgressAt = Date.now();\r\n }\r\n // In-loop processor seam (stream hook). Each chunk is offered to every\r\n // processor's `processOutputStream` before the loop handles it. A\r\n // processor `abort()` throws a TripWire; catch it locally so it is not\r\n // mistaken for a retryable engine error, then break out cleanly.\r\n if (processorChain) {\r\n try {\r\n await processorChain.runStream(event);\r\n } catch (err) {\r\n if (err instanceof TripWire) {\r\n emitTripwire(err);\r\n break;\r\n }\r\n throw err;\r\n }\r\n }\r\n if (event.type === \"text-delta\") {\r\n resetZeroByteToolInputRestart();\r\n streamedAssistantText += event.text;\r\n send({ type: \"text\", text: event.text });\r\n } else if (event.type === \"thinking-delta\") {\r\n thinkingBuffer += event.text;\r\n // Forward thinking deltas as a distinct event type so the UI\r\n // can render a collapsible \"Thinking…\" cell while the model\r\n // reasons, then collapse it when content arrives.\r\n send({ type: \"thinking\", text: event.text });\r\n } else if (event.type === \"tool-input-start\") {\r\n const key = event.id ?? event.name;\r\n if (key && event.name) {\r\n toolInputNames.set(key, event.name);\r\n toolInputBytes.set(key, 0);\r\n trackActiveToolInput(key, event.name, 0);\r\n }\r\n sendToolInputActivity(event.name, key, undefined, true);\r\n if (noteZeroByteToolInputStart(event.name)) {\r\n send({\r\n type: \"auto_continue\",\r\n reason: \"no_progress\",\r\n });\r\n endedForNoProgress = true;\r\n break;\r\n }\r\n } else if (event.type === \"tool-input-delta\") {\r\n const key = event.id ?? event.name;\r\n const toolName =\r\n event.name ??\r\n (event.id ? toolInputNames.get(event.id) : undefined);\r\n let progressBytes: number | undefined;\r\n let startedZeroByteInput = false;\r\n if (key) {\r\n const hadByteRecord = toolInputBytes.has(key);\r\n const previous = hadByteRecord\r\n ? (toolInputBytes.get(key) ?? 0)\r\n : 0;\r\n progressBytes =\r\n previous +\r\n new TextEncoder().encode(event.text ?? \"\").byteLength;\r\n toolInputBytes.set(key, progressBytes);\r\n if (!hadByteRecord || progressBytes > previous) {\r\n trackActiveToolInput(key, toolName, progressBytes);\r\n if (progressBytes > 0) {\r\n resetZeroByteToolInputRestart();\r\n } else if (!hadByteRecord) {\r\n startedZeroByteInput = true;\r\n }\r\n }\r\n }\r\n sendToolInputActivity(toolName, key, progressBytes);\r\n if (\r\n startedZeroByteInput &&\r\n toolName &&\r\n noteZeroByteToolInputStart(toolName)\r\n ) {\r\n send({\r\n type: \"auto_continue\",\r\n reason: \"no_progress\",\r\n });\r\n endedForNoProgress = true;\r\n break;\r\n }\r\n } else if (event.type === \"gateway-heartbeat\") {\r\n send({ type: \"stream_keepalive\" });\r\n } else if (event.type === \"tool-call\") {\r\n // The authoritative tool-call blocks arrive in assistant-content.\r\n } else if (event.type === \"tool-call-error\") {\r\n toolCallErrors.set(event.id, {\r\n name: event.name,\r\n input: event.input,\r\n error: event.error,\r\n });\r\n } else if (event.type === \"assistant-content\") {\r\n assistantContent = event.parts;\r\n } else if (event.type === \"usage\") {\r\n usage.inputTokens += event.inputTokens;\r\n usage.outputTokens += event.outputTokens;\r\n usage.cacheReadTokens += event.cacheReadTokens ?? 0;\r\n usage.cacheWriteTokens += event.cacheWriteTokens ?? 0;\r\n } else if (event.type === \"stop\") {\r\n terminalStopReason = event.reason;\r\n if (event.reason === \"error\") {\r\n throw new EngineError(event.error ?? \"Engine stream error\", {\r\n errorCode: event.errorCode,\r\n upgradeUrl: event.upgradeUrl,\r\n statusCode: event.statusCode,\r\n providerRetryable: event.providerRetryable,\r\n });\r\n }\r\n }\r\n if (hasNoProgressStalled()) {\r\n checkpointNoProgress();\r\n break;\r\n }\r\n }\r\n } finally {\r\n if (!eventIteratorDone) {\r\n await requestEventIteratorReturn(\r\n eventIterator,\r\n !eventIteratorReturnRequested,\r\n );\r\n }\r\n }\r\n\r\n if (endedForNoProgress) {\r\n return usage;\r\n }\r\n\r\n break;\r\n } catch (err: unknown) {\r\n if (signal.aborted) throw err;\r\n if (isContextTooLongError(err)) {\r\n // ── One-shot recovery: trim old tool results and retry once ────────\r\n // Only attempt recovery on the first overflow (retry === 0) to avoid\r\n // infinite trim loops. On subsequent overflows fall through to the\r\n // terminal error.\r\n if (retry === 0) {\r\n const trimmed = trimOldToolResults(contextMessages);\r\n if (trimmed !== null) {\r\n // Replace the sent messages for this iteration with the trimmed\r\n // version, clear any partial output, and retry immediately\r\n // (no delay — context errors are not transient).\r\n contextMessages = trimmed;\r\n send({ type: \"clear\" });\r\n continue;\r\n }\r\n }\r\n throw new EngineError(\r\n \"Conversation has grown too long. The agent tried to recover automatically but the context is still too large. You can continue in a new chat, or ask the agent to summarize the conversation and continue.\",\r\n { errorCode: \"context_length_exceeded\" },\r\n );\r\n }\r\n if (retry < maxRetriesForError(err) && isRetryableError(err)) {\r\n // Clear partial text from the failed attempt so the retry\r\n // doesn't produce garbled duplicate output. Keep the retry itself\r\n // silent so transient provider/backend failures do not leak into\r\n // the assistant's final answer.\r\n send({ type: \"clear\" });\r\n await retryDelay(retry, signal);\r\n continue;\r\n }\r\n throw err;\r\n }\r\n }\r\n\r\n // A processor aborted mid-stream. The tripwire event + final message were\r\n // already emitted; halt the loop without sending a normal `done`.\r\n if (tripwire) break;\r\n\r\n if (!assistantContent && toolCallErrors.size > 0) {\r\n assistantContent = [];\r\n }\r\n\r\n if (!assistantContent) {\r\n // No content — done\r\n break;\r\n }\r\n\r\n if (toolCallErrors.size > 0) {\r\n const existingToolCallIds = new Set(\r\n assistantContent\r\n .filter(\r\n (part): part is import(\"./engine/types.js\").EngineToolCallPart =>\r\n part.type === \"tool-call\",\r\n )\r\n .map((part) => part.id),\r\n );\r\n for (const [id, info] of toolCallErrors) {\r\n if (!existingToolCallIds.has(id)) {\r\n assistantContent.push({\r\n type: \"tool-call\",\r\n id,\r\n name: info.name,\r\n input: info.input,\r\n });\r\n }\r\n }\r\n }\r\n\r\n const assistantContentForHistory = assistantContent.map((part) =>\r\n part.type === \"tool-call\"\r\n ? {\r\n ...part,\r\n input: normalizeToolCallInputForHistory(part.input),\r\n }\r\n : part,\r\n );\r\n\r\n messages.push({ role: \"assistant\", content: assistantContentForHistory });\r\n\r\n const toolCallParts = assistantContent.filter(\r\n (p): p is import(\"./engine/types.js\").EngineToolCallPart =>\r\n p.type === \"tool-call\",\r\n );\r\n\r\n // In-loop processor seam (step hook). Fires once per model response, around\r\n // tool execution, with the tool calls the model just requested (empty for a\r\n // final answer) plus the stop reason and cumulative usage. A coverage gate\r\n // can inspect what the model is about to do and `abort()` before tools run.\r\n if (processorChain) {\r\n try {\r\n await processorChain.runStep({\r\n toolCalls: toolCallsFromContent(assistantContent),\r\n ...(terminalStopReason ? { finishReason: terminalStopReason } : {}),\r\n usage: {\r\n inputTokens: usage.inputTokens,\r\n outputTokens: usage.outputTokens,\r\n cacheReadTokens: usage.cacheReadTokens,\r\n cacheWriteTokens: usage.cacheWriteTokens,\r\n },\r\n });\r\n } catch (err) {\r\n if (err instanceof TripWire) {\r\n emitTripwire(err);\r\n break;\r\n }\r\n throw err;\r\n }\r\n }\r\n\r\n const flushUnstreamedAssistantText = () => {\r\n if (streamedAssistantText) return;\r\n const text = collectTextParts(assistantContentForHistory);\r\n if (text) send({ type: \"text\", text });\r\n };\r\n\r\n if (toolCallParts.length === 0) {\r\n if (terminalStopReason === \"max_tokens\") {\r\n flushUnstreamedAssistantText();\r\n appendAgentLoopContinuation(messages, \"max_tokens\");\r\n continue;\r\n }\r\n let guard: Awaited<ReturnType<AgentLoopFinalResponseGuard>> | null = null;\r\n if (opts.finalResponseGuard) {\r\n try {\r\n guard = await opts.finalResponseGuard({\r\n messages,\r\n assistantContent: assistantContentForHistory,\r\n text: collectTextParts(assistantContentForHistory),\r\n toolCalls: [...toolCallHistory],\r\n toolResults: [...toolResultHistory],\r\n retryCount: finalGuardRetries,\r\n executionMode: opts.executionMode ?? \"act\",\r\n });\r\n } catch (err) {\r\n send({ type: \"clear\" });\r\n throw err;\r\n }\r\n }\r\n let guardEmittedFallback = false;\r\n if (guard) {\r\n const retryMessage =\r\n typeof guard === \"string\" ? guard : guard.retryMessage;\r\n const fallbackMessage =\r\n typeof guard === \"string\" ? guard : guard.fallbackMessage;\r\n if (finalGuardRetries < 1) {\r\n finalGuardRetries += 1;\r\n send({ type: \"clear\" });\r\n messages.push({\r\n role: \"user\",\r\n content: [{ type: \"text\", text: retryMessage }],\r\n });\r\n continue;\r\n }\r\n send({ type: \"clear\" });\r\n send({ type: \"text\", text: fallbackMessage ?? retryMessage });\r\n guardEmittedFallback = true;\r\n } else {\r\n flushUnstreamedAssistantText();\r\n }\r\n // Some providers (notably OpenAI Responses for gpt-5+) can stream a\r\n // successful turn that contains only reasoning content and zero output\r\n // text — typically when reasoning consumes the entire output-token\r\n // budget. Without a final text part the SSE stream still ends with a\r\n // clean `done`, which renders as a totally empty assistant bubble.\r\n // Retry so a reasoning-budget miss can still finish; each retry raises\r\n // the token ceiling and steps reasoning effort down a tier so it's not\r\n // just re-issuing the identical doomed request. If retries also come\r\n // back empty, surface a plain-language error.\r\n const hasEmptyFinalResponse =\r\n !guardEmittedFallback &&\r\n collectTextParts(assistantContentForHistory).trim().length === 0 &&\r\n streamedAssistantText.trim().length === 0;\r\n if (hasEmptyFinalResponse) {\r\n if (emptyFinalResponseRetries < EMPTY_FINAL_RESPONSE_RETRY_LIMIT) {\r\n emptyFinalResponseRetries += 1;\r\n effectiveMaxOutputTokens =\r\n resolveEmptyResponseRetryMaxOutputTokens(model);\r\n effectiveReasoningEffort = stepDownReasoningEffort(\r\n effectiveReasoningEffort,\r\n );\r\n appendAgentLoopContinuation(messages, \"max_tokens\");\r\n continue;\r\n }\r\n send({\r\n type: \"text\",\r\n text: \"The model returned an empty response. This usually means reasoning used the full output-token budget. Try again, or pick a different model from the model menu.\",\r\n });\r\n } else {\r\n emptyFinalResponseRetries = 0;\r\n effectiveMaxOutputTokens = opts.maxOutputTokens;\r\n effectiveReasoningEffort = opts.reasoningEffort;\r\n }\r\n break;\r\n }\r\n\r\n // Reached only when the model made tool calls (toolCallParts.length > 0),\r\n // i.e. it's about to do more work and produce a *new* final answer. Give\r\n // that next final-answer cycle a fresh guard-retry budget; otherwise\r\n // finalGuardRetries stays at 1 from a prior cycle and the guard is\r\n // permanently disabled for the rest of a long multi-step run.\r\n finalGuardRetries = 0;\r\n emptyFinalResponseRetries = 0;\r\n\r\n flushUnstreamedAssistantText();\r\n\r\n let requestedActionStop: { message: string; errorCode?: string } | null =\r\n null;\r\n\r\n // Human-in-the-loop approvals granted by the user for this turn (opt-in;\r\n // empty for the overwhelming majority of turns). Keyed by the stable\r\n // tool-call approval key so a re-issued continuation can let an approved\r\n // call run. The model cannot populate this — it comes from the request.\r\n const approvedToolCallKeys = new Set<string>(opts.approvedToolCalls ?? []);\r\n\r\n const runToolCall = async (\r\n toolCall: import(\"./engine/types.js\").EngineToolCallPart,\r\n ): Promise<EngineContentPart> => {\r\n const wireToolInput = JSON.stringify(toolCall.input ?? {});\r\n const normalizedToolInput = normalizeToolCallInputForHistory(\r\n toolCall.input,\r\n );\r\n const actionEntry = actions[toolCall.name];\r\n const sourceSweepGuard = shouldGuardRepeatedSourceSweep({\r\n toolName: toolCall.name,\r\n entry: actionEntry,\r\n priorToolCalls: sourceSweepToolCallHistory,\r\n });\r\n const sourceSweepDelegationGuard =\r\n sourceSweepDelegationGuardActive &&\r\n isLikelySourceSweepDelegation({\r\n toolName: toolCall.name,\r\n input: toolCall.input,\r\n })\r\n ? sourceSweepDelegationGuardMessage(\r\n getToolAction(toolCall.name, toolCall.input),\r\n )\r\n : null;\r\n toolCallHistory.push({\r\n name: toolCall.name,\r\n input: normalizedToolInput,\r\n });\r\n sourceSweepToolCallHistory.push({\r\n name: toolCall.name,\r\n input: normalizedToolInput,\r\n });\r\n const recordToolResult = (content: string, isError: boolean) => {\r\n toolResultHistory.push({\r\n name: toolCall.name,\r\n content,\r\n isError,\r\n });\r\n };\r\n const finalizeToolErrorResult = (rawResult: string): string => {\r\n const sanitizedResult = sanitizeToolErrorText(rawResult);\r\n const errorKey = `${toolCallCacheKey(\r\n toolCall.name,\r\n toolCall.input,\r\n )}:${normalizeToolErrorForBreaker(sanitizedResult)}`;\r\n const count = (repeatedToolErrors.get(errorKey) ?? 0) + 1;\r\n repeatedToolErrors.set(errorKey, count);\r\n if (count < MAX_IDENTICAL_TOOL_ERRORS) return sanitizedResult;\r\n const result =\r\n `Stopped after ${count} identical errors from ${toolCall.name} with the same arguments. ` +\r\n `Last error: ${sanitizedResult}`;\r\n requestedActionStop ??= {\r\n message:\r\n `Stopped because ${toolCall.name} failed ${count} times with the same arguments and error. ` +\r\n \"Fix the underlying issue or change the arguments before retrying.\",\r\n errorCode: \"repeated_identical_tool_error\",\r\n };\r\n return result;\r\n };\r\n if (sourceSweepGuard) {\r\n sourceSweepDelegationGuardActive = true;\r\n const result = sourceSweepGuard.message;\r\n send({\r\n type: \"tool_start\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, string>,\r\n });\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n completedSideEffect: false,\r\n });\r\n recordToolResult(result, false);\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n };\r\n }\r\n\r\n if (sourceSweepDelegationGuard) {\r\n const result = sourceSweepDelegationGuard;\r\n send({\r\n type: \"tool_start\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, string>,\r\n });\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n completedSideEffect: false,\r\n });\r\n recordToolResult(result, false);\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n };\r\n }\r\n\r\n if (!actionEntry) {\r\n const result = finalizeToolErrorResult(\r\n `Error: Unknown tool \"${toolCall.name}\"`,\r\n );\r\n send({\r\n type: \"tool_start\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, string>,\r\n });\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n isError: true,\r\n completedSideEffect: false,\r\n });\r\n recordToolResult(result, true);\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n isError: true,\r\n };\r\n }\r\n\r\n // Human-in-the-loop approval gate (opt-in via defineAction\r\n // `needsApproval`; default off). When an action requires approval and\r\n // this specific call has NOT been approved by a human, pause the turn\r\n // instead of executing. The action's side effect never happens until a\r\n // human re-issues the turn approving this call's stable key.\r\n const approvalKey = toolCallCacheKey(toolCall.name, toolCall.input);\r\n if (actionEntry.needsApproval && !approvedToolCallKeys.has(approvalKey)) {\r\n let mustApprove = false;\r\n try {\r\n mustApprove =\r\n typeof actionEntry.needsApproval === \"function\"\r\n ? Boolean(\r\n await actionEntry.needsApproval(toolCall.input, {\r\n userEmail: getRequestUserEmail(),\r\n orgId: getRequestOrgId() ?? null,\r\n caller: \"tool\",\r\n }),\r\n )\r\n : actionEntry.needsApproval === true;\r\n } catch {\r\n // Fail closed: a throwing predicate means we require approval rather\r\n // than silently running a high-consequence action.\r\n mustApprove = true;\r\n }\r\n if (mustApprove) {\r\n send({\r\n type: \"tool_start\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, string>,\r\n });\r\n send({\r\n type: \"approval_required\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, string>,\r\n approvalKey,\r\n ...(toolCall.id ? { toolCallId: toolCall.id } : {}),\r\n });\r\n // Audit the blocked attempt: the action did NOT run, but \"the agent\r\n // tried to do X and was gated\" is itself worth recording. Best-effort,\r\n // but AWAITED (not fire-and-forget) so the row isn't lost to a\r\n // serverless freeze / request teardown when the turn pauses.\r\n try {\r\n const { recordActionAudit } = await import(\"../audit/record.js\");\r\n await recordActionAudit({\r\n config: undefined,\r\n args: toolCall.input,\r\n ctx: {\r\n actionName: toolCall.name,\r\n caller: \"tool\",\r\n userEmail: getRequestUserEmail(),\r\n orgId: getRequestOrgId() ?? null,\r\n ...(opts.threadId ? { threadId: opts.threadId } : {}),\r\n ...(opts.turnId ? { turnId: opts.turnId } : {}),\r\n },\r\n status: \"denied\",\r\n });\r\n } catch {\r\n // Best-effort — auditing must never break the approval pause.\r\n }\r\n const result =\r\n `Awaiting human approval to run \"${toolCall.name}\". This action did ` +\r\n `NOT execute — a human must approve this specific call before it ` +\r\n `can run. The turn is paused; do not retry.`;\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n completedSideEffect: false,\r\n });\r\n recordToolResult(result, false);\r\n requestedActionStop ??= {\r\n message: `Waiting for your approval to run ${toolCall.name}.`,\r\n errorCode: \"needs-approval\",\r\n };\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n };\r\n }\r\n }\r\n\r\n const DEFAULT_TOOL_RESULT_CHARS = 50_000;\r\n // Default action tools should not undercut durable/background runs. The\r\n // run-manager still aborts foreground hosted runs around 40s, while\r\n // background runs get nearly the full 15-minute function budget.\r\n const DEFAULT_TOOL_TIMEOUT_MS = 12 * 60_000;\r\n const toolTimeoutMs =\r\n actionEntry.timeoutMs ??\r\n opts.toolLimits?.timeoutMs ??\r\n DEFAULT_TOOL_TIMEOUT_MS;\r\n const toolMaxResultChars =\r\n actionEntry.maxResultChars ??\r\n opts.toolLimits?.maxResultChars ??\r\n DEFAULT_TOOL_RESULT_CHARS;\r\n\r\n // TOOL-CALL JOURNAL HARD-BLOCK (resume safety, tool-layer enforcement).\r\n // The prompt-level resume journal already TELLS a resuming model not to\r\n // re-run completed tool calls; this enforces it at the tool layer so a\r\n // re-dispatched write call whose exact (tool name + input) already\r\n // completed in an earlier interrupted chunk of this turn does NOT execute\r\n // its side effect again — we return the journaled result instead and emit\r\n // the normal tool_start/tool_done so the transcript stays coherent.\r\n //\r\n // Gated on a non-readOnly tool + an existing prior-chunk journal (so fresh\r\n // calls with no completed journal entry are completely unaffected). The\r\n // snapshot was taken before this chunk's tools ran, so it can only match a\r\n // PRIOR completion, never one from the current chunk.\r\n if (!actionEntry.readOnly && toolCallJournal) {\r\n const journaled = findCompletedJournalEntry(\r\n toolCallJournal,\r\n toolCall.name,\r\n toolCall.input,\r\n consumedJournalKeys,\r\n );\r\n if (journaled) {\r\n const recordedResult = journaled.result ?? \"\";\r\n const result =\r\n `(Already completed in an earlier interrupted attempt - not re-run to avoid a duplicate side effect.)\\n\\n` +\r\n recordedResult;\r\n send({\r\n type: \"tool_start\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, string>,\r\n });\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n completedSideEffect: true,\r\n });\r\n recordToolResult(result, false);\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n };\r\n }\r\n }\r\n\r\n // Guard against write tools that have been interrupted too many times in\r\n // this turn (connection drop mid-execution → agent retries → repeat).\r\n // A write tool that keeps failing likely has a timeout / large-payload\r\n // problem; retrying indefinitely creates duplicates and confuses users.\r\n //\r\n // LEDGER RECOVERY: before applying the give-up budget, check whether the\r\n // previous invocation's zombie actually completed and wrote its result to\r\n // the durable ledger. If so, return the ledger result without re-executing\r\n // (prevents the duplicate side effect) and skip counting it toward the\r\n // interruption budget. A just-abandoned long tool may need a short grace\r\n // period before its detached promise writes the ledger, so wait while the\r\n // current run still has budget instead of immediately re-running it.\r\n if (!actionEntry.readOnly) {\r\n const writeCacheKey = toolCallCacheKey(toolCall.name, toolCall.input);\r\n const priorInterruptions =\r\n writeToolInterruptions.get(writeCacheKey) ?? 0;\r\n\r\n if (priorInterruptions > 0 && opts.threadId) {\r\n const ledgerResult = await waitForInterruptedToolLedgerEntry({\r\n threadId: opts.threadId,\r\n toolKey: writeCacheKey,\r\n toolName: toolCall.name,\r\n timeoutMs: toolTimeoutMs,\r\n signal,\r\n send,\r\n });\r\n if (ledgerResult !== null) {\r\n // Zombie completed — recover the real result without re-executing.\r\n const result =\r\n `(Recovered from prior interrupted chunk — action already completed.)\\n\\n` +\r\n ledgerResult;\r\n send({\r\n type: \"tool_start\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, string>,\r\n });\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n completedSideEffect: true,\r\n ...(actionEntry.chatUI ? { chatUI: actionEntry.chatUI } : {}),\r\n });\r\n recordToolResult(result, false);\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n };\r\n }\r\n }\r\n\r\n if (priorInterruptions >= MAX_WRITE_TOOL_INTERRUPTIONS) {\r\n const result =\r\n `The ${toolCall.name} action was interrupted ${priorInterruptions} time(s) in this session — ` +\r\n `likely a connection timeout with a large payload. Please start a new chat and try again, ` +\r\n `or split the request into smaller pieces.`;\r\n send({\r\n type: \"tool_start\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, string>,\r\n });\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n isError: true,\r\n completedSideEffect: false,\r\n });\r\n recordToolResult(result, true);\r\n requestedActionStop ??= {\r\n message:\r\n `I stopped because the ${toolCall.name} action was interrupted ${priorInterruptions} time(s) in a row. ` +\r\n `This usually means the connection timed out while processing a large request. ` +\r\n `Please start a new chat and try again, or break the request into smaller parts.`,\r\n errorCode: \"repeated_write_tool_interruption\",\r\n };\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n isError: true,\r\n };\r\n }\r\n }\r\n\r\n // Stop BEFORE emitting tool_start if the run was already aborted —\r\n // typically because the ledger wait above polled for minutes and the soft\r\n // timeout fired meanwhile. Emitting tool_start/tool_done here would leave a\r\n // bogus interrupted pair in the transcript for a tool that never re-ran,\r\n // and re-invoking would spawn a duplicate zombie. Return the interrupted\r\n // marker (no events) so the next continuation recovers via the ledger.\r\n // (A second guard inside the try below still covers an abort that lands in\r\n // the tiny sync window between here and the action invocation.)\r\n if (signal.aborted) {\r\n recordToolResult(INTERRUPTED_TOOL_RESULT_MARKER, false);\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: INTERRUPTED_TOOL_RESULT_MARKER,\r\n };\r\n }\r\n\r\n send({\r\n type: \"tool_start\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, string>,\r\n });\r\n\r\n const toolCallSchemaError = toolCallErrors.get(toolCall.id);\r\n if (toolCallSchemaError) {\r\n const result = finalizeToolErrorResult(\r\n toolInputSchemaErrorResult(\r\n toolCall.name,\r\n toolCallSchemaError.input,\r\n toolCallSchemaError.error,\r\n ),\r\n );\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n isError: true,\r\n completedSideEffect: false,\r\n });\r\n recordToolResult(result, true);\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n isError: true,\r\n };\r\n }\r\n\r\n const rawToolInputError = validateRawToolInput(\r\n actionEntry,\r\n toolCall.input,\r\n );\r\n if (rawToolInputError) {\r\n const result = finalizeToolErrorResult(\r\n toolInputSchemaErrorResult(\r\n toolCall.name,\r\n toolCall.input,\r\n rawToolInputError,\r\n ),\r\n );\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n isError: true,\r\n completedSideEffect: false,\r\n });\r\n recordToolResult(result, true);\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n isError: true,\r\n };\r\n }\r\n\r\n const cacheKey =\r\n actionEntry.readOnly === true\r\n ? toolCallCacheKey(toolCall.name, toolCall.input)\r\n : null;\r\n if (cacheKey && readOnlyToolResultCache.has(cacheKey)) {\r\n const repeats = (duplicateReadOnlyToolCalls.get(cacheKey) ?? 0) + 1;\r\n duplicateReadOnlyToolCalls.set(cacheKey, repeats);\r\n const previousResult = readOnlyToolResultCache.get(cacheKey) ?? \"\";\r\n const result =\r\n `Skipped duplicate read-only call to ${toolCall.name}: identical input already ran in this turn. ` +\r\n `Use the previous result already in the conversation instead of calling this tool again.\\n\\n` +\r\n `Previous result:\\n${previousResult}`;\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n completedSideEffect: false,\r\n });\r\n recordToolResult(result, false);\r\n if (repeats >= 3) {\r\n requestedActionStop ??= {\r\n message:\r\n \"I stopped because the agent kept asking for the same read-only context it already had. Please send the request again if you want me to retry from a fresh turn.\",\r\n errorCode: \"duplicate_read_only_tool\",\r\n };\r\n }\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n };\r\n }\r\n\r\n if (\r\n opts.executionMode === \"plan\" &&\r\n !isPlanModeToolCallAllowed(toolCall.name, toolCall.input, actionEntry)\r\n ) {\r\n const result = planModeBlockedMessage(toolCall.name);\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n isError: true,\r\n completedSideEffect: false,\r\n });\r\n recordToolResult(result, true);\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n isError: true,\r\n };\r\n }\r\n\r\n let result: string;\r\n let isError = false;\r\n let mcpApp:\r\n | import(\"../mcp-client/app-result.js\").AgentMcpAppPayload\r\n | undefined;\r\n let toolResultImages:\r\n | import(\"./engine/types.js\").EngineToolResultImagePart[]\r\n | undefined;\r\n try {\r\n // The run may have been aborted while we waited above for an\r\n // interrupted tool's ledger result (the wait can poll for minutes).\r\n // Re-check before invoking the action: starting it now would spawn a\r\n // fresh zombie execution — a duplicate side effect / double charge —\r\n // which the ledger-recovery path exists to prevent. The Promise.race\r\n // \"Run aborted\" leg below only rejects AFTER the action is invoked, so\r\n // it cannot guard this. Throw here instead, handled like any abort.\r\n if (signal.aborted) {\r\n throw new Error(\"Run aborted\");\r\n }\r\n const timeoutSignal = AbortSignal.timeout(toolTimeoutMs);\r\n const actionUserEmail = opts.ownerEmail ?? getRequestUserEmail();\r\n const actionOrgId = opts.orgId ?? getRequestOrgId() ?? null;\r\n const actionContext = {\r\n send,\r\n userEmail: actionUserEmail ?? undefined,\r\n orgId: actionOrgId,\r\n caller: \"tool\" as const,\r\n attachments: opts.attachments,\r\n signal,\r\n // Audit attribution: the action name + the agent thread/turn that\r\n // triggered this call, so a mutation can be traced to its run.\r\n actionName: toolCall.name,\r\n ...(opts.threadId ? { threadId: opts.threadId } : {}),\r\n ...(opts.turnId ? { turnId: opts.turnId } : {}),\r\n };\r\n const requestContext = getRequestContext();\r\n const invokeAction = () =>\r\n actionEntry.run(\r\n toolCall.input as Record<string, string>,\r\n actionContext,\r\n );\r\n // Keep a reference to the action promise so we can attach a zombie-\r\n // detection continuation AFTER Promise.race abandons it on run abort.\r\n // The promise itself is not awaited here — Promise.race owns the await.\r\n const actionPromise = Promise.resolve(\r\n runWithRequestContext(\r\n {\r\n ...(requestContext ?? {}),\r\n ...(actionUserEmail ? { userEmail: actionUserEmail } : {}),\r\n ...(actionOrgId ? { orgId: actionOrgId } : {}),\r\n ...(requestContext?.run ? { run: requestContext.run } : {}),\r\n },\r\n invokeAction,\r\n ),\r\n );\r\n\r\n // When the run is aborted (soft-timeout / user cancel) while this tool\r\n // call is in flight, Promise.race below will throw \"Run aborted\" and the\r\n // action's promise becomes a zombie — it keeps running but its result is\r\n // never returned to the loop. If the zombie eventually resolves, write\r\n // the result to the durable ledger keyed by (threadId, toolKey) so the\r\n // next continuation chunk can recover it instead of re-executing the\r\n // side effect.\r\n if (opts.threadId && !actionEntry.readOnly) {\r\n const ledgerThreadId = opts.threadId;\r\n const ledgerToolKey = toolCallCacheKey(toolCall.name, toolCall.input);\r\n actionPromise\r\n .then((zombieRaw: unknown) => {\r\n const zombieMcp = isMcpActionResult(zombieRaw) ? zombieRaw : null;\r\n if (\r\n zombieMcp &&\r\n zombieMcp.raw &&\r\n typeof zombieMcp.raw === \"object\" &&\r\n (zombieMcp.raw as Record<string, unknown>).isError === true\r\n ) {\r\n return;\r\n }\r\n const zombieText = zombieMcp ? zombieMcp.text : zombieRaw;\r\n const zombieStr =\r\n typeof zombieText === \"string\"\r\n ? zombieText\r\n : JSON.stringify(zombieText, null, 2);\r\n void writeLedgerEntry(ledgerThreadId, ledgerToolKey, zombieStr);\r\n })\r\n .catch(() => {\r\n // Action errored in the zombie — no result to ledger.\r\n });\r\n }\r\n\r\n const raw = await Promise.race([\r\n actionPromise,\r\n new Promise<never>((_, reject) => {\r\n timeoutSignal.addEventListener(\"abort\", () =>\r\n reject(\r\n new Error(\r\n `Tool call timed out after ${toolTimeoutMs / 1000} seconds`,\r\n ),\r\n ),\r\n );\r\n }),\r\n // Stop waiting on the tool when the run itself is aborted (e.g. the\r\n // run-manager soft timeout, or a user cancel). Without this leg the\r\n // loop blocks on an in-flight tool for up to TOOL_TIMEOUT_MS after\r\n // the run signal has already fired.\r\n new Promise<never>((_, reject) => {\r\n if (signal.aborted) {\r\n reject(new Error(\"Run aborted\"));\r\n return;\r\n }\r\n signal.addEventListener(\r\n \"abort\",\r\n () => reject(new Error(\"Run aborted\")),\r\n { once: true },\r\n );\r\n }),\r\n ]);\r\n const mcpResult = isMcpActionResult(raw) ? raw : null;\r\n const rawForAgent = mcpResult ? mcpResult.text : raw;\r\n if (\r\n mcpResult &&\r\n mcpResult.raw &&\r\n typeof mcpResult.raw === \"object\" &&\r\n (mcpResult.raw as Record<string, unknown>).isError === true\r\n ) {\r\n isError = true;\r\n }\r\n mcpApp = mcpResult?.mcpApp;\r\n // Demo mode: the agent must see the same fake data the UI shows, so\r\n // it can't read out a real name/email on a live screen share. Redact\r\n // the structured result (not the JSON string) so IDs/dates/URLs stay\r\n // intact and follow-up tool calls still work. Gated — the expensive\r\n // walk only runs when demo mode is on.\r\n let redacted: unknown = rawForAgent;\r\n const demoMode = await isDemoModeEnabled();\r\n if (demoMode) {\r\n mcpApp = undefined;\r\n if (typeof rawForAgent === \"string\") {\r\n try {\r\n redacted = JSON.stringify(\r\n redactDemoData(JSON.parse(rawForAgent)),\r\n null,\r\n 2,\r\n );\r\n } catch {\r\n redacted = redactDemoString(rawForAgent);\r\n }\r\n } else {\r\n redacted = redactDemoData(rawForAgent);\r\n }\r\n }\r\n // Vision images for the model: MCP tools return standard `image`\r\n // content parts; first-party actions opt in via the well-known\r\n // `_agentImages` result field (stripped from the JSON the model\r\n // reads, even in demo mode). Demo mode drops the images themselves —\r\n // text redaction can't scrub pixels, and a screenshot would leak the\r\n // real contact names/emails/numbers the redaction exists to hide. The images array\r\n // never touches the ledger — only the compact text notes appended\r\n // below are persisted.\r\n let imageNotes: string[] = [];\r\n if (mcpResult) {\r\n if (!demoMode) {\r\n const mcpImages = extractMcpToolResultImages(mcpResult.raw);\r\n if (mcpImages.length > 0) toolResultImages = mcpImages;\r\n }\r\n } else {\r\n const extracted = extractAgentImagesFromActionResult(redacted);\r\n redacted = extracted.value;\r\n imageNotes = extracted.notes;\r\n if (extracted.images.length > 0 && !demoMode) {\r\n toolResultImages = extracted.images;\r\n }\r\n }\r\n if (toolResultImages) {\r\n imageNotes = [\r\n ...describeToolResultImages(toolResultImages),\r\n ...imageNotes,\r\n ];\r\n }\r\n let resultStr =\r\n typeof redacted === \"string\"\r\n ? redacted\r\n : JSON.stringify(redacted, null, 2);\r\n if (resultStr.length > toolMaxResultChars) {\r\n const truncated = resultStr.slice(0, toolMaxResultChars);\r\n resultStr = `${truncated}\\n\\n...[truncated — full result was ${resultStr.length.toLocaleString()} chars; only first ${toolMaxResultChars.toLocaleString()} shown]`;\r\n }\r\n // Image notes go after truncation so they always survive into the\r\n // persisted result string (the durable record that an image existed).\r\n if (imageNotes.length > 0) {\r\n resultStr = `${resultStr}\\n\\n${imageNotes.join(\"\\n\")}`;\r\n }\r\n result = resultStr;\r\n if (toolCall.name === TOOL_SEARCH_ACTION_NAME && !isError) {\r\n const added = expandActiveTools(\r\n extractToolSearchResultNames(rawForAgent),\r\n );\r\n if (added.length > 0) {\r\n result += `\\n\\nLoaded matching tool schemas for next step: ${added.join(\", \")}`;\r\n }\r\n }\r\n } catch (err: any) {\r\n if (isAgentActionStopError(err)) {\r\n const message =\r\n sanitizeToolErrorValue(err.message) ||\r\n `Stopped after ${toolCall.name} failed.`;\r\n result = sanitizeToolErrorValue(err.toolResult || message);\r\n requestedActionStop ??= {\r\n message,\r\n ...(err.errorCode ? { errorCode: err.errorCode } : {}),\r\n };\r\n } else {\r\n const message = sanitizeToolErrorValue(err);\r\n result = `Error running ${toolCall.name}: ${message}${rateLimitRecoveryHint(message)}`;\r\n }\r\n isError = true;\r\n }\r\n if (isError) {\r\n result = finalizeToolErrorResult(result);\r\n }\r\n\r\n // Auto-refresh the UI after a successful mutating tool call. Any action\r\n // that isn't explicitly read-only is assumed to mutate. The client's\r\n // useDbSync listener sees a change event with source:\"action\" and\r\n // invalidates [\"action\"] queries so list-* / get-* refetch. This makes\r\n // refresh after agent writes reliable without the model needing to\r\n // remember to call `refresh-screen` itself.\r\n if (!isError && actionEntry.readOnly !== true) {\r\n try {\r\n const { notifyActionChange } =\r\n await import(\"../server/action-change.js\");\r\n const owner = opts.ownerEmail ?? getRequestUserEmail() ?? undefined;\r\n const orgId = opts.orgId ?? getRequestOrgId() ?? undefined;\r\n await notifyActionChange({\r\n actionName: toolCall.name,\r\n ...(owner ? { owner } : {}),\r\n ...(orgId ? { orgId } : {}),\r\n });\r\n } catch {\r\n // poll module may be unavailable in non-server contexts — ignore\r\n }\r\n }\r\n\r\n send({\r\n type: \"tool_done\",\r\n tool: toolCall.name,\r\n input: toolCall.input as Record<string, unknown>,\r\n result,\r\n ...(isError ? { isError: true } : {}),\r\n ...(isError\r\n ? { completedSideEffect: false }\r\n : actionEntry.readOnly !== true\r\n ? { completedSideEffect: true }\r\n : {}),\r\n ...(mcpApp ? { mcpApp } : {}),\r\n ...(actionEntry.chatUI ? { chatUI: actionEntry.chatUI } : {}),\r\n });\r\n recordToolResult(result, isError);\r\n if (!isError) {\r\n if (cacheKey) {\r\n readOnlyToolResultCache.set(cacheKey, result);\r\n } else {\r\n readOnlyToolResultCache.clear();\r\n duplicateReadOnlyToolCalls.clear();\r\n }\r\n }\r\n return {\r\n type: \"tool-result\" as const,\r\n toolCallId: toolCall.id,\r\n toolName: toolCall.name,\r\n toolInput: wireToolInput,\r\n content: result,\r\n ...(isError ? { isError } : {}),\r\n ...(!isError && toolResultImages && toolResultImages.length > 0\r\n ? { images: toolResultImages }\r\n : {}),\r\n };\r\n };\r\n\r\n type ParallelBatchKind = \"read\" | \"parallel-write\";\r\n const getParallelBatchKind = (\r\n toolCall: import(\"./engine/types.js\").EngineToolCallPart,\r\n ): ParallelBatchKind | null => {\r\n const entry = actions[toolCall.name];\r\n // Unknown tool name → serialize (null), don't fold it into the read-only\r\n // parallel batch. Misclassifying it as \"read\" lets it run via Promise.all\r\n // alongside genuine reads, which can reorder it ahead of a later mutating\r\n // call and break the model's intended sequencing.\r\n if (!entry) return null;\r\n if (entry.readOnly === true) return \"read\";\r\n if (entry.parallelSafe === true) return \"parallel-write\";\r\n return null;\r\n };\r\n\r\n // Engines can emit several tool-call blocks in one turn. Read-only calls\r\n // are always parallel. Mutating calls remain serialized by default, but\r\n // consecutive actions that explicitly declare `parallelSafe` can run in a\r\n // write batch. Reads and writes are separate batches so the model's stated\r\n // order still controls what data a same-turn read can observe.\r\n const toolResultParts: EngineContentPart[] = [];\r\n let parallelBatch: import(\"./engine/types.js\").EngineToolCallPart[] = [];\r\n let parallelBatchKind: ParallelBatchKind | null = null;\r\n const flushParallelBatch = async () => {\r\n if (parallelBatch.length === 0) return;\r\n const batch = parallelBatch;\r\n parallelBatch = [];\r\n parallelBatchKind = null;\r\n toolResultParts.push(...(await Promise.all(batch.map(runToolCall))));\r\n };\r\n\r\n for (const toolCall of toolCallParts) {\r\n const batchKind = getParallelBatchKind(toolCall);\r\n if (batchKind) {\r\n if (parallelBatchKind && parallelBatchKind !== batchKind) {\r\n await flushParallelBatch();\r\n }\r\n parallelBatchKind = batchKind;\r\n parallelBatch.push(toolCall);\r\n } else {\r\n await flushParallelBatch();\r\n toolResultParts.push(await runToolCall(toolCall));\r\n }\r\n }\r\n await flushParallelBatch();\r\n\r\n messages.push({ role: \"user\", content: toolResultParts });\r\n if (requestedActionStop) {\r\n // TypeScript can't track ??= through async closures; cast to known type.\r\n const stop = requestedActionStop as {\r\n message: string;\r\n errorCode?: string;\r\n };\r\n send({ type: \"text\", text: stop.message });\r\n break;\r\n }\r\n }\r\n\r\n // A processor halted the run: the `tripwire` event and final message were\r\n // already emitted at the abort site. Do NOT send the normal `done` — the run\r\n // ended on a guardrail, not a clean turn. The result hook still fires below\r\n // so processors can observe the (halted) final text.\r\n if (tripwire) {\r\n if (processorChain) {\r\n try {\r\n await processorChain.runResult(\r\n collectTextParts(\r\n messages.flatMap((m) => (m.role === \"assistant\" ? m.content : [])),\r\n ),\r\n );\r\n } catch (err) {\r\n if (!(err instanceof TripWire)) throw err;\r\n // A result-hook abort is a no-op: the run is already halting.\r\n }\r\n }\r\n return usage;\r\n }\r\n\r\n if (!signal.aborted) {\r\n // In-loop processor seam (result hook). Fires once at clean run end with the\r\n // final assistant text so processors (e.g. a proof-of-done gate) can record\r\n // a verdict. A result-hook abort cannot un-finish a completed run, so a\r\n // TripWire here is swallowed.\r\n if (processorChain) {\r\n try {\r\n await processorChain.runResult(\r\n collectTextParts(\r\n messages.flatMap((m) => (m.role === \"assistant\" ? m.content : [])),\r\n ),\r\n );\r\n } catch (err) {\r\n if (!(err instanceof TripWire)) throw err;\r\n }\r\n }\r\n send({ type: \"done\" });\r\n // Clean up any zombie-completion ledger entries for this thread now that\r\n // the turn completed normally. If the run was aborted the ledger must stay\r\n // intact so the next continuation chunk can still recover from it.\r\n if (opts.threadId) {\r\n void clearLedgerForThread(opts.threadId).catch(() => {});\r\n\r\n // Observational Memory (producer): after a clean turn, run a best-effort\r\n // compaction pass so long threads accrue observations/reflections that the\r\n // consumer above will surface on later turns. Both the Observer and the\r\n // Reflector no-op below their token thresholds, so this is cheap for short\r\n // threads. Fire-and-forget; any failure is swallowed so OM never affects\r\n // the user-visible turn.\r\n if (opts.ownerEmail) {\r\n const compactThreadId = opts.threadId;\r\n void maybeCompactThread({\r\n threadId: compactThreadId,\r\n ownerEmail: opts.ownerEmail,\r\n orgId: opts.orgId ?? null,\r\n messages,\r\n }).catch((err) => {\r\n console.warn(\r\n \"[observational-memory] post-turn compaction skipped:\",\r\n err instanceof Error ? err.message : String(err),\r\n );\r\n });\r\n }\r\n }\r\n }\r\n return usage;\r\n}\r\n\r\nfunction backgroundChatProgressRunId(turnId: string): string {\r\n const normalized = turnId\r\n .trim()\r\n .replace(/[^a-zA-Z0-9._:-]+/g, \"-\")\r\n .replace(/^-+|-+$/g, \"\")\r\n .slice(0, 160);\r\n return `agent-chat-${normalized || \"turn\"}`;\r\n}\r\n\r\nfunction isRecoverableContinuationError(event: {\r\n type: \"error\";\r\n error: string;\r\n errorCode?: string;\r\n recoverable?: boolean;\r\n}): boolean {\r\n const code = String(event.errorCode ?? \"\").toLowerCase();\r\n const message = event.error.toLowerCase();\r\n if (code === \"builder_gateway_error\") return false;\r\n return (\r\n event.recoverable === true ||\r\n code === \"builder_gateway_timeout\" ||\r\n code === \"builder_gateway_network_error\" ||\r\n code === \"provider_network_error\" ||\r\n code === \"stale_run\" ||\r\n code === \"timeout\" ||\r\n code === \"timeout_error\" ||\r\n code === \"http_408\" ||\r\n code === \"http_429\" ||\r\n code === \"http_529\" ||\r\n code === \"run_timeout\" ||\r\n message.includes(\"timeout\") ||\r\n message.includes(\"connection error\") ||\r\n message.includes(\"temporarily unavailable\")\r\n );\r\n}\r\n\r\nfunction endsAtInternalContinuationBoundary(run: ActiveRun): boolean {\r\n const last = run.events.at(-1)?.event;\r\n if (!last) return false;\r\n if (last.type === \"auto_continue\" || last.type === \"loop_limit\") {\r\n return true;\r\n }\r\n return last.type === \"error\" && isRecoverableContinuationError(last);\r\n}\r\n\r\nfunction isPreparingActionActivityEvent(\r\n event: AgentChatEvent,\r\n): event is Extract<AgentChatEvent, { type: \"activity\" }> {\r\n if (event.type !== \"activity\") return false;\r\n const label = event.label.trim().toLowerCase();\r\n return label.startsWith(\"preparing \") && label.includes(\" action\");\r\n}\r\n\r\nexport function lastUnfinishedPreparingActionToolFromEvents(\r\n events: readonly AgentChatEvent[],\r\n): string | undefined {\r\n const active = new Map<\r\n string,\r\n {\r\n id?: string;\r\n order: number;\r\n tool: string;\r\n }\r\n >();\r\n const idlessToolStarts = new Map<string, number>();\r\n const removeOldestMatchingActivePreparation = (\r\n tool: string,\r\n shouldRemove: (value: {\r\n id?: string;\r\n order: number;\r\n tool: string;\r\n }) => boolean = () => true,\r\n ) => {\r\n let oldest:\r\n | {\r\n key: string;\r\n order: number;\r\n }\r\n | undefined;\r\n for (const [key, value] of active) {\r\n if (value.tool !== tool || !shouldRemove(value)) continue;\r\n if (!oldest || value.order < oldest.order) {\r\n oldest = {\r\n key,\r\n order: value.order,\r\n };\r\n }\r\n }\r\n if (oldest) active.delete(oldest.key);\r\n return Boolean(oldest);\r\n };\r\n const removeMatchingActivePreparation = (event: {\r\n id?: string;\r\n tool?: string;\r\n type: \"tool_done\" | \"tool_start\";\r\n }) => {\r\n const id = event.id?.trim();\r\n const tool = event.tool?.trim();\r\n if (!tool) return;\r\n if (id) {\r\n if (!active.delete(`id:${id}`)) {\r\n removeOldestMatchingActivePreparation(tool, (value) => !value.id);\r\n }\r\n return;\r\n }\r\n\r\n if (event.type === \"tool_start\") {\r\n if (removeOldestMatchingActivePreparation(tool)) {\r\n idlessToolStarts.set(tool, (idlessToolStarts.get(tool) ?? 0) + 1);\r\n }\r\n return;\r\n }\r\n\r\n const startedCount = idlessToolStarts.get(tool) ?? 0;\r\n if (startedCount > 0) {\r\n if (startedCount === 1) {\r\n idlessToolStarts.delete(tool);\r\n } else {\r\n idlessToolStarts.set(tool, startedCount - 1);\r\n }\r\n return;\r\n }\r\n removeOldestMatchingActivePreparation(tool);\r\n };\r\n events.forEach((event, order) => {\r\n if (isPreparingActionActivityEvent(event)) {\r\n const tool = event.tool?.trim();\r\n if (tool) {\r\n const id = event.id?.trim();\r\n const key = id ? `id:${id}` : `tool:${tool}:${order}`;\r\n active.set(key, {\r\n tool,\r\n order,\r\n ...(id ? { id } : {}),\r\n });\r\n }\r\n return;\r\n }\r\n if (event.type === \"tool_start\" || event.type === \"tool_done\") {\r\n removeMatchingActivePreparation(event);\r\n return;\r\n }\r\n if (event.type === \"error\" && isRecoverableContinuationError(event)) {\r\n return;\r\n }\r\n if (\r\n event.type === \"clear\" ||\r\n event.type === \"done\" ||\r\n event.type === \"error\" ||\r\n event.type === \"missing_api_key\"\r\n ) {\r\n active.clear();\r\n idlessToolStarts.clear();\r\n }\r\n });\r\n let latest:\r\n | {\r\n order: number;\r\n tool: string;\r\n }\r\n | undefined;\r\n for (const value of active.values()) {\r\n if (!latest || value.order > latest.order) {\r\n latest = value;\r\n }\r\n }\r\n return latest?.tool;\r\n}\r\n\r\nfunction endsAfterCompletedToolWithoutAssistantFinal(run: ActiveRun): boolean {\r\n let completedToolAfterLastAssistantText = false;\r\n for (const { event } of run.events) {\r\n if (event.type === \"text\" && event.text.trim().length > 0) {\r\n completedToolAfterLastAssistantText = false;\r\n continue;\r\n }\r\n if (event.type === \"tool_done\" && event.isError !== true) {\r\n completedToolAfterLastAssistantText = true;\r\n continue;\r\n }\r\n if (\r\n event.type === \"clear\" ||\r\n event.type === \"error\" ||\r\n event.type === \"missing_api_key\" ||\r\n event.type === \"auto_continue\" ||\r\n event.type === \"loop_limit\"\r\n ) {\r\n completedToolAfterLastAssistantText = false;\r\n }\r\n }\r\n return completedToolAfterLastAssistantText;\r\n}\r\n\r\nfunction lastUnfinishedPreparingActionTool(run: ActiveRun): string | undefined {\r\n return lastUnfinishedPreparingActionToolFromEvents(\r\n run.events.map(({ event }) => event),\r\n );\r\n}\r\n\r\nexport function backgroundContinuationReasonForRun(\r\n run: ActiveRun,\r\n): AgentLoopContinuationReason {\r\n const last = run.events.at(-1)?.event;\r\n if (last?.type === \"loop_limit\") return \"loop_limit\";\r\n if (\r\n last?.type === \"auto_continue\" &&\r\n isAgentLoopContinuationReason(last.reason)\r\n ) {\r\n return last.reason;\r\n }\r\n if (last?.type === \"error\" && isRecoverableContinuationError(last)) {\r\n return continuationReasonForResumableError(\r\n new EngineError(last.error, { errorCode: last.errorCode }),\r\n );\r\n }\r\n if (endsAfterCompletedToolWithoutAssistantFinal(run)) {\r\n return \"stream_ended\";\r\n }\r\n return \"run_timeout\";\r\n}\r\n\r\nexport async function runAgentLoopWithMainChatInternalContinuations(\r\n opts: Parameters<typeof runAgentLoop>[0] & {\r\n /**\r\n * Opt-in: also catch a thrown `isResumableEngineError` (gateway drop /\r\n * transport interruption surviving engine retries) and retry it in-process\r\n * — the same \"continue from where you left off\" treatment already applied\r\n * to in-loop `auto_continue` events below — instead of letting it\r\n * propagate out to the caller. Default false/omitted preserves the exact\r\n * prior behavior: such an error is NOT caught here and propagates to\r\n * `startRun`'s outer catch, which marks the run \"errored\" and (for a\r\n * background worker) hands off to `chainServerDrivenContinuation` for a\r\n * fresh invocation.\r\n *\r\n * Only safe to enable when the CALLER is a proven durable-background\r\n * worker (`isInBackgroundFunctionRuntime()`): such a worker has minutes of\r\n * remaining budget on this same invocation, so resuming in-process avoids\r\n * a self-dispatch entirely — critically, it avoids the bg-function\r\n * self-dispatch 404 (a background function cannot invoke its own public\r\n * URL from inside a live invocation) that this same recoverable-error\r\n * path would otherwise hit via `chainServerDrivenContinuation`. A\r\n * foreground turn (~40s budget) must NOT set this — it keeps depending on\r\n * the existing cross-invocation recovery (foreground self-chain or the\r\n * client's `auto_continue` re-POST), unchanged.\r\n */\r\n resumeResumableErrorsInProcess?: boolean;\r\n /**\r\n * Override for the per-invocation continuation attempt cap. Defaults to\r\n * `MAIN_CHAT_INTERNAL_CONTINUATION_LIMIT` (6) when omitted — unchanged for\r\n * every existing caller. A proven background-function worker (15-min\r\n * budget) can pass a higher cap (e.g. `MAX_BACKGROUND_RUN_CONTINUATIONS`)\r\n * so a run that needs several resumable-error recoveries within one\r\n * 13-minute chunk isn't cut off at the foreground-sized limit.\r\n */\r\n maxContinuations?: number;\r\n },\r\n): Promise<Awaited<ReturnType<typeof runAgentLoop>>> {\r\n const usage: Awaited<ReturnType<typeof runAgentLoop>> = {\r\n inputTokens: 0,\r\n outputTokens: 0,\r\n cacheReadTokens: 0,\r\n cacheWriteTokens: 0,\r\n model: opts.model,\r\n };\r\n const addUsage = (next: Awaited<ReturnType<typeof runAgentLoop>>) => {\r\n usage.inputTokens += next.inputTokens;\r\n usage.outputTokens += next.outputTokens;\r\n usage.cacheReadTokens += next.cacheReadTokens;\r\n usage.cacheWriteTokens += next.cacheWriteTokens;\r\n usage.model = next.model;\r\n };\r\n\r\n const resumeResumableErrorsInProcess =\r\n opts.resumeResumableErrorsInProcess === true;\r\n const maxContinuations =\r\n typeof opts.maxContinuations === \"number\" && opts.maxContinuations > 0\r\n ? opts.maxContinuations\r\n : MAIN_CHAT_INTERNAL_CONTINUATION_LIMIT;\r\n\r\n const localTurnEvents: AgentChatEvent[] = [];\r\n let lastAttemptWasUnfinishedContinuation = false;\r\n for (\r\n let attempt = 0;\r\n !opts.signal.aborted && attempt < maxContinuations;\r\n attempt++\r\n ) {\r\n lastAttemptWasUnfinishedContinuation = false;\r\n let continuationReason: AgentLoopContinuationReason | undefined;\r\n const attemptStartIndex = localTurnEvents.length;\r\n const send = (event: AgentChatEvent) => {\r\n localTurnEvents.push(event);\r\n if (\r\n event.type === \"auto_continue\" &&\r\n isAgentLoopContinuationReason(event.reason)\r\n ) {\r\n continuationReason = event.reason;\r\n return;\r\n }\r\n opts.send(event);\r\n };\r\n\r\n try {\r\n const nextUsage = await runAgentLoop({ ...opts, send });\r\n addUsage(nextUsage);\r\n } catch (err) {\r\n // Preserve exact prior behavior unless explicitly opted in: an aborted\r\n // signal (real soft-timeout / user stop) or a non-resumable error is\r\n // always rethrown, and when `resumeResumableErrorsInProcess` is not\r\n // set, EVERY thrown error is rethrown exactly as before.\r\n if (\r\n !resumeResumableErrorsInProcess ||\r\n opts.signal.aborted ||\r\n !isResumableEngineError(err)\r\n ) {\r\n throw err;\r\n }\r\n continuationReason = continuationReasonForResumableError(err);\r\n }\r\n\r\n if (!continuationReason || opts.signal.aborted) {\r\n return usage;\r\n }\r\n\r\n lastAttemptWasUnfinishedContinuation = true;\r\n const attemptEvents = localTurnEvents.slice(attemptStartIndex);\r\n const completedSideEffect = attemptEvents.some(\r\n (event) =>\r\n event.type === \"tool_done\" &&\r\n event.completedSideEffect === true &&\r\n event.isError !== true,\r\n );\r\n if (!completedSideEffect) {\r\n opts.send({ type: \"clear\" });\r\n }\r\n const actionPreparationTool =\r\n lastUnfinishedPreparingActionToolFromEvents(localTurnEvents);\r\n appendAgentLoopContinuation(opts.messages, continuationReason, {\r\n ...(actionPreparationTool ? { actionPreparationTool } : {}),\r\n });\r\n }\r\n\r\n if (!opts.signal.aborted && lastAttemptWasUnfinishedContinuation) {\r\n opts.send({\r\n type: \"error\",\r\n error: RUN_BUDGET_EXHAUSTED_MESSAGE,\r\n errorCode: RUN_BUDGET_EXHAUSTED_ERROR_CODE,\r\n recoverable: true,\r\n });\r\n }\r\n return usage;\r\n}\r\n\r\nfunction endsAtContinuationBoundary(run: ActiveRun): boolean {\r\n return (\r\n endsAtInternalContinuationBoundary(run) ||\r\n endsAfterCompletedToolWithoutAssistantFinal(run)\r\n );\r\n}\r\n\r\n/**\r\n * Hard cap on server-driven background→background continuation chunks for a\r\n * single logical turn. A `backgroundFunction` run gets a ~13-min soft timeout,\r\n * so reaching this boundary at all is the rare exception (most turns finish in\r\n * one chunk). The cap bounds a pathological turn that would otherwise chain\r\n * background invocations forever, mirroring `MAX_AGENT_TEAM_CONTINUATIONS`.\r\n */\r\nexport const MAX_BACKGROUND_RUN_CONTINUATIONS = 20;\r\n\r\n/**\r\n * Whether this run should self-fire the next server-driven continuation chunk\r\n * instead of depending on the client to re-POST `auto_continue`. True for\r\n * either of two independently-gated cases, both requiring a recoverable\r\n * unfinished boundary (not aborted/stopped) and a chain still under its\r\n * budget:\r\n * - a durable-background WORKER run (`isBackgroundWorker`) — unconditional,\r\n * unchanged from before; or\r\n * - a FOREGROUND run when the resolved `foregroundSelfChainEligible` gate is\r\n * true (see `isAgentChatForegroundSelfChainEnabled` in\r\n * `durable-background.ts`) AND this specific run was never dispatched to\r\n * the durable background worker (`dispatchedToBackground` false) — a run\r\n * already headed to the durable background path chains via the\r\n * `isBackgroundWorker` branch above, never both.\r\n * Aborted / user-stopped runs do NOT chain either way.\r\n */\r\nexport function shouldChainBackgroundContinuation(opts: {\r\n isBackgroundWorker: boolean;\r\n run: ActiveRun;\r\n continuationCount: number;\r\n /**\r\n * Opt-in: allow a FOREGROUND (non-background-worker) run to also\r\n * self-chain server-side. Default false — preserves the exact prior\r\n * behavior (foreground runs never chain; the client's `auto_continue`\r\n * re-POST is the only continuation path) when omitted.\r\n */\r\n foregroundSelfChainEligible?: boolean;\r\n /**\r\n * True when this run was dispatched to the durable background worker\r\n * (`dispatchToBackground` in the handler). When true, foreground self-chain\r\n * is never eligible — the run either IS the background worker (chains via\r\n * `isBackgroundWorker`) or is a foreground POST whose recovery is already\r\n * owned by the background circuit-breaker, not this path.\r\n */\r\n dispatchedToBackground?: boolean;\r\n}): boolean {\r\n const eligible =\r\n opts.isBackgroundWorker ||\r\n (opts.foregroundSelfChainEligible === true &&\r\n opts.dispatchedToBackground !== true);\r\n return (\r\n eligible &&\r\n opts.run.status !== \"aborted\" &&\r\n endsAtContinuationBoundary(opts.run) &&\r\n opts.continuationCount < MAX_BACKGROUND_RUN_CONTINUATIONS\r\n );\r\n}\r\n\r\nexport async function markBackgroundContinuationChunkTerminal(opts: {\r\n runId: string;\r\n continuationReason: AgentLoopContinuationReason;\r\n deps?: {\r\n updateRunStatusIfRunning?: typeof updateRunStatusIfRunning;\r\n setRunTerminalReason?: typeof setRunTerminalReason;\r\n };\r\n}): Promise<boolean> {\r\n const updateStatus =\r\n opts.deps?.updateRunStatusIfRunning ?? updateRunStatusIfRunning;\r\n const setTerminalReason =\r\n opts.deps?.setRunTerminalReason ?? setRunTerminalReason;\r\n const updated = await updateStatus(opts.runId, \"completed\");\r\n if (updated) {\r\n await setTerminalReason(opts.runId, opts.continuationReason);\r\n }\r\n return updated;\r\n}\r\n\r\nexport async function claimBackgroundWorkerRunEarly(opts: {\r\n runId: string;\r\n threadId?: string | null;\r\n markerTurnId?: string | null;\r\n requestTurnId?: string | null;\r\n continuationCount: number;\r\n runsInBackgroundFunction: boolean;\r\n backgroundRuntimeDetail?: string;\r\n deps?: {\r\n recordRunDiagnostic?: typeof recordRunDiagnostic;\r\n insertRun?: typeof insertRun;\r\n claimBackgroundRun?: typeof claimBackgroundRun;\r\n updateRunHeartbeat?: typeof updateRunHeartbeat;\r\n };\r\n}): Promise<{ claimed: true } | { claimed: false; skipped: string }> {\r\n const record = opts.deps?.recordRunDiagnostic ?? recordRunDiagnostic;\r\n const insert = opts.deps?.insertRun ?? insertRun;\r\n const claim = opts.deps?.claimBackgroundRun ?? claimBackgroundRun;\r\n const heartbeat = opts.deps?.updateRunHeartbeat ?? updateRunHeartbeat;\r\n const threadId =\r\n typeof opts.threadId === \"string\" && opts.threadId.trim()\r\n ? opts.threadId.trim()\r\n : opts.runId;\r\n const turnId =\r\n typeof opts.markerTurnId === \"string\" && opts.markerTurnId.trim()\r\n ? opts.markerTurnId.trim()\r\n : typeof opts.requestTurnId === \"string\" && opts.requestTurnId.trim()\r\n ? opts.requestTurnId.trim()\r\n : opts.runId;\r\n\r\n await record(\r\n opts.runId,\r\n RUN_DIAG_STAGE.workerEntered,\r\n [\r\n `runsInBackgroundFunction=${opts.runsInBackgroundFunction}`,\r\n `continuationCount=${opts.continuationCount}`,\r\n opts.backgroundRuntimeDetail,\r\n ]\r\n .filter(Boolean)\r\n .join(\" \"),\r\n ).catch(() => {});\r\n\r\n if (opts.continuationCount > 0) {\r\n await insert(opts.runId, threadId, turnId, {\r\n dispatchMode: \"background\",\r\n }).catch(() => {});\r\n }\r\n\r\n const won = await claim(opts.runId);\r\n if (!won) {\r\n await record(opts.runId, RUN_DIAG_STAGE.workerClaimLost).catch(() => {});\r\n return { claimed: false, skipped: \"already-claimed\" };\r\n }\r\n\r\n await record(opts.runId, RUN_DIAG_STAGE.workerClaimed).catch(() => {});\r\n await heartbeat(opts.runId).catch(() => {});\r\n return { claimed: true };\r\n}\r\n\r\n/** Injectable dependencies for `chainServerDrivenContinuation` (unit tests). */\r\nexport interface ChainServerDrivenContinuationDeps {\r\n countRunsForTurn?: typeof countRunsForTurn;\r\n insertRun?: typeof insertRun;\r\n fireInternalDispatch?: typeof fireInternalDispatch;\r\n readBackgroundRunClaim?: typeof readBackgroundRunClaim;\r\n updateRunHeartbeat?: typeof updateRunHeartbeat;\r\n updateRunStatusIfRunning?: typeof updateRunStatusIfRunning;\r\n setRunTerminalReason?: typeof setRunTerminalReason;\r\n recordRunDiagnostic?: typeof recordRunDiagnostic;\r\n markBackgroundContinuationChunkTerminal?: typeof markBackgroundContinuationChunkTerminal;\r\n generateRunId?: typeof generateRunId;\r\n sleep?: (ms: number) => Promise<void>;\r\n}\r\n\r\n/** Retry-budget sizing for one `chainServerDrivenContinuation` dispatch. */\r\nexport interface ContinuationDispatchBudget {\r\n maxDispatchAttempts: number;\r\n dispatchResponseTimeoutMs: number;\r\n /** Cap (ms) on the per-gap exponential backoff. `Infinity` preserves the\r\n * original uncapped `500 * 2 ** attempt` schedule for the two budgets\r\n * that predate this cap (their attempt counts are low enough it never\r\n * mattered); only the larger proven-in-background-function budget uses a\r\n * real cap so its extra attempts don't add unbounded backoff. */\r\n backoffCapMs: number;\r\n}\r\n\r\n/**\r\n * Sizes the dispatch retry budget by *remaining wall-clock capacity*, not by\r\n * dispatch TARGET — the two are independent concerns. `chainViaDurableBackground`\r\n * only picks where the dispatch goes (see `continuationDispatchPath` above);\r\n * this picks how hard to retry getting it there.\r\n *\r\n * Three cases:\r\n * - `chainViaDurableBackground === true`: the durable worker chain dispatching\r\n * to the Netlify background function url. Unchanged: 3 attempts / 15s.\r\n * - `chainViaDurableBackground === false` and\r\n * `workerProvenInBackgroundFunction === true`: a worker PROVEN (by runtime\r\n * function name, see `shouldUseBackgroundFunctionTimeoutForWorker`) to\r\n * already be executing inside a real `-background` function — it was\r\n * forced onto the regular-function dispatch target only because a\r\n * background function cannot invoke its own URL from within a live\r\n * invocation (see the caller's `&& !runsInBackgroundFunction` comment),\r\n * NOT because it lacks time or a connected-client fallback. This worker\r\n * has up to `BACKGROUND_SOFT_TIMEOUT_CEILING_MS` (13min) of soft-timeout\r\n * budget behind it and up to Netlify's ~15min hard function limit ahead —\r\n * roughly 2 minutes of remaining wall clock — and, being a background\r\n * worker, NO connected client to fall back on if the handoff is dropped.\r\n * Demoting it to the foreground's 2-attempt/10s budget is exactly the bug\r\n * this type documents: 5 attempts / 15s response timeout, with backoff\r\n * capped at 4s/gap (500ms, 1s, 2s, 4s across the 4 gaps ≈ 7.5s total).\r\n * Worst case: 5 × 15s dispatch + ~7.5s backoff ≈ 82.5s, safely inside the\r\n * ~2min of remaining budget before the function's hard kill.\r\n * - Otherwise: a true foreground caller not proven in a background\r\n * function. Unchanged: 2 attempts / 10s — it has a live connected client\r\n * as a fallback (the terminal `auto_continue` event still reaches it).\r\n */\r\nexport function resolveContinuationDispatchBudget(opts: {\r\n chainViaDurableBackground: boolean;\r\n workerProvenInBackgroundFunction: boolean;\r\n}): ContinuationDispatchBudget {\r\n if (opts.chainViaDurableBackground) {\r\n return {\r\n maxDispatchAttempts: 3,\r\n dispatchResponseTimeoutMs: 15_000,\r\n backoffCapMs: Infinity,\r\n };\r\n }\r\n if (opts.workerProvenInBackgroundFunction) {\r\n return {\r\n maxDispatchAttempts: 5,\r\n dispatchResponseTimeoutMs: 15_000,\r\n backoffCapMs: 4_000,\r\n };\r\n }\r\n return {\r\n maxDispatchAttempts: 2,\r\n dispatchResponseTimeoutMs: 10_000,\r\n backoffCapMs: Infinity,\r\n };\r\n}\r\n\r\n/**\r\n * Server-driven continuation handoff for a chunk that hit its soft-timeout\r\n * boundary still unfinished: mint the next chunk's runId, PRE-INSERT its run\r\n * row (so `/runs/active` never shows an idle gap and a lost dispatch is\r\n * reaped loudly instead of hanging silently), fire the HMAC-signed\r\n * `_process-run` self-dispatch carrying ids only (the body is persisted on\r\n * the row as `dispatch_payload`), fully AWAIT the dispatch acknowledgment\r\n * with retries, and mark this chunk terminal only after the handoff landed.\r\n * On failure every path is loud: the successor row is errored, the failure\r\n * is recorded as the run's diag stage, and this chunk is flipped to errored\r\n * with a terminal reason — never a silent loss. (For a FOREGROUND self-chain\r\n * the client additionally still receives the terminal `auto_continue` event\r\n * — run-manager emits it after this callback — so the existing client\r\n * re-POST path takes over as the fallback.)\r\n *\r\n * `chainViaDurableBackground` selects the dispatch target:\r\n * - true → the durable-background worker chain (unchanged behavior): the\r\n * resolved background-function url on hosted Netlify (15-min budget), 3\r\n * attempts, 15s response timeout (Netlify async functions 202 on enqueue).\r\n * - false → the OPT-IN foreground self-chain: the framework `_process-run`\r\n * route on the REGULAR function. With `AGENT_CHAT_DURABLE_BACKGROUND`\r\n * off the `-background` function is never emitted into the deploy\r\n * output, so the regular function is the only guaranteed target; the\r\n * successor keeps the 40s chunk clamp (`backgroundFunctionRuntimeExpected`\r\n * is false for this path). The regular function responds only after the\r\n * successor chunk FINISHES (~40s), so a response timeout is NOT proof of\r\n * a dead handoff — after a failed/timed-out attempt the successor's\r\n * ATOMIC CLAIM is consulted (`readBackgroundRunClaim`): a row that\r\n * flipped to `background-processing` (or already went terminal) proves\r\n * the handoff landed, so no retry is fired.\r\n *\r\n * `chainViaDurableBackground` does NOT alone determine the retry BUDGET —\r\n * see `resolveContinuationDispatchBudget` and `workerProvenInBackgroundFunction`\r\n * below: a worker forced onto this same `false` target because it is proven\r\n * to already be inside a real background function gets a materially larger\r\n * budget than a true foreground caller, since it has no connected-client\r\n * fallback and minutes of remaining wall clock instead of seconds.\r\n *\r\n * Never throws — all failure paths are handled (recorded + marked) inside.\r\n */\r\nexport async function chainServerDrivenContinuation(opts: {\r\n event: unknown;\r\n run: ActiveRun;\r\n effectiveThreadId: string;\r\n effectiveTurnId: string;\r\n /** The current chunk's request body — the successor's rehydration payload\r\n * is derived from it (marker stripped, `internalContinuation` set). */\r\n requestBody: Record<string, unknown>;\r\n backgroundContinuationCount: number;\r\n chainViaDurableBackground: boolean;\r\n /** True only when this worker is PROVEN (by runtime function name) to\r\n * already be executing inside a real Netlify `-background` function —\r\n * distinct from `chainViaDurableBackground`, which is forced `false` for\r\n * this exact worker (it cannot dispatch to its own function URL from a\r\n * live invocation). Widens the retry budget; does NOT change the dispatch\r\n * target. See `resolveContinuationDispatchBudget`. Defaults to `false`. */\r\n workerProvenInBackgroundFunction?: boolean;\r\n deps?: ChainServerDrivenContinuationDeps;\r\n}): Promise<void> {\r\n const d = {\r\n countRunsForTurn: opts.deps?.countRunsForTurn ?? countRunsForTurn,\r\n insertRun: opts.deps?.insertRun ?? insertRun,\r\n fireInternalDispatch:\r\n opts.deps?.fireInternalDispatch ?? fireInternalDispatch,\r\n readBackgroundRunClaim:\r\n opts.deps?.readBackgroundRunClaim ?? readBackgroundRunClaim,\r\n updateRunHeartbeat: opts.deps?.updateRunHeartbeat ?? updateRunHeartbeat,\r\n updateRunStatusIfRunning:\r\n opts.deps?.updateRunStatusIfRunning ?? updateRunStatusIfRunning,\r\n setRunTerminalReason:\r\n opts.deps?.setRunTerminalReason ?? setRunTerminalReason,\r\n recordRunDiagnostic: opts.deps?.recordRunDiagnostic ?? recordRunDiagnostic,\r\n markBackgroundContinuationChunkTerminal:\r\n opts.deps?.markBackgroundContinuationChunkTerminal ??\r\n markBackgroundContinuationChunkTerminal,\r\n generateRunId: opts.deps?.generateRunId ?? generateRunId,\r\n sleep:\r\n opts.deps?.sleep ??\r\n ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))),\r\n };\r\n const { run, effectiveThreadId, effectiveTurnId } = opts;\r\n const runId = run.runId;\r\n\r\n // DURABLE PER-TURN LEDGER: bound the total number of runs one logical turn\r\n // may consume, counted in SQL. The in-marker `continuationCount` resets\r\n // whenever a fresh POST starts a new chain for the same turn (client\r\n // recovery, duplicate delivery), so it cannot bound cross-chain loops — the\r\n // SQL count survives every recovery path and is what actually kills a\r\n // pathological turn (the \"dozens of runs on one prompt\" incident class).\r\n const turnRunCount = await d\r\n .countRunsForTurn(effectiveThreadId, effectiveTurnId)\r\n .catch(() => null);\r\n if (\r\n turnRunCount !== null &&\r\n turnRunCount > MAX_BACKGROUND_RUN_CONTINUATIONS + 5\r\n ) {\r\n console.error(\r\n `[agent-chat] turn ${effectiveTurnId} consumed ${turnRunCount} runs — refusing to chain further`,\r\n runId,\r\n );\r\n const statusUpdated = await d\r\n .updateRunStatusIfRunning(runId, \"errored\")\r\n .catch(() => false);\r\n if (statusUpdated) {\r\n await d\r\n .setRunTerminalReason(runId, \"turn_continuation_budget_exhausted\")\r\n .catch(() => {});\r\n }\r\n return;\r\n }\r\n\r\n // Mint the next chunk's runId here and sign the dispatch token over it, so\r\n // the `_process-run` route's HMAC check and the worker's run identity\r\n // agree. Fresh runId (not this chunk's) so its seq log starts clean; same\r\n // turnId folds the assistant message across chunks.\r\n const nextRunId = d.generateRunId();\r\n const actionPreparationTool = lastUnfinishedPreparingActionTool(run);\r\n const continuationReason = backgroundContinuationReasonForRun(run);\r\n const continuationDispatchPath = opts.chainViaDurableBackground\r\n ? resolveAgentChatProcessRunDispatchPath()\r\n : AGENT_CHAT_PROCESS_RUN_PATH;\r\n const continuationExpectsNetlifyBackgroundFunction =\r\n dispatchPathTargetsNetlifyBackgroundFunction(continuationDispatchPath);\r\n const dispatchBudget = resolveContinuationDispatchBudget({\r\n chainViaDurableBackground: opts.chainViaDurableBackground,\r\n workerProvenInBackgroundFunction:\r\n opts.workerProvenInBackgroundFunction === true,\r\n });\r\n const maxDispatchAttempts = dispatchBudget.maxDispatchAttempts;\r\n const dispatchResponseTimeoutMs = dispatchBudget.dispatchResponseTimeoutMs;\r\n const continuationMarker = {\r\n runId: nextRunId,\r\n turnId: effectiveTurnId,\r\n continuationCount: opts.backgroundContinuationCount + 1,\r\n continuationReason,\r\n ...(actionPreparationTool ? { actionPreparationTool } : {}),\r\n backgroundFunctionRuntimeExpected:\r\n continuationExpectsNetlifyBackgroundFunction,\r\n };\r\n // Strip this chunk's own marker before persisting/forwarding — the next\r\n // chunk gets the fresh marker above.\r\n const continuationBody: Record<string, unknown> = {\r\n ...opts.requestBody,\r\n internalContinuation: true,\r\n };\r\n delete continuationBody[AGENT_CHAT_BACKGROUND_RUN_FIELD];\r\n try {\r\n await d\r\n .recordRunDiagnostic(\r\n runId,\r\n RUN_DIAG_STAGE.workerSetupStep,\r\n `chain_dispatch_start nextRunId=${nextRunId} reason=${continuationReason} path=${continuationDispatchPath}`,\r\n )\r\n .catch(() => {});\r\n // ── TRANSACTIONAL HANDOFF ──────────────────────────────────────────────\r\n // 1. Insert the successor row (with its rehydration payload) BEFORE\r\n // firing the dispatch, so:\r\n // - /runs/active shows an active run continuously across the chunk\r\n // boundary (no idle gap for the client to misread as \"the turn\r\n // ended\"), and\r\n // - a lost dispatch leaves a row the unclaimed-run sweep reaps into a\r\n // LOUD error instead of a silent hang.\r\n // 2. Await the dispatch response fully (`awaitResponse`) — this\r\n // invocation is about to finish, and the old 250ms settle race let a\r\n // still-in-flight handoff fetch be killed by the post-return freeze\r\n // WITHOUT rejecting: the turn just stopped, silently. A Netlify\r\n // background function 202s on enqueue (normally well under a second);\r\n // a regular-function target instead responds only after the successor\r\n // chunk finishes, so its timeout falls back to the claim check below.\r\n // Retried with backoff for transient network blips.\r\n let nextRowInserted = false;\r\n try {\r\n await d.insertRun(nextRunId, effectiveThreadId, effectiveTurnId, {\r\n dispatchMode: \"background\",\r\n dispatchPayload: JSON.stringify(continuationBody),\r\n });\r\n nextRowInserted = true;\r\n } catch (insertErr) {\r\n await d\r\n .recordRunDiagnostic(\r\n runId,\r\n RUN_DIAG_STAGE.workerSetupStep,\r\n `chain_successor_insert_failed nextRunId=${nextRunId} ${\r\n insertErr instanceof Error ? insertErr.message : String(insertErr)\r\n }`,\r\n )\r\n .catch(() => {});\r\n console.error(\r\n \"[agent-chat] continuation insertRun failed; dispatching with inline body:\",\r\n insertErr instanceof Error ? insertErr.message : insertErr,\r\n );\r\n }\r\n const dispatchBody = nextRowInserted\r\n ? {\r\n internalContinuation: true,\r\n [AGENT_CHAT_BACKGROUND_RUN_FIELD]: {\r\n ...continuationMarker,\r\n payloadRef: true,\r\n },\r\n }\r\n : {\r\n ...continuationBody,\r\n [AGENT_CHAT_BACKGROUND_RUN_FIELD]: continuationMarker,\r\n };\r\n let dispatched = false;\r\n let lastDispatchErr: unknown;\r\n for (\r\n let attempt = 0;\r\n attempt < maxDispatchAttempts && !dispatched;\r\n attempt++\r\n ) {\r\n try {\r\n if (attempt > 0) {\r\n // Uncapped budgets (durable-background and true-foreground) keep\r\n // the original `500 * 2 ** attempt` schedule unchanged. The capped\r\n // budget (proven-in-background-function) instead uses a schedule\r\n // starting at 500ms and doubling per gap, capped at\r\n // `backoffCapMs` — see `resolveContinuationDispatchBudget` for why\r\n // this stays well inside the worker's remaining wall clock even\r\n // with 5 attempts.\r\n const backoffMs = Number.isFinite(dispatchBudget.backoffCapMs)\r\n ? Math.min(500 * 2 ** (attempt - 1), dispatchBudget.backoffCapMs)\r\n : 500 * 2 ** attempt;\r\n await d.sleep(backoffMs);\r\n // Keep the pre-inserted successor row visibly alive while we\r\n // retry: the awaited attempts + backoff can outlast\r\n // UNCLAIMED_BACKGROUND_RUN_GRACE_MS (25s), and without a fresh\r\n // heartbeat the unclaimed-run reaper / sweep could error a handoff\r\n // we are still delivering.\r\n if (nextRowInserted) {\r\n await d.updateRunHeartbeat(nextRunId).catch(() => {});\r\n }\r\n }\r\n await d.fireInternalDispatch({\r\n event: opts.event,\r\n // Durable chain: same path resolution as the initial dispatch —\r\n // on hosted Netlify the background function's DEFAULT url (no\r\n // custom config.path; async via background:true; never shadowed\r\n // because /.netlify/* is excluded from the /* catch-all) so each\r\n // chunk keeps the 15-min budget; off-Netlify the in-process\r\n // framework route. Foreground self-chain: always the framework\r\n // `_process-run` route on the regular function (see the fn doc).\r\n path: continuationDispatchPath,\r\n taskId: nextRunId,\r\n body: dispatchBody,\r\n awaitResponse: true,\r\n responseTimeoutMs: dispatchResponseTimeoutMs,\r\n });\r\n dispatched = true;\r\n } catch (dispatchErr) {\r\n lastDispatchErr = dispatchErr;\r\n // Regular-function targets (foreground self-chain) respond only\r\n // after the successor chunk FINISHES, so an await timeout is not\r\n // proof of a dead handoff. The successor's ATOMIC CLAIM is: a row\r\n // that left `dispatch_mode='background'` (claimed) or is already\r\n // terminal proves the handoff landed — stop retrying. A duplicate\r\n // delivery would lose the claim and no-op anyway; skipping it saves\r\n // wall-clock this close to the invocation deadline.\r\n if (!opts.chainViaDurableBackground && nextRowInserted) {\r\n const claim = await d\r\n .readBackgroundRunClaim(nextRunId)\r\n .catch(() => null);\r\n if (\r\n claim &&\r\n ((claim.dispatchMode && claim.dispatchMode !== \"background\") ||\r\n (claim.status && claim.status !== \"running\"))\r\n ) {\r\n dispatched = true;\r\n break;\r\n }\r\n }\r\n console.error(\r\n `[agent-chat] background continuation dispatch attempt ${attempt + 1} failed:`,\r\n dispatchErr instanceof Error ? dispatchErr.message : dispatchErr,\r\n );\r\n }\r\n }\r\n if (!dispatched) {\r\n // The pre-inserted successor row would otherwise sit unclaimed until\r\n // the sweep reaps it — error it now so the failure is immediate and\r\n // truthful.\r\n if (nextRowInserted) {\r\n const nextStatusUpdated = await d\r\n .updateRunStatusIfRunning(nextRunId, \"errored\")\r\n .catch(() => false);\r\n if (nextStatusUpdated) {\r\n await d\r\n .setRunTerminalReason(\r\n nextRunId,\r\n \"background_continuation_dispatch_failed\",\r\n )\r\n .catch(() => {});\r\n }\r\n }\r\n throw lastDispatchErr instanceof Error\r\n ? lastDispatchErr\r\n : new Error(String(lastDispatchErr));\r\n }\r\n await d\r\n .recordRunDiagnostic(\r\n runId,\r\n RUN_DIAG_STAGE.workerSetupStep,\r\n `chain_dispatch_sent nextRunId=${nextRunId} reason=${continuationReason}`,\r\n )\r\n .catch(() => {});\r\n await d\r\n .markBackgroundContinuationChunkTerminal({\r\n runId,\r\n continuationReason,\r\n })\r\n .catch(() => {});\r\n } catch (chainErr) {\r\n // Chain dispatch failed — fail loud so the held row goes terminal\r\n // instead of spinning. The reaper would also catch it, but this is\r\n // immediate and truthful. (Foreground self-chain: the client still\r\n // receives the terminal auto_continue after this returns, so its\r\n // existing re-POST continuation path takes over.)\r\n await d\r\n .recordRunDiagnostic(\r\n runId,\r\n RUN_DIAG_STAGE.workerThrew,\r\n `chain_dispatch_failed nextRunId=${nextRunId} ${\r\n chainErr instanceof Error ? chainErr.message : String(chainErr)\r\n }`,\r\n )\r\n .catch(() => {});\r\n console.error(\r\n \"[agent-chat] background continuation dispatch failed:\",\r\n chainErr instanceof Error ? chainErr.message : chainErr,\r\n );\r\n const statusUpdated = await d\r\n .updateRunStatusIfRunning(runId, \"errored\")\r\n .catch(() => false);\r\n if (statusUpdated) {\r\n await d\r\n .setRunTerminalReason(runId, \"background_continuation_dispatch_failed\")\r\n .catch(() => {});\r\n }\r\n }\r\n}\r\n\r\nfunction progressStepFromAgentChatEvent(event: AgentChatEvent): string | null {\r\n switch (event.type) {\r\n case \"activity\":\r\n return event.label;\r\n case \"tool_start\":\r\n return `Using ${event.tool}.`;\r\n case \"tool_done\":\r\n return `Finished ${event.tool}.`;\r\n case \"agent_call\":\r\n return event.status === \"start\"\r\n ? `Calling ${event.agent}.`\r\n : event.status === \"done\"\r\n ? `Finished ${event.agent}.`\r\n : `${event.agent} failed.`;\r\n case \"agent_task\":\r\n return event.status === \"running\"\r\n ? \"Started background task.\"\r\n : event.status === \"completed\"\r\n ? \"Background task completed.\"\r\n : \"Background task failed.\";\r\n case \"agent_task_update\":\r\n return event.currentStep || event.preview || \"Background task updated.\";\r\n case \"text\":\r\n return \"Agent is responding.\";\r\n default:\r\n return null;\r\n }\r\n}\r\n\r\nexport function createProductionAgentHandler(\r\n options: ProductionAgentOptions,\r\n): H3EventHandler {\r\n // Undefined = let each engine pick its own defaultModel at request time.\r\n const configuredModel = options.model;\r\n\r\n // Resolve actions — prefer `actions`, fall back to deprecated `scripts`\r\n const resolvedActions = options.actions ?? options.scripts ?? {};\r\n\r\n // Engine tools are derived from the action registry at request time so that\r\n // registries which mutate after handler creation (e.g. MCP servers added via\r\n // the settings UI) show up to the LLM without a process restart. MCP tools\r\n // are also scope-filtered per request — a user-scope server added by Alice\r\n // must not appear in Bob's tool list in a shared-process deployment.\r\n const getEngineTools = (\r\n actions: Record<string, ActionEntry> = resolvedActions,\r\n ) => {\r\n const filtered: Record<string, ActionEntry> = {};\r\n for (const [name, entry] of Object.entries(actions)) {\r\n if (name.startsWith(\"mcp__\") && !isMcpToolAllowedForRequest(name)) {\r\n continue;\r\n }\r\n filtered[name] = entry;\r\n }\r\n return actionsToEngineTools(filtered);\r\n };\r\n\r\n return defineEventHandler(async (event) => {\r\n // Diagnostic-only setup-timing instrumentation. Captures wall-clock offsets\r\n // from handler entry through the work done BEFORE startRun so a slow pre-run\r\n // setup phase is visible in the run diagnostics. Never alters control flow.\r\n const setupT0 = Date.now();\r\n const setupMarks: Record<string, number> = {};\r\n const setupMark = (k: string) => {\r\n setupMarks[k] = Date.now() - setupT0;\r\n };\r\n if (getMethod(event) !== \"POST\") {\r\n setResponseStatus(event, 405);\r\n return { error: \"Method not allowed\" };\r\n }\r\n\r\n let body: AgentChatRequest;\r\n // The durable-background `_process-run` route already consumed and verified\r\n // the request body (h3 v2's web Request body stream is single-use, so a\r\n // second readBody would fail). It stashes the verified+augmented body here\r\n // so this re-entered handler reads it instead of the spent stream.\r\n const preInjectedBody = (event as any)?.context\r\n ?.__agentChatBackgroundBody as AgentChatRequest | undefined;\r\n if (preInjectedBody && typeof preInjectedBody === \"object\") {\r\n body = preInjectedBody;\r\n } else {\r\n try {\r\n body = await readBody(event);\r\n } catch {\r\n setResponseStatus(event, 400);\r\n return { error: \"Invalid request body\" };\r\n }\r\n }\r\n\r\n const {\r\n message,\r\n history = [],\r\n structuredHistory,\r\n references = [],\r\n threadId,\r\n attachments,\r\n displayMessage,\r\n internalContinuation,\r\n turnId: requestTurnId,\r\n model: requestModel,\r\n engine: requestEngine,\r\n effort: requestEffort,\r\n browserTabId,\r\n scope,\r\n trackInRunsTray,\r\n } = body;\r\n setupMark(\"bodyParsed\");\r\n\r\n // Durable-background marker. Present ONLY when this handler was re-entered\r\n // as the Netlify background worker via the `_process-run` self-dispatch\r\n // (the route HMAC-verifies the dispatch before invoking us). When set, we\r\n // run the loop inline with the background soft-timeout, reusing the\r\n // pre-claimed runId/turnId — we must NOT re-claim the slot or re-dispatch.\r\n const backgroundRunMarker =\r\n body[AGENT_CHAT_BACKGROUND_RUN_FIELD] &&\r\n typeof body[AGENT_CHAT_BACKGROUND_RUN_FIELD] === \"object\" &&\r\n typeof body[AGENT_CHAT_BACKGROUND_RUN_FIELD]!.runId === \"string\"\r\n ? body[AGENT_CHAT_BACKGROUND_RUN_FIELD]!\r\n : null;\r\n const isBackgroundWorker = backgroundRunMarker !== null;\r\n // DIAGNOSTIC-ONLY: progressive per-stage hang localizer for the bg worker.\r\n // The worker's runId is available EARLY on the marker (the general `runId`\r\n // var resolves much later), so capture it now and emit the LAST setup stage\r\n // reached as the run's `diag_stage`. Best-effort, gated on the worker, never\r\n // blocks or alters control flow.\r\n const bgRunId = isBackgroundWorker\r\n ? (backgroundRunMarker?.runId as string)\r\n : null;\r\n const workerStep = (s: string) => {\r\n if (bgRunId)\r\n void recordRunDiagnostic(\r\n bgRunId,\r\n RUN_DIAG_STAGE.workerSetupStep,\r\n `${s}=${Date.now() - setupT0}ms`,\r\n ).catch(() => {});\r\n };\r\n // Whether this worker is REALLY executing inside a 15-min Netlify\r\n // `-background` function (proven by the runtime function name), not merely a\r\n // `_process-run` re-entry that may have landed on the ~60s synchronous\r\n // function. Only a true value unlocks the ~13-min soft-timeout budget; a\r\n // worker on the 60s function keeps the 40s clamp and checkpoints cleanly.\r\n const runsInBackgroundFunction =\r\n isBackgroundWorker &&\r\n shouldUseBackgroundFunctionTimeoutForWorker(backgroundRunMarker);\r\n const backgroundRuntimeDetail = isBackgroundWorker\r\n ? backgroundRuntimeDiagnosticDetail(backgroundRunMarker)\r\n : \"\";\r\n // How many server-driven background continuations have already chained into\r\n // this logical turn (0 on the first chunk). Used to bound the chain.\r\n const backgroundContinuationCount =\r\n isBackgroundWorker &&\r\n typeof backgroundRunMarker?.continuationCount === \"number\" &&\r\n Number.isFinite(backgroundRunMarker.continuationCount)\r\n ? Math.max(0, Math.floor(backgroundRunMarker.continuationCount))\r\n : 0;\r\n let backgroundRunClaimedEarly = false;\r\n if (isBackgroundWorker && bgRunId) {\r\n const earlyClaim = await claimBackgroundWorkerRunEarly({\r\n runId: bgRunId,\r\n threadId,\r\n markerTurnId:\r\n typeof backgroundRunMarker?.turnId === \"string\"\r\n ? backgroundRunMarker.turnId\r\n : null,\r\n requestTurnId,\r\n continuationCount: backgroundContinuationCount,\r\n runsInBackgroundFunction,\r\n backgroundRuntimeDetail,\r\n });\r\n if (!earlyClaim.claimed) {\r\n return { ok: true, skipped: earlyClaim.skipped };\r\n }\r\n backgroundRunClaimedEarly = true;\r\n }\r\n // The foreground POST decides whether to dispatch into a background\r\n // function. The background worker itself never re-dispatches.\r\n const dispatchToBackground =\r\n !isBackgroundWorker &&\r\n isAgentChatDurableBackgroundEnabled({\r\n appOptIn: options.durableBackgroundRuns === true,\r\n });\r\n const requestBrowserTabId = normalizeBrowserTabId(browserTabId);\r\n const requestChatScope = normalizeChatScope(scope);\r\n const requestRunCtx = ensureRequestRunContext();\r\n if (requestRunCtx) {\r\n requestRunCtx.browserTabId = requestBrowserTabId;\r\n requestRunCtx.chatScope = requestChatScope;\r\n // Let template extraContext / system-prompt builders detect the durable\r\n // background worker so they can skip heavy hang-prone enrichment (e.g. the\r\n // analytics data-dictionary read) that otherwise stalls the worker before\r\n // it claims its run. Set early — before the system-prompt build runs.\r\n requestRunCtx.isBackgroundWorker = isBackgroundWorker;\r\n }\r\n const requestMode: AgentExecutionMode =\r\n body.mode === \"plan\" ? \"plan\" : \"act\";\r\n const hasMessageText =\r\n typeof message === \"string\" && message.trim().length > 0;\r\n const hasAttachments = Array.isArray(attachments) && attachments.length > 0;\r\n if (!hasMessageText && !hasAttachments) {\r\n setResponseStatus(event, 400);\r\n return { error: \"message is required\" };\r\n }\r\n let requestMessage = hasMessageText ? message : \"Use the attached context.\";\r\n let requestAttachments = Array.isArray(attachments) ? attachments : [];\r\n let requestDisplayMessage = displayMessage;\r\n\r\n // Resolve owner first so we can look up a per-owner API key. Users\r\n // who bring their own key use their key for this request (durable\r\n // across serverless cold starts via the settings table).\r\n const ownerEmail = await resolveAgentOwnerEmail(options, event);\r\n const preparedRequest = await options.prepareRequest?.({\r\n event,\r\n ownerEmail,\r\n message: requestMessage,\r\n displayMessage: requestDisplayMessage,\r\n attachments: requestAttachments,\r\n references,\r\n threadId,\r\n internalContinuation: Boolean(internalContinuation),\r\n mode: requestMode,\r\n });\r\n if (preparedRequest) {\r\n if (\r\n typeof preparedRequest.message === \"string\" &&\r\n preparedRequest.message.trim().length > 0\r\n ) {\r\n requestMessage = preparedRequest.message;\r\n }\r\n if (typeof preparedRequest.displayMessage === \"string\") {\r\n requestDisplayMessage = preparedRequest.displayMessage;\r\n }\r\n if (Array.isArray(preparedRequest.attachments)) {\r\n requestAttachments = preparedRequest.attachments;\r\n }\r\n }\r\n // DIAGNOSTIC-ONLY: owner/request context prep (resolveAgentOwnerEmail +\r\n // prepareRequest) finished. A worker stuck before this points at the\r\n // owner/request-context awaits.\r\n workerStep(\"db_request_ctx\");\r\n\r\n // DIAGNOSTIC-ONLY: bracket attachment upload + text-attachment persistence.\r\n workerStep(\"attach_start\");\r\n // Pre-upload chat attachments (images AND files/PDFs) through the framework\r\n // file-upload provider (Builder.io by default). The model still sees the\r\n // base64 multimodal content for the current turn; each uploaded attachment\r\n // also gets a hosted `url` injected so the agent can embed it in slides,\r\n // docs, or outbound messages, and callers can persist a URL reference\r\n // instead of the raw base64.\r\n //\r\n // When no provider is configured, leave attachments untouched and inject a\r\n // hint recommending Builder.io connect — the model can still see images via\r\n // base64, and files via their data URL / text, but has no hosted URL.\r\n if (\r\n hasAttachments &&\r\n requestAttachments.some(\r\n (a) => a.type === \"image\" || a.type === \"file\" || a.type === \"document\",\r\n )\r\n ) {\r\n try {\r\n const preUpload = await preUploadAttachments({\r\n attachments: requestAttachments,\r\n ownerEmail,\r\n includeFiles: true,\r\n });\r\n if (preUpload.injectedText) {\r\n requestMessage = requestMessage\r\n ? `${requestMessage}\\n\\n${preUpload.injectedText}`\r\n : preUpload.injectedText;\r\n }\r\n } catch (err) {\r\n console.warn(\r\n \"[agent-native] preUploadAttachments failed:\",\r\n err instanceof Error ? err.message : String(err),\r\n );\r\n }\r\n }\r\n\r\n // Persist text-ish attachments as thread-scoped agent_scratch resources so\r\n // the model can page through them with the `read-attachment` tool. We do\r\n // this here — before buildUserContentWithAttachments — so the resource IDs\r\n // are available when we inject the truncation notice into the text content.\r\n const textAttachmentResourceMap = new Map<\r\n number,\r\n { resourceId: string; path: string; totalChars: number }\r\n >();\r\n if (hasAttachments && threadId) {\r\n try {\r\n const { persistTextAttachmentsAsResources } =\r\n await import(\"../server/attachment-actions.js\");\r\n const stored = await persistTextAttachmentsAsResources({\r\n attachments: requestAttachments,\r\n threadId,\r\n ownerEmail,\r\n });\r\n for (const [k, v] of stored) {\r\n textAttachmentResourceMap.set(k, v);\r\n }\r\n } catch (err) {\r\n console.warn(\r\n \"[agent-native] persistTextAttachmentsAsResources failed:\",\r\n err instanceof Error ? err.message : String(err),\r\n );\r\n }\r\n }\r\n // DIAGNOSTIC-ONLY: attachment upload + persistence finished.\r\n workerStep(\"attach_done\");\r\n\r\n // When a per-request engine override is specified, resolve the API key\r\n // for that provider instead of the global active engine's provider.\r\n // DIAGNOSTIC-ONLY: bracket per-owner API-key resolution (settings/app_secrets reads).\r\n workerStep(\"apikey_start\");\r\n let userApiKey: string | undefined;\r\n if (requestEngine) {\r\n const provider = engineToProvider(requestEngine);\r\n userApiKey = await getOwnerApiKey(provider, ownerEmail);\r\n const envVar = PROVIDER_TO_ENV[provider];\r\n if (\r\n !userApiKey &&\r\n envVar &&\r\n canUseDeployCredentialFallbackForRequest(envVar)\r\n ) {\r\n // Read-only env fallback for the requested provider.\r\n userApiKey = envVar ? readDeployCredentialEnv(envVar) : undefined;\r\n }\r\n } else {\r\n userApiKey = await getOwnerActiveApiKey(ownerEmail);\r\n }\r\n // DIAGNOSTIC-ONLY: API-key resolution finished.\r\n workerStep(\"apikey_done\");\r\n\r\n // `options.apiKey` is the value the template constructed the plugin with\r\n // (often wired from a deployment env var). Honor it as host-provided\r\n // read-only configuration after scoped keys when deploy fallback is safe.\r\n const hostApiKey = canUseDeployCredentialFallbackForRequest(\r\n \"ANTHROPIC_API_KEY\",\r\n )\r\n ? (options.apiKey ?? readDeployCredentialEnv(\"ANTHROPIC_API_KEY\"))\r\n : undefined;\r\n const effectiveApiKey = userApiKey ?? hostApiKey;\r\n\r\n // Resolve engine — per-request engine override takes priority\r\n // DIAGNOSTIC-ONLY: bracket engine resolution (Builder credential / app-default\r\n // settings reads inside resolveEngine).\r\n workerStep(\"engine_start\");\r\n let engine: AgentEngine;\r\n try {\r\n engine = await resolveEngine({\r\n engineOption: requestEngine ?? options.engine,\r\n apiKey: effectiveApiKey,\r\n model: configuredModel,\r\n appId: options.appId,\r\n });\r\n } catch {\r\n engine = await resolveEngine({\r\n apiKey: effectiveApiKey,\r\n appId: options.appId,\r\n });\r\n }\r\n // DIAGNOSTIC-ONLY: engine resolution finished.\r\n workerStep(\"engine_done\");\r\n\r\n // Honor the model the user picked in the settings UI (written via\r\n // `manage-agent-engine` action=\"set\"), but only when the caller hasn't overridden it for\r\n // this request or at plugin construction time. Read per-request so a\r\n // dropdown change in the UI takes effect without a server restart. Skip\r\n // the DB read entirely when a higher-precedence value is set.\r\n // DIAGNOSTIC-ONLY: bracket stored-model resolution (getStoredModelForEngine\r\n // settings read).\r\n workerStep(\"model_start\");\r\n const modelCandidate =\r\n requestModel ??\r\n configuredModel ??\r\n (await getStoredModelForEngine(engine, { appId: options.appId })) ??\r\n engine.defaultModel;\r\n // DIAGNOSTIC-ONLY: stored-model resolution finished.\r\n workerStep(\"model_done\");\r\n const model = normalizeModelForEngine(engine, modelCandidate);\r\n const reasoningEffort = normalizeReasoningEffortForModel(\r\n model,\r\n isReasoningEffort(requestEffort)\r\n ? requestEffort\r\n : options.reasoningEffort,\r\n );\r\n\r\n options.onEngineResolved?.(engine, model);\r\n\r\n // One-line per-turn resolution log so it's obvious in dev which engine\r\n // is actually handling the request. `requestEngine` is what the client\r\n // sent from the model picker; `engine.name` is what resolveEngine picked.\r\n // Divergence between them is the usual cause of \"status says builder but\r\n // no [builder-engine] log lines appear\" confusion.\r\n console.log(\r\n `[agent-chat] resolved engine=${engine.name} model=${model} requestEngine=${requestEngine ?? \"(none)\"}`,\r\n );\r\n\r\n if (\r\n !(await isResolvedEngineUsableForRequest(engine, {\r\n apiKey: effectiveApiKey,\r\n }))\r\n ) {\r\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\r\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\r\n setResponseHeader(event, \"Connection\", \"keep-alive\");\r\n const encoder = new TextEncoder();\r\n return new ReadableStream({\r\n start(controller) {\r\n controller.enqueue(\r\n encoder.encode(\r\n `data: ${JSON.stringify({\r\n type: \"error\",\r\n error: LLM_MISSING_CREDENTIALS_MESSAGE,\r\n errorCode: LLM_MISSING_CREDENTIALS_ERROR_CODE,\r\n })}\\n\\n`,\r\n ),\r\n );\r\n controller.close();\r\n },\r\n });\r\n }\r\n\r\n setupMark(\"prepDone\");\r\n // DIAGNOSTIC-ONLY: engine/model/api-key resolution finished. A worker that\r\n // reached db_request_ctx but not env_config hung in attachment upload or\r\n // engine/model resolution.\r\n workerStep(\"env_config\");\r\n // Run all independent pre-send steps in parallel. Each of these hits\r\n // the DB or invokes an action; running them sequentially was the\r\n // single biggest contributor to pre-LLM latency.\r\n const enrichedMessageThunk = () =>\r\n enrichMessage(requestMessage, references);\r\n const loopSettingsThunk = () =>\r\n readAgentLoopSettings({\r\n userEmail: ownerEmail ?? getRequestUserEmail() ?? null,\r\n orgId: getRequestOrgId() ?? null,\r\n }).catch(() => readAgentLoopSettings({}));\r\n\r\n let systemPromptError: any = null;\r\n const systemPromptThunk = (): Promise<string> =>\r\n (async (): Promise<string> => {\r\n const sysPromptStart = Date.now();\r\n try {\r\n const built =\r\n typeof options.systemPrompt === \"function\"\r\n ? await options.systemPrompt(event)\r\n : options.systemPrompt;\r\n return built;\r\n } catch (error) {\r\n systemPromptError = error;\r\n return \"\";\r\n } finally {\r\n setupMarks.sysPromptMs = Date.now() - sysPromptStart;\r\n }\r\n })();\r\n\r\n // Precise current time is volatile (changes every request) and must never\r\n // live in the cached system-prompt prefix — see buildRuntimeContextPrompt\r\n // in runtime-context.ts. It is injected here, per-turn, into the user\r\n // message instead, following the same pattern as the screen/url/selection\r\n // context below. This keeps \"what time is it\" answerable while leaving\r\n // the system prompt's runtime-context block stable at day granularity.\r\n const timeContextThunk = (): Promise<string> =>\r\n (async (): Promise<string> => {\r\n try {\r\n const tzRaw = getHeader(event, \"x-user-timezone\");\r\n const timezone =\r\n typeof tzRaw === \"string\" &&\r\n tzRaw.trim().length > 0 &&\r\n tzRaw.trim().length < 64\r\n ? tzRaw.trim()\r\n : undefined;\r\n return buildCurrentTimeUserContext({ timezone });\r\n } catch {\r\n return buildCurrentTimeUserContext();\r\n }\r\n })();\r\n\r\n const screenContextThunk = (): Promise<string> =>\r\n (async (): Promise<string> => {\r\n const screenStart = Date.now();\r\n try {\r\n const viewScreenAction = resolvedActions[\"view-screen\"];\r\n if (viewScreenAction) {\r\n const result = await viewScreenAction.run(\r\n {},\r\n {\r\n userEmail: getRequestUserEmail(),\r\n orgId: getRequestOrgId() ?? null,\r\n caller: \"tool\",\r\n },\r\n );\r\n if (result && result !== \"(no output)\") {\r\n const screenText =\r\n typeof result === \"string\"\r\n ? result\r\n : JSON.stringify(result, null, 2);\r\n return `\\n\\n<current-screen>\\n${capScreenContext(screenText)}\\n</current-screen>`;\r\n }\r\n } else {\r\n const navigation = await readAppStateForBrowserTab(\r\n \"navigation\",\r\n requestBrowserTabId,\r\n );\r\n if (navigation) {\r\n return `\\n\\n<current-screen>\\n${capScreenContext(JSON.stringify(navigation, null, 2))}\\n</current-screen>`;\r\n }\r\n }\r\n } catch {\r\n // DB not ready or no navigation state — skip silently\r\n } finally {\r\n setupMarks.screenMs = Date.now() - screenStart;\r\n }\r\n return \"\";\r\n })();\r\n\r\n const urlContextThunk = (): Promise<string> =>\r\n (async (): Promise<string> => {\r\n try {\r\n const url = (await readAppStateForBrowserTab(\r\n \"__url__\",\r\n requestBrowserTabId,\r\n )) as {\r\n pathname?: string;\r\n search?: string;\r\n hash?: string;\r\n searchParams?: Record<string, string>;\r\n } | null;\r\n if (url && (url.pathname || url.search || url.hash)) {\r\n const lines: string[] = [];\r\n if (url.pathname) lines.push(`pathname: ${url.pathname}`);\r\n const extensionId = url.pathname\r\n ? extensionIdFromPathname(url.pathname)\r\n : null;\r\n if (extensionId) lines.push(`extensionId: ${extensionId}`);\r\n if (url.search) lines.push(`search: ${url.search}`);\r\n if (url.hash) lines.push(`hash: ${url.hash}`);\r\n if (url.searchParams && Object.keys(url.searchParams).length > 0) {\r\n lines.push(\"searchParams:\");\r\n for (const [k, v] of Object.entries(url.searchParams)) {\r\n lines.push(` ${k}: ${v}`);\r\n }\r\n }\r\n return `\\n\\n<current-url>\\n${lines.join(\"\\n\")}\\n</current-url>`;\r\n }\r\n } catch {\r\n // DB not ready — skip silently\r\n }\r\n return \"\";\r\n })();\r\n\r\n // Selection context: written by the client when the user presses Cmd+I\r\n // with text selected on the page. Treat anything older than 5 minutes\r\n // as stale and ignore it.\r\n const SELECTION_TTL_MS = 5 * 60 * 1000;\r\n const selectionContextThunk = (): Promise<string> =>\r\n (async (): Promise<string> => {\r\n try {\r\n const sel = (await readAppState(\"pending-selection-context\")) as {\r\n text?: string;\r\n capturedAt?: number;\r\n } | null;\r\n if (!sel?.text) return \"\";\r\n const capturedAt =\r\n typeof sel.capturedAt === \"number\" ? sel.capturedAt : 0;\r\n if (Date.now() - capturedAt > SELECTION_TTL_MS) return \"\";\r\n return (\r\n `\\n\\nThe user has selected the following text and pressed Cmd+I to focus the agent. ` +\r\n `Treat this as the immediate context to act on:\\n` +\r\n `<selection>\\n${capSelectionContext(sel.text)}\\n</selection>`\r\n );\r\n } catch {\r\n // DB not ready — skip silently\r\n }\r\n return \"\";\r\n })();\r\n\r\n // On the first message of a conversation, inject workspace inventory\r\n // so the agent knows what files, skills, jobs, and custom agents exist.\r\n // Templates can opt out via `skipFilesContext: true` when the inventory\r\n // is unrelated to the app's job (e.g. a voice-first macro tracker).\r\n const filesContextThunk = (): Promise<string> =>\r\n (async (): Promise<string> => {\r\n let filesContext = \"\";\r\n if (options.skipFilesContext) return filesContext;\r\n if (history.length === 0) {\r\n try {\r\n const {\r\n resourceListAccessible,\r\n SHARED_OWNER,\r\n WORKSPACE_OWNER,\r\n resourceGet,\r\n } = await import(\"../resources/store.js\");\r\n const {\r\n getResourceKind,\r\n parseCustomAgentProfile,\r\n parseRemoteAgentManifest,\r\n parseSkillMetadata,\r\n } = await import(\"../resources/metadata.js\");\r\n const ownerEmail = getRequestUserEmail();\r\n const orgId = getRequestOrgId();\r\n if (!ownerEmail) throw new Error(\"no authenticated user\");\r\n const allResources = await resourceListAccessible(\r\n ownerEmail,\r\n undefined,\r\n { userEmail: ownerEmail, orgId },\r\n );\r\n\r\n if (allResources.length > 0) {\r\n const fileLines: string[] = [];\r\n const skillLines: string[] = [];\r\n const agentLines: string[] = [];\r\n const jobLines: string[] = [];\r\n for (const r of allResources) {\r\n const scope =\r\n r.owner === WORKSPACE_OWNER\r\n ? \"workspace\"\r\n : r.owner === SHARED_OWNER\r\n ? \"shared\"\r\n : \"personal\";\r\n const kind = getResourceKind(r.path);\r\n if (kind === \"file\") {\r\n fileLines.push(` ${r.path} (${scope})`);\r\n continue;\r\n }\r\n\r\n if (kind === \"job\") {\r\n jobLines.push(` ${r.path} (${scope})`);\r\n continue;\r\n }\r\n\r\n if (\r\n kind === \"skill\" ||\r\n kind === \"agent\" ||\r\n kind === \"remote-agent\"\r\n ) {\r\n const full = await resourceGet(r.id, {\r\n userEmail: ownerEmail,\r\n orgId,\r\n });\r\n if (!full) continue;\r\n if (kind === \"skill\") {\r\n const skill = parseSkillMetadata(full.content, r.path);\r\n skillLines.push(\r\n ` ${skill?.name || r.path} — ${compactInventoryDescription(skill?.description || r.path)} (${scope}, ${r.path})`,\r\n );\r\n } else if (kind === \"agent\") {\r\n const agent = parseCustomAgentProfile(full.content, r.path);\r\n agentLines.push(\r\n ` ${agent?.name || r.path} — ${compactInventoryDescription(agent?.description || \"Custom workspace agent\")} (${scope}, ${r.path}${agent?.model ? `, model: ${agent.model}` : \"\"})`,\r\n );\r\n } else {\r\n const agent = parseRemoteAgentManifest(\r\n full.content,\r\n r.path,\r\n );\r\n agentLines.push(\r\n ` ${agent?.name || r.path} — ${compactInventoryDescription(agent?.description || \"Connected A2A agent\")} (${scope}, remote via ${r.path})`,\r\n );\r\n }\r\n }\r\n }\r\n const blocks: string[] = [];\r\n if (fileLines.length > 0) {\r\n const lines = limitInventoryLines(fileLines, \"files\");\r\n blocks.push(\r\n `<available-files>\\nFiles in the workspace:\\n${lines.join(\"\\n\")}\\n\\nTo read a resource file's contents, use the resources tool with action \"read\" and the file path.\\n</available-files>`,\r\n );\r\n }\r\n if (skillLines.length > 0) {\r\n const lines = limitInventoryLines(skillLines, \"skills\");\r\n blocks.push(\r\n `<available-skills>\\nSkills in the workspace:\\n${lines.join(\"\\n\")}\\n\\nBefore using a matching workspace skill, read its path with the resources tool using action \"read\"; slash-selected skills are inlined automatically when available.\\n</available-skills>`,\r\n );\r\n }\r\n if (agentLines.length > 0) {\r\n const lines = limitInventoryLines(agentLines, \"agents\");\r\n blocks.push(\r\n `<available-agents>\\nCustom and connected agents in the workspace:\\n${lines.join(\"\\n\")}\\n\\nCustom agents under agents/*.md can be mentioned or used via agent-teams (action: \"spawn\") with the agent parameter.\\n</available-agents>`,\r\n );\r\n }\r\n if (jobLines.length > 0) {\r\n const lines = limitInventoryLines(jobLines, \"jobs\");\r\n blocks.push(\r\n `<available-jobs>\\nScheduled tasks in the workspace:\\n${lines.join(\"\\n\")}\\n</available-jobs>`,\r\n );\r\n }\r\n filesContext =\r\n blocks.length > 0 ? `\\n\\n${blocks.join(\"\\n\\n\")}` : \"\";\r\n }\r\n } catch {\r\n // Resources not available — skip silently\r\n }\r\n }\r\n return filesContext;\r\n })();\r\n\r\n // Durable bg worker: a pre-send step that HANGS (rather than erroring) would\r\n // otherwise stall the worker until the foreground inline-recovery grace\r\n // (~16s) — wasting the entire 15-min durable budget and leaving the run\r\n // un-claimed (the exact analytics symptom: diag stuck at model_done,\r\n // preStart≈18s). `presendCap` takes a THUNK (not an eagerly-started promise):\r\n // the work runs INSIDE the cap, after the timer is armed, so a step whose\r\n // own synchronous prefix is heavy can still be timed out — an eagerly-created\r\n // promise would start (and could block the loop) before the cap ever wrapped\r\n // it. On timeout it records `presend_timeout:<label>` so a stalled phase is\r\n // attributable, then degrades to the fallback so the worker proceeds to\r\n // claim. Foreground keeps the un-capped path (thunk invoked immediately), so\r\n // its behaviour is unchanged. A rejected step (e.g. enrichMessage has no\r\n // .catch) resolves to the fallback instead of rejecting the whole batch.\r\n const presendCap = <T>(\r\n label: string,\r\n thunk: () => Promise<T>,\r\n fallback: T,\r\n ms: number,\r\n ): Promise<T> => {\r\n if (!isBackgroundWorker) return thunk();\r\n return new Promise<T>((resolve) => {\r\n const timer = setTimeout(() => {\r\n workerStep(`presend_timeout:${label}`);\r\n resolve(fallback);\r\n }, ms);\r\n // Defer invocation one microtask so every sibling cap arms its timer\r\n // before any thunk's synchronous prefix runs.\r\n void Promise.resolve()\r\n .then(thunk)\r\n .then(\r\n (v) => {\r\n clearTimeout(timer);\r\n resolve(v);\r\n },\r\n () => {\r\n clearTimeout(timer);\r\n resolve(fallback);\r\n },\r\n );\r\n });\r\n };\r\n const fallbackLoopSettings: AgentLoopSettings = {\r\n maxIterations: getDefaultMaxIterations(),\r\n defaultMaxIterations: getDefaultMaxIterations(),\r\n minMaxIterations: MIN_AGENT_MAX_ITERATIONS,\r\n maxMaxIterations: MAX_AGENT_MAX_ITERATIONS,\r\n scope: \"default\",\r\n source: \"default\",\r\n };\r\n const [\r\n systemPrompt,\r\n timeBlock,\r\n screenBlock,\r\n urlBlock,\r\n selectionBlock,\r\n filesContext,\r\n loopSettings,\r\n enrichedMessage,\r\n ] = await Promise.all([\r\n presendCap(\"systemPrompt\", systemPromptThunk, \"\", 13000),\r\n presendCap(\"time\", timeContextThunk, \"\", 9000),\r\n presendCap(\"screen\", screenContextThunk, \"\", 9000),\r\n presendCap(\"url\", urlContextThunk, \"\", 9000),\r\n presendCap(\"selection\", selectionContextThunk, \"\", 9000),\r\n presendCap(\"files\", filesContextThunk, \"\", 12000),\r\n presendCap(\"loopSettings\", loopSettingsThunk, fallbackLoopSettings, 9000),\r\n presendCap(\"enrichedMessage\", enrichedMessageThunk, requestMessage, 9000),\r\n ]);\r\n setupMark(\"ctxAll\");\r\n // DIAGNOSTIC-ONLY: all parallel context gathering (system prompt, screen,\r\n // files, loop settings, enriched message) resolved.\r\n workerStep(\"context_all\");\r\n\r\n if (systemPromptError) {\r\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\r\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\r\n const encoder = new TextEncoder();\r\n const err = systemPromptError;\r\n return new ReadableStream({\r\n start(controller) {\r\n controller.enqueue(\r\n encoder.encode(\r\n `data: ${JSON.stringify({ type: \"error\", error: `Failed to load system prompt: ${err?.message ?? String(err)}` })}\\n\\n`,\r\n ),\r\n );\r\n controller.close();\r\n },\r\n });\r\n }\r\n const screenContext = timeBlock + screenBlock + urlBlock + selectionBlock;\r\n const requestActions =\r\n requestMode === \"plan\"\r\n ? createPlanModeActionRegistry(resolvedActions)\r\n : resolvedActions;\r\n const availableRequestTools = getEngineTools(requestActions);\r\n const requestTools = filterInitialEngineTools(\r\n availableRequestTools,\r\n options.initialToolNames,\r\n );\r\n setupMark(\"actions\");\r\n // DIAGNOSTIC-ONLY: action/tool resolution + engine-tool filtering finished.\r\n workerStep(\"action_tool_setup\");\r\n const requestSystemPrompt =\r\n requestMode === \"plan\"\r\n ? `${systemPrompt}\\n\\n${PLAN_MODE_SYSTEM_PROMPT}`\r\n : systemPrompt;\r\n\r\n // Pre-compute agent references for A2A resolution inside the run\r\n const agentRefs = references.filter((r) => r.type === \"agent\");\r\n const customAgentRefs = references.filter((r) => r.type === \"custom-agent\");\r\n const planModeAgentNote =\r\n requestMode === \"plan\" && agentRefs.length > 0\r\n ? \"\\n\\n<plan-mode-note>Connected external agent mentions were not called because Plan mode is read-only. Mention that they can be called after the user switches to Act mode if the plan needs them.</plan-mode-note>\"\r\n : \"\";\r\n\r\n const userContent = buildUserContentWithAttachments({\r\n text: enrichedMessage + screenContext + filesContext + planModeAgentNote,\r\n attachments: requestAttachments,\r\n });\r\n\r\n const historyMessages =\r\n structuredHistoryToEngineMessages(structuredHistory) ??\r\n history\r\n .filter((m) => m.content.trim())\r\n .map(\r\n (m): EngineMessage => ({\r\n role: m.role as \"user\" | \"assistant\",\r\n content: [{ type: \"text\" as const, text: m.content }],\r\n }),\r\n );\r\n\r\n const messages: EngineMessage[] = [\r\n ...historyMessages,\r\n { role: \"user\" as const, content: userContent },\r\n ];\r\n\r\n // Atomically claim the run slot for this thread. The claim checks SQL for\r\n // a live (non-stale) running row so two near-simultaneous POSTs on\r\n // different serverless isolates both see the correct state — a plain\r\n // read-then-act check races on multi-isolate deployments because both\r\n // reads see no running row before either insert commits.\r\n //\r\n // The background worker SKIPS this: the foreground POST already claimed the\r\n // slot and inserted the run row before dispatching, so re-claiming here\r\n // would falsely 409 against the row the foreground holds.\r\n if (threadId && !isBackgroundWorker) {\r\n const slot = await tryClaimRunSlot(threadId);\r\n if (!slot.claimed) {\r\n setResponseStatus(event, 409);\r\n return {\r\n error: \"Run already in progress for this thread\",\r\n activeRunId: slot.activeRunId,\r\n };\r\n }\r\n }\r\n\r\n // Start agent loop in background via run-manager. The background worker\r\n // reuses the runId carried in the marker (signed into the dispatch token):\r\n // - First background chunk (count 0): the foreground generated + INSERTED\r\n // this runId, so the event stream the client is already subscribed to is\r\n // the one we write to.\r\n // - Chained continuation chunk (count > 0): the prior chunk minted a FRESH\r\n // runId for this one (a reused runId would restart `startRun`'s in-memory\r\n // seq log at 0 and collide with the prior chunk's persisted seqs, which\r\n // insertRunEvent's ON CONFLICT would drop — making the continuation\r\n // invisible). A fresh runId on the SAME thread + SAME turnId folds onto\r\n // one assistant message and is surfaced by the existing\r\n // `/runs/active?threadId` reconnect path. The continuation worker inserts\r\n // its own background row below (the foreground only inserted chunk-0's).\r\n const isChainedBackgroundContinuation =\r\n isBackgroundWorker && backgroundContinuationCount > 0;\r\n const runId = backgroundRunMarker?.runId ?? generateRunId();\r\n const effectiveThreadId = threadId ?? runId;\r\n const effectiveTurnId =\r\n typeof backgroundRunMarker?.turnId === \"string\" &&\r\n backgroundRunMarker.turnId.trim()\r\n ? backgroundRunMarker.turnId.trim()\r\n : typeof requestTurnId === \"string\" && requestTurnId.trim()\r\n ? requestTurnId.trim()\r\n : runId;\r\n const messageToPersist =\r\n typeof requestDisplayMessage === \"string\" &&\r\n requestDisplayMessage.trim().length > 0\r\n ? requestDisplayMessage\r\n : requestMessage;\r\n\r\n // Server-driven background continuation: when the background worker re-fired\r\n // itself at a soft-timeout boundary (a chained continuation chunk), rebuild\r\n // the conversation from the persisted thread_data so the next chunk resumes\r\n // from committed progress instead of restarting from the original user\r\n // message (which would re-do work — the re-hydration thrash the design doc\r\n // calls out). Mirrors the agent-teams continuation, which seeds from\r\n // thread_data + appends a continuation nudge. Falls back to the body-derived\r\n // `messages` if thread_data is empty/unreadable — a continuation that\r\n // restarts is worse than one that resumes, but both are correct.\r\n if (isChainedBackgroundContinuation && effectiveThreadId) {\r\n try {\r\n const { getThread } = await import(\"../chat-threads/store.js\");\r\n const { threadDataToEngineMessages } =\r\n await import(\"./thread-data-builder.js\");\r\n const priorThreadData = (await getThread(effectiveThreadId))\r\n ?.threadData;\r\n const resumed = threadDataToEngineMessages(priorThreadData);\r\n if (resumed.length > 0) {\r\n const actionPreparationTool =\r\n typeof backgroundRunMarker?.actionPreparationTool === \"string\" &&\r\n backgroundRunMarker.actionPreparationTool.trim()\r\n ? backgroundRunMarker.actionPreparationTool.trim()\r\n : undefined;\r\n const continuationReason = isAgentLoopContinuationReason(\r\n backgroundRunMarker?.continuationReason,\r\n )\r\n ? backgroundRunMarker.continuationReason\r\n : \"run_timeout\";\r\n appendAgentLoopContinuation(resumed, continuationReason, {\r\n ...(actionPreparationTool ? { actionPreparationTool } : {}),\r\n });\r\n messages.length = 0;\r\n messages.push(...resumed);\r\n }\r\n } catch {\r\n // Keep the body-derived messages — never drop the run.\r\n }\r\n }\r\n setupMark(\"depsThread\");\r\n // DIAGNOSTIC-ONLY: owner/thread resolution + runId/effectiveThreadId +\r\n // chained-continuation thread fetch finished.\r\n workerStep(\"owner_thread\");\r\n\r\n // Persist the user's turn exactly once. The foreground POST does this\r\n // before dispatching; the background worker must NOT repeat it (it re-enters\r\n // with the same body, which would double-persist the user message).\r\n if (options.onRunPrepared && !internalContinuation && !isBackgroundWorker) {\r\n await options.onRunPrepared({\r\n runId,\r\n threadId,\r\n message: messageToPersist,\r\n attachments: requestAttachments,\r\n });\r\n }\r\n\r\n // ─── Durable-background dispatch decision ──────────────────────────────\r\n // Flag active (hosted + A2A_SECRET + AGENT_CHAT_DURABLE_BACKGROUND) and we\r\n // are the FOREGROUND POST: insert the run row (marked background), fire an\r\n // HMAC-signed self-dispatch into the Netlify background function (15-min\r\n // budget), and return the SSE subscription immediately. The client streams\r\n // the same events via the cross-isolate SQL-poll path with no client\r\n // change. With the flag OFF this whole branch is skipped and the inline\r\n // `startRun` path below runs exactly as before (byte-for-byte).\r\n if (dispatchToBackground) {\r\n let backgroundRowInserted = false;\r\n try {\r\n // Insert the run row up front so /runs/active sees it immediately and\r\n // the slot stays held while the background function cold-starts. Mark\r\n // it background-dispatched so the stale reaper uses the wider window.\r\n // The full request body is persisted ON the row (dispatch_payload) so\r\n // the self-POST below can carry only the tiny marker — Netlify caps\r\n // background-function request bodies at 256KB, and a large chat\r\n // history (inline attachments especially) silently exceeded that.\r\n await insertRun(runId, effectiveThreadId, effectiveTurnId, {\r\n dispatchMode: \"background\",\r\n dispatchPayload: JSON.stringify(body),\r\n });\r\n backgroundRowInserted = true;\r\n } catch (err) {\r\n // A duplicate-PK collision means the row already exists (ret­ried POST);\r\n // any other failure means we can't safely hand off — fall back to the\r\n // inline path rather than dropping the turn.\r\n console.error(\r\n \"[agent-chat] background insertRun failed; falling back to inline:\",\r\n err instanceof Error ? err.message : err,\r\n );\r\n }\r\n\r\n let dispatched = false;\r\n const backgroundDispatchPath = resolveAgentChatProcessRunDispatchPath();\r\n const expectsNetlifyBackgroundFunction =\r\n dispatchPathTargetsNetlifyBackgroundFunction(backgroundDispatchPath);\r\n try {\r\n await fireInternalDispatch({\r\n event,\r\n // On hosted Netlify this resolves to the background function's DEFAULT\r\n // url (/.netlify/functions/<name>, or per-app <app>-agent-background for\r\n // workspaces) — the function declares NO custom config.path, so it keeps\r\n // its default url, and `background: true` makes that url async (202,\r\n // 15-min budget). The `server` /* catch-all already excludes /.netlify/*\r\n // so it never shadows it. Off-Netlify this resolves to the framework\r\n // `_process-run` route and the same in-process catch-all handles it\r\n // inline. `fireInternalDispatch` strips the app base path for\r\n // /.netlify/* targets so the request reaches the host-root function url;\r\n // the Authorization Bearer HMAC is preserved either way.\r\n path: backgroundDispatchPath,\r\n taskId: runId,\r\n // When the row (and its persisted payload) landed, send only the\r\n // marker — the worker rehydrates the body from dispatch_payload\r\n // (`payloadRef`), keeping the self-POST far under Netlify's 256KB\r\n // background-function body cap. If the insert failed we fall back to\r\n // carrying the full body inline, exactly as before.\r\n body: backgroundRowInserted\r\n ? {\r\n [AGENT_CHAT_BACKGROUND_RUN_FIELD]: {\r\n runId,\r\n turnId: effectiveTurnId,\r\n backgroundFunctionRuntimeExpected:\r\n expectsNetlifyBackgroundFunction,\r\n payloadRef: true,\r\n },\r\n }\r\n : {\r\n ...body,\r\n // Carry the pre-claimed identity so the worker reuses this run.\r\n [AGENT_CHAT_BACKGROUND_RUN_FIELD]: {\r\n runId,\r\n turnId: effectiveTurnId,\r\n backgroundFunctionRuntimeExpected:\r\n expectsNetlifyBackgroundFunction,\r\n },\r\n },\r\n });\r\n dispatched = true;\r\n } catch (err) {\r\n console.error(\r\n \"[agent-chat] background dispatch failed; falling back to inline:\",\r\n err instanceof Error ? err.message : err,\r\n );\r\n }\r\n\r\n // ─── Circuit-breaker: a 202 only ENQUEUES the background invocation ─────\r\n // It is NOT proof the worker executed. If the generated background-function\r\n // wrapper fails to import `./main.mjs` or hand off to the Nitro\r\n // `_process-run` route, the worker never reaches `claimBackgroundRun`: the\r\n // row sits at `dispatch_mode='background'` until the reaper errors it\r\n // (\"worker never claimed the run\"). `resolveBackgroundDispatchOutcome`\r\n // polls briefly for the claim and decides:\r\n // - \"stream\": a worker claimed the run → subscribe to it.\r\n // - \"subscribe\": a (delayed) worker already owns it → subscribe, NEVER\r\n // run a second copy.\r\n // - \"inline\": dispatch failed OR no worker claimed within grace → we\r\n // atomically own the run; recover by running it inline so a\r\n // dead worker degrades to a working synchronous turn.\r\n const backgroundOutcome = await resolveBackgroundDispatchOutcome({\r\n dispatched,\r\n backgroundRowInserted,\r\n runId,\r\n graceMs: BACKGROUND_CLAIM_GRACE_MS,\r\n reaperGraceMs: UNCLAIMED_BACKGROUND_RUN_GRACE_MS,\r\n pollIntervalMs: BACKGROUND_CLAIM_POLL_MS,\r\n readClaim: readBackgroundRunClaim,\r\n claim: claimBackgroundRun,\r\n });\r\n\r\n if (\r\n backgroundOutcome.action === \"stream\" ||\r\n backgroundOutcome.action === \"subscribe\"\r\n ) {\r\n const stream = subscribeToRun(runId, 0);\r\n if (stream) {\r\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\r\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\r\n setResponseHeader(event, \"Connection\", \"keep-alive\");\r\n setResponseHeader(event, \"X-Run-Id\", runId);\r\n setResponseHeader(event, \"X-Dispatch-Mode\", \"background\");\r\n return stream;\r\n }\r\n // A background worker owns this run but we cannot subscribe — surface an\r\n // error rather than risk a double-run by falling through to inline.\r\n const terminalReason =\r\n backgroundOutcome.action === \"stream\"\r\n ? \"background_subscribe_failed\"\r\n : \"background_dispatch_failed\";\r\n const statusUpdated = await updateRunStatusIfRunning(\r\n runId,\r\n \"errored\",\r\n ).catch(() => false);\r\n if (statusUpdated) {\r\n await setRunTerminalReason(runId, terminalReason).catch(() => {});\r\n }\r\n setResponseStatus(event, 500);\r\n return {\r\n error:\r\n backgroundOutcome.action === \"stream\"\r\n ? \"Failed to subscribe to background run\"\r\n : \"Failed to dispatch background run\",\r\n };\r\n }\r\n\r\n // backgroundOutcome.action === \"inline\": we atomically own the run (or\r\n // there was no row to reconcile), so falling through to the inline\r\n // `startRun` path below cannot double-execute. `startRun` calls `insertRun`\r\n // again, but its duplicate-PK collision is swallowed, so an existing\r\n // `background-processing` row is reused — no double row.\r\n if (backgroundOutcome.reason === \"worker-never-claimed\") {\r\n // The async 202 landed but no worker claimed within grace. PRESERVE the\r\n // bg-fn's last-recorded diag_stage (route_entered / auth_failed / ... or\r\n // \"none\" if it never reached the route) in the recovery detail BEFORE we\r\n // overwrite diag_stage — otherwise foreground_inline_recovery clobbers\r\n // the only clue to WHY the worker died (its own logs are unreadable).\r\n const priorClaim = await readBackgroundRunClaim(runId).catch(\r\n () => null,\r\n );\r\n const priorDiag = priorClaim?.diagStage ?? \"none\";\r\n console.error(\r\n \"[agent-chat] background worker did not claim the 202-dispatched run \" +\r\n `within grace; recovering inline. bgFnPriorDiag=${priorDiag}`,\r\n runId,\r\n );\r\n await recordRunDiagnostic(\r\n runId,\r\n RUN_DIAG_STAGE.foregroundInlineRecovery,\r\n `202 dispatched but no worker claimed within grace; bgFnPriorDiag=${priorDiag}`,\r\n ).catch(() => {});\r\n }\r\n // Fall through to the inline `startRun` path below.\r\n }\r\n\r\n const trackedProgressOwner =\r\n trackInRunsTray === true && ownerEmail ? ownerEmail : null;\r\n const trackedProgressRunId = trackedProgressOwner\r\n ? backgroundChatProgressRunId(effectiveTurnId)\r\n : null;\r\n const trackedProgressMetadata = trackedProgressRunId\r\n ? {\r\n kind: \"agent-chat-background\",\r\n threadId: effectiveThreadId,\r\n surfaceUrl: `agent-native://threads/${encodeURIComponent(effectiveThreadId)}`,\r\n turnId: effectiveTurnId,\r\n }\r\n : null;\r\n // Foreground self-chain: gated on hosted runtime + A2A_SECRET, with an\r\n // explicit env opt-out, AND this specific run never having been routed to\r\n // the durable background worker. A run that WAS dispatched to background\r\n // (`dispatchToBackground`) already has its recovery owned by the background\r\n // circuit-breaker / `isBackgroundWorker` chain above — this flag must never\r\n // double up with that path, only stand in for it on plain foreground turns. A persistent\r\n // threadId is required: the client discovers the pre-inserted successor\r\n // via `/runs/active?threadId` and the successor chunk resumes from the\r\n // thread's persisted thread_data — without a thread there is neither a\r\n // discovery channel nor durable progress to resume from.\r\n const foregroundSelfChainEligible =\r\n !isBackgroundWorker &&\r\n !dispatchToBackground &&\r\n typeof threadId === \"string\" &&\r\n threadId.trim().length > 0 &&\r\n isAgentChatForegroundSelfChainEnabled();\r\n const willChainBackgroundContinuation = (run: ActiveRun) =>\r\n shouldChainBackgroundContinuation({\r\n isBackgroundWorker,\r\n run,\r\n continuationCount: backgroundContinuationCount,\r\n foregroundSelfChainEligible,\r\n dispatchedToBackground: dispatchToBackground,\r\n });\r\n\r\n const completeTrackedProgressRun = async (\r\n run: ActiveRun,\r\n completionError?: unknown,\r\n ) => {\r\n if (!trackedProgressRunId || !trackedProgressOwner) return;\r\n if (!completionError && willChainBackgroundContinuation(run)) {\r\n return;\r\n }\r\n const terminalStatus =\r\n run.status === \"aborted\"\r\n ? \"cancelled\"\r\n : run.status === \"errored\" || completionError\r\n ? \"failed\"\r\n : \"succeeded\";\r\n const step =\r\n terminalStatus === \"succeeded\"\r\n ? \"Agent finished.\"\r\n : terminalStatus === \"cancelled\"\r\n ? \"Agent run was cancelled.\"\r\n : \"Agent stopped with an error.\";\r\n await completeProgressRun(\r\n trackedProgressRunId,\r\n trackedProgressOwner,\r\n terminalStatus,\r\n {\r\n step,\r\n metadata: {\r\n ...(trackedProgressMetadata ?? {}),\r\n runId: run.runId,\r\n },\r\n },\r\n ).catch(() => {});\r\n };\r\n\r\n let lastTrackedProgressUpdateAt = 0;\r\n const updateTrackedProgressFromEvent = (event: AgentChatEvent) => {\r\n if (!trackedProgressRunId || !trackedProgressOwner) return;\r\n const step = progressStepFromAgentChatEvent(event);\r\n if (!step) return;\r\n const now = Date.now();\r\n if (now - lastTrackedProgressUpdateAt < 15_000) return;\r\n lastTrackedProgressUpdateAt = now;\r\n void updateRunProgress(trackedProgressRunId, trackedProgressOwner, {\r\n step,\r\n metadata: {\r\n ...(trackedProgressMetadata ?? {}),\r\n runId,\r\n },\r\n }).catch(() => {});\r\n };\r\n\r\n if (trackedProgressRunId && trackedProgressOwner && !internalContinuation) {\r\n await startProgressRun({\r\n id: trackedProgressRunId,\r\n owner: trackedProgressOwner,\r\n title: messageToPersist,\r\n step: \"Starting agent.\",\r\n metadata: trackedProgressMetadata ?? undefined,\r\n }).catch(() => {});\r\n }\r\n\r\n // The background worker must AWAIT the run to completion before returning,\r\n // or Netlify freezes/kills the function the instant the handler returns and\r\n // the detached run dies mid-turn (mirrors the agent-teams processor, which\r\n // wraps startRun in `await new Promise(resolve => startRun(..., onComplete:\r\n // () => resolve()))`). We resolve this when the run's onComplete fires.\r\n let resolveBackgroundRunDone: (() => void) | null = null;\r\n const backgroundRunDone = isBackgroundWorker\r\n ? new Promise<void>((resolve) => {\r\n resolveBackgroundRunDone = resolve;\r\n })\r\n : null;\r\n\r\n const baseHandleRunComplete =\r\n options.onRunComplete || trackedProgressRunId\r\n ? async (run: ActiveRun) => {\r\n try {\r\n await options.onRunComplete?.(run, threadId);\r\n } catch (err) {\r\n await completeTrackedProgressRun(run, err);\r\n throw err;\r\n }\r\n await completeTrackedProgressRun(run);\r\n }\r\n : undefined;\r\n\r\n // Wrap so the background worker is unblocked even when there is no app\r\n // onRunComplete / tracked-progress callback configured. Also installed for\r\n // a foreground run eligible for self-chain — that path needs this same\r\n // wrapper to fire the continuation dispatch below.\r\n const handleRunComplete =\r\n isBackgroundWorker || foregroundSelfChainEligible || baseHandleRunComplete\r\n ? async (run: ActiveRun) => {\r\n try {\r\n // DIAGNOSTIC: a background worker that completed in an errored\r\n // state threw inside the loop. Record it (with the last error\r\n // event's message when available) so the failure cause is\r\n // readable from the client. Skipped for clean completions and for\r\n // recoverable soft-timeout boundaries (those chain a continuation\r\n // below, they did not \"throw\").\r\n if (\r\n isBackgroundWorker &&\r\n run.status === \"errored\" &&\r\n !willChainBackgroundContinuation(run)\r\n ) {\r\n const errEvent = [...run.events]\r\n .reverse()\r\n .find((e) => e.event.type === \"error\")?.event as\r\n | { error?: string; errorCode?: string }\r\n | undefined;\r\n await recordRunDiagnostic(\r\n run.runId,\r\n RUN_DIAG_STAGE.workerThrew,\r\n errEvent?.errorCode || errEvent?.error\r\n ? `${errEvent.errorCode ?? \"\"} ${errEvent.error ?? \"\"}`.trim()\r\n : \"run ended in errored state\",\r\n ).catch(() => {});\r\n }\r\n // Persist the (partial) assistant turn to thread_data FIRST — the\r\n // server-driven continuation below rebuilds from it, so it must be\r\n // committed before we re-fire.\r\n await baseHandleRunComplete?.(run);\r\n\r\n // Server-driven background→background continuation. If this chunk\r\n // hit its soft-timeout still unfinished (ended at an auto_continue\r\n // / loop_limit / recoverable boundary), chain the next chunk by\r\n // re-firing the `_process-run` self-dispatch with mode \"continue\"\r\n // (carried as internalContinuation + an incremented count),\r\n // instead of relying on the client to re-POST. Mirrors the\r\n // agent-teams `fireInternalDispatch({ body: { mode: \"continue\" }})`\r\n // chain. Bounded by MAX_BACKGROUND_RUN_CONTINUATIONS. Aborted /\r\n // user-stopped runs do NOT chain.\r\n // Self-chain server-side for EVERY durable worker, not only the\r\n // ones inside a `-background` function. Server-driven\r\n // continuation is the whole point of durable background: the run\r\n // must survive the client disconnecting (closed tab), so it\r\n // cannot depend on the browser re-POSTing `auto_continue`. A\r\n // worker on the regular ~60s function — a Netlify routing miss,\r\n // or a non-Netlify host (Vercel/Cloudflare/Render/Fly) that\r\n // never emits a `-background` function — checkpoints at the 40s\r\n // soft-timeout and self-dispatches the next 40s chunk; a worker\r\n // in a real `-background` function chains ~13-min chunks. Only\r\n // the per-chunk BUDGET differs by function type (gated by\r\n // `runsInBackgroundFunction` at the startRun call below); the\r\n // continuation itself must stay server-driven on both. (The\r\n // self-chain is only reachable when the initial dispatch already\r\n // succeeded — a dispatch fast-fail degrades to the inline\r\n // foreground fallback, which is not a worker and rides the\r\n // connected client's auto_continue instead.)\r\n if (willChainBackgroundContinuation(run)) {\r\n // Full handoff discipline lives in\r\n // `chainServerDrivenContinuation` (exported + unit-tested):\r\n // per-turn SQL run budget, successor row PRE-INSERTED before\r\n // the dispatch, fully awaited dispatch with retries, loud\r\n // diag/terminal marking on failure. Never throws.\r\n await chainServerDrivenContinuation({\r\n event,\r\n run,\r\n effectiveThreadId,\r\n effectiveTurnId,\r\n requestBody: body as unknown as Record<string, unknown>,\r\n backgroundContinuationCount,\r\n // Re-evaluate the durable gate rather than keying off\r\n // isBackgroundWorker: a successor chunk of a FOREGROUND\r\n // self-chain re-enters as a worker too, and must keep\r\n // chaining via the regular function — the Netlify\r\n // `-background` function is only emitted into the deploy\r\n // output when the durable flag is on.\r\n //\r\n // `&& !runsInBackgroundFunction`: a worker PROVEN to already\r\n // be executing inside the real `-background` function must\r\n // never dispatch back to that same function's own URL — a\r\n // background function invoking itself by URL from inside a\r\n // live invocation is a documented Netlify platform\r\n // limitation (404), unlike the initial foreground→background\r\n // dispatch or a worker that landed on the regular function\r\n // (a genuinely different function calling the background\r\n // one, which works). This only changes the dispatch TARGET\r\n // for that one proven-in-bg-function case — by this point\r\n // (with the in-process resumable-error resume above) it is\r\n // reached only when the chunk genuinely exhausted its\r\n // budget, so falling back to the regular `_process-run`\r\n // function (40s clamp) here is the correct, safe target.\r\n chainViaDurableBackground:\r\n isAgentChatDurableBackgroundEnabled({\r\n appOptIn: options.durableBackgroundRuns === true,\r\n }) && !runsInBackgroundFunction,\r\n // Only changes the retry BUDGET, never the dispatch target\r\n // above: a worker proven in a real background function has\r\n // minutes of remaining wall clock and no connected-client\r\n // fallback, so it must not be demoted to the foreground's\r\n // 2-attempt budget just because it was forced onto the\r\n // regular-function dispatch target. See\r\n // `resolveContinuationDispatchBudget`.\r\n workerProvenInBackgroundFunction: runsInBackgroundFunction,\r\n });\r\n }\r\n } finally {\r\n resolveBackgroundRunDone?.();\r\n }\r\n }\r\n : undefined;\r\n\r\n // Background worker: the run was claimed immediately after the authenticated\r\n // `_process-run` body was parsed, before owner/model/prompt/tool setup. That\r\n // early claim is what lets the foreground subscribe to the real background\r\n // worker instead of racing slow setup and falling back to the 40s inline\r\n // path. This late block is a defensive fallback for older/custom callers\r\n // that somehow reach here without the early claim.\r\n if (isBackgroundWorker) {\r\n if (!backgroundRunClaimedEarly) {\r\n await recordRunDiagnostic(\r\n runId,\r\n RUN_DIAG_STAGE.workerEntered,\r\n [\r\n `runsInBackgroundFunction=${runsInBackgroundFunction}`,\r\n `continuationCount=${backgroundContinuationCount}`,\r\n backgroundRuntimeDetail,\r\n ]\r\n .filter(Boolean)\r\n .join(\" \"),\r\n ).catch(() => {});\r\n if (isChainedBackgroundContinuation) {\r\n await insertRun(runId, effectiveThreadId, effectiveTurnId, {\r\n dispatchMode: \"background\",\r\n }).catch(() => {});\r\n }\r\n const won = await claimBackgroundRun(runId);\r\n if (!won) {\r\n await recordRunDiagnostic(\r\n runId,\r\n RUN_DIAG_STAGE.workerClaimLost,\r\n ).catch(() => {});\r\n return { ok: true, skipped: \"already-claimed\" };\r\n }\r\n await recordRunDiagnostic(runId, RUN_DIAG_STAGE.workerClaimed).catch(\r\n () => {},\r\n );\r\n await updateRunHeartbeat(runId).catch(() => {});\r\n }\r\n }\r\n\r\n // DIAGNOSTIC-ONLY: build the pre-startRun setup-timing breakdown now (so the\r\n // marks reflect the work done BEFORE the loop), but EMIT it from inside\r\n // startRun's callback below — the run row does not exist until startRun\r\n // inserts it, so a pre-startRun write would no-op on the inline path.\r\n setupMark(\"preStart\");\r\n // DIAGNOSTIC-ONLY: last stage before startRun fires. A worker that reaches\r\n // prestart but never workerStarted is hanging inside startRun itself.\r\n workerStep(\"prestart\");\r\n const setupDetail =\r\n Object.entries(setupMarks)\r\n .map(([k, v]) => `${k}=${v}`)\r\n .join(\" \") +\r\n ` total=${Date.now() - setupT0}` +\r\n (backgroundRuntimeDetail ? ` ${backgroundRuntimeDetail}` : \"\");\r\n\r\n startRun(\r\n runId,\r\n effectiveThreadId,\r\n async (rawSend, signal) => {\r\n const send = (event: AgentChatEvent) => {\r\n rawSend(event);\r\n updateTrackedProgressFromEvent(event);\r\n };\r\n\r\n send({ type: \"activity\", label: \"Starting agent\" });\r\n\r\n // DIAGNOSTIC: the agent loop body actually started running. For a\r\n // background worker, a run that is claimed but never reaches this stage\r\n // died between claiming and loop start. The pre-startRun setup-timing\r\n // breakdown rides along here so it persists now that the run row exists\r\n // (startRun inserted it), WITHOUT adding a separate DB hop to the\r\n // run-start path: on the worker it is folded into this same\r\n // already-awaited worker_started write (one hop, correctly ordered, no\r\n // clobber); on the inline path there is no later diag stage to overwrite,\r\n // so it is fire-and-forget to keep run-start non-blocking. Best-effort.\r\n if (isBackgroundWorker) {\r\n await recordRunDiagnostic(\r\n runId,\r\n RUN_DIAG_STAGE.workerStarted,\r\n setupDetail,\r\n ).catch(() => {});\r\n } else {\r\n void recordRunDiagnostic(\r\n runId,\r\n RUN_DIAG_STAGE.setupTimings,\r\n setupDetail,\r\n ).catch(() => {});\r\n }\r\n\r\n // Notify listeners that a run has started (used by agent teams)\r\n if (options.onRunStart) {\r\n await options.onRunStart(send, threadId ?? runId);\r\n }\r\n\r\n // Resolve custom workspace agent mentions first.\r\n if (customAgentRefs.length > 0) {\r\n const ownerEmail = getRequestUserEmail();\r\n if (!ownerEmail) throw new Error(\"no authenticated user\");\r\n const { findAccessibleCustomAgent } =\r\n await import(\"../resources/agents.js\");\r\n const customResults = await Promise.allSettled(\r\n customAgentRefs.map(async (ref) => {\r\n send({\r\n type: \"agent_call\",\r\n agent: ref.name,\r\n status: \"start\",\r\n });\r\n try {\r\n const profile = await findAccessibleCustomAgent(\r\n ownerEmail,\r\n ref.refId || ref.path || ref.name,\r\n );\r\n if (!profile) {\r\n throw new Error(\"Profile not found\");\r\n }\r\n\r\n const profilePrompt =\r\n `${requestSystemPrompt}\\n\\n<custom-agent-profile name=\"${profile.name}\" path=\"${profile.path}\">\\n` +\r\n (profile.description ? `${profile.description}\\n\\n` : \"\") +\r\n `${profile.instructions}\\n</custom-agent-profile>`;\r\n\r\n let responseText = \"\";\r\n const subUsage = await runAgentLoop({\r\n engine,\r\n model: profile.model ?? model,\r\n systemPrompt: profilePrompt,\r\n tools: requestTools,\r\n availableTools: availableRequestTools,\r\n messages: [\r\n {\r\n role: \"user\",\r\n content: [\r\n { type: \"text\", text: enrichedMessage + screenContext },\r\n ],\r\n },\r\n ],\r\n actions: requestActions,\r\n send: (event) => {\r\n if (event.type === \"text\") {\r\n responseText += event.text;\r\n send({\r\n type: \"agent_call_text\",\r\n agent: ref.name,\r\n text: event.text,\r\n });\r\n }\r\n },\r\n signal,\r\n reasoningEffort,\r\n providerOptions: options.providerOptions,\r\n executionMode: requestMode,\r\n maxIterations: loopSettings.maxIterations,\r\n });\r\n\r\n // Attribute custom-agent sub-calls under their own label\r\n // so the Usage panel separates them from the main chat.\r\n try {\r\n const ownerEmail = options.resolveOwnerEmail\r\n ? await options.resolveOwnerEmail(event)\r\n : getRequestUserEmail();\r\n if (!ownerEmail) {\r\n // Skip usage recording for unauthenticated runs.\r\n return;\r\n }\r\n const { recordUsage } = await import(\"../usage/store.js\");\r\n await recordUsage({\r\n ownerEmail,\r\n inputTokens: subUsage.inputTokens,\r\n outputTokens: subUsage.outputTokens,\r\n cacheReadTokens: subUsage.cacheReadTokens,\r\n cacheWriteTokens: subUsage.cacheWriteTokens,\r\n model: subUsage.model,\r\n label: `custom-agent:${ref.name}`,\r\n });\r\n } catch {}\r\n\r\n send({\r\n type: \"agent_call\",\r\n agent: ref.name,\r\n status: \"done\",\r\n });\r\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" type=\"custom-agent\">\\n${responseText}\\n</agent-response>`;\r\n } catch (err: any) {\r\n send({\r\n type: \"agent_call\",\r\n agent: ref.name,\r\n status: \"error\",\r\n });\r\n const message =\r\n userFacingLlmCredentialError(err, {\r\n agentName: ref.name,\r\n }) ?? `Failed to run ${ref.name}: ${err?.message}`;\r\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" type=\"custom-agent\" error=\"true\">\\n${message}\\n</agent-response>`;\r\n }\r\n }),\r\n );\r\n\r\n const customResponses = customResults\r\n .filter(\r\n (result): result is PromiseFulfilledResult<string> =>\r\n result.status === \"fulfilled\",\r\n )\r\n .map((result) => result.value);\r\n\r\n if (customResponses.length > 0) {\r\n const agentContext =\r\n \"Responses from custom workspace agents:\\n\\n\" +\r\n customResponses.join(\"\\n\\n\");\r\n const lastMsg = messages[messages.length - 1];\r\n if (lastMsg?.role === \"user\" && Array.isArray(lastMsg.content)) {\r\n const textPart = lastMsg.content.find(\r\n (p): p is import(\"./engine/types.js\").EngineTextPart =>\r\n p.type === \"text\",\r\n );\r\n if (textPart) {\r\n textPart.text = agentContext + \"\\n\\n\" + textPart.text;\r\n }\r\n }\r\n }\r\n }\r\n\r\n // Resolve connected agent @-mentions via A2A calls.\r\n if (agentRefs.length > 0 && requestMode !== \"plan\") {\r\n const [{ A2AClient, callAgent }, { resolveA2ACallerAuth }] =\r\n await Promise.all([\r\n import(\"../a2a/client.js\"),\r\n import(\"../a2a/caller-auth.js\"),\r\n ]);\r\n const results = await Promise.allSettled(\r\n agentRefs.map(async (ref) => {\r\n send({\r\n type: \"agent_call\",\r\n agent: ref.name,\r\n status: \"start\",\r\n });\r\n try {\r\n const callerAuth = await resolveA2ACallerAuth({\r\n includeGoogleToken: true,\r\n });\r\n const a2aClient = new A2AClient(ref.path, callerAuth.apiKey, {\r\n ...(callerAuth.apiKeyFallbacks\r\n ? { fallbackApiKeys: callerAuth.apiKeyFallbacks }\r\n : {}),\r\n });\r\n const a2aMetadata = callerAuth.metadata;\r\n\r\n let responseText = \"\";\r\n let lastSentLength = 0;\r\n\r\n try {\r\n for await (const task of a2aClient.stream(\r\n {\r\n role: \"user\",\r\n parts: [\r\n {\r\n type: \"text\",\r\n text: enrichedMessage + screenContext,\r\n },\r\n ],\r\n },\r\n Object.keys(a2aMetadata).length > 0\r\n ? { metadata: a2aMetadata }\r\n : undefined,\r\n )) {\r\n const newText =\r\n task.status?.message?.parts\r\n ?.filter(\r\n (p): p is { type: \"text\"; text: string } =>\r\n p.type === \"text\",\r\n )\r\n ?.map((p) => p.text)\r\n ?.join(\"\") ?? \"\";\r\n\r\n if (newText.length > lastSentLength) {\r\n send({\r\n type: \"agent_call_text\",\r\n agent: ref.name,\r\n text: newText.slice(lastSentLength),\r\n });\r\n lastSentLength = newText.length;\r\n }\r\n responseText = newText;\r\n }\r\n } catch {\r\n if (!responseText) {\r\n responseText = await callAgent(\r\n ref.path,\r\n enrichedMessage + screenContext,\r\n {\r\n apiKey: callerAuth.apiKey,\r\n userEmail: callerAuth.userEmail,\r\n orgDomain: callerAuth.orgDomain,\r\n orgSecret: callerAuth.orgSecret,\r\n },\r\n );\r\n }\r\n }\r\n responseText =\r\n userFacingLlmCredentialError(responseText, {\r\n agentName: ref.name,\r\n }) ?? responseText;\r\n\r\n send({\r\n type: \"agent_call\",\r\n agent: ref.name,\r\n status: \"done\",\r\n });\r\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\">\\n${responseText}\\n</agent-response>`;\r\n } catch (err: any) {\r\n send({\r\n type: \"agent_call\",\r\n agent: ref.name,\r\n status: \"error\",\r\n });\r\n const message =\r\n userFacingLlmCredentialError(err, {\r\n agentName: ref.name,\r\n }) ?? `Failed to reach ${ref.name}: ${err?.message}`;\r\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" error=\"true\">\\n${message}\\n</agent-response>`;\r\n }\r\n }),\r\n );\r\n\r\n const agentResponses_local: string[] = [];\r\n for (const result of results) {\r\n if (result.status === \"fulfilled\") {\r\n agentResponses_local.push(result.value);\r\n }\r\n }\r\n\r\n if (agentResponses_local.length > 0) {\r\n const agentContext =\r\n \"Responses from other agents:\\n\\n\" +\r\n agentResponses_local.join(\"\\n\\n\");\r\n const lastMsg = messages[messages.length - 1];\r\n if (lastMsg?.role === \"user\" && Array.isArray(lastMsg.content)) {\r\n const textPart = lastMsg.content.find(\r\n (p): p is import(\"./engine/types.js\").EngineTextPart =>\r\n p.type === \"text\",\r\n );\r\n if (textPart) {\r\n textPart.text = agentContext + \"\\n\\n\" + textPart.text;\r\n }\r\n }\r\n }\r\n }\r\n\r\n // Apply experiment variant overrides (A/B testing)\r\n let effectiveModel = model;\r\n try {\r\n const { resolveActiveExperimentConfig } =\r\n await import(\"../observability/experiments.js\");\r\n if (!ownerEmail) {\r\n // Without an authenticated owner we can't resolve user-scoped experiments.\r\n throw new Error(\"no authenticated user\");\r\n }\r\n const expConfig = await resolveActiveExperimentConfig(ownerEmail);\r\n if (expConfig) {\r\n if (typeof expConfig.configs.model === \"string\") {\r\n effectiveModel = expConfig.configs.model;\r\n }\r\n }\r\n } catch {\r\n // Experiments module unavailable — use default model\r\n }\r\n\r\n // TODO(processor-seam): thread `processors` from ProductionAgentOptions\r\n // through to runAgentLoop here once the handler exposes a way to\r\n // configure them (e.g. a `processors` field on ProductionAgentOptions\r\n // or a per-request resolver). The loop-level seam (runAgentLoop's\r\n // `processors` opt + ProcessorChain/TripWire) is the deliverable and is\r\n // already callable directly by sub-agents, A2A, MCP, and tests; this is\r\n // only the HTTP-handler convenience plumbing.\r\n const agentLoopOpts = {\r\n engine,\r\n model: effectiveModel,\r\n systemPrompt: requestSystemPrompt,\r\n tools: requestTools,\r\n availableTools: availableRequestTools,\r\n messages,\r\n actions: requestActions,\r\n send,\r\n signal,\r\n ownerEmail,\r\n orgId: getRequestOrgId() ?? null,\r\n attachments: requestAttachments,\r\n reasoningEffort,\r\n // The interactive chat turn needs real completion headroom — the\r\n // flat per-engine defaults (4096-8192) exist for internal/eval\r\n // callers and are far below what a hard, long-context turn needs\r\n // once extended thinking is in play. See output-tokens.ts.\r\n maxOutputTokens: resolveMainChatMaxOutputTokens(effectiveModel),\r\n providerOptions: options.providerOptions,\r\n executionMode: requestMode,\r\n maxIterations: loopSettings.maxIterations,\r\n finalResponseGuard: options.finalResponseGuard,\r\n ...(options.toolLimits ? { toolLimits: options.toolLimits } : {}),\r\n ...(threadId\r\n ? { threadId: effectiveThreadId, turnId: effectiveTurnId }\r\n : {}),\r\n // Human-in-the-loop approval grants for this turn (sanitized — the\r\n // request is untrusted; accept only a bounded list of string keys).\r\n ...(Array.isArray(body.approvedToolCalls) &&\r\n body.approvedToolCalls.length\r\n ? {\r\n approvedToolCalls: body.approvedToolCalls\r\n .filter((k: unknown): k is string => typeof k === \"string\")\r\n .slice(0, 200),\r\n }\r\n : {}),\r\n // A worker PROVEN to be running inside the real 15-min Netlify\r\n // `-background` function (`runsInBackgroundFunction`) has minutes of\r\n // budget left on THIS invocation. Let it catch a recoverable\r\n // transport/gateway error (isResumableEngineError) and resume the\r\n // agent loop in-process instead of unwinding out to `startRun`'s\r\n // outer catch, which would otherwise hand off to\r\n // `chainServerDrivenContinuation` — and for a worker already inside\r\n // the background function, that hand-off is a same-function\r\n // self-dispatch that 404s on Netlify (a background function cannot\r\n // invoke its own public URL from inside a live invocation). A\r\n // foreground turn or a worker that landed on the regular ~60s\r\n // function (runsInBackgroundFunction false) must NOT set this — it\r\n // keeps depending on the existing cross-invocation recovery\r\n // (foreground self-chain / client auto_continue re-POST), unchanged.\r\n ...(runsInBackgroundFunction\r\n ? {\r\n resumeResumableErrorsInProcess: true,\r\n maxContinuations: MAX_BACKGROUND_RUN_CONTINUATIONS,\r\n }\r\n : {}),\r\n };\r\n\r\n send({ type: \"activity\", label: \"Contacting model\" });\r\n\r\n // loopUsage is always assigned — either via instrumentAgentLoop or\r\n // runAgentLoop before use below. The definite-assignment guard is\r\n // conservative because the try/catch makes the control flow non-obvious.\r\n let loopUsage: AgentLoopUsage = undefined!;\r\n let instrumented = false;\r\n try {\r\n const { getObservabilityConfig, instrumentAgentLoop } =\r\n await import(\"../observability/traces.js\");\r\n const obsConfig = await getObservabilityConfig();\r\n if (obsConfig.enabled) {\r\n instrumented = true;\r\n loopUsage = await instrumentAgentLoop({\r\n runAgentLoop: runAgentLoopWithMainChatInternalContinuations,\r\n loopOpts: agentLoopOpts,\r\n runId,\r\n threadId: threadId ?? null,\r\n userId: ownerEmail,\r\n config: obsConfig,\r\n classifyError: () => {\r\n if (\r\n agentLoopOpts.signal.aborted &&\r\n agentLoopOpts.signal.reason === \"run_timeout\"\r\n ) {\r\n return {\r\n status: \"success\",\r\n errorMessage: null,\r\n metadata: {\r\n terminalReason: \"run_timeout\",\r\n recoverableContinuation: true,\r\n },\r\n };\r\n }\r\n return null;\r\n },\r\n });\r\n }\r\n } catch (err) {\r\n // If instrumentation setup failed, fall through to uninstrumented.\r\n // If the agent loop itself failed (via instrumentAgentLoop), re-throw.\r\n if (instrumented) throw err;\r\n }\r\n if (!instrumented) {\r\n loopUsage =\r\n await runAgentLoopWithMainChatInternalContinuations(agentLoopOpts);\r\n }\r\n\r\n // Record token usage for cost monitoring so the Usage panel in\r\n // settings works in every mode, including local dev.\r\n try {\r\n const ownerEmail = options.resolveOwnerEmail\r\n ? await options.resolveOwnerEmail(event)\r\n : getRequestUserEmail();\r\n if (\r\n ownerEmail &&\r\n (loopUsage.inputTokens > 0 ||\r\n loopUsage.outputTokens > 0 ||\r\n loopUsage.cacheReadTokens > 0 ||\r\n loopUsage.cacheWriteTokens > 0)\r\n ) {\r\n const { recordUsage } = await import(\"../usage/store.js\");\r\n await recordUsage({\r\n ownerEmail,\r\n inputTokens: loopUsage.inputTokens,\r\n outputTokens: loopUsage.outputTokens,\r\n cacheReadTokens: loopUsage.cacheReadTokens,\r\n cacheWriteTokens: loopUsage.cacheWriteTokens,\r\n model: loopUsage.model,\r\n label: body.usageLabel || \"chat\",\r\n });\r\n }\r\n } catch {\r\n // Usage recording failed — don't break the run\r\n }\r\n },\r\n handleRunComplete,\r\n {\r\n softTimeoutMs: options.runSoftTimeoutMs,\r\n useHostedSoftTimeoutDefault: true,\r\n // Lift the soft-timeout clamp to ~13min ONLY when this run is actually\r\n // executing inside a real Netlify `-background` function (15-min budget,\r\n // no ~60s wall). Being the `_process-run` worker (`isBackgroundWorker`)\r\n // is NOT sufficient: if the `-background` function wasn't emitted, or\r\n // Netlify routed the self-POST to the synchronous function, the worker\r\n // landed on the regular ~60s `server` function — there it MUST keep the\r\n // 40s clamp and checkpoint before the wall, or it overshoots the 60s\r\n // hard kill and re-dispatches in a loop. `runsInBackgroundFunction`\r\n // gates the 13-min budget on the proven runtime, not merely on \"I'm the\r\n // worker.\" Foreground runs never set this, so their 40s clamp is\r\n // unchanged.\r\n backgroundFunction: runsInBackgroundFunction,\r\n noProgressTimeoutMs: options.runNoProgressTimeoutMs,\r\n // Fold continuation runs of one logical turn onto a single durable\r\n // assistant message. Falls back to the runId (turn == run) when the\r\n // client doesn't supply a turnId.\r\n turnId: effectiveTurnId,\r\n dispatchMode: foregroundSelfChainEligible\r\n ? \"foreground-self-chain\"\r\n : \"foreground\",\r\n },\r\n );\r\n\r\n // Background worker: await the run to completion so Netlify keeps the\r\n // background function alive for the whole turn (the client is streaming the\r\n // same events via the foreground POST's cross-isolate SQL subscription).\r\n // The onComplete wrapper above resolves `backgroundRunDone`.\r\n if (isBackgroundWorker) {\r\n if (backgroundRunDone) await backgroundRunDone;\r\n return { ok: true, runId };\r\n }\r\n\r\n // Subscribe to the run and stream events to the client\r\n const stream = subscribeToRun(runId, 0);\r\n if (!stream) {\r\n setResponseStatus(event, 500);\r\n return { error: \"Failed to start agent run\" };\r\n }\r\n\r\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\r\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\r\n setResponseHeader(event, \"Connection\", \"keep-alive\");\r\n setResponseHeader(event, \"X-Run-Id\", runId);\r\n setResponseHeader(\r\n event,\r\n \"X-Dispatch-Mode\",\r\n foregroundSelfChainEligible ? \"foreground-self-chain\" : \"foreground\",\r\n );\r\n\r\n return stream;\r\n });\r\n}\r\n\r\nexport {\r\n getActiveRunForThread,\r\n getActiveRunForThreadAsync,\r\n getRun,\r\n abortRun,\r\n subscribeToRun,\r\n};\r\n"]}
1
+ {"version":3,"file":"production-agent.js","sourceRoot":"","sources":["../../src/agent/production-agent.ts"],"names":[],"mappings":"AAAA,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EACL,kBAAkB,EAClB,SAAS,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EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;QACrD,iBAAiB,CAAC,KAAK,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;QAC5C,iBAAiB,CACf,KAAK,EACL,iBAAiB,EACjB,2BAA2B,CAAC,CAAC,CAAC,uBAAuB,CAAC,CAAC,CAAC,YAAY,CACrE,CAAC;QAEF,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,OAAO,EACL,qBAAqB,EACrB,0BAA0B,EAC1B,MAAM,EACN,QAAQ,EACR,cAAc,GACf,CAAC","sourcesContent":["import Ajv from \"ajv\";\nimport {\n defineEventHandler,\n getHeader,\n setResponseHeader,\n setResponseStatus,\n getMethod,\n} from \"h3\";\nimport type { EventHandler as H3EventHandler } from \"h3\";\n\nimport { isAgentActionStopError } from \"../action.js\";\nimport { readAppState } from \"../application-state/script-helpers.js\";\nimport { isReadOnlyShellCommand } from \"../coding-tools/index.js\";\nimport { isDemoModeEnabled } from \"../demo/config.js\";\nimport { redactDemoData, redactDemoString } from \"../demo/redact.js\";\nimport { extensionIdFromPathname } from \"../extensions/path.js\";\nimport { preUploadAttachments } from \"../file-upload/pre-upload-attachments.js\";\nimport { isMcpActionResult } from \"../mcp-client/app-result.js\";\nimport { extractMcpToolResultImages } from \"../mcp-client/index.js\";\nimport { isMcpToolAllowedForRequest } from \"../mcp-client/visibility.js\";\nimport {\n completeRun as completeProgressRun,\n startRun as startProgressRun,\n updateRunProgress,\n} from \"../progress/registry.js\";\nimport {\n getFrontmatterValue,\n parseFrontmatter,\n} from \"../resources/metadata.js\";\nimport {\n canUseDeployCredentialFallbackForRequest,\n getProviderCredentialAuthFailure,\n readDeployCredentialEnv,\n} from \"../server/credential-provider.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport {\n getRequestRunContext,\n ensureRequestRunContext,\n getRequestContext,\n getRequestOrgId,\n getRequestUserEmail,\n runWithRequestContext,\n} from \"../server/request-context.js\";\nimport { fireInternalDispatch } from \"../server/self-dispatch.js\";\nimport {\n isReasoningEffort,\n normalizeReasoningEffortForModel,\n stepDownReasoningEffort,\n type ReasoningEffort,\n} from \"../shared/reasoning-effort.js\";\nimport { actionPreparationContinuationNote } from \"./action-continuation-guidance.js\";\nimport { applyContextDirectives } from \"./context-xray/apply-directives.js\";\nimport { loadContextDirectives } from \"./context-xray/directives-store.js\";\nimport {\n buildManifest,\n writeContextManifest,\n} from \"./context-xray/manifest.js\";\nimport { computeProtectedSegmentIds } from \"./context-xray/segments.js\";\nimport {\n AGENT_CHAT_BACKGROUND_RUN_FIELD,\n AGENT_CHAT_PROCESS_RUN_PATH,\n backgroundRuntimeDiagnosticDetail,\n dispatchPathTargetsNetlifyBackgroundFunction,\n isAgentChatDurableBackgroundEnabled,\n isAgentChatForegroundSelfChainEnabled,\n resolveAgentChatProcessRunDispatchPath,\n shouldUseBackgroundFunctionTimeoutForWorker,\n} from \"./durable-background.js\";\nimport {\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n LLM_MISSING_CREDENTIALS_MESSAGE,\n userFacingLlmCredentialError,\n} from \"./engine/credential-errors.js\";\nimport {\n resolveEngine,\n registerBuiltinEngines,\n getStoredModelForEngine,\n normalizeModelForEngine,\n isResolvedEngineUsableForRequest,\n} from \"./engine/index.js\";\nimport {\n resolveEmptyResponseRetryMaxOutputTokens,\n resolveMainChatMaxOutputTokens,\n resolveMaxOutputTokensForEngine,\n} from \"./engine/output-tokens.js\";\nimport { PROVIDER_TO_ENV } from \"./engine/provider-env-vars.js\";\nimport {\n backfillEngineMessagesToolResults,\n stringifyToolUseInputForGateway,\n unmatchedToolResultReplayText,\n} from \"./engine/translate-anthropic.js\";\nimport type {\n AgentEngine,\n EngineTool,\n EngineMessage,\n EngineContentPart,\n EngineEvent,\n EngineToolResultPart,\n} from \"./engine/types.js\";\nimport { EngineError } from \"./engine/types.js\";\nimport {\n type AgentLoopSettings,\n getDefaultMaxIterations,\n MAX_AGENT_MAX_ITERATIONS,\n MIN_AGENT_MAX_ITERATIONS,\n normalizeMaxIterations,\n readAgentLoopSettings,\n} from \"./loop-settings.js\";\nimport {\n maybeCompactThread,\n buildObservationalContext,\n hasObservationalMemory,\n serializeObservationalMemoryBlock,\n} from \"./observational-memory/index.js\";\nimport {\n ProcessorChain,\n TripWire,\n toolCallsFromContent,\n type Processor,\n} from \"./processors.js\";\nimport {\n startRun,\n subscribeToRun,\n getActiveRunForThread,\n getActiveRunForThreadAsync,\n getRun,\n abortRun,\n tryClaimRunSlot,\n} from \"./run-manager.js\";\nimport type { ActiveRun } from \"./run-manager.js\";\nimport {\n writeLedgerEntry,\n readLedgerEntry,\n clearLedgerForThread,\n getCurrentTurnEventsForThread,\n insertRun,\n updateRunHeartbeat,\n updateRunStatusIfRunning,\n setRunTerminalReason,\n claimBackgroundRun,\n readBackgroundRunClaim,\n recordRunDiagnostic,\n countRunsForTurn,\n RUN_DIAG_STAGE,\n UNCLAIMED_BACKGROUND_RUN_GRACE_MS,\n} from \"./run-store.js\";\nimport { buildCurrentTimeUserContext } from \"./runtime-context.js\";\nimport {\n classifyToolCallJournal,\n findCompletedJournalEntry,\n type ToolCallJournal,\n} from \"./tool-call-journal.js\";\nimport {\n redactSensitiveFields,\n sanitizeToolErrorText,\n sanitizeToolErrorValue,\n} from \"./tool-error-redaction.js\";\nimport {\n describeToolResultImages,\n extractAgentImagesFromActionResult,\n} from \"./tool-result-images.js\";\nimport {\n createToolSearchEntry,\n TOOL_SEARCH_ACTION_NAME,\n} from \"./tool-search.js\";\nimport type {\n ActionTool,\n AgentNativeJsonSchema,\n AgentChatAttachment,\n AgentChatRequest,\n AgentChatEvent,\n AgentChatReference,\n AgentChatStructuredMessage,\n} from \"./types.js\";\n\n// Register built-in engines on first import\nregisterBuiltinEngines();\n\nexport { PROVIDER_TO_ENV };\n\n/**\n * Grace window + poll interval for the foreground circuit-breaker that confirms\n * a background worker actually CLAIMED a 202-dispatched run before recovering\n * inline. The grace must cover the worker's cold-start + per-request init before\n * it reaches `claimBackgroundRun`: light apps win the claim in ~1-2s, but heavy\n * apps (e.g. analytics) were observed in prod taking >8s, so an 8s grace made\n * their worker lose the race every time and always fall back to inline (adding\n * ~8s latency with no background budget). 15s covers the slow apps while staying\n * well within the foreground's ~40s soft-timeout.\n */\nexport const BACKGROUND_CLAIM_GRACE_MS = 15_000;\n/**\n * Safety margin subtracted from the unclaimed-reaper grace when deciding how\n * long the foreground may keep waiting for a slow-but-live worker to claim. The\n * foreground recovers the run inline this many ms BEFORE `reapUnclaimedBackgroundRun`\n * would error an unclaimed row, so the foreground always wins the race to claim\n * and the two never collide — see `resolveBackgroundDispatchOutcome`.\n */\nexport const BACKGROUND_REAPER_SAFETY_MARGIN_MS = 2_000;\nexport const BACKGROUND_CLAIM_POLL_MS = 400;\n\nexport type BackgroundDispatchOutcome =\n | { action: \"stream\" }\n | { action: \"subscribe\" }\n | {\n action: \"inline\";\n reason: \"dispatch-failed\" | \"worker-never-claimed\" | \"no-row\";\n };\n\n/**\n * `diag_stage` is persisted as a JSON payload (`{ stage, detail?, at }`) by\n * `recordRunDiagnostic`. Extract the bare stage name so it can be compared to\n * `RUN_DIAG_STAGE` constants. Falls back to the raw value when it is not JSON\n * (defensive — legacy rows or tests may store a bare stage).\n */\nfunction parseRunDiagStage(raw: string | null | undefined): string | null {\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as { stage?: unknown };\n if (parsed && typeof parsed.stage === \"string\") return parsed.stage;\n } catch {\n // Not JSON — treat the raw value as the stage name.\n }\n return typeof raw === \"string\" ? raw : null;\n}\n\n/**\n * Decide what the foreground should do after attempting a durable background\n * dispatch. A Netlify async background function returns 202 the instant it\n * ENQUEUES the invocation — that is NOT proof the worker executed. If the\n * generated wrapper fails to import/hand off to the route, the worker never\n * reaches `claimBackgroundRun` and the run is reaped as \"worker never claimed\".\n *\n * So after a successful dispatch we poll briefly for the worker to CLAIM the run:\n * - claimed within grace → \"stream\" (subscribe to the worker)\n * - dispatch failed OR no claim → recover inline by atomically claiming the\n * run ourselves: if we win → \"inline\"; if a (delayed) worker already won\n * it → \"subscribe\" (never double-run).\n *\n * Pure except for the injected `readClaim`/`claim`/`now`/`sleep` deps, so each\n * branch is unit-testable.\n */\nexport async function resolveBackgroundDispatchOutcome(opts: {\n dispatched: boolean;\n backgroundRowInserted: boolean;\n runId: string;\n graceMs: number;\n /**\n * The unclaimed-run reaper's grace (`UNCLAIMED_BACKGROUND_RUN_GRACE_MS`). When\n * provided, the foreground may keep waiting PAST `graceMs` while the worker is\n * provably alive and still in setup — but it recovers inline before the run has\n * been unclaimed this long (minus the safety margin), so it always claims\n * before the reaper can fire. Omit to disable the extension (behaves exactly\n * like the base grace).\n */\n reaperGraceMs?: number;\n /** Margin subtracted from `reaperGraceMs` (default `BACKGROUND_REAPER_SAFETY_MARGIN_MS`). */\n reaperSafetyMarginMs?: number;\n pollIntervalMs: number;\n readClaim: (runId: string) => Promise<{\n dispatchMode: string | null;\n status: string | null;\n diagStage?: string | null;\n /** COALESCE(heartbeat_at, started_at) — the reaper's liveness basis. */\n lastLivenessAt?: number | null;\n } | null>;\n claim: (runId: string) => Promise<boolean>;\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n}): Promise<BackgroundDispatchOutcome> {\n const now = opts.now ?? (() => Date.now());\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n\n // Pre-claim diag stages that prove the worker is ALIVE and executing: it\n // reached the route, passed HMAC auth, and is grinding through handler setup\n // (system prompt build / action loading) on its way to `claimBackgroundRun`.\n // A dead handoff — the generated wrapper never reached the route — never\n // records these, so it is NOT eligible for the extended grace.\n const ALIVE_IN_SETUP: ReadonlySet<string> = new Set([\n RUN_DIAG_STAGE.authPassed,\n RUN_DIAG_STAGE.workerEntered,\n ]);\n // Pre-claim diag stages that prove the worker DIED before claiming — stop\n // waiting and recover inline immediately instead of burning the rest of the\n // grace on a worker that already failed.\n const DIED_BEFORE_CLAIM: ReadonlySet<string> = new Set([\n RUN_DIAG_STAGE.authFailed,\n RUN_DIAG_STAGE.routeThrew,\n RUN_DIAG_STAGE.workerThrew,\n ]);\n\n if (opts.dispatched) {\n // One now() at entry + one per iteration (so callers/tests that model a\n // stepping clock stay deterministic).\n const startedAt = now();\n const baseDeadline = startedAt + opts.graceMs;\n const reaperGraceMs = opts.reaperGraceMs;\n const reaperMargin =\n opts.reaperSafetyMarginMs ?? BACKGROUND_REAPER_SAFETY_MARGIN_MS;\n for (;;) {\n const claim = await opts.readClaim(opts.runId).catch(() => null);\n if (\n claim &&\n ((claim.dispatchMode && claim.dispatchMode !== \"background\") ||\n (claim.status && claim.status !== \"running\"))\n ) {\n return { action: \"stream\" };\n }\n // `diag_stage` is stored as JSON ({stage, detail?, at}); compare on the\n // bare stage name, not the raw payload.\n const stage = parseRunDiagStage(claim?.diagStage);\n // Worker recorded a pre-claim death — no point waiting out the grace.\n if (stage && DIED_BEFORE_CLAIM.has(stage)) break;\n const elapsedNow = now();\n // The unclaimed-reaper errors any still-`background` row once it has been\n // unclaimed for `reaperGraceMs`, measured from the row's OWN liveness\n // (COALESCE(heartbeat_at, started_at)) — NOT from when we began polling.\n // Recover inline just before that point so the foreground claims the run\n // first; anchoring to the row's liveness makes this immune to dispatch\n // latency between insertRun and the start of polling.\n const reaperWillFireSoon =\n reaperGraceMs != null &&\n claim?.lastLivenessAt != null &&\n elapsedNow - claim.lastLivenessAt >= reaperGraceMs - reaperMargin;\n if (reaperWillFireSoon) break;\n // ADAPTIVE GRACE: past the base window, keep polling ONLY while the worker\n // is provably alive and still in setup (heavy cold start). A dead handoff\n // never recorded an ALIVE_IN_SETUP stage, so it recovers inline at the base\n // grace; the reaper-anchored break above bounds how long a live worker can\n // extend. The extension is enabled only when a reaper grace was provided.\n const aliveInSetup =\n reaperGraceMs != null &&\n claim?.status === \"running\" &&\n !!stage &&\n ALIVE_IN_SETUP.has(stage);\n if (elapsedNow >= baseDeadline && !aliveInSetup) break;\n await sleep(opts.pollIntervalMs);\n }\n }\n\n // Dispatch fast-failed OR no worker claimed within grace → recover inline.\n if (!opts.backgroundRowInserted) {\n // No row to reconcile (insert failed / non-duplicate) — run a fresh inline\n // turn; `startRun` inserts the row.\n return { action: \"inline\", reason: \"no-row\" };\n }\n let claimedInline = false;\n try {\n claimedInline = await opts.claim(opts.runId);\n } catch {\n claimedInline = false;\n }\n if (claimedInline) {\n return {\n action: \"inline\",\n reason: opts.dispatched ? \"worker-never-claimed\" : \"dispatch-failed\",\n };\n }\n // The atomic claim was lost: a (delayed) background worker already owns the\n // run — subscribe to it, never run a second copy.\n return { action: \"subscribe\" };\n}\n\nconst SAFE_BROWSER_TAB_ID_RE = /^[A-Za-z0-9_-]{1,96}$/;\n\nfunction normalizeBrowserTabId(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return SAFE_BROWSER_TAB_ID_RE.test(trimmed) ? trimmed : undefined;\n}\n\nfunction normalizeChatScope(\n value: unknown,\n): { type: string; id: string; label?: string } | null | undefined {\n if (value == null) return null;\n if (typeof value !== \"object\") return undefined;\n const record = value as Record<string, unknown>;\n const type = typeof record.type === \"string\" ? record.type.trim() : \"\";\n const id = typeof record.id === \"string\" ? record.id.trim() : \"\";\n if (!type || !id || type.length > 64 || id.length > 256) {\n return undefined;\n }\n const label =\n typeof record.label === \"string\" && record.label.trim().length > 0\n ? record.label.trim().slice(0, 256)\n : undefined;\n return { type, id, ...(label ? { label } : {}) };\n}\n\nfunction appStateKeyForBrowserTab(key: string, browserTabId?: string): string {\n return browserTabId ? `${key}:${browserTabId}` : key;\n}\n\nasync function readAppStateForBrowserTab<T>(\n key: string,\n browserTabId?: string,\n): Promise<T | null> {\n const tabKey = appStateKeyForBrowserTab(key, browserTabId);\n if (tabKey !== key) {\n const scoped = (await readAppState(tabKey).catch(() => null)) as T | null;\n if (scoped) return scoped;\n }\n return (await readAppState(key)) as T | null;\n}\n\n/**\n * Look up a user's persisted API key for the given provider. Returns\n * `undefined` for unauthenticated callers.\n *\n * Read order:\n * 1. `app_secrets` — encrypted user override, then active org/workspace.\n * 2. Legacy `user-api-key:<provider>:<email>` settings row — pre-migration\n * data that hasn't been backfilled yet. Surfaced for compat only;\n * writes always go to app_secrets now.\n */\nexport async function getOwnerApiKey(\n provider: string,\n ownerEmail: string | null | undefined,\n): Promise<string | undefined> {\n if (!ownerEmail) return undefined;\n const secretKey =\n PROVIDER_TO_ENV[provider] ?? `${provider.toUpperCase()}_API_KEY`;\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n const refs: Array<{\n scope: \"user\" | \"org\" | \"workspace\";\n scopeId: string;\n }> = [{ scope: \"user\", scopeId: ownerEmail }];\n const orgId = getRequestOrgId();\n if (orgId) {\n refs.push(\n { scope: \"org\", scopeId: orgId },\n { scope: \"workspace\", scopeId: orgId },\n );\n } else {\n refs.push({ scope: \"workspace\", scopeId: `solo:${ownerEmail}` });\n }\n for (const ref of refs) {\n const fromSecrets = await readAppSecret({\n key: secretKey,\n scope: ref.scope,\n scopeId: ref.scopeId,\n });\n if (\n fromSecrets?.value &&\n !(await getProviderCredentialAuthFailure({\n key: secretKey,\n value: fromSecrets.value,\n }))\n ) {\n return fromSecrets.value;\n }\n }\n } catch {\n // app_secrets table not ready — fall through to legacy lookup.\n }\n try {\n const { getSetting } = await import(\"../settings/store.js\");\n const stored = await getSetting(`user-api-key:${provider}:${ownerEmail}`);\n const key =\n stored && typeof stored.key === \"string\" ? stored.key.trim() : \"\";\n if (\n key &&\n !(await getProviderCredentialAuthFailure({ key: secretKey, value: key }))\n ) {\n return key;\n }\n if (provider === \"anthropic\") {\n const legacy = await getSetting(`user-anthropic-api-key:${ownerEmail}`);\n const legacyKey =\n legacy && typeof legacy.key === \"string\" ? legacy.key.trim() : \"\";\n if (\n legacyKey &&\n !(await getProviderCredentialAuthFailure({\n key: secretKey,\n value: legacyKey,\n }))\n ) {\n return legacyKey;\n }\n return undefined;\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Derive the provider name from the active engine setting.\n * \"ai-sdk:openai\" → \"openai\", \"anthropic\" → \"anthropic\"\n */\nexport function engineToProvider(engineName: string): string {\n return engineName.startsWith(\"ai-sdk:\") ? engineName.slice(7) : engineName;\n}\n\n/**\n * Resolve the active engine's provider and look up the user's API key for it.\n *\n * If the owner has no scoped key, fall back to provider keys supplied by the\n * hosting environment only when the current request can safely use deploy-level\n * credentials. This is a read from process-level config, not a request-scoped\n * write to `process.env`.\n *\n * Callers that layer another deployment-key fallback after this should keep the\n * same precedence: scoped key first, host-provided env key second.\n */\nexport async function getOwnerActiveApiKey(\n ownerEmail: string | null | undefined,\n): Promise<string | undefined> {\n try {\n const { getSetting } = await import(\"../settings/store.js\");\n const engineSetting = await getSetting(\"agent-engine\");\n const activeEngine =\n (engineSetting?.engine as string | undefined) ?? \"anthropic\";\n const provider = engineToProvider(activeEngine);\n const userKey = await getOwnerApiKey(provider, ownerEmail);\n if (userKey) return userKey;\n const envVar = PROVIDER_TO_ENV[provider];\n if (!envVar || !canUseDeployCredentialFallbackForRequest(envVar)) {\n return undefined;\n }\n const envKey = readDeployCredentialEnv(envVar);\n if (\n envKey &&\n !(await getProviderCredentialAuthFailure({ key: envVar, value: envKey }))\n ) {\n return envKey;\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/** @deprecated Use getOwnerApiKey(\"anthropic\", ownerEmail) instead */\nexport async function getOwnerAnthropicApiKey(\n ownerEmail: string | null | undefined,\n): Promise<string | undefined> {\n return getOwnerApiKey(\"anthropic\", ownerEmail);\n}\n\n/**\n * Context passed as the optional second argument to an action's `run`.\n * Defined in `../action.js` (cycle-free home) and re-exported here so existing\n * importers (e.g. `scripts/call-agent.ts`) keep their import path.\n */\nexport type { ActionRunContext, ActionCaller } from \"../action.js\";\n\nexport interface ActionEntry {\n tool: ActionTool;\n run: (\n args: any,\n context?: import(\"../action.js\").ActionRunContext,\n ) => Promise<any> | any;\n /** Standard Schema input validator when declared through defineAction. */\n schema?: unknown;\n /** HTTP exposure config. `false` = agent-only. Omitted = auto-inferred from name. */\n http?: import(\"../action.js\").ActionHttpConfig | false;\n /** Whether HTTP/frontend action calls must have an authenticated owner.\n * Defaults to true; false lets safe metadata/read actions run with\n * `ctx.userEmail` undefined when auth resolution returns 401/403. */\n requiresAuth?: boolean;\n /** Max HTTP request body in bytes; the route 413s on `Content-Length` before\n * parsing. For public, no-auth POST actions. */\n maxBodyBytes?: number;\n /** Whether the action is exposed to the agent as a callable tool. Only an\n * explicit `false` hides it from every agent tool surface (in-app assistant,\n * MCP, A2A, job/trigger runners) while leaving it frontend/HTTP-callable.\n * Set by `defineAction`'s `agentTool` option. */\n agentTool?: boolean;\n /** Explicit opt-in metadata for public agent protocols. Public routes never\n * imply public tool exposure; MCP/A2A/OpenAPI surfaces must filter for this. */\n publicAgent?: import(\"../action.js\").PublicAgentActionConfig;\n /** If true, completion does NOT trigger a screen-refresh change event.\n * Set automatically by `defineAction` when `http.method === \"GET\"`. */\n readOnly?: boolean;\n /** False keeps a read-only tool available in Act mode but hides/blocks it in\n * Plan mode. Use for tools that perform substantive work even without\n * mutating state. */\n allowInPlanMode?: boolean;\n /** If true, this action can run concurrently with other same-turn\n * read-only/parallel-safe tool calls. Only use for actions that handle\n * their own write ordering and idempotency. */\n parallelSafe?: boolean;\n /** Whether this action may be invoked from the tools-iframe bridge.\n * **Default-allow opt-out**: only an explicit `false` returns 403.\n * - `true` / `undefined` — allow.\n * - `false` — explicit deny; the tools bridge returns 403.\n * See `defineAction` (`packages/core/src/action.ts`) and audit H5 in\n * `security-audit/05-tools-sandbox.md`. */\n toolCallable?: boolean;\n /** Optional deep-link builder. When set, MCP/A2A surfaces append an\n * \"Open in <app> →\" link built from the call's args + result. Pure, sync,\n * best-effort. See `defineAction` and the `external-agents` skill. */\n link?: import(\"../action.js\").ActionLinkBuilder;\n /** Optional MCP Apps UI resource for hosts that support inline interactive\n * app iframes. CLI/non-UI hosts still receive the normal tool result and\n * any deep link from `link`. */\n mcpApp?: import(\"../action.js\").ActionMcpAppConfig;\n /** Optional native Agent-Native chat renderer for this action's result. */\n chatUI?: import(\"../action-ui.js\").ActionChatUIConfig;\n /**\n * Per-tool timeout override in milliseconds. When set, the agent loop uses\n * this value instead of the global TOOL_TIMEOUT_MS (60 s) for this action.\n * Useful for long-running tools such as sandboxed code execution.\n */\n timeoutMs?: number;\n /**\n * Per-tool max-result-chars override. When set, the agent loop truncates\n * the result to this many characters instead of the global 50 000 cap.\n */\n maxResultChars?: number;\n /**\n * Opt-in human-in-the-loop approval gate (default off). When truthy (or a\n * predicate that resolves truthy for the call's args), the loop emits\n * `approval_required` and stops the turn instead of executing this action,\n * until a human approves the specific call. Set by `defineAction`'s\n * `needsApproval` option. See `packages/core/docs/content/actions.mdx`.\n */\n needsApproval?:\n | boolean\n | ((\n args: any,\n ctx?: import(\"../action.js\").ActionRunContext,\n ) => boolean | Promise<boolean>);\n}\n\n/** @deprecated Use `ActionEntry` instead */\nexport type ScriptEntry = ActionEntry;\n\nexport type AgentExecutionMode = \"act\" | \"plan\";\n\nexport const PLAN_MODE_SYSTEM_PROMPT = `## Plan Mode Active\n\nYou are in Plan mode. This turn is for research, clarification, and a proposed approach only.\n\nHard rules:\n- Use only read-only tools. Do not edit files, write resources, run mutating bash commands, mutate SQL rows, navigate the UI, send notifications, create jobs, create tools, call external agents, or change external systems.\n- If a needed detail is unclear, ask a concise clarifying question before proposing a plan.\n- When ready, present a concrete plan with the files/tools you expect to touch, the intended changes, validation steps, and notable risks.\n- Do not treat approval as implicit while Plan mode is still active. Tell the user to switch to Act mode with the mode selector or /act before implementation.`;\n\nconst PLAN_MODE_BLOCKED_READONLY_TOOLS = new Set([\n \"refresh-screen\",\n \"set-search-params\",\n \"set-url-path\",\n]);\n\nconst PLAN_MODE_ALLOWED_ACTIONS: Record<string, readonly string[]> = {\n resources: [\"list\", \"read\"],\n \"chat-history\": [\"search\"],\n \"agent-teams\": [\"status\", \"read-result\", \"list\"],\n \"manage-jobs\": [\"list\"],\n \"manage-automations\": [\"list-events\", \"list\"],\n \"manage-notifications\": [\"list\"],\n \"manage-progress\": [\"list\"],\n \"manage-agent-engine\": [\"list\"],\n};\n\nconst PLAN_MODE_WEB_REQUEST_METHODS = new Set([\"GET\", \"HEAD\"]);\nconst SOURCE_SWEEP_AGENT_TEAM_ALLOWED_ACTIONS = [\n \"status\",\n \"read-result\",\n \"list\",\n] as const;\n\nfunction getToolAction(name: string, args: unknown): string {\n const raw =\n args && typeof args === \"object\" && \"action\" in args\n ? (args as Record<string, unknown>).action\n : undefined;\n if (raw == null && name === \"chat-history\") return \"search\";\n return String(raw ?? \"\").toLowerCase();\n}\n\nfunction getWebRequestMethod(args: unknown): string {\n const raw =\n args && typeof args === \"object\" && \"method\" in args\n ? (args as Record<string, unknown>).method\n : undefined;\n return String(raw ?? \"GET\").toUpperCase();\n}\n\nfunction restrictActionEnum(\n parameters: ActionTool[\"parameters\"] | undefined,\n allowedActions: readonly string[],\n): ActionTool[\"parameters\"] | undefined {\n if (!parameters) return parameters;\n const actionParam = parameters.properties.action;\n if (!actionParam) return parameters;\n return {\n ...parameters,\n properties: {\n ...parameters.properties,\n action: {\n ...actionParam,\n enum: [...allowedActions],\n },\n },\n };\n}\n\nfunction restrictWebRequestMethods(\n parameters: ActionTool[\"parameters\"] | undefined,\n): ActionTool[\"parameters\"] | undefined {\n if (!parameters) return parameters;\n const methodParam = parameters.properties.method;\n if (!methodParam) return parameters;\n return {\n ...parameters,\n properties: {\n ...parameters.properties,\n method: {\n ...methodParam,\n enum: [...PLAN_MODE_WEB_REQUEST_METHODS],\n },\n },\n };\n}\n\nfunction planModeBlockedMessage(toolName: string, reason?: string): string {\n return (\n `Plan mode blocked \\`${toolName}\\`` +\n (reason ? ` (${reason})` : \"\") +\n \". Switch to Act mode after the user approves the plan, then retry the action.\"\n );\n}\n\nexport function isPlanModeToolCallAllowed(\n name: string,\n input: unknown,\n entry: ActionEntry,\n): boolean {\n if (entry.allowInPlanMode === false) return false;\n if (PLAN_MODE_BLOCKED_READONLY_TOOLS.has(name)) return false;\n\n if (name === \"web-request\") {\n return PLAN_MODE_WEB_REQUEST_METHODS.has(getWebRequestMethod(input));\n }\n\n if (name === \"bash\") {\n return isPlanModeReadOnlyBashCall(input);\n }\n\n const allowedActions = PLAN_MODE_ALLOWED_ACTIONS[name];\n if (allowedActions) {\n return allowedActions.includes(getToolAction(name, input));\n }\n\n return entry.readOnly === true;\n}\n\nfunction isPlanModeReadOnlyBashCall(input: unknown): boolean {\n if (!input || typeof input !== \"object\") return false;\n const command = (input as Record<string, unknown>).command;\n if (typeof command !== \"string\") return false;\n return isReadOnlyShellCommand(command);\n}\n\nfunction createPlanModeGuardedAction(\n name: string,\n entry: ActionEntry,\n allowedActions: readonly string[],\n): ActionEntry {\n return {\n ...entry,\n readOnly: true,\n tool: {\n ...entry.tool,\n description:\n `${entry.tool.description}\\n\\nPlan mode: only these read-only actions are available: ` +\n allowedActions.map((action) => `\"${action}\"`).join(\", \") +\n \".\",\n parameters: restrictActionEnum(entry.tool.parameters, allowedActions),\n },\n run: async (args, context) => {\n const action = getToolAction(name, args);\n if (!allowedActions.includes(action)) {\n return planModeBlockedMessage(\n name,\n `action=\"${action || \"(missing)\"}\"`,\n );\n }\n return entry.run(args, context);\n },\n };\n}\n\nfunction createPlanModeWebRequestAction(entry: ActionEntry): ActionEntry {\n return {\n ...entry,\n readOnly: true,\n tool: {\n ...entry.tool,\n description: `${entry.tool.description}\\n\\nPlan mode: only GET and HEAD requests are allowed.`,\n parameters: restrictWebRequestMethods(entry.tool.parameters),\n },\n run: async (args, context) => {\n const method = getWebRequestMethod(args);\n if (!PLAN_MODE_WEB_REQUEST_METHODS.has(method)) {\n return planModeBlockedMessage(\"web-request\", `method=\"${method}\"`);\n }\n return entry.run(args, context);\n },\n };\n}\n\nfunction createPlanModeBashAction(entry: ActionEntry): ActionEntry {\n return {\n ...entry,\n readOnly: true,\n tool: {\n ...entry.tool,\n description: `${entry.tool.description}\\n\\nPlan mode: only read-only inspection commands such as pwd, ls, find, rg, grep, cat, sed -n, head, tail, wc, and git status/diff/show/log are allowed.`,\n },\n run: async (args, context) => {\n if (!isPlanModeReadOnlyBashCall(args)) {\n return planModeBlockedMessage(\"bash\", \"command is not read-only\");\n }\n return entry.run(args, context);\n },\n };\n}\n\nfunction createPlanModeBlockedAction(\n name: string,\n entry: ActionEntry,\n reason?: string,\n): ActionEntry {\n return {\n ...entry,\n allowInPlanMode: false,\n readOnly: true,\n tool: {\n ...entry.tool,\n description: `${entry.tool.description}\\n\\nPlan mode blocked: ${reason ?? \"not available while planning\"}.`,\n },\n run: async () => planModeBlockedMessage(name, reason),\n };\n}\n\nexport function createPlanModeActionRegistry(\n actions: Record<string, ActionEntry>,\n): Record<string, ActionEntry> {\n const filtered: Record<string, ActionEntry> = {};\n\n for (const [name, entry] of Object.entries(actions)) {\n if (name === TOOL_SEARCH_ACTION_NAME) continue;\n if (entry.allowInPlanMode === false) {\n filtered[name] = createPlanModeBlockedAction(\n name,\n entry,\n \"not available while planning\",\n );\n continue;\n }\n if (PLAN_MODE_BLOCKED_READONLY_TOOLS.has(name)) {\n filtered[name] = createPlanModeBlockedAction(\n name,\n entry,\n \"not available while planning\",\n );\n continue;\n }\n\n const allowedActions = PLAN_MODE_ALLOWED_ACTIONS[name];\n if (allowedActions) {\n filtered[name] = createPlanModeGuardedAction(name, entry, allowedActions);\n continue;\n }\n\n if (name === \"web-request\") {\n filtered[name] = createPlanModeWebRequestAction(entry);\n continue;\n }\n\n if (name === \"bash\") {\n filtered[name] = createPlanModeBashAction(entry);\n continue;\n }\n\n if (entry.readOnly === true) {\n filtered[name] = entry;\n } else {\n filtered[name] = createPlanModeBlockedAction(\n name,\n entry,\n \"write or side-effecting tool\",\n );\n }\n }\n\n if (actions[TOOL_SEARCH_ACTION_NAME]) {\n filtered[TOOL_SEARCH_ACTION_NAME] = createToolSearchEntry(() => filtered);\n }\n\n return filtered;\n}\n\nexport interface ProductionAgentOptions {\n /** Action entries for the agent. Use `actions` (preferred) or `scripts` (deprecated alias). */\n actions?: Record<string, ActionEntry>;\n /** @deprecated Use `actions` instead */\n scripts?: Record<string, ActionEntry>;\n /** Static system prompt string, or async function called per-request with the H3 event */\n systemPrompt: string | ((event: any) => string | Promise<string>);\n /** Falls back to ANTHROPIC_API_KEY env var. Ignored when `engine` is provided. */\n apiKey?: string;\n /** Agent engine to use. Defaults to the \"anthropic\" engine. */\n engine?:\n | AgentEngine\n | string\n | { name: string; config: Record<string, unknown> };\n /** Model to use. Defaults to the resolved engine's default model. */\n model?: string;\n /** App/template id used for org-scoped per-app model defaults. */\n appId?: string;\n /** Default reasoning effort for requests that do not supply an override. */\n reasoningEffort?: ReasoningEffort;\n /** Provider-specific options passed through to the engine */\n providerOptions?: EngineMessage extends never ? never : any;\n /** Called when a run completes (for server-side thread persistence) */\n onRunComplete?: (run: ActiveRun, threadId: string | undefined) => void;\n /** Called after request validation but before a run is started. */\n onRunPrepared?: (details: {\n runId: string;\n threadId: string | undefined;\n message: string;\n attachments?: AgentChatAttachment[];\n }) => void | Promise<void>;\n /**\n * Optional per-template request normalizer. Runs after owner resolution and\n * before system/context assembly so templates can materialize uploaded chat\n * attachments or append app-specific, non-visible instructions.\n */\n prepareRequest?: (details: {\n event: any;\n ownerEmail: string | null;\n message: string;\n displayMessage?: string;\n attachments: AgentChatAttachment[];\n references: AgentChatReference[];\n threadId?: string;\n internalContinuation?: boolean;\n mode: AgentExecutionMode;\n }) =>\n | void\n | {\n message?: string;\n displayMessage?: string;\n attachments?: AgentChatAttachment[];\n }\n | Promise<void | {\n message?: string;\n displayMessage?: string;\n attachments?: AgentChatAttachment[];\n }>;\n /** Optional per-app agent run chunk budget in milliseconds. Defaults to\n * AGENT_RUN_SOFT_TIMEOUT_MS when set, otherwise no framework-imposed\n * timeout. When reached, the client receives an internal auto-continuation\n * signal instead of a user-facing warning. */\n runSoftTimeoutMs?: number;\n /** Optional no-progress watchdog override for this app's runs. */\n runNoProgressTimeoutMs?: number;\n /**\n * Opt this app into durable Netlify background-function agent-chat runs. This\n * is a runtime opt-in layered on top of the hosted-runtime + A2A_SECRET gates;\n * single-template Netlify deploys must also enable the deploy-time\n * `AGENT_CHAT_DURABLE_BACKGROUND` flag so the background function is emitted.\n */\n durableBackgroundRuns?: boolean;\n /** Called when a run starts, with the send function for emitting events and the threadId */\n onRunStart?: (\n send: (event: AgentChatEvent) => void,\n threadId: string,\n ) => void | Promise<void>;\n /**\n * Called after the engine + model are resolved for this request. Used by\n * the plugin layer to thread the parent's choices into sub-agents so\n * delegated tasks don't default back to Anthropic + Claude.\n */\n onEngineResolved?: (engine: AgentEngine, model: string) => void;\n /** Resolve the owner email from the H3 event (for usage tracking) */\n resolveOwnerEmail?: (event: any) => string | Promise<string>;\n /**\n * Optional final-answer guard. If it returns a message after a text-only\n * assistant turn, the loop clears that draft once and asks the model to\n * continue with the returned corrective instruction before allowing a final.\n */\n finalResponseGuard?: AgentLoopFinalResponseGuard;\n /**\n * Skip auto-injecting the workspace files/skills/agents inventory on the\n * first message of a conversation. Useful for minimal/voice apps where\n * the ~2KB inventory of unrelated resources is noise, not signal.\n * Default: false (inventory is injected).\n */\n skipFilesContext?: boolean;\n /**\n * Optional starter tool catalog. When set, the first model request includes\n * only these tool schemas plus `tool-search`; the full action registry remains\n * searchable, and matching tool schemas from `tool-search` results are added\n * to the next model request. This keeps first-token latency low without\n * forcing rarely used capabilities into every prompt. The framework also\n * promotes common provider/corpus/code-execution tools when the current\n * app/mode registry exposes them, so prompts that teach broad integrations do\n * not describe tools that require an extra discovery turn before use.\n */\n initialToolNames?: string[];\n /**\n * App-level default tool limits. Each action's own `timeoutMs` /\n * `maxResultChars` takes precedence; this sets the fallback for actions\n * that don't declare their own limits.\n */\n toolLimits?: { timeoutMs?: number; maxResultChars?: number };\n}\n\nexport async function resolveAgentOwnerEmail(\n options: Pick<ProductionAgentOptions, \"resolveOwnerEmail\">,\n event: any,\n): Promise<string | null> {\n let ownerEmail: string | null = null;\n if (options.resolveOwnerEmail) {\n try {\n ownerEmail = await options.resolveOwnerEmail(event);\n } catch {\n ownerEmail = null;\n }\n }\n return ownerEmail ?? getRequestUserEmail() ?? null;\n}\n\nconst MAX_RETRIES = 3;\n/**\n * Retry budget override for `builder_gateway_error` — the no-detail Builder\n * gateway fallback. Production data shows this code is almost never\n * transient: it's the gateway emitting `{type:\"stop\",reason:\"error\"}` with\n * no explanation, which usually means the upstream provider rejected the\n * call (model quota, account misconfiguration). Retrying the same request\n * synchronously rarely recovers, and each retry emits a `clear` event that\n * wipes the user's visible content and re-streams from scratch — three\n * cycles of \"regenerate, clear, regenerate\" inside a single run for a\n * failure mode where retrying doesn't help. Keep the budget at 1 so we\n * cover genuinely transient cases without the visible flicker storm.\n */\nconst BUILDER_GATEWAY_ERROR_MAX_RETRIES = 1;\nconst RETRY_BASE_DELAY_MS = 2000;\n\nfunction maxRetriesForError(err: unknown): number {\n if (err instanceof EngineError) {\n const code = (err.errorCode ?? \"\").toLowerCase();\n if (code === \"builder_gateway_error\") {\n return BUILDER_GATEWAY_ERROR_MAX_RETRIES;\n }\n }\n return MAX_RETRIES;\n}\nconst TOOL_INPUT_ACTIVITY_INTERVAL_MS = 1500;\nconst ACTION_PREPARATION_NO_PROGRESS_TIMEOUT_MS = 90_000;\nconst ACTION_PREPARATION_ZERO_BYTE_RESTART_LIMIT = 2;\nconst MODEL_STREAM_NO_PROGRESS_TIMEOUT_MS = 90_000;\n// Raised from 1 -> 2 now that each retry actually adapts (raises the token\n// ceiling and steps reasoning effort down a tier) instead of re-issuing the\n// exact same doomed request twice.\nconst EMPTY_FINAL_RESPONSE_RETRY_LIMIT = 2;\nconst MAIN_CHAT_INTERNAL_CONTINUATION_LIMIT = 6;\nconst RUN_BUDGET_EXHAUSTED_ERROR_CODE = \"run_budget_exhausted\";\nconst RUN_BUDGET_EXHAUSTED_MESSAGE =\n \"I ran out of time before finishing this step. \" +\n \"I stopped rather than keep retrying silently. \" +\n \"Check any completed tool cards above before retrying, ideally as one smaller follow-up.\";\nconst MAX_TEXT_ATTACHMENT_CHARS = 60_000;\nconst MAX_SELECTION_CONTEXT_CHARS = 8_000;\nconst MAX_RESOURCE_INVENTORY_ITEMS = 40;\nconst MAX_RESOURCE_INVENTORY_DESCRIPTION_CHARS = 160;\nconst MAX_INLINE_SKILL_REFERENCE_CHARS = 40_000;\nconst SOURCE_SWEEP_TOOL_CALL_THRESHOLD = 12;\n\n/**\n * Hard cap on the `<current-screen>` block injected into EVERY user message.\n *\n * The screen snapshot comes from the template's `view-screen` action, which can\n * be unbounded — e.g. a recording/meeting page returns the full transcript +\n * every segment. Injected on every turn with no cap, that single block can blow\n * past the model's context window and hard-error the chat with\n * `context_length_exceeded` (observed: a brand-new \"hi\" message failing because\n * an open recording's transcript shipped in `<current-screen>`). Keep this to a\n * compact page summary; the agent can call `view-screen` (or a data action like\n * `get-recording-player-data`) for full detail on demand.\n */\nconst MAX_SCREEN_CONTEXT_CHARS = 10_000;\n\nfunction capScreenContext(text: string): string {\n if (text.length <= MAX_SCREEN_CONTEXT_CHARS) return text;\n return `${text.slice(0, MAX_SCREEN_CONTEXT_CHARS)}\\n\\n…[current-screen snapshot truncated after ${MAX_SCREEN_CONTEXT_CHARS.toLocaleString()} chars to protect the context window. Call the view-screen action for the full snapshot, or a data action (e.g. get-recording-player-data) for full transcripts.]`;\n}\n\nfunction capSelectionContext(text: string): string {\n if (text.length <= MAX_SELECTION_CONTEXT_CHARS) return text;\n return `${text.slice(0, MAX_SELECTION_CONTEXT_CHARS)}\\n\\n…[selection truncated after ${MAX_SELECTION_CONTEXT_CHARS.toLocaleString()} chars. Ask the user or use an app data action if the omitted text is required.]`;\n}\n\nfunction compactInventoryDescription(description: string): string {\n const oneLine = description.replace(/\\s+/g, \" \").trim();\n if (oneLine.length <= MAX_RESOURCE_INVENTORY_DESCRIPTION_CHARS) {\n return oneLine;\n }\n return `${oneLine.slice(0, MAX_RESOURCE_INVENTORY_DESCRIPTION_CHARS - 1)}…`;\n}\n\nfunction limitInventoryLines(lines: string[], label: string): string[] {\n if (lines.length <= MAX_RESOURCE_INVENTORY_ITEMS) return lines;\n const omitted = lines.length - MAX_RESOURCE_INVENTORY_ITEMS;\n return [\n ...lines.slice(0, MAX_RESOURCE_INVENTORY_ITEMS),\n ` … ${omitted} more ${label} omitted; use the resources tool with action \"list\" or \"read\" for the full inventory.`,\n ];\n}\n\nfunction generateRunId(): string {\n return `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\nfunction toolInputActivityLabel(toolName?: string): string {\n return toolName ? `Preparing ${toolName} action` : \"Preparing action input\";\n}\n\n/** Check if an error is transient and should be retried\n * @internal exported for unit tests only\n */\nexport function isContextTooLongError(err: unknown): boolean {\n if (!(err instanceof Error)) return false;\n const msg = err.message.toLowerCase();\n if (\n msg.includes(\"context_length_exceeded\") ||\n msg.includes(\"input_too_long\") ||\n msg.includes(\"too many tokens\") ||\n msg.includes(\"prompt is too long\") ||\n msg.includes(\"reduce the length\") ||\n // Gemini phrasing\n msg.includes(\"input token count exceeds\") ||\n msg.includes(\"request too large\")\n )\n return true;\n if (err instanceof EngineError) {\n const code = (err.errorCode ?? \"\").toLowerCase();\n if (code.includes(\"context_length\") || code.includes(\"input_too_long\"))\n return true;\n }\n return false;\n}\n\n/** @internal exported for unit tests only */\nexport function isRetryableError(err: unknown): boolean {\n if (!(err instanceof Error)) return false;\n const msg = err.message.toLowerCase();\n const engineErr = err instanceof EngineError ? err : null;\n const code = (engineErr?.errorCode ?? \"\").toLowerCase();\n\n // Hard non-retryable codes — check these first.\n if (code === \"builder_gateway_timeout\") return false;\n if (\n code === \"rate_limit_exceeded\" ||\n msg.includes(\"daily gateway request cap\")\n )\n return false;\n\n // Prefer structured fields from the engine before falling back to message\n // keyword matching — avoids false positives on user-supplied text that\n // happens to contain \"rate_limit\" etc.\n if (engineErr) {\n // Provider explicitly said it is retryable.\n if (engineErr.providerRetryable === true) return true;\n // HTTP status-code checks (429, 500, 502, 503, 529 = Anthropic overloaded).\n const sc = engineErr.statusCode;\n if (sc === 429 || sc === 500 || sc === 502 || sc === 503 || sc === 529)\n return true;\n }\n\n return (\n code === \"builder_gateway_error\" ||\n code === \"builder_gateway_network_error\" ||\n code === \"provider_network_error\" ||\n code === \"http_429\" ||\n code === \"http_500\" ||\n code === \"http_502\" ||\n code === \"http_503\" ||\n code === \"http_504\" ||\n code === \"timeout\" ||\n // Anthropic\n msg.includes(\"overloaded\") ||\n msg.includes(\"rate_limit\") ||\n // Bare provider rate-limit messages that carry no structured status,\n // e.g. the Anthropic/AI-SDK \"429 status code (no body)\" format.\n /\\b429\\b/.test(msg) ||\n msg.includes(\"529\") ||\n // OpenAI phrasing\n msg.includes(\"rate limit reached\") ||\n // Google / Gemini\n msg.includes(\"resource_exhausted\") ||\n msg.includes(\"quota exceeded\") ||\n // Generic HTTP codes\n msg.includes(\"502\") ||\n msg.includes(\"503\") ||\n msg.includes(\"504\") ||\n msg.includes(\"gateway error\") ||\n msg.includes(\"socket hang up\") ||\n msg.includes(\"connection reset\") ||\n // Anthropic SDK APIConnectionError default message is exactly\n // \"Connection error.\" — Builder gateway often forwards it as a stop\n // event with no structured code. Without this match the run fails in\n // ~3s and the client recovery loop storms POSTs.\n msg.includes(\"connection error\") ||\n msg.includes(\"too many requests\") ||\n msg.includes(\"timeout\") ||\n msg.includes(\"gateway timeout\") ||\n msg.includes(\"inactivity timeout\") ||\n msg.includes(\"too much time has passed without sending any data\")\n );\n}\n\n// ---------------------------------------------------------------------------\n// Context-window overflow recovery\n// ---------------------------------------------------------------------------\n\n/**\n * Number of recent messages to protect when trimming tool results.\n * Messages in the tail of this length are left completely intact; only\n * older messages have their tool-result text replaced with a stub.\n */\nconst CONTEXT_TRIM_KEEP_TAIL = 10;\nconst CONTEXT_TRIM_STUB =\n \"[result trimmed to save context — re-run the tool if needed]\";\n\n/**\n * Attempt one aggressive trim of old tool-result content to reduce the\n * context window usage. Tool-result messages older than the last\n * {@link CONTEXT_TRIM_KEEP_TAIL} messages have their text replaced with a\n * short stub. All user/assistant text messages and the recent tail are\n * preserved exactly.\n *\n * Returns a new array — the original is not mutated.\n * Returns `null` when there are no trimable tool results (so the caller can\n * skip the retry).\n */\nexport function trimOldToolResults(\n messages: EngineMessage[],\n keepTail = CONTEXT_TRIM_KEEP_TAIL,\n): EngineMessage[] | null {\n const cutoff = Math.max(0, messages.length - keepTail);\n let trimmed = false;\n\n const result = messages.map((msg, idx): EngineMessage => {\n // Keep messages in the protected tail intact\n if (idx >= cutoff) return msg;\n\n // Only touch user messages that contain tool-result parts\n if (msg.role !== \"user\") return msg;\n\n const hasToolResult = msg.content.some((p) => p.type === \"tool-result\");\n if (!hasToolResult) return msg;\n\n const stubbedContent = msg.content.map(\n (p): import(\"./engine/types.js\").EngineContentPart => {\n if (p.type !== \"tool-result\") return p;\n trimmed = true;\n return { ...p, content: CONTEXT_TRIM_STUB };\n },\n );\n\n return { role: \"user\", content: stubbedContent };\n });\n\n return trimmed ? result : null;\n}\n\n/** Wait with exponential backoff, respecting abort signal */\nfunction retryDelay(attempt: number, signal: AbortSignal): Promise<void> {\n const baseMs = RETRY_BASE_DELAY_MS * Math.pow(2, attempt);\n const jitter = baseMs * 0.1;\n const ms = Math.max(0, baseMs + (Math.random() * 2 - 1) * jitter);\n return new Promise((resolve, reject) => {\n if (signal.aborted) return reject(new Error(\"aborted\"));\n const onAbort = () => {\n clearTimeout(timer);\n reject(new Error(\"aborted\"));\n };\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\ntype SupportedImageMediaType =\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\";\n\nfunction isSupportedImageMediaType(\n mediaType: string,\n): mediaType is SupportedImageMediaType {\n return (\n mediaType === \"image/jpeg\" ||\n mediaType === \"image/png\" ||\n mediaType === \"image/gif\" ||\n mediaType === \"image/webp\"\n );\n}\n\nfunction isSvgMediaType(mediaType: string | undefined): boolean {\n return mediaType?.split(\";\")[0]?.trim().toLowerCase() === \"image/svg+xml\";\n}\n\nfunction escapeAttachmentAttribute(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n}\n\nfunction unwrapTextAttachmentEnvelope(text: string): string {\n const match = text.match(/^<attachment\\b[^>]*>\\n([\\s\\S]*)\\n<\\/attachment>$/);\n return match ? match[1] : text;\n}\n\nfunction truncateTextAttachment(text: string, attachmentName?: string): string {\n if (text.length <= MAX_TEXT_ATTACHMENT_CHARS) return text;\n\n const omitted = text.length - MAX_TEXT_ATTACHMENT_CHARS;\n const readHint = attachmentName\n ? ` Use the \\`read-attachment\\` tool with name=\"${escapeAttachmentAttribute(attachmentName)}\" to read the rest.`\n : \"\";\n return `${text.slice(0, MAX_TEXT_ATTACHMENT_CHARS)}\\n\\n[Attachment truncated after ${MAX_TEXT_ATTACHMENT_CHARS.toLocaleString()} characters; ${omitted.toLocaleString()} characters omitted.${readHint}]`;\n}\n\nfunction formatTextAttachment(att: AgentChatAttachment): string | null {\n if (typeof att.text !== \"string\" || att.text.length === 0) return null;\n const text = truncateTextAttachment(\n unwrapTextAttachmentEnvelope(att.text),\n att.name,\n );\n\n const attrs = [\n `name=\"${escapeAttachmentAttribute(att.name || \"attachment\")}\"`,\n att.contentType\n ? `contentType=\"${escapeAttachmentAttribute(att.contentType)}\"`\n : null,\n att.type ? `type=\"${escapeAttachmentAttribute(att.type)}\"` : null,\n ].filter(Boolean);\n\n return `<attachment ${attrs.join(\" \")}>\\n${text}\\n</attachment>`;\n}\n\nfunction dataUrlToFilePart(\n att: AgentChatAttachment,\n): { type: \"file\"; data: string; mediaType: string; filename?: string } | null {\n if (att.type !== \"file\" || typeof att.data !== \"string\") return null;\n const match = att.data.match(/^data:([^;]+);base64,(.+)$/);\n if (!match) return null;\n return {\n type: \"file\",\n data: match[2],\n mediaType: att.contentType || match[1],\n filename: att.name || undefined,\n };\n}\n\nexport function buildUserContentWithAttachments(opts: {\n text: string;\n attachments?: AgentChatAttachment[];\n}): EngineContentPart[] {\n const userContent: EngineContentPart[] = [];\n const textAttachments: string[] = [];\n\n for (const att of opts.attachments ?? []) {\n const uploadedUrl = (att as any).url as string | undefined;\n if ((att as any).referenceOnly === true && uploadedUrl) {\n const label = att.name ? `\"${att.name}\"` : \"A file\";\n const contentType = att.contentType ? ` (${att.contentType})` : \"\";\n textAttachments.push(\n `[${label} was uploaded to ${uploadedUrl} as a reference-only file${contentType}. Use the URL for embedding/reference if needed; do not inline raw file contents unless the target app sanitizes it.]`,\n );\n continue;\n }\n\n if (att.type === \"image\") {\n if (!att.data) {\n if (uploadedUrl) {\n const label = att.name ? `\"${att.name}\"` : \"An image\";\n textAttachments.push(\n `[${label} was uploaded to ${uploadedUrl}, but was not sent as a vision image because no supported base64 image data was present. Use the URL for embedding/reference if needed.]`,\n );\n }\n continue;\n }\n const match = att.data.match(/^data:(image\\/[^;]+);base64,(.+)$/);\n if (match && isSupportedImageMediaType(match[1])) {\n userContent.push({\n type: \"image\",\n data: match[2],\n mediaType: match[1],\n });\n } else {\n // The client sent an image in an unsupported format (HEIC, TIFF, AVIF,\n // etc.). Inject a short text placeholder so the model knows the image\n // was present but could not be processed, rather than silently omitting\n // it and leaving the model confused (\"I don't see an image\").\n const mime = match?.[1] ?? att.contentType ?? \"unknown format\";\n const label = att.name ? `\"${att.name}\"` : \"An image\";\n const uploadedHint = uploadedUrl\n ? ` It is available at ${uploadedUrl}; use that URL for embedding/reference if the task does not require vision analysis.`\n : \"\";\n if (uploadedUrl && isSvgMediaType(mime)) {\n textAttachments.push(\n `[${label} was uploaded to ${uploadedUrl} as an SVG reference (${mime}). ` +\n `It was not sent as a vision image because SVG files are handled as reference-only vector files. ` +\n `Use the URL for embedding/reference if needed; ask for a JPEG, PNG, GIF, or WebP export only if rendered-pixel vision analysis is required.]`,\n );\n continue;\n }\n textAttachments.push(\n `[${label} could not be processed — unsupported image format (${mime}). ` +\n uploadedHint +\n ` Inform the user that only JPEG, PNG, GIF, and WebP images are supported for vision analysis, ` +\n `and ask them to convert the file before attaching.]`,\n );\n }\n continue;\n }\n\n const filePart = dataUrlToFilePart(att);\n if (filePart) {\n userContent.push(filePart);\n continue;\n }\n\n const textAttachment = formatTextAttachment(att);\n if (textAttachment) {\n textAttachments.push(textAttachment);\n }\n }\n\n userContent.push({\n type: \"text\",\n text:\n textAttachments.length > 0\n ? `${textAttachments.join(\"\\n\\n\")}\\n\\n${opts.text}`\n : opts.text,\n });\n\n return userContent;\n}\n\nfunction coerceStructuredToolResultWire(part: {\n toolCallId?: unknown;\n content?: unknown;\n}): { toolCallId: string; content: string } {\n const toolCallId =\n typeof part.toolCallId === \"string\"\n ? part.toolCallId.trim()\n : part.toolCallId === undefined || part.toolCallId === null\n ? \"\"\n : String(part.toolCallId).trim();\n let content = \"\";\n if (typeof part.content === \"string\") {\n content = part.content;\n } else if (part.content !== undefined && part.content !== null) {\n try {\n content = JSON.stringify(part.content);\n } catch {\n content = String(part.content);\n }\n }\n return { toolCallId, content };\n}\n\nexport function structuredHistoryToEngineMessages(\n history: AgentChatStructuredMessage[] | undefined,\n): EngineMessage[] | null {\n if (!Array.isArray(history)) return null;\n\n const toolUseById = new Map<string, { name: string; input: unknown }>();\n\n const messages: EngineMessage[] = [];\n for (const message of history) {\n if (\n !message ||\n (message.role !== \"user\" && message.role !== \"assistant\") ||\n !Array.isArray(message.content)\n ) {\n continue;\n }\n\n const content: EngineContentPart[] = [];\n for (const part of message.content) {\n if (!part || typeof part !== \"object\") continue;\n if (part.type === \"text\" && typeof part.text === \"string\") {\n if (part.text.length > 0) {\n content.push({ type: \"text\", text: part.text });\n }\n continue;\n }\n\n if (part.type === \"tool-call\" && message.role === \"assistant\") {\n const id =\n typeof part.id === \"string\"\n ? part.id\n : typeof part.toolCallId === \"string\"\n ? part.toolCallId\n : \"\";\n const name =\n typeof part.name === \"string\"\n ? part.name\n : typeof part.toolName === \"string\"\n ? part.toolName\n : \"\";\n if (!id || !name) continue;\n const input = part.input ?? part.args ?? {};\n toolUseById.set(id, { name, input });\n content.push({\n type: \"tool-call\",\n id,\n name,\n input,\n });\n continue;\n }\n\n if (part.type === \"tool-result\" && message.role === \"user\") {\n const wire = coerceStructuredToolResultWire(part);\n const lookup =\n wire.toolCallId.length > 0\n ? toolUseById.get(wire.toolCallId)\n : undefined;\n const toolName =\n typeof part.toolName === \"string\" && part.toolName.trim().length > 0\n ? part.toolName\n : lookup?.name;\n if (!toolName?.trim()) {\n content.push({\n type: \"text\",\n text: unmatchedToolResultReplayText({\n toolCallId:\n wire.toolCallId.length > 0 ? wire.toolCallId : \"(missing)\",\n content: wire.content,\n isError: part.isError,\n }),\n });\n continue;\n }\n if (!wire.toolCallId) {\n // Named tool but no id — cannot emit a valid paired `tool-result`.\n content.push({\n type: \"text\",\n text: unmatchedToolResultReplayText({\n toolCallId: \"(missing)\",\n content: wire.content,\n isError: part.isError,\n }),\n });\n continue;\n }\n const toolInput =\n typeof part.toolInput === \"string\" && part.toolInput.length > 0\n ? part.toolInput\n : stringifyToolUseInputForGateway(lookup?.input);\n content.push({\n type: \"tool-result\",\n toolCallId: wire.toolCallId,\n toolName,\n toolInput,\n content: wire.content,\n ...(part.isError ? { isError: true } : {}),\n });\n }\n }\n\n if (content.length > 0) {\n messages.push({ role: message.role, content });\n }\n }\n\n return messages.length > 0\n ? backfillEngineMessagesToolResults(messages)\n : null;\n}\n\n/** Build enriched message with file/skill/mention references */\nfunction capInlineSkillReferenceContent(text: string): string {\n const trimmed = text.trim();\n if (trimmed.length <= MAX_INLINE_SKILL_REFERENCE_CHARS) return trimmed;\n const omitted = trimmed.length - MAX_INLINE_SKILL_REFERENCE_CHARS;\n return `${trimmed.slice(0, MAX_INLINE_SKILL_REFERENCE_CHARS)}\\n\\n[Skill content truncated after ${MAX_INLINE_SKILL_REFERENCE_CHARS.toLocaleString()} chars; ${omitted.toLocaleString()} chars omitted.]`;\n}\n\nfunction escapeReferenceAttribute(value: string): string {\n return value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n}\n\nfunction isRuntimeVisibleSkillContent(content: string): boolean {\n const frontmatter = parseFrontmatter(content);\n const scope = getFrontmatterValue(frontmatter, \"scope\")?.trim().toLowerCase();\n return scope !== \"dev\";\n}\n\nexport async function resolveSkillReferenceContent(\n ref: AgentChatReference,\n): Promise<string | null> {\n if (!ref.path && !ref.name) return null;\n\n if (ref.source === \"resource\") {\n const ownerEmail = getRequestUserEmail();\n if (!ownerEmail || !ref.path) return null;\n try {\n const { resourceEffectiveContext, resourceGet } =\n await import(\"../resources/store.js\");\n const resourceOptions = {\n userEmail: ownerEmail,\n orgId: getRequestOrgId() ?? null,\n };\n const effective = await resourceEffectiveContext(ownerEmail, ref.path, {\n ...resourceOptions,\n });\n if (!effective.effectiveResource) return null;\n const full = await resourceGet(effective.effectiveResource.id, {\n ...resourceOptions,\n });\n if (!full?.content || !isRuntimeVisibleSkillContent(full.content)) {\n return null;\n }\n return full.content;\n } catch {\n return null;\n }\n }\n\n try {\n const { loadAgentsBundle, getRuntimeSkills } =\n await import(\"../server/agents-bundle.js\");\n const bundle = await loadAgentsBundle();\n const normalizedPath = ref.path?.replace(/\\/+$/g, \"\");\n const skill = getRuntimeSkills(bundle).find((candidate) => {\n const skillPath = candidate.dir.replace(/\\/+$/g, \"\");\n return (\n candidate.meta.name === ref.name ||\n normalizedPath === skillPath ||\n normalizedPath === `${skillPath}/SKILL.md`\n );\n });\n return skill?.content ?? null;\n } catch {\n return null;\n }\n}\n\nasync function enrichMessage(\n message: string,\n references: AgentChatReference[],\n): Promise<string> {\n if (references.length === 0) return message;\n\n const fileRefs = references.filter((r) => r.type === \"file\");\n const skillRefs = references.filter((r) => r.type === \"skill\");\n const customAgentRefs = references.filter((r) => r.type === \"custom-agent\");\n const mentionRefs = references.filter((r) => r.type === \"mention\");\n\n const parts: string[] = [];\n if (fileRefs.length > 0) {\n parts.push(\n \"Referenced files:\\n\" +\n fileRefs\n .map(\n (r) => `- ${r.path}${r.source === \"resource\" ? \" (resource)\" : \"\"}`,\n )\n .join(\"\\n\"),\n );\n }\n if (skillRefs.length > 0) {\n const skillLines = await Promise.all(\n skillRefs.map(async (r) => {\n const content = await resolveSkillReferenceContent(r);\n if (content?.trim()) {\n return `- ${r.name} (${r.path})\\n\\n<applied-skill name=\"${escapeReferenceAttribute(r.name)}\" path=\"${escapeReferenceAttribute(r.path)}\" source=\"${escapeReferenceAttribute(r.source)}\">\\n${capInlineSkillReferenceContent(content)}\\n</applied-skill>`;\n }\n return `- ${r.name} (${r.path})${\n r.source === \"resource\"\n ? ' — content was not inlined; read with the resources tool (action: \"read\") if needed'\n : \" — content was not inlined; read with the read tool if needed\"\n }`;\n }),\n );\n parts.push(\n \"Applied skills (read and follow before acting):\\n\" +\n skillLines.join(\"\\n\"),\n );\n }\n if (customAgentRefs.length > 0) {\n parts.push(\n \"Requested custom agents:\\n\" +\n customAgentRefs\n .map(\n (r) =>\n `- ${r.name}${r.refId ? ` (id: ${r.refId})` : \"\"}${r.path ? ` (path: ${r.path})` : \"\"}`,\n )\n .join(\"\\n\"),\n );\n }\n if (mentionRefs.length > 0) {\n parts.push(\n \"Referenced items:\\n\" +\n mentionRefs\n .map(\n (r) =>\n `- [${r.refType || \"item\"}] ${r.name}${r.refId ? ` (id: ${r.refId})` : \"\"}${r.path ? ` (path: ${r.path})` : \"\"}`,\n )\n .join(\"\\n\"),\n );\n }\n\n return `${parts.join(\"\\n\\n\")}\\n\\n${message}`;\n}\n\n/** Accumulated token usage from an agent loop run */\nexport interface AgentLoopUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n model: string;\n}\n\nexport interface AgentLoopToolCallSummary {\n name: string;\n input: unknown;\n}\n\nexport interface AgentLoopToolResultSummary {\n name: string;\n content: string;\n isError: boolean;\n}\n\nexport interface AgentLoopFinalResponseGuardContext {\n messages: EngineMessage[];\n assistantContent: EngineContentPart[];\n text: string;\n toolCalls: AgentLoopToolCallSummary[];\n toolResults: AgentLoopToolResultSummary[];\n retryCount: number;\n executionMode: AgentExecutionMode;\n}\n\nexport type AgentLoopFinalResponseGuardResult =\n | string\n | {\n retryMessage: string;\n fallbackMessage?: string;\n };\n\nexport type AgentLoopFinalResponseGuard = (\n context: AgentLoopFinalResponseGuardContext,\n) =>\n | AgentLoopFinalResponseGuardResult\n | null\n | undefined\n | Promise<AgentLoopFinalResponseGuardResult | null | undefined>;\n\nfunction collectTextParts(parts: EngineContentPart[]): string {\n return parts\n .filter(\n (part): part is import(\"./engine/types.js\").EngineTextPart =>\n part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\");\n}\n\nexport const AGENT_INTERNAL_CONTINUE_PROMPT =\n \"Continue from where you left off and finish the user's original request. Do not repeat completed work, do not mention internal reconnects, time limits, or step limits, and continue as if this is the same uninterrupted run.\";\n\nexport type AgentLoopContinuationReason =\n | \"run_timeout\"\n | \"loop_limit\"\n | \"max_tokens\"\n | \"stream_ended\"\n | \"gateway_timeout\"\n | \"network_interrupted\"\n | \"no_progress\";\n\nexport function appendAgentLoopContinuation(\n messages: EngineMessage[],\n reason: AgentLoopContinuationReason,\n options: { actionPreparationTool?: string } = {},\n) {\n const note =\n reason === \"loop_limit\"\n ? \"The previous run reached an internal step budget.\"\n : reason === \"max_tokens\"\n ? \"The previous LLM call reached the model output-token cap before the response finished.\"\n : reason === \"stream_ended\"\n ? \"The previous stream ended before the agent sent a final completion signal.\"\n : reason === \"gateway_timeout\"\n ? \"The previous LLM call hit an upstream gateway timeout before the response finished streaming.\"\n : reason === \"network_interrupted\"\n ? \"The previous LLM call was cut off by a transport-level interruption (socket dropped, connection reset, or stream closed unexpectedly).\"\n : reason === \"no_progress\"\n ? \"The previous run stopped producing progress events while the connection stayed open.\"\n : \"The previous run reached an internal execution budget.\";\n const actionInputNote = options.actionPreparationTool\n ? actionPreparationContinuationNote(options.actionPreparationTool)\n : \"\";\n messages.push({\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: `${AGENT_INTERNAL_CONTINUE_PROMPT}\\n\\nInternal note: ${note}${actionInputNote}`,\n },\n ],\n });\n}\n\nfunction isAgentLoopContinuationReason(\n reason: unknown,\n): reason is AgentLoopContinuationReason {\n return (\n reason === \"run_timeout\" ||\n reason === \"loop_limit\" ||\n reason === \"max_tokens\" ||\n reason === \"stream_ended\" ||\n reason === \"gateway_timeout\" ||\n reason === \"network_interrupted\" ||\n reason === \"no_progress\"\n );\n}\n\n/**\n * True when an error thrown by `runAgentLoop` is a recoverable transport- or\n * gateway-level interruption that the agent can resume from rather than a\n * terminal failure. The continuation pattern works because the LLM call's\n * conversation prefix is preserved on the next attempt — Anthropic's prompt\n * cache rescues the latency, and the agent gets a \"you got cut off, continue\"\n * nudge so it doesn't redo work it already finished.\n *\n * Distinct from `isRetryableError` which guides per-engine quick retries:\n * `isResumableEngineError` is checked AFTER engine retries are exhausted, at\n * the run level. It catches both gateway-reported timeouts (where engine\n * retries don't apply because the gateway already gave up) and transport\n * errors that survived engine retry budgets.\n */\nexport function isResumableEngineError(err: unknown): boolean {\n if (!(err instanceof Error)) return false;\n const code =\n err instanceof EngineError ? (err.errorCode ?? \"\").toLowerCase() : \"\";\n if (\n code === \"builder_gateway_timeout\" ||\n code === \"builder_gateway_network_error\" ||\n code === \"provider_network_error\"\n ) {\n return true;\n }\n if (\n code === \"http_502\" ||\n code === \"http_503\" ||\n code === \"http_504\" ||\n code === \"timeout\"\n ) {\n return true;\n }\n const text = errorSearchText(err);\n return (\n text.includes(\"socket hang up\") ||\n text.includes(\"econnreset\") ||\n text.includes(\"enetreset\") ||\n text.includes(\"econnaborted\") ||\n text.includes(\"fetch failed\") ||\n text.includes(\"network error\") ||\n text.includes(\"connection error\") ||\n text.includes(\"connection reset\") ||\n text.includes(\"connection closed\") ||\n text.includes(\"stream closed\") ||\n text.includes(\"inactivity timeout\") ||\n text.includes(\"gateway timeout\") ||\n text.includes(\"upstream timeout\") ||\n text.includes(\"function timeout\") ||\n text.includes(\"too much time has passed without sending any data\") ||\n text.includes(\"terminated\")\n );\n}\n\n/**\n * Map a resumable error to the most descriptive continuation reason. Used\n * when surfacing the resume to the agent and to clients via the\n * `auto_continue` event.\n */\nexport function continuationReasonForResumableError(\n err: unknown,\n): \"gateway_timeout\" | \"network_interrupted\" {\n const code =\n err instanceof EngineError ? (err.errorCode ?? \"\").toLowerCase() : \"\";\n if (code === \"builder_gateway_timeout\") return \"gateway_timeout\";\n const text = err instanceof Error ? err.message.toLowerCase() : \"\";\n if (\n text.includes(\"gateway timeout\") ||\n text.includes(\"upstream timeout\") ||\n text.includes(\"function timeout\")\n ) {\n return \"gateway_timeout\";\n }\n return \"network_interrupted\";\n}\n\nfunction errorSearchText(err: unknown): string {\n const parts: string[] = [];\n if (err instanceof Error) {\n parts.push(err.name, err.message);\n const maybe = err as Error & { code?: unknown; cause?: unknown };\n if (typeof maybe.code === \"string\") parts.push(maybe.code);\n if (maybe.cause) parts.push(errorSearchText(maybe.cause));\n } else {\n parts.push(String(err));\n }\n return parts.join(\" \").toLowerCase();\n}\n\nfunction textFromEngineMessage(message: EngineMessage): string {\n return message.content\n .filter(\n (part): part is import(\"./engine/types.js\").EngineTextPart =>\n part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nfunction isInternalContinuationTurn(messages: EngineMessage[]): boolean {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message.role !== \"user\") continue;\n return textFromEngineMessage(message).startsWith(\n AGENT_INTERNAL_CONTINUE_PROMPT,\n );\n }\n return false;\n}\n\nfunction isToolResultOnlyUserMessage(message: EngineMessage): boolean {\n return (\n message.role === \"user\" &&\n message.content.length > 0 &&\n message.content.every((part) => part.type === \"tool-result\")\n );\n}\n\n/** Start of the active turn on an internal continuation (real user prompt). */\nfunction findCurrentTurnStartForContinuation(\n messages: EngineMessage[],\n): number {\n let i = messages.length - 1;\n while (i >= 0) {\n const message = messages[i];\n if (message.role !== \"user\") {\n i--;\n continue;\n }\n const userText = textFromEngineMessage(message);\n if (userText.startsWith(AGENT_INTERNAL_CONTINUE_PROMPT)) {\n i--;\n continue;\n }\n if (isToolResultOnlyUserMessage(message)) {\n i--;\n continue;\n }\n return i;\n }\n return 0;\n}\n\n/**\n * First message index that is safe to start a trimmed window on. A window must\n * not begin with a tool-result-only user message — that would orphan it from\n * the assistant tool-call turn it answers and break Anthropic's tool_use /\n * tool_result pairing. We walk forward from `desiredStart` to the first\n * non-orphaned boundary; if none exists we refuse to trim (return -1).\n */\nfunction findSafeWindowStart(\n messages: EngineMessage[],\n desiredStart: number,\n): number {\n for (let i = Math.max(0, desiredStart); i < messages.length; i++) {\n if (!isToolResultOnlyUserMessage(messages[i])) return i;\n }\n return -1;\n}\n\n/**\n * Observational Memory consumer (threshold-gated, conservative).\n *\n * Builds the three-tier OM context for a thread and, ONLY when the thread has\n * already crossed the compaction threshold (i.e. it has at least one persisted\n * observation/reflection), returns a rewritten message list that:\n * - prepends a single system-role \"Observational Memory\" block holding the\n * reflections + observations, and\n * - replaces the raw older history with just the recent-raw-message window,\n * keeping the current user turn and any pending tool results intact.\n *\n * For threads with NO OM entries (every short thread) it returns the input\n * array unchanged by reference, so the common path is byte-for-byte identical.\n *\n * Best-effort: any failure returns the input unchanged so OM can never break a\n * normal turn.\n */\nasync function applyObservationalMemoryToContext(\n messages: EngineMessage[],\n opts: {\n threadId: string;\n ownerEmail?: string | null;\n orgId?: string | null;\n },\n): Promise<EngineMessage[]> {\n if (!opts.ownerEmail) return messages;\n\n try {\n const context = await buildObservationalContext({\n threadId: opts.threadId,\n ownerEmail: opts.ownerEmail,\n orgId: opts.orgId ?? null,\n messages,\n });\n\n // No compacted memory yet → short thread, leave context untouched.\n if (!hasObservationalMemory(context)) return messages;\n\n const block = serializeObservationalMemoryBlock(context);\n if (!block.trim()) return messages;\n\n // EngineMessage has no \"system\" role; the framework injects auxiliary\n // context as leading user messages (same convention as the continuation\n // nudge and the resume journal note), and the serialized block is clearly\n // self-labeled \"[Observational Memory]\".\n const omMessage: EngineMessage = {\n role: \"user\",\n content: [{ type: \"text\", text: block }],\n };\n\n // Trim the raw prefix to only the recent-raw window. The window is the tail\n // of `messages`, so it always contains the latest user turn and any pending\n // tool results. Guard the boundary so we never start mid tool_use/result\n // pair; if a safe boundary can't be found, additively inject the memory\n // block WITHOUT trimming (the conservative fallback) so we never drop a\n // pending tool result.\n const recentCount = context.recentMessages.length;\n if (recentCount === 0 || recentCount >= messages.length) {\n return [omMessage, ...messages];\n }\n const desiredStart = messages.length - recentCount;\n const safeStart = findSafeWindowStart(messages, desiredStart);\n if (safeStart < 0) {\n // Whole tail is tool-result-only (degenerate) — don't trim.\n return [omMessage, ...messages];\n }\n return [omMessage, ...messages.slice(safeStart)];\n } catch (err) {\n console.warn(\n \"[observational-memory] context injection skipped:\",\n err instanceof Error ? err.message : String(err),\n );\n return messages;\n }\n}\n\nfunction seedReadOnlyToolResultsFromHistory(\n messages: EngineMessage[],\n actions: Record<string, ActionEntry>,\n): Map<string, string> {\n const cache = new Map<string, string>();\n if (!isInternalContinuationTurn(messages)) return cache;\n\n const pendingToolCalls = new Map<string, { name: string; input: unknown }>();\n for (const message of messages) {\n if (message.role === \"assistant\") {\n for (const part of message.content) {\n if (part.type !== \"tool-call\") continue;\n const entry = actions[part.name];\n if (entry?.readOnly !== true) continue;\n pendingToolCalls.set(part.id, {\n name: part.name,\n input: part.input,\n });\n }\n continue;\n }\n\n for (const part of message.content) {\n if (part.type !== \"tool-result\") continue;\n const call = pendingToolCalls.get(part.toolCallId);\n if (!call) continue;\n if (!isReusableReadOnlyToolResult(part)) continue;\n cache.set(toolCallCacheKey(call.name, call.input), part.content);\n }\n }\n\n return cache;\n}\n\nfunction isReusableReadOnlyToolResult(part: EngineToolResultPart): boolean {\n if (part.isError) return false;\n const lower = part.content.trim().toLowerCase();\n if (!lower) return false;\n return !(\n lower.startsWith(\"invalid action parameters for \") ||\n lower.startsWith(\"error running \") ||\n lower.includes(\"run aborted\") ||\n lower.includes(\"tool call timed out\") ||\n lower.includes(\"stale_run\") ||\n lower.includes(\"connection_error\")\n );\n}\n\n/**\n * Counts how many times each write (non-read-only) tool call was interrupted\n * before returning a result in the continuation history. When a connection\n * drops mid-tool-execution the client sends a placeholder result\n * (\"Interrupted before this tool returned a result.\") so the model knows\n * what was attempted. If the same write tool is called again with identical\n * input in the next continuation, this count prevents infinite retry loops.\n */\nconst INTERRUPTED_TOOL_RESULT_MARKER =\n \"Interrupted before this tool returned a result.\";\nconst MAX_WRITE_TOOL_INTERRUPTIONS = 2;\nconst MAX_IDENTICAL_TOOL_ERRORS = 3;\n\nfunction seedWriteToolInterruptionsFromHistory(\n messages: EngineMessage[],\n actions: Record<string, ActionEntry>,\n): Map<string, number> {\n const interruptions = new Map<string, number>();\n if (!isInternalContinuationTurn(messages)) return interruptions;\n\n const turnStart = findCurrentTurnStartForContinuation(messages);\n const turnMessages = messages.slice(turnStart);\n\n const pendingToolCalls = new Map<string, { name: string; input: unknown }>();\n for (const message of turnMessages) {\n if (message.role === \"assistant\") {\n for (const part of message.content) {\n if (part.type !== \"tool-call\") continue;\n const entry = actions[part.name];\n if (entry?.readOnly === true) continue;\n pendingToolCalls.set(part.id, { name: part.name, input: part.input });\n }\n continue;\n }\n\n for (const part of message.content) {\n if (part.type !== \"tool-result\") continue;\n const call = pendingToolCalls.get(part.toolCallId);\n if (!call) continue;\n if (\n typeof part.content === \"string\" &&\n part.content.includes(INTERRUPTED_TOOL_RESULT_MARKER)\n ) {\n const key = toolCallCacheKey(call.name, call.input);\n interruptions.set(key, (interruptions.get(key) ?? 0) + 1);\n }\n }\n }\n\n return interruptions;\n}\n\n/**\n * Convert ActionEntry registry to EngineTool array.\n */\nexport function actionsToEngineTools(\n actions: Record<string, ActionEntry>,\n): EngineTool[] {\n const tools: EngineTool[] = [];\n for (const [name, entry] of Object.entries(actions)) {\n if (entry.agentTool === false) continue;\n const inputSchema = normalizeToolInputSchema(entry.tool.parameters);\n if (!inputSchema) {\n console.warn(\n `[agent] Skipping tool \"${name}\" because its input schema is not an object.`,\n );\n continue;\n }\n tools.push({\n name,\n description: entry.tool.description,\n inputSchema,\n });\n }\n return tools;\n}\n\nexport function filterInitialEngineTools(\n tools: EngineTool[],\n initialToolNames?: string[],\n): EngineTool[] {\n if (!initialToolNames) return tools;\n const names = new Set(initialToolNames);\n names.add(TOOL_SEARCH_ACTION_NAME);\n for (const tool of tools) {\n if (isDefaultLeanInitialToolName(tool.name)) {\n names.add(tool.name);\n }\n }\n return tools.filter((tool) => names.has(tool.name));\n}\n\nconst DEFAULT_LEAN_INITIAL_TOOL_NAMES = new Set([\n // Broad provider/API/corpus primitives should be callable as soon as the\n // prompt teaches them; waiting for a discovery round-trip caused prod runs to\n // waste turns on provider work that was described but not loaded.\n \"data-source-status\",\n \"provider-api-catalog\",\n \"provider-api-docs\",\n \"provider-api-request\",\n \"provider-corpus-job\",\n \"provider-corpus-jobs\",\n \"query-staged-dataset\",\n \"list-staged-datasets\",\n \"delete-staged-dataset\",\n \"run-code\",\n \"get-code-execution\",\n \"list-extensions\",\n \"get-extension\",\n \"update-extension\",\n \"list-extension-history\",\n \"get-extension-history-version\",\n // Common first-class integration shortcuts. These are included only when the\n // current app/mode registry actually exposes them.\n \"bigquery\",\n \"search-bigquery-schema\",\n \"bigquery-table-info\",\n \"ga4\",\n \"amplitude\",\n \"prometheus\",\n \"grafana\",\n \"sentry\",\n \"stripe\",\n \"account-deep-dive\",\n \"slack-messages\",\n \"hubspot-deals\",\n \"hubspot-records\",\n \"hubspot-pipelines\",\n \"hubspot-metrics\",\n \"gong-calls\",\n \"github-repo-files\",\n \"jira\",\n \"jira-search\",\n \"gcloud\",\n \"notion-search\",\n \"pylon-search\",\n]);\n\nfunction isDefaultLeanInitialToolName(name: string): boolean {\n if (DEFAULT_LEAN_INITIAL_TOOL_NAMES.has(name)) return true;\n return (\n name.startsWith(\"provider-api-\") || name.startsWith(\"provider-corpus-\")\n );\n}\n\nfunction extractToolSearchResultNames(value: unknown): string[] {\n if (!value || typeof value !== \"object\") return [];\n const result = value as { query?: unknown; results?: unknown };\n if (typeof result.query !== \"string\" || result.query.trim().length === 0) {\n return [];\n }\n if (!Array.isArray(result.results)) return [];\n const names: string[] = [];\n for (const item of result.results) {\n if (!item || typeof item !== \"object\") continue;\n const name = (item as Record<string, unknown>).name;\n if (typeof name === \"string\" && name.trim()) names.push(name);\n }\n return names;\n}\n\nfunction extractToolSearchResultNamesFromMessages(\n messages: EngineMessage[],\n): string[] {\n const names: string[] = [];\n for (const message of messages) {\n if (message.role !== \"user\") continue;\n for (const part of message.content) {\n if (\n part.type !== \"tool-result\" ||\n part.toolName !== TOOL_SEARCH_ACTION_NAME ||\n typeof part.content !== \"string\"\n ) {\n continue;\n }\n try {\n names.push(...extractToolSearchResultNames(JSON.parse(part.content)));\n } catch {\n // Tool results are best-effort history hints; ignore non-JSON content.\n }\n }\n }\n return names;\n}\n\nfunction normalizeToolInputSchema(\n schema: ActionTool[\"parameters\"] | undefined,\n): EngineTool[\"inputSchema\"] | null {\n if (!schema) return { type: \"object\", properties: {} };\n if (schema.type !== \"object\") return null;\n return {\n ...schema,\n type: \"object\",\n properties:\n schema.properties && typeof schema.properties === \"object\"\n ? schema.properties\n : {},\n required: Array.isArray(schema.required) ? schema.required : [],\n };\n}\n\nfunction stringifyToolInput(input: unknown): string {\n try {\n const str = JSON.stringify(redactSensitiveFields(input));\n if (!str) return String(input);\n return str.length > 500 ? `${str.slice(0, 500)}…` : str;\n } catch {\n return String(input);\n }\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n }\n const obj = value as Record<string, unknown>;\n return `{${Object.keys(obj)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(obj[key])}`)\n .join(\",\")}}`;\n}\n\nfunction toolCallCacheKey(toolName: string, input: unknown): string {\n return `${toolName}:${stableStringify(normalizeToolCallInputForHistory(input))}`;\n}\n\nconst INTERRUPTED_TOOL_LEDGER_POLL_MS =\n process.env.NODE_ENV === \"test\" ? 0 : 2_000;\n\nasync function waitForInterruptedToolLedgerEntry(opts: {\n threadId: string;\n toolKey: string;\n toolName: string;\n timeoutMs: number;\n signal: AbortSignal;\n send: (event: AgentChatEvent) => void;\n}): Promise<string | null> {\n const pollMs = INTERRUPTED_TOOL_LEDGER_POLL_MS;\n // Wait up to the tool's OWN declared timeout — the abandoned zombie can keep\n // running that long (e.g. a 12-minute image generation, whose provider keeps\n // generating after the run aborts), and giving up early re-runs the same\n // write tool while the original is still in flight, duplicating work and\n // double-charging. A flat sub-tool-timeout cap (previously 5 min) silently\n // truncated long tools. The run's AbortSignal still bounds this to the run's\n // remaining budget: when the run is cut off, the poll returns null and the\n // re-dispatch hits the already-aborted signal instead of launching a real\n // second call, so the wait never outlives the run.\n const maxWaitMs =\n process.env.NODE_ENV === \"test\" ? 1 : Math.max(0, opts.timeoutMs);\n const maxPolls =\n process.env.NODE_ENV === \"test\"\n ? 3\n : Math.max(1, Math.ceil(maxWaitMs / Math.max(1, pollMs)) + 1);\n\n for (let attempt = 0; attempt < maxPolls; attempt++) {\n if (opts.signal.aborted) return null;\n const ledgerResult = await readLedgerEntry(opts.threadId, opts.toolKey);\n if (ledgerResult !== null) return ledgerResult;\n\n if (attempt >= maxPolls - 1) break;\n opts.send({\n type: \"activity\",\n tool: opts.toolName,\n label: `Waiting for previous ${opts.toolName} result.`,\n });\n if (pollMs <= 0) continue;\n await new Promise<void>((resolve) => {\n let settled = false;\n const done = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n opts.signal.removeEventListener(\"abort\", done);\n resolve();\n };\n const timer = setTimeout(done, pollMs);\n opts.signal.addEventListener(\"abort\", done, { once: true });\n });\n }\n\n return null;\n}\n\nfunction normalizeToolErrorForBreaker(error: string): string {\n return error.replace(/\\s+/g, \" \").trim();\n}\n\nfunction rateLimitRecoveryHint(message: string): string {\n if (\n !/\\b(?:429|rate[-\\s]?limit|rate limited|quota exceeded|too many requests|calls limit exceeded)\\b/i.test(\n message,\n )\n ) {\n return \"\";\n }\n return \"\\n\\nProvider rate-limit guidance: stop retrying this provider in this turn. Report the rate limit as a coverage gap, include any evidence already gathered, and ask the user to retry after the provider quota resets if full coverage is required.\";\n}\n\nconst SOURCE_SWEEP_TOOL_NAME =\n /\\b(?:api|calls?|deals?|events?|issues?|messages?|metrics?|provider|query|records?|request|search|tickets?|transcripts?)\\b/i;\n\nconst SOURCE_SWEEP_PROVIDER_TOKEN =\n /\\b(?:amplitude|apollo|bigquery|commonroom|data-source|ga4|github|gong|grafana|hubspot|jira|mixpanel|notion|posthog|postgres|postgresql|pylon|sentry|slack|stripe)\\b/i;\n\nconst SOURCE_SWEEP_EXCLUDED_TOOLS = new Set([\n \"chat-history\",\n \"list-staged-datasets\",\n \"manage-agent-engine\",\n \"manage-agent-loop-settings\",\n \"manage-automations\",\n \"manage-jobs\",\n \"manage-notifications\",\n \"manage-progress\",\n \"read-attachment\",\n \"refresh-screen\",\n \"resources\",\n \"tool-search\",\n \"view-screen\",\n]);\n\nfunction normalizeToolNameForHeuristics(name: string): string {\n return name.replace(/[_-]+/g, \" \");\n}\n\nfunction isLikelySourceSweepTool(\n name: string,\n entry: ActionEntry | undefined,\n): boolean {\n if (!entry || entry.readOnly === false) return false;\n const lower = name.toLowerCase();\n if (SOURCE_SWEEP_EXCLUDED_TOOLS.has(lower)) return false;\n const normalized = normalizeToolNameForHeuristics(lower);\n return (\n SOURCE_SWEEP_PROVIDER_TOKEN.test(normalized) ||\n SOURCE_SWEEP_TOOL_NAME.test(normalized)\n );\n}\n\nfunction hasExhaustedSourceSweepBudget(opts: {\n priorToolCalls: readonly AgentLoopToolCallSummary[];\n actions: Record<string, ActionEntry>;\n threshold?: number;\n}): boolean {\n const threshold = opts.threshold ?? SOURCE_SWEEP_TOOL_CALL_THRESHOLD;\n const counts = new Map<string, number>();\n for (const call of opts.priorToolCalls) {\n if (!isLikelySourceSweepTool(call.name, opts.actions[call.name])) continue;\n const next = (counts.get(call.name) ?? 0) + 1;\n if (next >= threshold) return true;\n counts.set(call.name, next);\n }\n return false;\n}\n\nfunction sourceSweepDelegationText(input: unknown): string {\n if (!input || typeof input !== \"object\") return \"\";\n const record = input as Record<string, unknown>;\n return [\"task\", \"instructions\", \"message\", \"name\"]\n .map((key) => record[key])\n .filter((value): value is string => typeof value === \"string\")\n .join(\"\\n\");\n}\n\nfunction isLikelySourceSweepDelegation(opts: {\n toolName: string;\n input: unknown;\n}): boolean {\n if (opts.toolName !== \"agent-teams\") return false;\n const action = getToolAction(opts.toolName, opts.input);\n if (![\"spawn\", \"send\"].includes(action)) return false;\n const normalized = normalizeToolNameForHeuristics(\n sourceSweepDelegationText(opts.input).toLowerCase(),\n );\n if (!normalized) return false;\n return (\n SOURCE_SWEEP_PROVIDER_TOKEN.test(normalized) ||\n SOURCE_SWEEP_TOOL_NAME.test(normalized)\n );\n}\n\nfunction sourceSweepDelegationGuardMessage(action: string): string {\n return (\n `Skipped agent-teams ${action || \"action\"}: this turn already exhausted ` +\n `a read-only source/search convergence budget. Do not move that same ` +\n `provider/source sweep into agent teams, background sub-agents, or a ` +\n `follow-up thread; delegation is not a bulk mechanism and does not remove ` +\n `provider quota, timeout, or cost limits. Continue in the main turn with a ` +\n `bulk/code/provider API path if one is available, or answer from gathered ` +\n `evidence with explicit coverage gaps.`\n );\n}\n\nfunction restrictAgentTeamsAfterSourceSweep(tools: EngineTool[]): EngineTool[] {\n return tools.map((tool) => {\n if (tool.name !== \"agent-teams\") return tool;\n const actionParam = tool.inputSchema.properties?.action;\n if (!actionParam || typeof actionParam !== \"object\") return tool;\n return {\n ...tool,\n description:\n `${tool.description}\\n\\nSource-sweep budget exhausted: only these ` +\n `read-only coordination actions are available: ` +\n SOURCE_SWEEP_AGENT_TEAM_ALLOWED_ACTIONS.map(\n (action) => `\"${action}\"`,\n ).join(\", \") +\n \". Do not spawn or message background sub-agents to continue the same provider/source sweep.\",\n inputSchema: {\n ...tool.inputSchema,\n properties: {\n ...tool.inputSchema.properties,\n action: {\n ...actionParam,\n enum: [...SOURCE_SWEEP_AGENT_TEAM_ALLOWED_ACTIONS],\n },\n },\n },\n };\n });\n}\n\nexport function repeatedSourceSweepGuardMessage(opts: {\n toolName: string;\n priorCalls: number;\n threshold?: number;\n}): string {\n const threshold = opts.threshold ?? SOURCE_SWEEP_TOOL_CALL_THRESHOLD;\n return (\n `Skipped ${opts.toolName}: this turn already made ${opts.priorCalls} ` +\n `call(s) to the same read-only source/search tool, which exceeds the ` +\n `${threshold}-call convergence budget. Stop calling ${opts.toolName} ` +\n `one item at a time and change strategy before answering. If a broader ` +\n `read-only bulk/source mechanism is available, use it now: provider API ` +\n `catalog/docs/request tools with pagination or staging, code execution ` +\n `against staged/provider data, workspace files, or another batch-capable ` +\n `tool that can join, grep, classify, count, or aggregate without flooding ` +\n `the chat context. Do not ask the user whether to run the obvious bulk/code ` +\n `workflow when it is read-only and needed to satisfy their request; either ` +\n `do it in this turn or state exactly why it is unavailable. Do not delegate ` +\n `this same one-item-at-a-time source sweep to agent teams, background ` +\n `sub-agents, or a follow-up thread; delegation is not a bulk mechanism and ` +\n `does not remove provider quota, timeout, or cost limits. Do not leave the ` +\n `user with a \"come back later\" answer for this turn. If no broader path ` +\n `exists or quota/timeouts block it, answer from the evidence already ` +\n `gathered: state the source filters, count what was inspected, list ` +\n `confirmed hits, and explicitly name remaining gaps or uninspected records.`\n );\n}\n\nexport function shouldGuardRepeatedSourceSweep(opts: {\n toolName: string;\n entry: ActionEntry | undefined;\n priorToolCalls: readonly AgentLoopToolCallSummary[];\n threshold?: number;\n}): { toolName: string; priorCalls: number; message: string } | null {\n if (!isLikelySourceSweepTool(opts.toolName, opts.entry)) return null;\n const threshold = opts.threshold ?? SOURCE_SWEEP_TOOL_CALL_THRESHOLD;\n const priorCalls = opts.priorToolCalls.filter(\n (call) => call.name === opts.toolName,\n ).length;\n if (priorCalls < threshold) return null;\n return {\n toolName: opts.toolName,\n priorCalls,\n message: repeatedSourceSweepGuardMessage({\n toolName: opts.toolName,\n priorCalls,\n threshold,\n }),\n };\n}\n\nfunction seedSourceSweepToolCallsFromHistory(\n messages: EngineMessage[],\n actions: Record<string, ActionEntry>,\n): AgentLoopToolCallSummary[] {\n if (!isInternalContinuationTurn(messages)) return [];\n\n const seeded: AgentLoopToolCallSummary[] = [];\n const turnStart = findCurrentTurnStartForContinuation(messages);\n for (const message of messages.slice(turnStart)) {\n if (message.role !== \"assistant\") continue;\n for (const part of message.content) {\n if (part.type !== \"tool-call\") continue;\n if (!isLikelySourceSweepTool(part.name, actions[part.name])) continue;\n seeded.push({\n name: part.name,\n input: normalizeToolCallInputForHistory(part.input),\n });\n }\n }\n return seeded;\n}\n\nfunction normalizeToolCallInputForHistory(\n input: unknown,\n): Record<string, unknown> {\n if (input && typeof input === \"object\" && !Array.isArray(input)) {\n return input as Record<string, unknown>;\n }\n return { rawInput: input };\n}\n\nfunction toolInputSchemaErrorResult(\n toolName: string,\n input: unknown,\n error: string,\n): string {\n return (\n `Invalid action parameters for ${toolName}: ${sanitizeToolErrorText(error)}. ` +\n `Received: ${stringifyToolInput(input)}. ` +\n \"The tool was not executed; retry with arguments that match the tool schema.\"\n );\n}\n\ntype RawJsonSchema = AgentNativeJsonSchema;\n\nconst rawToolInputAjv = new Ajv({\n strict: false,\n allErrors: true,\n coerceTypes: true,\n useDefaults: false,\n removeAdditional: false,\n});\n\ntype RawToolInputValidator = (input: unknown) => string | null;\n\nconst rawToolInputValidatorCache = new WeakMap<object, RawToolInputValidator>();\n\nfunction ajvRawToolInputValidator(\n schema: RawJsonSchema,\n): RawToolInputValidator {\n const validate = rawToolInputAjv.compile(schema);\n return (input) =>\n validate(input)\n ? null\n : rawToolInputAjv.errorsText(validate.errors, {\n separator: \"; \",\n dataVar: \"input\",\n });\n}\n\n/**\n * Non-codegen structural fallback for runtimes that forbid dynamic code\n * generation. Ajv compiles validators via `new Function`, which workerd\n * (Cloudflare Workers) rejects with `EvalError: Code generation from strings\n * disallowed` — previously EVERY raw-JSON-schema tool call was refused with\n * \"tool schema is invalid\" (the slides agent, dispatch's tool-search, and\n * any action without a live zod schema were unusable on the unified worker).\n * This fallback only enforces object-ness and `required` keys; anything\n * subtler is left to the action's own authoritative parameter validation at\n * execution time. Deliberately permissive: Ajv runs with `coerceTypes`, so\n * per-property type checks here would reject inputs Ajv would have coerced.\n */\nexport function validateRawToolInputWithoutCodegen(\n schema: RawJsonSchema,\n input: unknown,\n): string | null {\n if (!schema || typeof schema !== \"object\") return null;\n const schemaRecord = schema as Record<string, unknown>;\n if (schemaRecord.type !== \"object\") return null;\n if (!input || typeof input !== \"object\" || Array.isArray(input)) {\n return \"input must be object\";\n }\n const errors: string[] = [];\n const required = schemaRecord.required;\n if (Array.isArray(required)) {\n for (const key of required) {\n if (\n typeof key === \"string\" &&\n (input as Record<string, unknown>)[key] === undefined\n ) {\n errors.push(`input must have required property '${key}'`);\n }\n }\n }\n return errors.length > 0 ? errors.join(\"; \") : null;\n}\n\nfunction getRawToolInputValidator(\n schema: RawJsonSchema,\n): RawToolInputValidator {\n const cached = rawToolInputValidatorCache.get(schema);\n if (cached) return cached;\n let validator: RawToolInputValidator;\n try {\n validator = ajvRawToolInputValidator(schema);\n } catch {\n // Ajv could not compile (codegen-restricted runtime or a schema Ajv\n // rejects). Degrade to the structural fallback instead of refusing the\n // tool call — the action still validates its parameters when it runs.\n validator = (input) => validateRawToolInputWithoutCodegen(schema, input);\n }\n rawToolInputValidatorCache.set(schema, validator);\n return validator;\n}\n\nfunction shouldValidateRawToolParameters(entry: ActionEntry): boolean {\n const maybeSchema = entry.schema as\n | { \"~standard\"?: unknown }\n | null\n | undefined;\n return !maybeSchema?.[\"~standard\"] && Boolean(entry.tool.parameters);\n}\n\nfunction validateRawToolInput(\n entry: ActionEntry,\n input: unknown,\n): string | null {\n if (!shouldValidateRawToolParameters(entry)) return null;\n const parameters = entry.tool.parameters;\n if (!parameters) return null;\n let validator: RawToolInputValidator;\n try {\n validator = getRawToolInputValidator(parameters);\n } catch (err) {\n return `tool schema is invalid: ${sanitizeToolErrorValue(err)}`;\n }\n return validator(input === undefined ? {} : input);\n}\n\n/**\n * The core agent loop — calls the engine iteratively until no more tool calls.\n * Decoupled from HTTP transport so it can run in the background.\n * Returns accumulated token usage for cost tracking.\n */\nexport async function runAgentLoop(opts: {\n engine: AgentEngine;\n model: string;\n systemPrompt: string;\n tools: EngineTool[];\n availableTools?: EngineTool[];\n messages: EngineMessage[];\n actions: Record<string, ActionEntry>;\n send: (event: AgentChatEvent) => void;\n signal: AbortSignal;\n ownerEmail?: string | null;\n orgId?: string | null;\n /**\n * Attachments submitted with this turn (pasted text, files, images), passed\n * through to each tool's `ActionRunContext.attachments` so actions can\n * consume a large pasted artifact by reference instead of having the model\n * re-emit it as a tool argument. See `create-extension`'s\n * `contentFromAttachment`.\n */\n attachments?: AgentChatAttachment[];\n reasoningEffort?: ReasoningEffort;\n providerOptions?: any;\n maxOutputTokens?: number;\n executionMode?: AgentExecutionMode;\n maxIterations?: number;\n finalResponseGuard?: AgentLoopFinalResponseGuard;\n threadId?: string;\n turnId?: string;\n /**\n * App-level default limits applied to every tool call unless the individual\n * ActionEntry overrides them with its own timeoutMs / maxResultChars.\n */\n toolLimits?: { timeoutMs?: number; maxResultChars?: number };\n /**\n * Stable approval keys granted by a human for actions declared\n * `needsApproval`. A call whose key is present here runs even though the\n * action requires approval; otherwise the loop pauses with\n * `approval_required`. See `AgentChatRequest.approvedToolCalls`.\n */\n approvedToolCalls?: string[];\n /**\n * In-loop processor seam (see `processors.ts`). Each processor can observe\n * streamed chunks, observe model responses around tool execution, and\n * `abort()` the run. Loop-internal config, NOT a tool/authoring surface —\n * processors only observe/mutate-stream/abort; they never define app\n * behavior or replace actions. When omitted or empty, none of the seam code\n * runs and the loop is byte-for-byte unchanged (zero overhead).\n */\n processors?: Processor[];\n}): Promise<AgentLoopUsage> {\n const {\n engine,\n model,\n systemPrompt,\n tools,\n availableTools,\n messages,\n actions,\n send,\n signal,\n } = opts;\n const availableToolMap = new Map(\n (availableTools ?? tools).map((tool) => [tool.name, tool]),\n );\n const activeToolNames = new Set(tools.map((tool) => tool.name));\n let activeTools = tools;\n\n const expandActiveTools = (names: string[]): string[] => {\n const added: string[] = [];\n for (const name of names) {\n if (activeToolNames.has(name)) continue;\n const tool = availableToolMap.get(name);\n if (!tool) continue;\n activeToolNames.add(name);\n added.push(name);\n }\n if (added.length > 0) {\n activeTools = (availableTools ?? tools).filter((tool) =>\n activeToolNames.has(tool.name),\n );\n }\n return added;\n };\n\n expandActiveTools(extractToolSearchResultNamesFromMessages(messages));\n\n // Build the processor chain only when at least one processor is supplied so\n // the common (no-processors) path is unchanged and carries zero overhead.\n const processorChain =\n opts.processors && opts.processors.length > 0\n ? new ProcessorChain(opts.processors)\n : null;\n\n const usage: AgentLoopUsage = {\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n model,\n };\n\n const maxIterations = normalizeMaxIterations(\n opts.maxIterations,\n getDefaultMaxIterations(),\n );\n const toolCallHistory: AgentLoopToolCallSummary[] = [];\n const sourceSweepToolCallHistory = seedSourceSweepToolCallsFromHistory(\n messages,\n actions,\n );\n let sourceSweepDelegationGuardActive = hasExhaustedSourceSweepBudget({\n priorToolCalls: sourceSweepToolCallHistory,\n actions,\n });\n const toolResultHistory: AgentLoopToolResultSummary[] = [];\n const runCtx = getRequestRunContext();\n if (runCtx) {\n runCtx.toolCalls = toolCallHistory;\n runCtx.toolResults = toolResultHistory;\n }\n const readOnlyToolResultCache = seedReadOnlyToolResultsFromHistory(\n messages,\n actions,\n );\n const duplicateReadOnlyToolCalls = new Map<string, number>();\n const writeToolInterruptions = seedWriteToolInterruptionsFromHistory(\n messages,\n actions,\n );\n const repeatedToolErrors = new Map<string, number>();\n\n // Tool-call journal hard-block (resume safety). Snapshot the per-turn journal\n // ONCE here, before any tool runs in this chunk, so it reflects only PRIOR\n // run chunks of this logical turn. A write tool whose exact call already\n // completed in an earlier interrupted chunk must not re-fire its side effect;\n // when matched, runToolCall returns the journaled result instead of executing.\n // Loaded eagerly (not lazily mid-loop) so the current chunk's own\n // asynchronously-persisted tool_done events can never leak in and make a\n // same-chunk call wrongly short-circuit. Best-effort: any ledger failure\n // leaves the journal empty and all calls run normally. Fresh first-turn calls\n // see an empty journal and are unaffected.\n let toolCallJournal: ToolCallJournal | null = null;\n const consumedJournalKeys = new Set<string>();\n if (opts.threadId) {\n try {\n const priorEvents = await getCurrentTurnEventsForThread(opts.threadId);\n if (priorEvents.length > 0) {\n // A logical turn can span multiple background continuation runs. Final\n // response guards must see successful reads from earlier chunks, not\n // only tools executed after the latest handoff. Otherwise a guard can\n // reject a grounded answer (or a successfully-created artifact) after\n // the evidence-producing query completed in a predecessor run.\n for (const event of priorEvents) {\n if (event.type === \"tool_start\") {\n toolCallHistory.push({\n name: event.tool,\n input: event.input,\n });\n } else if (event.type === \"tool_done\") {\n toolResultHistory.push({\n name: event.tool,\n content: event.result,\n isError: event.isError === true,\n });\n }\n }\n toolCallJournal = classifyToolCallJournal(priorEvents);\n }\n } catch {\n // Journal is a hardening layer, never a gate — a failed ledger read just\n // means no hard-block this turn.\n }\n }\n\n let finalGuardRetries = 0;\n let emptyFinalResponseRetries = 0;\n let iterations = 0;\n // Overridden (raised tokens, lowered effort) only after an empty-final-\n // response retry below — kept separate from `opts.maxOutputTokens`/\n // `opts.reasoningEffort` so the very first attempt is unaffected and later\n // tool-loop turns revert to the caller's original request after a success.\n let effectiveMaxOutputTokens = opts.maxOutputTokens;\n let effectiveReasoningEffort = opts.reasoningEffort;\n\n // Set when an in-loop processor aborts via `abort()` / throws a `TripWire`.\n // The loop emits the `tripwire` event, surfaces the reason as a final\n // assistant message, and stops cleanly.\n let tripwire: TripWire | null = null;\n const emitTripwire = (err: TripWire) => {\n tripwire = err;\n send({\n type: \"tripwire\",\n reason: err.message,\n ...(err.processor ? { processor: err.processor } : {}),\n });\n send({ type: \"text\", text: err.message });\n messages.push({\n role: \"assistant\",\n content: [{ type: \"text\", text: err.message }],\n });\n };\n\n while (true) {\n if (signal.aborted) break;\n if (++iterations > maxIterations) {\n appendAgentLoopContinuation(messages, \"loop_limit\");\n iterations = 1;\n }\n\n let assistantContent: EngineContentPart[] | undefined;\n let streamedAssistantText = \"\";\n let terminalStopReason:\n | Extract<EngineEvent, { type: \"stop\" }>[\"reason\"]\n | undefined;\n const toolCallErrors = new Map<\n string,\n { name: string; input: unknown; error: string }\n >();\n let contextMessages = messages;\n\n if (opts.threadId) {\n try {\n const directives = await loadContextDirectives(opts.threadId, {\n ownerEmail: opts.ownerEmail ?? null,\n });\n const protectedSegmentIds = computeProtectedSegmentIds(messages);\n const { messages: transformedMessages, appliedStatus } =\n applyContextDirectives(messages, directives, {\n protectedSegmentIds,\n });\n const manifest = await buildManifest({\n threadId: opts.threadId,\n ...(opts.turnId ? { turnId: opts.turnId } : {}),\n model,\n rawMessages: messages,\n sentMessages: transformedMessages,\n appliedStatus,\n directives,\n protectedSegmentIds,\n source: \"structured\",\n enforceable: true,\n });\n contextMessages = transformedMessages;\n void writeContextManifest(opts.threadId, manifest).catch((err) => {\n console.warn(\n \"[context-xray] failed to write manifest:\",\n err instanceof Error ? err.message : String(err),\n );\n });\n } catch (err) {\n console.warn(\n \"[context-xray] context transform skipped:\",\n err instanceof Error ? err.message : String(err),\n );\n }\n\n // Observational Memory (consumer): for long threads that have already been\n // compacted, fold the reflections+observations in as a leading context\n // block and prefer the recent-raw-message window over the full raw\n // history. No-op (returns the same array) for short threads with no OM\n // entries, so the common path is unchanged. Runs after the context-xray\n // transform so the two compose; best-effort inside the helper. Gated on an\n // authenticated owner so anonymous threads never read OM scoped to a\n // shared default identity.\n if (opts.ownerEmail) {\n contextMessages = await applyObservationalMemoryToContext(\n contextMessages,\n {\n threadId: opts.threadId,\n ownerEmail: opts.ownerEmail,\n orgId: opts.orgId ?? null,\n },\n );\n }\n }\n\n for (let retry = 0; ; retry++) {\n assistantContent = undefined;\n streamedAssistantText = \"\";\n terminalStopReason = undefined;\n toolCallErrors.clear();\n try {\n const streamOpts = {\n model,\n systemPrompt,\n messages: contextMessages,\n tools: sourceSweepDelegationGuardActive\n ? restrictAgentTeamsAfterSourceSweep(activeTools)\n : activeTools,\n abortSignal: signal,\n maxOutputTokens: resolveMaxOutputTokensForEngine(\n engine.name,\n effectiveMaxOutputTokens,\n model,\n ),\n reasoningEffort: effectiveReasoningEffort,\n providerOptions: opts.providerOptions,\n };\n\n const eventStream = engine.stream(streamOpts);\n let thinkingBuffer = \"\";\n const toolInputNames = new Map<string, string>();\n const toolInputBytes = new Map<string, number>();\n let lastToolInputActivityAt = 0;\n type ActiveToolInputPreparation = {\n id: string;\n toolName?: string;\n startedAt: number;\n lastProgressAt: number;\n bytes: number;\n };\n type ZeroByteToolInputRestart = {\n toolName: string;\n firstStartedAt: number;\n lastStartedAt: number;\n count: number;\n };\n const activeToolInputs = new Map<string, ActiveToolInputPreparation>();\n let zeroByteToolInputRestart: ZeroByteToolInputRestart | undefined;\n let endedForNoProgress = false;\n let lastModelStreamProgressAt = Date.now();\n const sendToolInputActivity = (\n toolName: string | undefined,\n toolInputId?: string,\n progressBytes?: number,\n force = false,\n ) => {\n const now = Date.now();\n if (\n !force &&\n now - lastToolInputActivityAt < TOOL_INPUT_ACTIVITY_INTERVAL_MS\n ) {\n return;\n }\n lastToolInputActivityAt = now;\n send({\n type: \"activity\",\n label: toolInputActivityLabel(toolName),\n ...(toolName ? { tool: toolName } : {}),\n ...(toolInputId ? { id: toolInputId } : {}),\n ...(typeof progressBytes === \"number\" ? { progressBytes } : {}),\n });\n };\n const actionPreparationDeadlineAt = () => {\n let deadlineAt = Number.POSITIVE_INFINITY;\n if (zeroByteToolInputRestart) {\n deadlineAt = Math.min(\n deadlineAt,\n zeroByteToolInputRestart.firstStartedAt +\n ACTION_PREPARATION_NO_PROGRESS_TIMEOUT_MS,\n );\n }\n let earliestStartedAt = Number.POSITIVE_INFINITY;\n let latestPositiveProgressAt = 0;\n for (const active of activeToolInputs.values()) {\n if (active.startedAt < earliestStartedAt) {\n earliestStartedAt = active.startedAt;\n }\n if (\n active.bytes > 0 &&\n active.lastProgressAt > latestPositiveProgressAt\n ) {\n latestPositiveProgressAt = active.lastProgressAt;\n }\n }\n const progressAt =\n latestPositiveProgressAt > 0\n ? latestPositiveProgressAt\n : earliestStartedAt;\n if (Number.isFinite(progressAt)) {\n deadlineAt = Math.min(\n deadlineAt,\n progressAt + ACTION_PREPARATION_NO_PROGRESS_TIMEOUT_MS,\n );\n }\n return Number.isFinite(deadlineAt) ? deadlineAt : undefined;\n };\n const modelStreamNoProgressDeadlineAt = () =>\n lastModelStreamProgressAt + MODEL_STREAM_NO_PROGRESS_TIMEOUT_MS;\n const noProgressDeadlineAt = () => {\n const actionDeadlineAt = actionPreparationDeadlineAt();\n const modelDeadlineAt = modelStreamNoProgressDeadlineAt();\n return actionDeadlineAt === undefined\n ? modelDeadlineAt\n : Math.min(actionDeadlineAt, modelDeadlineAt);\n };\n const hasNoProgressStalled = () => Date.now() >= noProgressDeadlineAt();\n const checkpointNoProgress = () => {\n if (endedForNoProgress) return;\n send({\n type: \"auto_continue\",\n reason: \"no_progress\",\n });\n endedForNoProgress = true;\n };\n let eventIteratorReturnRequested = false;\n const requestEventIteratorReturn = (\n iterator: AsyncIterator<EngineEvent>,\n awaitReturn: boolean,\n ) => {\n if (eventIteratorReturnRequested) return;\n eventIteratorReturnRequested = true;\n let returnPromise:\n | ReturnType<NonNullable<typeof iterator.return>>\n | undefined;\n try {\n returnPromise = iterator.return?.();\n } catch {\n return;\n }\n if (!returnPromise) return;\n if (awaitReturn) return returnPromise.catch(() => undefined);\n void returnPromise.catch(() => undefined);\n };\n const nextEngineEventWithNoProgressTimeout = async (\n iterator: AsyncIterator<EngineEvent>,\n ): Promise<IteratorResult<EngineEvent>> => {\n const deadlineAt = noProgressDeadlineAt();\n const timeoutMs = Math.max(0, deadlineAt - Date.now());\n if (timeoutMs <= 0) {\n checkpointNoProgress();\n requestEventIteratorReturn(iterator, false);\n return { done: true, value: undefined };\n }\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const next = iterator.next();\n void next.catch(() => undefined);\n const timeout = new Promise<\"timeout\">((resolve) => {\n timeoutId = setTimeout(() => resolve(\"timeout\"), timeoutMs);\n });\n try {\n const result = await Promise.race([next, timeout]);\n if (result === \"timeout\") {\n checkpointNoProgress();\n requestEventIteratorReturn(iterator, false);\n return { done: true, value: undefined };\n }\n return result;\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n }\n };\n const trackActiveToolInput = (\n key: string,\n toolName: string | undefined,\n bytes: number,\n ) => {\n const now = Date.now();\n const previous = activeToolInputs.get(key);\n const resolvedToolName = toolName ?? previous?.toolName;\n activeToolInputs.set(key, {\n id: key,\n ...(resolvedToolName ? { toolName: resolvedToolName } : {}),\n startedAt: previous?.startedAt ?? now,\n lastProgressAt: now,\n bytes,\n });\n };\n const resetZeroByteToolInputRestart = (toolName?: string) => {\n if (!zeroByteToolInputRestart) return;\n if (!toolName || zeroByteToolInputRestart.toolName === toolName) {\n zeroByteToolInputRestart = undefined;\n }\n };\n const noteZeroByteToolInputStart = (toolName?: string) => {\n if (!toolName) return false;\n const now = Date.now();\n if (zeroByteToolInputRestart?.toolName === toolName) {\n zeroByteToolInputRestart = {\n ...zeroByteToolInputRestart,\n lastStartedAt: now,\n count: zeroByteToolInputRestart.count + 1,\n };\n } else {\n zeroByteToolInputRestart = {\n toolName,\n firstStartedAt: now,\n lastStartedAt: now,\n count: 1,\n };\n }\n return (\n zeroByteToolInputRestart.count >=\n ACTION_PREPARATION_ZERO_BYTE_RESTART_LIMIT &&\n now - zeroByteToolInputRestart.firstStartedAt >=\n ACTION_PREPARATION_NO_PROGRESS_TIMEOUT_MS\n );\n };\n const eventIterator = eventStream[Symbol.asyncIterator]();\n let eventIteratorDone = false;\n try {\n while (true) {\n const nextEvent =\n await nextEngineEventWithNoProgressTimeout(eventIterator);\n if (nextEvent.done) {\n eventIteratorDone = true;\n break;\n }\n const event = nextEvent.value;\n if (hasNoProgressStalled()) {\n checkpointNoProgress();\n break;\n }\n if (event.type !== \"gateway-heartbeat\") {\n lastModelStreamProgressAt = Date.now();\n }\n // In-loop processor seam (stream hook). Each chunk is offered to every\n // processor's `processOutputStream` before the loop handles it. A\n // processor `abort()` throws a TripWire; catch it locally so it is not\n // mistaken for a retryable engine error, then break out cleanly.\n if (processorChain) {\n try {\n await processorChain.runStream(event);\n } catch (err) {\n if (err instanceof TripWire) {\n emitTripwire(err);\n break;\n }\n throw err;\n }\n }\n if (event.type === \"text-delta\") {\n resetZeroByteToolInputRestart();\n streamedAssistantText += event.text;\n send({ type: \"text\", text: event.text });\n } else if (event.type === \"thinking-delta\") {\n thinkingBuffer += event.text;\n // Forward thinking deltas as a distinct event type so the UI\n // can render a collapsible \"Thinking…\" cell while the model\n // reasons, then collapse it when content arrives.\n send({ type: \"thinking\", text: event.text });\n } else if (event.type === \"tool-input-start\") {\n const key = event.id ?? event.name;\n if (key && event.name) {\n toolInputNames.set(key, event.name);\n toolInputBytes.set(key, 0);\n trackActiveToolInput(key, event.name, 0);\n }\n sendToolInputActivity(event.name, key, undefined, true);\n if (noteZeroByteToolInputStart(event.name)) {\n send({\n type: \"auto_continue\",\n reason: \"no_progress\",\n });\n endedForNoProgress = true;\n break;\n }\n } else if (event.type === \"tool-input-delta\") {\n const key = event.id ?? event.name;\n const toolName =\n event.name ??\n (event.id ? toolInputNames.get(event.id) : undefined);\n let progressBytes: number | undefined;\n let startedZeroByteInput = false;\n if (key) {\n const hadByteRecord = toolInputBytes.has(key);\n const previous = hadByteRecord\n ? (toolInputBytes.get(key) ?? 0)\n : 0;\n progressBytes =\n previous +\n new TextEncoder().encode(event.text ?? \"\").byteLength;\n toolInputBytes.set(key, progressBytes);\n if (!hadByteRecord || progressBytes > previous) {\n trackActiveToolInput(key, toolName, progressBytes);\n if (progressBytes > 0) {\n resetZeroByteToolInputRestart();\n } else if (!hadByteRecord) {\n startedZeroByteInput = true;\n }\n }\n }\n sendToolInputActivity(toolName, key, progressBytes);\n if (\n startedZeroByteInput &&\n toolName &&\n noteZeroByteToolInputStart(toolName)\n ) {\n send({\n type: \"auto_continue\",\n reason: \"no_progress\",\n });\n endedForNoProgress = true;\n break;\n }\n } else if (event.type === \"gateway-heartbeat\") {\n send({ type: \"stream_keepalive\" });\n } else if (event.type === \"tool-call\") {\n // The authoritative tool-call blocks arrive in assistant-content.\n } else if (event.type === \"tool-call-error\") {\n toolCallErrors.set(event.id, {\n name: event.name,\n input: event.input,\n error: event.error,\n });\n } else if (event.type === \"assistant-content\") {\n assistantContent = event.parts;\n } else if (event.type === \"usage\") {\n usage.inputTokens += event.inputTokens;\n usage.outputTokens += event.outputTokens;\n usage.cacheReadTokens += event.cacheReadTokens ?? 0;\n usage.cacheWriteTokens += event.cacheWriteTokens ?? 0;\n } else if (event.type === \"stop\") {\n terminalStopReason = event.reason;\n if (event.reason === \"error\") {\n throw new EngineError(event.error ?? \"Engine stream error\", {\n errorCode: event.errorCode,\n upgradeUrl: event.upgradeUrl,\n statusCode: event.statusCode,\n providerRetryable: event.providerRetryable,\n });\n }\n }\n if (hasNoProgressStalled()) {\n checkpointNoProgress();\n break;\n }\n }\n } finally {\n if (!eventIteratorDone) {\n await requestEventIteratorReturn(\n eventIterator,\n !eventIteratorReturnRequested,\n );\n }\n }\n\n if (endedForNoProgress) {\n return usage;\n }\n\n break;\n } catch (err: unknown) {\n if (signal.aborted) throw err;\n if (isContextTooLongError(err)) {\n // ── One-shot recovery: trim old tool results and retry once ────────\n // Only attempt recovery on the first overflow (retry === 0) to avoid\n // infinite trim loops. On subsequent overflows fall through to the\n // terminal error.\n if (retry === 0) {\n const trimmed = trimOldToolResults(contextMessages);\n if (trimmed !== null) {\n // Replace the sent messages for this iteration with the trimmed\n // version, clear any partial output, and retry immediately\n // (no delay — context errors are not transient).\n contextMessages = trimmed;\n send({ type: \"clear\" });\n continue;\n }\n }\n throw new EngineError(\n \"Conversation has grown too long. The agent tried to recover automatically but the context is still too large. You can continue in a new chat, or ask the agent to summarize the conversation and continue.\",\n { errorCode: \"context_length_exceeded\" },\n );\n }\n if (retry < maxRetriesForError(err) && isRetryableError(err)) {\n // Clear partial text from the failed attempt so the retry\n // doesn't produce garbled duplicate output. Keep the retry itself\n // silent so transient provider/backend failures do not leak into\n // the assistant's final answer.\n send({ type: \"clear\" });\n await retryDelay(retry, signal);\n continue;\n }\n throw err;\n }\n }\n\n // A processor aborted mid-stream. The tripwire event + final message were\n // already emitted; halt the loop without sending a normal `done`.\n if (tripwire) break;\n\n if (!assistantContent && toolCallErrors.size > 0) {\n assistantContent = [];\n }\n\n if (!assistantContent) {\n // No content — done\n break;\n }\n\n if (toolCallErrors.size > 0) {\n const existingToolCallIds = new Set(\n assistantContent\n .filter(\n (part): part is import(\"./engine/types.js\").EngineToolCallPart =>\n part.type === \"tool-call\",\n )\n .map((part) => part.id),\n );\n for (const [id, info] of toolCallErrors) {\n if (!existingToolCallIds.has(id)) {\n assistantContent.push({\n type: \"tool-call\",\n id,\n name: info.name,\n input: info.input,\n });\n }\n }\n }\n\n const assistantContentForHistory = assistantContent.map((part) =>\n part.type === \"tool-call\"\n ? {\n ...part,\n input: normalizeToolCallInputForHistory(part.input),\n }\n : part,\n );\n\n messages.push({ role: \"assistant\", content: assistantContentForHistory });\n\n const toolCallParts = assistantContent.filter(\n (p): p is import(\"./engine/types.js\").EngineToolCallPart =>\n p.type === \"tool-call\",\n );\n\n // In-loop processor seam (step hook). Fires once per model response, around\n // tool execution, with the tool calls the model just requested (empty for a\n // final answer) plus the stop reason and cumulative usage. A coverage gate\n // can inspect what the model is about to do and `abort()` before tools run.\n if (processorChain) {\n try {\n await processorChain.runStep({\n toolCalls: toolCallsFromContent(assistantContent),\n ...(terminalStopReason ? { finishReason: terminalStopReason } : {}),\n usage: {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cacheReadTokens: usage.cacheReadTokens,\n cacheWriteTokens: usage.cacheWriteTokens,\n },\n });\n } catch (err) {\n if (err instanceof TripWire) {\n emitTripwire(err);\n break;\n }\n throw err;\n }\n }\n\n const flushUnstreamedAssistantText = () => {\n if (streamedAssistantText) return;\n const text = collectTextParts(assistantContentForHistory);\n if (text) send({ type: \"text\", text });\n };\n\n if (toolCallParts.length === 0) {\n if (terminalStopReason === \"max_tokens\") {\n flushUnstreamedAssistantText();\n appendAgentLoopContinuation(messages, \"max_tokens\");\n continue;\n }\n let guard: Awaited<ReturnType<AgentLoopFinalResponseGuard>> | null = null;\n if (opts.finalResponseGuard) {\n try {\n guard = await opts.finalResponseGuard({\n messages,\n assistantContent: assistantContentForHistory,\n text: collectTextParts(assistantContentForHistory),\n toolCalls: [...toolCallHistory],\n toolResults: [...toolResultHistory],\n retryCount: finalGuardRetries,\n executionMode: opts.executionMode ?? \"act\",\n });\n } catch (err) {\n send({ type: \"clear\" });\n throw err;\n }\n }\n let guardEmittedFallback = false;\n if (guard) {\n const retryMessage =\n typeof guard === \"string\" ? guard : guard.retryMessage;\n const fallbackMessage =\n typeof guard === \"string\" ? guard : guard.fallbackMessage;\n if (finalGuardRetries < 1) {\n finalGuardRetries += 1;\n send({ type: \"clear\" });\n messages.push({\n role: \"user\",\n content: [{ type: \"text\", text: retryMessage }],\n });\n continue;\n }\n send({ type: \"clear\" });\n send({ type: \"text\", text: fallbackMessage ?? retryMessage });\n guardEmittedFallback = true;\n } else {\n flushUnstreamedAssistantText();\n }\n // Some providers (notably OpenAI Responses for gpt-5+) can stream a\n // successful turn that contains only reasoning content and zero output\n // text — typically when reasoning consumes the entire output-token\n // budget. Without a final text part the SSE stream still ends with a\n // clean `done`, which renders as a totally empty assistant bubble.\n // Retry so a reasoning-budget miss can still finish; each retry raises\n // the token ceiling and steps reasoning effort down a tier so it's not\n // just re-issuing the identical doomed request. If retries also come\n // back empty, surface a plain-language error.\n const hasEmptyFinalResponse =\n !guardEmittedFallback &&\n collectTextParts(assistantContentForHistory).trim().length === 0 &&\n streamedAssistantText.trim().length === 0;\n if (hasEmptyFinalResponse) {\n if (emptyFinalResponseRetries < EMPTY_FINAL_RESPONSE_RETRY_LIMIT) {\n emptyFinalResponseRetries += 1;\n effectiveMaxOutputTokens =\n resolveEmptyResponseRetryMaxOutputTokens(model);\n effectiveReasoningEffort = stepDownReasoningEffort(\n effectiveReasoningEffort,\n );\n appendAgentLoopContinuation(messages, \"max_tokens\");\n continue;\n }\n send({\n type: \"text\",\n text: \"The model returned an empty response. This usually means reasoning used the full output-token budget. Try again, or pick a different model from the model menu.\",\n });\n } else {\n emptyFinalResponseRetries = 0;\n effectiveMaxOutputTokens = opts.maxOutputTokens;\n effectiveReasoningEffort = opts.reasoningEffort;\n }\n break;\n }\n\n // Reached only when the model made tool calls (toolCallParts.length > 0),\n // i.e. it's about to do more work and produce a *new* final answer. Give\n // that next final-answer cycle a fresh guard-retry budget; otherwise\n // finalGuardRetries stays at 1 from a prior cycle and the guard is\n // permanently disabled for the rest of a long multi-step run.\n finalGuardRetries = 0;\n emptyFinalResponseRetries = 0;\n\n flushUnstreamedAssistantText();\n\n let requestedActionStop: { message: string; errorCode?: string } | null =\n null;\n\n // Human-in-the-loop approvals granted by the user for this turn (opt-in;\n // empty for the overwhelming majority of turns). Keyed by the stable\n // tool-call approval key so a re-issued continuation can let an approved\n // call run. The model cannot populate this — it comes from the request.\n const approvedToolCallKeys = new Set<string>(opts.approvedToolCalls ?? []);\n\n const runToolCall = async (\n toolCall: import(\"./engine/types.js\").EngineToolCallPart,\n ): Promise<EngineContentPart> => {\n const wireToolInput = JSON.stringify(toolCall.input ?? {});\n const normalizedToolInput = normalizeToolCallInputForHistory(\n toolCall.input,\n );\n const actionEntry = actions[toolCall.name];\n const sourceSweepGuard = shouldGuardRepeatedSourceSweep({\n toolName: toolCall.name,\n entry: actionEntry,\n priorToolCalls: sourceSweepToolCallHistory,\n });\n const sourceSweepDelegationGuard =\n sourceSweepDelegationGuardActive &&\n isLikelySourceSweepDelegation({\n toolName: toolCall.name,\n input: toolCall.input,\n })\n ? sourceSweepDelegationGuardMessage(\n getToolAction(toolCall.name, toolCall.input),\n )\n : null;\n toolCallHistory.push({\n name: toolCall.name,\n input: normalizedToolInput,\n });\n sourceSweepToolCallHistory.push({\n name: toolCall.name,\n input: normalizedToolInput,\n });\n const recordToolResult = (content: string, isError: boolean) => {\n toolResultHistory.push({\n name: toolCall.name,\n content,\n isError,\n });\n };\n const finalizeToolErrorResult = (rawResult: string): string => {\n const sanitizedResult = sanitizeToolErrorText(rawResult);\n const errorKey = `${toolCallCacheKey(\n toolCall.name,\n toolCall.input,\n )}:${normalizeToolErrorForBreaker(sanitizedResult)}`;\n const count = (repeatedToolErrors.get(errorKey) ?? 0) + 1;\n repeatedToolErrors.set(errorKey, count);\n if (count < MAX_IDENTICAL_TOOL_ERRORS) return sanitizedResult;\n const result =\n `Stopped after ${count} identical errors from ${toolCall.name} with the same arguments. ` +\n `Last error: ${sanitizedResult}`;\n requestedActionStop ??= {\n message:\n `Stopped because ${toolCall.name} failed ${count} times with the same arguments and error. ` +\n \"Fix the underlying issue or change the arguments before retrying.\",\n errorCode: \"repeated_identical_tool_error\",\n };\n return result;\n };\n if (sourceSweepGuard) {\n sourceSweepDelegationGuardActive = true;\n const result = sourceSweepGuard.message;\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n completedSideEffect: false,\n });\n recordToolResult(result, false);\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n };\n }\n\n if (sourceSweepDelegationGuard) {\n const result = sourceSweepDelegationGuard;\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n completedSideEffect: false,\n });\n recordToolResult(result, false);\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n };\n }\n\n if (!actionEntry) {\n const result = finalizeToolErrorResult(\n `Error: Unknown tool \"${toolCall.name}\"`,\n );\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n isError: true,\n completedSideEffect: false,\n });\n recordToolResult(result, true);\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n isError: true,\n };\n }\n\n // Human-in-the-loop approval gate (opt-in via defineAction\n // `needsApproval`; default off). When an action requires approval and\n // this specific call has NOT been approved by a human, pause the turn\n // instead of executing. The action's side effect never happens until a\n // human re-issues the turn approving this call's stable key.\n const approvalKey = toolCallCacheKey(toolCall.name, toolCall.input);\n if (actionEntry.needsApproval && !approvedToolCallKeys.has(approvalKey)) {\n let mustApprove = false;\n try {\n mustApprove =\n typeof actionEntry.needsApproval === \"function\"\n ? Boolean(\n await actionEntry.needsApproval(toolCall.input, {\n userEmail: getRequestUserEmail(),\n orgId: getRequestOrgId() ?? null,\n caller: \"tool\",\n }),\n )\n : actionEntry.needsApproval === true;\n } catch {\n // Fail closed: a throwing predicate means we require approval rather\n // than silently running a high-consequence action.\n mustApprove = true;\n }\n if (mustApprove) {\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n send({\n type: \"approval_required\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n approvalKey,\n ...(toolCall.id ? { toolCallId: toolCall.id } : {}),\n });\n // Audit the blocked attempt: the action did NOT run, but \"the agent\n // tried to do X and was gated\" is itself worth recording. Best-effort,\n // but AWAITED (not fire-and-forget) so the row isn't lost to a\n // serverless freeze / request teardown when the turn pauses.\n try {\n const { recordActionAudit } = await import(\"../audit/record.js\");\n await recordActionAudit({\n config: undefined,\n args: toolCall.input,\n ctx: {\n actionName: toolCall.name,\n caller: \"tool\",\n userEmail: getRequestUserEmail(),\n orgId: getRequestOrgId() ?? null,\n ...(opts.threadId ? { threadId: opts.threadId } : {}),\n ...(opts.turnId ? { turnId: opts.turnId } : {}),\n },\n status: \"denied\",\n });\n } catch {\n // Best-effort — auditing must never break the approval pause.\n }\n const result =\n `Awaiting human approval to run \"${toolCall.name}\". This action did ` +\n `NOT execute — a human must approve this specific call before it ` +\n `can run. The turn is paused; do not retry.`;\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n completedSideEffect: false,\n });\n recordToolResult(result, false);\n requestedActionStop ??= {\n message: `Waiting for your approval to run ${toolCall.name}.`,\n errorCode: \"needs-approval\",\n };\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n };\n }\n }\n\n const DEFAULT_TOOL_RESULT_CHARS = 50_000;\n // Default action tools should not undercut durable/background runs. The\n // run-manager still aborts foreground hosted runs around 40s, while\n // background runs get nearly the full 15-minute function budget.\n const DEFAULT_TOOL_TIMEOUT_MS = 12 * 60_000;\n const toolTimeoutMs =\n actionEntry.timeoutMs ??\n opts.toolLimits?.timeoutMs ??\n DEFAULT_TOOL_TIMEOUT_MS;\n const toolMaxResultChars =\n actionEntry.maxResultChars ??\n opts.toolLimits?.maxResultChars ??\n DEFAULT_TOOL_RESULT_CHARS;\n\n // TOOL-CALL JOURNAL HARD-BLOCK (resume safety, tool-layer enforcement).\n // The prompt-level resume journal already TELLS a resuming model not to\n // re-run completed tool calls; this enforces it at the tool layer so a\n // re-dispatched write call whose exact (tool name + input) already\n // completed in an earlier interrupted chunk of this turn does NOT execute\n // its side effect again — we return the journaled result instead and emit\n // the normal tool_start/tool_done so the transcript stays coherent.\n //\n // Gated on a non-readOnly tool + an existing prior-chunk journal (so fresh\n // calls with no completed journal entry are completely unaffected). The\n // snapshot was taken before this chunk's tools ran, so it can only match a\n // PRIOR completion, never one from the current chunk.\n if (!actionEntry.readOnly && toolCallJournal) {\n const journaled = findCompletedJournalEntry(\n toolCallJournal,\n toolCall.name,\n toolCall.input,\n consumedJournalKeys,\n );\n if (journaled) {\n const recordedResult = journaled.result ?? \"\";\n const result =\n `(Already completed in an earlier interrupted attempt - not re-run to avoid a duplicate side effect.)\\n\\n` +\n recordedResult;\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n completedSideEffect: true,\n });\n recordToolResult(result, false);\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n };\n }\n }\n\n // Guard against write tools that have been interrupted too many times in\n // this turn (connection drop mid-execution → agent retries → repeat).\n // A write tool that keeps failing likely has a timeout / large-payload\n // problem; retrying indefinitely creates duplicates and confuses users.\n //\n // LEDGER RECOVERY: before applying the give-up budget, check whether the\n // previous invocation's zombie actually completed and wrote its result to\n // the durable ledger. If so, return the ledger result without re-executing\n // (prevents the duplicate side effect) and skip counting it toward the\n // interruption budget. A just-abandoned long tool may need a short grace\n // period before its detached promise writes the ledger, so wait while the\n // current run still has budget instead of immediately re-running it.\n if (!actionEntry.readOnly) {\n const writeCacheKey = toolCallCacheKey(toolCall.name, toolCall.input);\n const priorInterruptions =\n writeToolInterruptions.get(writeCacheKey) ?? 0;\n\n if (priorInterruptions > 0 && opts.threadId) {\n const ledgerResult = await waitForInterruptedToolLedgerEntry({\n threadId: opts.threadId,\n toolKey: writeCacheKey,\n toolName: toolCall.name,\n timeoutMs: toolTimeoutMs,\n signal,\n send,\n });\n if (ledgerResult !== null) {\n // Zombie completed — recover the real result without re-executing.\n const result =\n `(Recovered from prior interrupted chunk — action already completed.)\\n\\n` +\n ledgerResult;\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n completedSideEffect: true,\n ...(actionEntry.chatUI ? { chatUI: actionEntry.chatUI } : {}),\n });\n recordToolResult(result, false);\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n };\n }\n }\n\n if (priorInterruptions >= MAX_WRITE_TOOL_INTERRUPTIONS) {\n const result =\n `The ${toolCall.name} action was interrupted ${priorInterruptions} time(s) in this session — ` +\n `likely a connection timeout with a large payload. Please start a new chat and try again, ` +\n `or split the request into smaller pieces.`;\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n isError: true,\n completedSideEffect: false,\n });\n recordToolResult(result, true);\n requestedActionStop ??= {\n message:\n `I stopped because the ${toolCall.name} action was interrupted ${priorInterruptions} time(s) in a row. ` +\n `This usually means the connection timed out while processing a large request. ` +\n `Please start a new chat and try again, or break the request into smaller parts.`,\n errorCode: \"repeated_write_tool_interruption\",\n };\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n isError: true,\n };\n }\n }\n\n // Stop BEFORE emitting tool_start if the run was already aborted —\n // typically because the ledger wait above polled for minutes and the soft\n // timeout fired meanwhile. Emitting tool_start/tool_done here would leave a\n // bogus interrupted pair in the transcript for a tool that never re-ran,\n // and re-invoking would spawn a duplicate zombie. Return the interrupted\n // marker (no events) so the next continuation recovers via the ledger.\n // (A second guard inside the try below still covers an abort that lands in\n // the tiny sync window between here and the action invocation.)\n if (signal.aborted) {\n recordToolResult(INTERRUPTED_TOOL_RESULT_MARKER, false);\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: INTERRUPTED_TOOL_RESULT_MARKER,\n };\n }\n\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n\n const toolCallSchemaError = toolCallErrors.get(toolCall.id);\n if (toolCallSchemaError) {\n const result = finalizeToolErrorResult(\n toolInputSchemaErrorResult(\n toolCall.name,\n toolCallSchemaError.input,\n toolCallSchemaError.error,\n ),\n );\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n isError: true,\n completedSideEffect: false,\n });\n recordToolResult(result, true);\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n isError: true,\n };\n }\n\n const rawToolInputError = validateRawToolInput(\n actionEntry,\n toolCall.input,\n );\n if (rawToolInputError) {\n const result = finalizeToolErrorResult(\n toolInputSchemaErrorResult(\n toolCall.name,\n toolCall.input,\n rawToolInputError,\n ),\n );\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n isError: true,\n completedSideEffect: false,\n });\n recordToolResult(result, true);\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n isError: true,\n };\n }\n\n const cacheKey =\n actionEntry.readOnly === true\n ? toolCallCacheKey(toolCall.name, toolCall.input)\n : null;\n if (cacheKey && readOnlyToolResultCache.has(cacheKey)) {\n const repeats = (duplicateReadOnlyToolCalls.get(cacheKey) ?? 0) + 1;\n duplicateReadOnlyToolCalls.set(cacheKey, repeats);\n const previousResult = readOnlyToolResultCache.get(cacheKey) ?? \"\";\n const result =\n `Skipped duplicate read-only call to ${toolCall.name}: identical input already ran in this turn. ` +\n `Use the previous result already in the conversation instead of calling this tool again.\\n\\n` +\n `Previous result:\\n${previousResult}`;\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n completedSideEffect: false,\n });\n recordToolResult(result, false);\n if (repeats >= 3) {\n requestedActionStop ??= {\n message:\n \"I stopped because the agent kept asking for the same read-only context it already had. Please send the request again if you want me to retry from a fresh turn.\",\n errorCode: \"duplicate_read_only_tool\",\n };\n }\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n };\n }\n\n if (\n opts.executionMode === \"plan\" &&\n !isPlanModeToolCallAllowed(toolCall.name, toolCall.input, actionEntry)\n ) {\n const result = planModeBlockedMessage(toolCall.name);\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n isError: true,\n completedSideEffect: false,\n });\n recordToolResult(result, true);\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n isError: true,\n };\n }\n\n let result: string;\n let isError = false;\n let mcpApp:\n | import(\"../mcp-client/app-result.js\").AgentMcpAppPayload\n | undefined;\n let toolResultImages:\n | import(\"./engine/types.js\").EngineToolResultImagePart[]\n | undefined;\n try {\n // The run may have been aborted while we waited above for an\n // interrupted tool's ledger result (the wait can poll for minutes).\n // Re-check before invoking the action: starting it now would spawn a\n // fresh zombie execution — a duplicate side effect / double charge —\n // which the ledger-recovery path exists to prevent. The Promise.race\n // \"Run aborted\" leg below only rejects AFTER the action is invoked, so\n // it cannot guard this. Throw here instead, handled like any abort.\n if (signal.aborted) {\n throw new Error(\"Run aborted\");\n }\n const timeoutSignal = AbortSignal.timeout(toolTimeoutMs);\n const actionUserEmail = opts.ownerEmail ?? getRequestUserEmail();\n const actionOrgId = opts.orgId ?? getRequestOrgId() ?? null;\n const actionContext = {\n send,\n userEmail: actionUserEmail ?? undefined,\n orgId: actionOrgId,\n caller: \"tool\" as const,\n attachments: opts.attachments,\n signal,\n // Audit attribution: the action name + the agent thread/turn that\n // triggered this call, so a mutation can be traced to its run.\n actionName: toolCall.name,\n ...(opts.threadId ? { threadId: opts.threadId } : {}),\n ...(opts.turnId ? { turnId: opts.turnId } : {}),\n };\n const requestContext = getRequestContext();\n const invokeAction = () =>\n actionEntry.run(\n toolCall.input as Record<string, string>,\n actionContext,\n );\n // Keep a reference to the action promise so we can attach a zombie-\n // detection continuation AFTER Promise.race abandons it on run abort.\n // The promise itself is not awaited here — Promise.race owns the await.\n const actionPromise = Promise.resolve(\n runWithRequestContext(\n {\n ...(requestContext ?? {}),\n ...(actionUserEmail ? { userEmail: actionUserEmail } : {}),\n ...(actionOrgId ? { orgId: actionOrgId } : {}),\n ...(requestContext?.run ? { run: requestContext.run } : {}),\n },\n invokeAction,\n ),\n );\n\n // When the run is aborted (soft-timeout / user cancel) while this tool\n // call is in flight, Promise.race below will throw \"Run aborted\" and the\n // action's promise becomes a zombie — it keeps running but its result is\n // never returned to the loop. If the zombie eventually resolves, write\n // the result to the durable ledger keyed by (threadId, toolKey) so the\n // next continuation chunk can recover it instead of re-executing the\n // side effect.\n if (opts.threadId && !actionEntry.readOnly) {\n const ledgerThreadId = opts.threadId;\n const ledgerToolKey = toolCallCacheKey(toolCall.name, toolCall.input);\n actionPromise\n .then((zombieRaw: unknown) => {\n const zombieMcp = isMcpActionResult(zombieRaw) ? zombieRaw : null;\n if (\n zombieMcp &&\n zombieMcp.raw &&\n typeof zombieMcp.raw === \"object\" &&\n (zombieMcp.raw as Record<string, unknown>).isError === true\n ) {\n return;\n }\n const zombieText = zombieMcp ? zombieMcp.text : zombieRaw;\n const zombieStr =\n typeof zombieText === \"string\"\n ? zombieText\n : JSON.stringify(zombieText, null, 2);\n void writeLedgerEntry(ledgerThreadId, ledgerToolKey, zombieStr);\n })\n .catch(() => {\n // Action errored in the zombie — no result to ledger.\n });\n }\n\n const raw = await Promise.race([\n actionPromise,\n new Promise<never>((_, reject) => {\n timeoutSignal.addEventListener(\"abort\", () =>\n reject(\n new Error(\n `Tool call timed out after ${toolTimeoutMs / 1000} seconds`,\n ),\n ),\n );\n }),\n // Stop waiting on the tool when the run itself is aborted (e.g. the\n // run-manager soft timeout, or a user cancel). Without this leg the\n // loop blocks on an in-flight tool for up to TOOL_TIMEOUT_MS after\n // the run signal has already fired.\n new Promise<never>((_, reject) => {\n if (signal.aborted) {\n reject(new Error(\"Run aborted\"));\n return;\n }\n signal.addEventListener(\n \"abort\",\n () => reject(new Error(\"Run aborted\")),\n { once: true },\n );\n }),\n ]);\n const mcpResult = isMcpActionResult(raw) ? raw : null;\n const rawForAgent = mcpResult ? mcpResult.text : raw;\n if (\n mcpResult &&\n mcpResult.raw &&\n typeof mcpResult.raw === \"object\" &&\n (mcpResult.raw as Record<string, unknown>).isError === true\n ) {\n isError = true;\n }\n mcpApp = mcpResult?.mcpApp;\n // Demo mode: the agent must see the same fake data the UI shows, so\n // it can't read out a real name/email on a live screen share. Redact\n // the structured result (not the JSON string) so IDs/dates/URLs stay\n // intact and follow-up tool calls still work. Gated — the expensive\n // walk only runs when demo mode is on.\n let redacted: unknown = rawForAgent;\n const demoMode = await isDemoModeEnabled();\n if (demoMode) {\n mcpApp = undefined;\n if (typeof rawForAgent === \"string\") {\n try {\n redacted = JSON.stringify(\n redactDemoData(JSON.parse(rawForAgent)),\n null,\n 2,\n );\n } catch {\n redacted = redactDemoString(rawForAgent);\n }\n } else {\n redacted = redactDemoData(rawForAgent);\n }\n }\n // Vision images for the model: MCP tools return standard `image`\n // content parts; first-party actions opt in via the well-known\n // `_agentImages` result field (stripped from the JSON the model\n // reads, even in demo mode). Demo mode drops the images themselves —\n // text redaction can't scrub pixels, and a screenshot would leak the\n // real contact names/emails/numbers the redaction exists to hide. The images array\n // never touches the ledger — only the compact text notes appended\n // below are persisted.\n let imageNotes: string[] = [];\n if (mcpResult) {\n if (!demoMode) {\n const mcpImages = extractMcpToolResultImages(mcpResult.raw);\n if (mcpImages.length > 0) toolResultImages = mcpImages;\n }\n } else {\n const extracted = extractAgentImagesFromActionResult(redacted);\n redacted = extracted.value;\n imageNotes = extracted.notes;\n if (extracted.images.length > 0 && !demoMode) {\n toolResultImages = extracted.images;\n }\n }\n if (toolResultImages) {\n imageNotes = [\n ...describeToolResultImages(toolResultImages),\n ...imageNotes,\n ];\n }\n let resultStr =\n typeof redacted === \"string\"\n ? redacted\n : JSON.stringify(redacted, null, 2);\n if (resultStr.length > toolMaxResultChars) {\n const truncated = resultStr.slice(0, toolMaxResultChars);\n resultStr = `${truncated}\\n\\n...[truncated — full result was ${resultStr.length.toLocaleString()} chars; only first ${toolMaxResultChars.toLocaleString()} shown]`;\n }\n // Image notes go after truncation so they always survive into the\n // persisted result string (the durable record that an image existed).\n if (imageNotes.length > 0) {\n resultStr = `${resultStr}\\n\\n${imageNotes.join(\"\\n\")}`;\n }\n result = resultStr;\n if (toolCall.name === TOOL_SEARCH_ACTION_NAME && !isError) {\n const added = expandActiveTools(\n extractToolSearchResultNames(rawForAgent),\n );\n if (added.length > 0) {\n result += `\\n\\nLoaded matching tool schemas for next step: ${added.join(\", \")}`;\n }\n }\n } catch (err: any) {\n if (isAgentActionStopError(err)) {\n const message =\n sanitizeToolErrorValue(err.message) ||\n `Stopped after ${toolCall.name} failed.`;\n result = sanitizeToolErrorValue(err.toolResult || message);\n requestedActionStop ??= {\n message,\n ...(err.errorCode ? { errorCode: err.errorCode } : {}),\n };\n } else {\n const message = sanitizeToolErrorValue(err);\n result = `Error running ${toolCall.name}: ${message}${rateLimitRecoveryHint(message)}`;\n }\n isError = true;\n }\n if (isError) {\n result = finalizeToolErrorResult(result);\n }\n\n // Auto-refresh the UI after a successful mutating tool call. Any action\n // that isn't explicitly read-only is assumed to mutate. The client's\n // useDbSync listener sees a change event with source:\"action\" and\n // invalidates [\"action\"] queries so list-* / get-* refetch. This makes\n // refresh after agent writes reliable without the model needing to\n // remember to call `refresh-screen` itself.\n if (!isError && actionEntry.readOnly !== true) {\n try {\n const { notifyActionChange } =\n await import(\"../server/action-change.js\");\n const owner = opts.ownerEmail ?? getRequestUserEmail() ?? undefined;\n const orgId = opts.orgId ?? getRequestOrgId() ?? undefined;\n await notifyActionChange({\n actionName: toolCall.name,\n ...(owner ? { owner } : {}),\n ...(orgId ? { orgId } : {}),\n });\n } catch {\n // poll module may be unavailable in non-server contexts — ignore\n }\n }\n\n send({\n type: \"tool_done\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, unknown>,\n result,\n ...(isError ? { isError: true } : {}),\n ...(isError\n ? { completedSideEffect: false }\n : actionEntry.readOnly !== true\n ? { completedSideEffect: true }\n : {}),\n ...(mcpApp ? { mcpApp } : {}),\n ...(actionEntry.chatUI ? { chatUI: actionEntry.chatUI } : {}),\n });\n recordToolResult(result, isError);\n if (!isError) {\n if (cacheKey) {\n readOnlyToolResultCache.set(cacheKey, result);\n } else {\n readOnlyToolResultCache.clear();\n duplicateReadOnlyToolCalls.clear();\n }\n }\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n toolInput: wireToolInput,\n content: result,\n ...(isError ? { isError } : {}),\n ...(!isError && toolResultImages && toolResultImages.length > 0\n ? { images: toolResultImages }\n : {}),\n };\n };\n\n type ParallelBatchKind = \"read\" | \"parallel-write\";\n const getParallelBatchKind = (\n toolCall: import(\"./engine/types.js\").EngineToolCallPart,\n ): ParallelBatchKind | null => {\n const entry = actions[toolCall.name];\n // Unknown tool name → serialize (null), don't fold it into the read-only\n // parallel batch. Misclassifying it as \"read\" lets it run via Promise.all\n // alongside genuine reads, which can reorder it ahead of a later mutating\n // call and break the model's intended sequencing.\n if (!entry) return null;\n if (entry.readOnly === true) return \"read\";\n if (entry.parallelSafe === true) return \"parallel-write\";\n return null;\n };\n\n // Engines can emit several tool-call blocks in one turn. Read-only calls\n // are always parallel. Mutating calls remain serialized by default, but\n // consecutive actions that explicitly declare `parallelSafe` can run in a\n // write batch. Reads and writes are separate batches so the model's stated\n // order still controls what data a same-turn read can observe.\n const toolResultParts: EngineContentPart[] = [];\n let parallelBatch: import(\"./engine/types.js\").EngineToolCallPart[] = [];\n let parallelBatchKind: ParallelBatchKind | null = null;\n const flushParallelBatch = async () => {\n if (parallelBatch.length === 0) return;\n const batch = parallelBatch;\n parallelBatch = [];\n parallelBatchKind = null;\n toolResultParts.push(...(await Promise.all(batch.map(runToolCall))));\n };\n\n for (const toolCall of toolCallParts) {\n const batchKind = getParallelBatchKind(toolCall);\n if (batchKind) {\n if (parallelBatchKind && parallelBatchKind !== batchKind) {\n await flushParallelBatch();\n }\n parallelBatchKind = batchKind;\n parallelBatch.push(toolCall);\n } else {\n await flushParallelBatch();\n toolResultParts.push(await runToolCall(toolCall));\n }\n }\n await flushParallelBatch();\n\n messages.push({ role: \"user\", content: toolResultParts });\n if (requestedActionStop) {\n // TypeScript can't track ??= through async closures; cast to known type.\n const stop = requestedActionStop as {\n message: string;\n errorCode?: string;\n };\n send({ type: \"text\", text: stop.message });\n break;\n }\n }\n\n // A processor halted the run: the `tripwire` event and final message were\n // already emitted at the abort site. Do NOT send the normal `done` — the run\n // ended on a guardrail, not a clean turn. The result hook still fires below\n // so processors can observe the (halted) final text.\n if (tripwire) {\n if (processorChain) {\n try {\n await processorChain.runResult(\n collectTextParts(\n messages.flatMap((m) => (m.role === \"assistant\" ? m.content : [])),\n ),\n );\n } catch (err) {\n if (!(err instanceof TripWire)) throw err;\n // A result-hook abort is a no-op: the run is already halting.\n }\n }\n return usage;\n }\n\n if (!signal.aborted) {\n // In-loop processor seam (result hook). Fires once at clean run end with the\n // final assistant text so processors (e.g. a proof-of-done gate) can record\n // a verdict. A result-hook abort cannot un-finish a completed run, so a\n // TripWire here is swallowed.\n if (processorChain) {\n try {\n await processorChain.runResult(\n collectTextParts(\n messages.flatMap((m) => (m.role === \"assistant\" ? m.content : [])),\n ),\n );\n } catch (err) {\n if (!(err instanceof TripWire)) throw err;\n }\n }\n send({ type: \"done\" });\n // Clean up any zombie-completion ledger entries for this thread now that\n // the turn completed normally. If the run was aborted the ledger must stay\n // intact so the next continuation chunk can still recover from it.\n if (opts.threadId) {\n void clearLedgerForThread(opts.threadId).catch(() => {});\n\n // Observational Memory (producer): after a clean turn, run a best-effort\n // compaction pass so long threads accrue observations/reflections that the\n // consumer above will surface on later turns. Both the Observer and the\n // Reflector no-op below their token thresholds, so this is cheap for short\n // threads. Fire-and-forget; any failure is swallowed so OM never affects\n // the user-visible turn.\n if (opts.ownerEmail) {\n const compactThreadId = opts.threadId;\n void maybeCompactThread({\n threadId: compactThreadId,\n ownerEmail: opts.ownerEmail,\n orgId: opts.orgId ?? null,\n messages,\n }).catch((err) => {\n console.warn(\n \"[observational-memory] post-turn compaction skipped:\",\n err instanceof Error ? err.message : String(err),\n );\n });\n }\n }\n }\n return usage;\n}\n\nfunction backgroundChatProgressRunId(turnId: string): string {\n const normalized = turnId\n .trim()\n .replace(/[^a-zA-Z0-9._:-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 160);\n return `agent-chat-${normalized || \"turn\"}`;\n}\n\nfunction isRecoverableContinuationError(event: {\n type: \"error\";\n error: string;\n errorCode?: string;\n recoverable?: boolean;\n}): boolean {\n const code = String(event.errorCode ?? \"\").toLowerCase();\n const message = event.error.toLowerCase();\n if (code === \"builder_gateway_error\") return false;\n return (\n event.recoverable === true ||\n code === \"builder_gateway_timeout\" ||\n code === \"builder_gateway_network_error\" ||\n code === \"provider_network_error\" ||\n code === \"stale_run\" ||\n code === \"timeout\" ||\n code === \"timeout_error\" ||\n code === \"http_408\" ||\n code === \"http_429\" ||\n code === \"http_529\" ||\n code === \"run_timeout\" ||\n message.includes(\"timeout\") ||\n message.includes(\"connection error\") ||\n message.includes(\"temporarily unavailable\")\n );\n}\n\nfunction endsAtInternalContinuationBoundary(run: ActiveRun): boolean {\n const last = run.events.at(-1)?.event;\n if (!last) return false;\n if (last.type === \"auto_continue\" || last.type === \"loop_limit\") {\n return true;\n }\n return last.type === \"error\" && isRecoverableContinuationError(last);\n}\n\nfunction isPreparingActionActivityEvent(\n event: AgentChatEvent,\n): event is Extract<AgentChatEvent, { type: \"activity\" }> {\n if (event.type !== \"activity\") return false;\n const label = event.label.trim().toLowerCase();\n return label.startsWith(\"preparing \") && label.includes(\" action\");\n}\n\nexport function lastUnfinishedPreparingActionToolFromEvents(\n events: readonly AgentChatEvent[],\n): string | undefined {\n const active = new Map<\n string,\n {\n id?: string;\n order: number;\n tool: string;\n }\n >();\n const idlessToolStarts = new Map<string, number>();\n const removeOldestMatchingActivePreparation = (\n tool: string,\n shouldRemove: (value: {\n id?: string;\n order: number;\n tool: string;\n }) => boolean = () => true,\n ) => {\n let oldest:\n | {\n key: string;\n order: number;\n }\n | undefined;\n for (const [key, value] of active) {\n if (value.tool !== tool || !shouldRemove(value)) continue;\n if (!oldest || value.order < oldest.order) {\n oldest = {\n key,\n order: value.order,\n };\n }\n }\n if (oldest) active.delete(oldest.key);\n return Boolean(oldest);\n };\n const removeMatchingActivePreparation = (event: {\n id?: string;\n tool?: string;\n type: \"tool_done\" | \"tool_start\";\n }) => {\n const id = event.id?.trim();\n const tool = event.tool?.trim();\n if (!tool) return;\n if (id) {\n if (!active.delete(`id:${id}`)) {\n removeOldestMatchingActivePreparation(tool, (value) => !value.id);\n }\n return;\n }\n\n if (event.type === \"tool_start\") {\n if (removeOldestMatchingActivePreparation(tool)) {\n idlessToolStarts.set(tool, (idlessToolStarts.get(tool) ?? 0) + 1);\n }\n return;\n }\n\n const startedCount = idlessToolStarts.get(tool) ?? 0;\n if (startedCount > 0) {\n if (startedCount === 1) {\n idlessToolStarts.delete(tool);\n } else {\n idlessToolStarts.set(tool, startedCount - 1);\n }\n return;\n }\n removeOldestMatchingActivePreparation(tool);\n };\n events.forEach((event, order) => {\n if (isPreparingActionActivityEvent(event)) {\n const tool = event.tool?.trim();\n if (tool) {\n const id = event.id?.trim();\n const key = id ? `id:${id}` : `tool:${tool}:${order}`;\n active.set(key, {\n tool,\n order,\n ...(id ? { id } : {}),\n });\n }\n return;\n }\n if (event.type === \"tool_start\" || event.type === \"tool_done\") {\n removeMatchingActivePreparation(event);\n return;\n }\n if (event.type === \"error\" && isRecoverableContinuationError(event)) {\n return;\n }\n if (\n event.type === \"clear\" ||\n event.type === \"done\" ||\n event.type === \"error\" ||\n event.type === \"missing_api_key\"\n ) {\n active.clear();\n idlessToolStarts.clear();\n }\n });\n let latest:\n | {\n order: number;\n tool: string;\n }\n | undefined;\n for (const value of active.values()) {\n if (!latest || value.order > latest.order) {\n latest = value;\n }\n }\n return latest?.tool;\n}\n\nfunction endsAfterCompletedToolWithoutAssistantFinal(run: ActiveRun): boolean {\n let completedToolAfterLastAssistantText = false;\n for (const { event } of run.events) {\n if (event.type === \"text\" && event.text.trim().length > 0) {\n completedToolAfterLastAssistantText = false;\n continue;\n }\n if (event.type === \"tool_done\" && event.isError !== true) {\n completedToolAfterLastAssistantText = true;\n continue;\n }\n if (\n event.type === \"clear\" ||\n event.type === \"error\" ||\n event.type === \"missing_api_key\" ||\n event.type === \"auto_continue\" ||\n event.type === \"loop_limit\"\n ) {\n completedToolAfterLastAssistantText = false;\n }\n }\n return completedToolAfterLastAssistantText;\n}\n\nfunction lastUnfinishedPreparingActionTool(run: ActiveRun): string | undefined {\n return lastUnfinishedPreparingActionToolFromEvents(\n run.events.map(({ event }) => event),\n );\n}\n\nexport function backgroundContinuationReasonForRun(\n run: ActiveRun,\n): AgentLoopContinuationReason {\n const last = run.events.at(-1)?.event;\n if (last?.type === \"loop_limit\") return \"loop_limit\";\n if (\n last?.type === \"auto_continue\" &&\n isAgentLoopContinuationReason(last.reason)\n ) {\n return last.reason;\n }\n if (last?.type === \"error\" && isRecoverableContinuationError(last)) {\n return continuationReasonForResumableError(\n new EngineError(last.error, { errorCode: last.errorCode }),\n );\n }\n if (endsAfterCompletedToolWithoutAssistantFinal(run)) {\n return \"stream_ended\";\n }\n return \"run_timeout\";\n}\n\nexport async function runAgentLoopWithMainChatInternalContinuations(\n opts: Parameters<typeof runAgentLoop>[0] & {\n /**\n * Opt-in: also catch a thrown `isResumableEngineError` (gateway drop /\n * transport interruption surviving engine retries) and retry it in-process\n * — the same \"continue from where you left off\" treatment already applied\n * to in-loop `auto_continue` events below — instead of letting it\n * propagate out to the caller. Default false/omitted preserves the exact\n * prior behavior: such an error is NOT caught here and propagates to\n * `startRun`'s outer catch, which marks the run \"errored\" and (for a\n * background worker) hands off to `chainServerDrivenContinuation` for a\n * fresh invocation.\n *\n * Only safe to enable when the CALLER is a proven durable-background\n * worker (`isInBackgroundFunctionRuntime()`): such a worker has minutes of\n * remaining budget on this same invocation, so resuming in-process avoids\n * a self-dispatch entirely — critically, it avoids the bg-function\n * self-dispatch 404 (a background function cannot invoke its own public\n * URL from inside a live invocation) that this same recoverable-error\n * path would otherwise hit via `chainServerDrivenContinuation`. A\n * foreground turn (~40s budget) must NOT set this — it keeps depending on\n * the existing cross-invocation recovery (foreground self-chain or the\n * client's `auto_continue` re-POST), unchanged.\n */\n resumeResumableErrorsInProcess?: boolean;\n /**\n * Override for the per-invocation continuation attempt cap. Defaults to\n * `MAIN_CHAT_INTERNAL_CONTINUATION_LIMIT` (6) when omitted — unchanged for\n * every existing caller. A proven background-function worker (15-min\n * budget) can pass a higher cap (e.g. `MAX_BACKGROUND_RUN_CONTINUATIONS`)\n * so a run that needs several resumable-error recoveries within one\n * 13-minute chunk isn't cut off at the foreground-sized limit.\n */\n maxContinuations?: number;\n },\n): Promise<Awaited<ReturnType<typeof runAgentLoop>>> {\n const usage: Awaited<ReturnType<typeof runAgentLoop>> = {\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n model: opts.model,\n };\n const addUsage = (next: Awaited<ReturnType<typeof runAgentLoop>>) => {\n usage.inputTokens += next.inputTokens;\n usage.outputTokens += next.outputTokens;\n usage.cacheReadTokens += next.cacheReadTokens;\n usage.cacheWriteTokens += next.cacheWriteTokens;\n usage.model = next.model;\n };\n\n const resumeResumableErrorsInProcess =\n opts.resumeResumableErrorsInProcess === true;\n const maxContinuations =\n typeof opts.maxContinuations === \"number\" && opts.maxContinuations > 0\n ? opts.maxContinuations\n : MAIN_CHAT_INTERNAL_CONTINUATION_LIMIT;\n\n const localTurnEvents: AgentChatEvent[] = [];\n let lastAttemptWasUnfinishedContinuation = false;\n for (\n let attempt = 0;\n !opts.signal.aborted && attempt < maxContinuations;\n attempt++\n ) {\n lastAttemptWasUnfinishedContinuation = false;\n let continuationReason: AgentLoopContinuationReason | undefined;\n const attemptStartIndex = localTurnEvents.length;\n const send = (event: AgentChatEvent) => {\n localTurnEvents.push(event);\n if (\n event.type === \"auto_continue\" &&\n isAgentLoopContinuationReason(event.reason)\n ) {\n continuationReason = event.reason;\n return;\n }\n opts.send(event);\n };\n\n try {\n const nextUsage = await runAgentLoop({ ...opts, send });\n addUsage(nextUsage);\n } catch (err) {\n // Preserve exact prior behavior unless explicitly opted in: an aborted\n // signal (real soft-timeout / user stop) or a non-resumable error is\n // always rethrown, and when `resumeResumableErrorsInProcess` is not\n // set, EVERY thrown error is rethrown exactly as before.\n if (\n !resumeResumableErrorsInProcess ||\n opts.signal.aborted ||\n !isResumableEngineError(err)\n ) {\n throw err;\n }\n continuationReason = continuationReasonForResumableError(err);\n }\n\n if (!continuationReason || opts.signal.aborted) {\n return usage;\n }\n\n lastAttemptWasUnfinishedContinuation = true;\n const attemptEvents = localTurnEvents.slice(attemptStartIndex);\n const completedSideEffect = attemptEvents.some(\n (event) =>\n event.type === \"tool_done\" &&\n event.completedSideEffect === true &&\n event.isError !== true,\n );\n if (!completedSideEffect) {\n opts.send({ type: \"clear\" });\n }\n const actionPreparationTool =\n lastUnfinishedPreparingActionToolFromEvents(localTurnEvents);\n appendAgentLoopContinuation(opts.messages, continuationReason, {\n ...(actionPreparationTool ? { actionPreparationTool } : {}),\n });\n }\n\n if (!opts.signal.aborted && lastAttemptWasUnfinishedContinuation) {\n opts.send({\n type: \"error\",\n error: RUN_BUDGET_EXHAUSTED_MESSAGE,\n errorCode: RUN_BUDGET_EXHAUSTED_ERROR_CODE,\n recoverable: true,\n });\n }\n return usage;\n}\n\nfunction endsAtContinuationBoundary(run: ActiveRun): boolean {\n return (\n endsAtInternalContinuationBoundary(run) ||\n endsAfterCompletedToolWithoutAssistantFinal(run)\n );\n}\n\n/**\n * Hard cap on server-driven background→background continuation chunks for a\n * single logical turn. A `backgroundFunction` run gets a ~13-min soft timeout,\n * so reaching this boundary at all is the rare exception (most turns finish in\n * one chunk). The cap bounds a pathological turn that would otherwise chain\n * background invocations forever, mirroring `MAX_AGENT_TEAM_CONTINUATIONS`.\n */\nexport const MAX_BACKGROUND_RUN_CONTINUATIONS = 20;\n\n/**\n * Whether this run should self-fire the next server-driven continuation chunk\n * instead of depending on the client to re-POST `auto_continue`. True for\n * either of two independently-gated cases, both requiring a recoverable\n * unfinished boundary (not aborted/stopped) and a chain still under its\n * budget:\n * - a durable-background WORKER run (`isBackgroundWorker`) — unconditional,\n * unchanged from before; or\n * - a FOREGROUND run when the resolved `foregroundSelfChainEligible` gate is\n * true (see `isAgentChatForegroundSelfChainEnabled` in\n * `durable-background.ts`) AND this specific run was never dispatched to\n * the durable background worker (`dispatchedToBackground` false) — a run\n * already headed to the durable background path chains via the\n * `isBackgroundWorker` branch above, never both.\n * Aborted / user-stopped runs do NOT chain either way.\n */\nexport function shouldChainBackgroundContinuation(opts: {\n isBackgroundWorker: boolean;\n run: ActiveRun;\n continuationCount: number;\n /**\n * Opt-in: allow a FOREGROUND (non-background-worker) run to also\n * self-chain server-side. Default false — preserves the exact prior\n * behavior (foreground runs never chain; the client's `auto_continue`\n * re-POST is the only continuation path) when omitted.\n */\n foregroundSelfChainEligible?: boolean;\n /**\n * True when this run was dispatched to the durable background worker\n * (`dispatchToBackground` in the handler). When true, foreground self-chain\n * is never eligible — the run either IS the background worker (chains via\n * `isBackgroundWorker`) or is a foreground POST whose recovery is already\n * owned by the background circuit-breaker, not this path.\n */\n dispatchedToBackground?: boolean;\n}): boolean {\n const eligible =\n opts.isBackgroundWorker ||\n (opts.foregroundSelfChainEligible === true &&\n opts.dispatchedToBackground !== true);\n return (\n eligible &&\n opts.run.status !== \"aborted\" &&\n endsAtContinuationBoundary(opts.run) &&\n opts.continuationCount < MAX_BACKGROUND_RUN_CONTINUATIONS\n );\n}\n\nexport async function markBackgroundContinuationChunkTerminal(opts: {\n runId: string;\n continuationReason: AgentLoopContinuationReason;\n deps?: {\n updateRunStatusIfRunning?: typeof updateRunStatusIfRunning;\n setRunTerminalReason?: typeof setRunTerminalReason;\n };\n}): Promise<boolean> {\n const updateStatus =\n opts.deps?.updateRunStatusIfRunning ?? updateRunStatusIfRunning;\n const setTerminalReason =\n opts.deps?.setRunTerminalReason ?? setRunTerminalReason;\n const updated = await updateStatus(opts.runId, \"completed\");\n if (updated) {\n await setTerminalReason(opts.runId, opts.continuationReason);\n }\n return updated;\n}\n\nexport async function claimBackgroundWorkerRunEarly(opts: {\n runId: string;\n threadId?: string | null;\n markerTurnId?: string | null;\n requestTurnId?: string | null;\n continuationCount: number;\n runsInBackgroundFunction: boolean;\n backgroundRuntimeDetail?: string;\n deps?: {\n recordRunDiagnostic?: typeof recordRunDiagnostic;\n insertRun?: typeof insertRun;\n claimBackgroundRun?: typeof claimBackgroundRun;\n updateRunHeartbeat?: typeof updateRunHeartbeat;\n };\n}): Promise<{ claimed: true } | { claimed: false; skipped: string }> {\n const record = opts.deps?.recordRunDiagnostic ?? recordRunDiagnostic;\n const insert = opts.deps?.insertRun ?? insertRun;\n const claim = opts.deps?.claimBackgroundRun ?? claimBackgroundRun;\n const heartbeat = opts.deps?.updateRunHeartbeat ?? updateRunHeartbeat;\n const threadId =\n typeof opts.threadId === \"string\" && opts.threadId.trim()\n ? opts.threadId.trim()\n : opts.runId;\n const turnId =\n typeof opts.markerTurnId === \"string\" && opts.markerTurnId.trim()\n ? opts.markerTurnId.trim()\n : typeof opts.requestTurnId === \"string\" && opts.requestTurnId.trim()\n ? opts.requestTurnId.trim()\n : opts.runId;\n\n await record(\n opts.runId,\n RUN_DIAG_STAGE.workerEntered,\n [\n `runsInBackgroundFunction=${opts.runsInBackgroundFunction}`,\n `continuationCount=${opts.continuationCount}`,\n opts.backgroundRuntimeDetail,\n ]\n .filter(Boolean)\n .join(\" \"),\n ).catch(() => {});\n\n if (opts.continuationCount > 0) {\n await insert(opts.runId, threadId, turnId, {\n dispatchMode: \"background\",\n }).catch(() => {});\n }\n\n const won = await claim(opts.runId);\n if (!won) {\n await record(opts.runId, RUN_DIAG_STAGE.workerClaimLost).catch(() => {});\n return { claimed: false, skipped: \"already-claimed\" };\n }\n\n await record(opts.runId, RUN_DIAG_STAGE.workerClaimed).catch(() => {});\n await heartbeat(opts.runId).catch(() => {});\n return { claimed: true };\n}\n\n/** Injectable dependencies for `chainServerDrivenContinuation` (unit tests). */\nexport interface ChainServerDrivenContinuationDeps {\n countRunsForTurn?: typeof countRunsForTurn;\n insertRun?: typeof insertRun;\n fireInternalDispatch?: typeof fireInternalDispatch;\n readBackgroundRunClaim?: typeof readBackgroundRunClaim;\n updateRunHeartbeat?: typeof updateRunHeartbeat;\n updateRunStatusIfRunning?: typeof updateRunStatusIfRunning;\n setRunTerminalReason?: typeof setRunTerminalReason;\n recordRunDiagnostic?: typeof recordRunDiagnostic;\n markBackgroundContinuationChunkTerminal?: typeof markBackgroundContinuationChunkTerminal;\n generateRunId?: typeof generateRunId;\n sleep?: (ms: number) => Promise<void>;\n}\n\n/** Retry-budget sizing for one `chainServerDrivenContinuation` dispatch. */\nexport interface ContinuationDispatchBudget {\n maxDispatchAttempts: number;\n dispatchResponseTimeoutMs: number;\n /** Cap (ms) on the per-gap exponential backoff. `Infinity` preserves the\n * original uncapped `500 * 2 ** attempt` schedule for the two budgets\n * that predate this cap (their attempt counts are low enough it never\n * mattered); only the larger proven-in-background-function budget uses a\n * real cap so its extra attempts don't add unbounded backoff. */\n backoffCapMs: number;\n}\n\n/**\n * Sizes the dispatch retry budget by *remaining wall-clock capacity*, not by\n * dispatch TARGET — the two are independent concerns. `chainViaDurableBackground`\n * only picks where the dispatch goes (see `continuationDispatchPath` above);\n * this picks how hard to retry getting it there.\n *\n * Three cases:\n * - `chainViaDurableBackground === true`: the durable worker chain dispatching\n * to the Netlify background function url. Unchanged: 3 attempts / 15s.\n * - `chainViaDurableBackground === false` and\n * `workerProvenInBackgroundFunction === true`: a worker PROVEN (by runtime\n * function name, see `shouldUseBackgroundFunctionTimeoutForWorker`) to\n * already be executing inside a real `-background` function — it was\n * forced onto the regular-function dispatch target only because a\n * background function cannot invoke its own URL from within a live\n * invocation (see the caller's `&& !runsInBackgroundFunction` comment),\n * NOT because it lacks time or a connected-client fallback. This worker\n * has up to `BACKGROUND_SOFT_TIMEOUT_CEILING_MS` (13min) of soft-timeout\n * budget behind it and up to Netlify's ~15min hard function limit ahead —\n * roughly 2 minutes of remaining wall clock — and, being a background\n * worker, NO connected client to fall back on if the handoff is dropped.\n * Demoting it to the foreground's 2-attempt/10s budget is exactly the bug\n * this type documents: 5 attempts / 15s response timeout, with backoff\n * capped at 4s/gap (500ms, 1s, 2s, 4s across the 4 gaps ≈ 7.5s total).\n * Worst case: 5 × 15s dispatch + ~7.5s backoff ≈ 82.5s, safely inside the\n * ~2min of remaining budget before the function's hard kill.\n * - Otherwise: a true foreground caller not proven in a background\n * function. Unchanged: 2 attempts / 10s — it has a live connected client\n * as a fallback (the terminal `auto_continue` event still reaches it).\n */\nexport function resolveContinuationDispatchBudget(opts: {\n chainViaDurableBackground: boolean;\n workerProvenInBackgroundFunction: boolean;\n}): ContinuationDispatchBudget {\n if (opts.chainViaDurableBackground) {\n return {\n maxDispatchAttempts: 3,\n dispatchResponseTimeoutMs: 15_000,\n backoffCapMs: Infinity,\n };\n }\n if (opts.workerProvenInBackgroundFunction) {\n return {\n maxDispatchAttempts: 5,\n dispatchResponseTimeoutMs: 15_000,\n backoffCapMs: 4_000,\n };\n }\n return {\n maxDispatchAttempts: 2,\n dispatchResponseTimeoutMs: 10_000,\n backoffCapMs: Infinity,\n };\n}\n\n/**\n * Server-driven continuation handoff for a chunk that hit its soft-timeout\n * boundary still unfinished: mint the next chunk's runId, PRE-INSERT its run\n * row (so `/runs/active` never shows an idle gap and a lost dispatch is\n * reaped loudly instead of hanging silently), fire the HMAC-signed\n * `_process-run` self-dispatch carrying ids only (the body is persisted on\n * the row as `dispatch_payload`), fully AWAIT the dispatch acknowledgment\n * with retries, and mark this chunk terminal only after the handoff landed.\n * On failure every path is loud: the successor row is errored, the failure\n * is recorded as the run's diag stage, and this chunk is flipped to errored\n * with a terminal reason — never a silent loss. (For a FOREGROUND self-chain\n * the client additionally still receives the terminal `auto_continue` event\n * — run-manager emits it after this callback — so the existing client\n * re-POST path takes over as the fallback.)\n *\n * `chainViaDurableBackground` selects the dispatch target:\n * - true → the durable-background worker chain (unchanged behavior): the\n * resolved background-function url on hosted Netlify (15-min budget), 3\n * attempts, 15s response timeout (Netlify async functions 202 on enqueue).\n * - false → the OPT-IN foreground self-chain: the framework `_process-run`\n * route on the REGULAR function. With `AGENT_CHAT_DURABLE_BACKGROUND`\n * off the `-background` function is never emitted into the deploy\n * output, so the regular function is the only guaranteed target; the\n * successor keeps the 40s chunk clamp (`backgroundFunctionRuntimeExpected`\n * is false for this path). The regular function responds only after the\n * successor chunk FINISHES (~40s), so a response timeout is NOT proof of\n * a dead handoff — after a failed/timed-out attempt the successor's\n * ATOMIC CLAIM is consulted (`readBackgroundRunClaim`): a row that\n * flipped to `background-processing` (or already went terminal) proves\n * the handoff landed, so no retry is fired.\n *\n * `chainViaDurableBackground` does NOT alone determine the retry BUDGET —\n * see `resolveContinuationDispatchBudget` and `workerProvenInBackgroundFunction`\n * below: a worker forced onto this same `false` target because it is proven\n * to already be inside a real background function gets a materially larger\n * budget than a true foreground caller, since it has no connected-client\n * fallback and minutes of remaining wall clock instead of seconds.\n *\n * Never throws — all failure paths are handled (recorded + marked) inside.\n */\nexport async function chainServerDrivenContinuation(opts: {\n event: unknown;\n run: ActiveRun;\n effectiveThreadId: string;\n effectiveTurnId: string;\n /** The current chunk's request body — the successor's rehydration payload\n * is derived from it (marker stripped, `internalContinuation` set). */\n requestBody: Record<string, unknown>;\n backgroundContinuationCount: number;\n chainViaDurableBackground: boolean;\n /** True only when this worker is PROVEN (by runtime function name) to\n * already be executing inside a real Netlify `-background` function —\n * distinct from `chainViaDurableBackground`, which is forced `false` for\n * this exact worker (it cannot dispatch to its own function URL from a\n * live invocation). Widens the retry budget; does NOT change the dispatch\n * target. See `resolveContinuationDispatchBudget`. Defaults to `false`. */\n workerProvenInBackgroundFunction?: boolean;\n deps?: ChainServerDrivenContinuationDeps;\n}): Promise<void> {\n const d = {\n countRunsForTurn: opts.deps?.countRunsForTurn ?? countRunsForTurn,\n insertRun: opts.deps?.insertRun ?? insertRun,\n fireInternalDispatch:\n opts.deps?.fireInternalDispatch ?? fireInternalDispatch,\n readBackgroundRunClaim:\n opts.deps?.readBackgroundRunClaim ?? readBackgroundRunClaim,\n updateRunHeartbeat: opts.deps?.updateRunHeartbeat ?? updateRunHeartbeat,\n updateRunStatusIfRunning:\n opts.deps?.updateRunStatusIfRunning ?? updateRunStatusIfRunning,\n setRunTerminalReason:\n opts.deps?.setRunTerminalReason ?? setRunTerminalReason,\n recordRunDiagnostic: opts.deps?.recordRunDiagnostic ?? recordRunDiagnostic,\n markBackgroundContinuationChunkTerminal:\n opts.deps?.markBackgroundContinuationChunkTerminal ??\n markBackgroundContinuationChunkTerminal,\n generateRunId: opts.deps?.generateRunId ?? generateRunId,\n sleep:\n opts.deps?.sleep ??\n ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))),\n };\n const { run, effectiveThreadId, effectiveTurnId } = opts;\n const runId = run.runId;\n\n // DURABLE PER-TURN LEDGER: bound the total number of runs one logical turn\n // may consume, counted in SQL. The in-marker `continuationCount` resets\n // whenever a fresh POST starts a new chain for the same turn (client\n // recovery, duplicate delivery), so it cannot bound cross-chain loops — the\n // SQL count survives every recovery path and is what actually kills a\n // pathological turn (the \"dozens of runs on one prompt\" incident class).\n const turnRunCount = await d\n .countRunsForTurn(effectiveThreadId, effectiveTurnId)\n .catch(() => null);\n if (\n turnRunCount !== null &&\n turnRunCount > MAX_BACKGROUND_RUN_CONTINUATIONS + 5\n ) {\n console.error(\n `[agent-chat] turn ${effectiveTurnId} consumed ${turnRunCount} runs — refusing to chain further`,\n runId,\n );\n const statusUpdated = await d\n .updateRunStatusIfRunning(runId, \"errored\")\n .catch(() => false);\n if (statusUpdated) {\n await d\n .setRunTerminalReason(runId, \"turn_continuation_budget_exhausted\")\n .catch(() => {});\n }\n return;\n }\n\n // Mint the next chunk's runId here and sign the dispatch token over it, so\n // the `_process-run` route's HMAC check and the worker's run identity\n // agree. Fresh runId (not this chunk's) so its seq log starts clean; same\n // turnId folds the assistant message across chunks.\n const nextRunId = d.generateRunId();\n const actionPreparationTool = lastUnfinishedPreparingActionTool(run);\n const continuationReason = backgroundContinuationReasonForRun(run);\n const continuationDispatchPath = opts.chainViaDurableBackground\n ? resolveAgentChatProcessRunDispatchPath()\n : AGENT_CHAT_PROCESS_RUN_PATH;\n const continuationExpectsNetlifyBackgroundFunction =\n dispatchPathTargetsNetlifyBackgroundFunction(continuationDispatchPath);\n const dispatchBudget = resolveContinuationDispatchBudget({\n chainViaDurableBackground: opts.chainViaDurableBackground,\n workerProvenInBackgroundFunction:\n opts.workerProvenInBackgroundFunction === true,\n });\n const maxDispatchAttempts = dispatchBudget.maxDispatchAttempts;\n const dispatchResponseTimeoutMs = dispatchBudget.dispatchResponseTimeoutMs;\n const continuationMarker = {\n runId: nextRunId,\n turnId: effectiveTurnId,\n continuationCount: opts.backgroundContinuationCount + 1,\n continuationReason,\n ...(actionPreparationTool ? { actionPreparationTool } : {}),\n backgroundFunctionRuntimeExpected:\n continuationExpectsNetlifyBackgroundFunction,\n };\n // Strip this chunk's own marker before persisting/forwarding — the next\n // chunk gets the fresh marker above.\n const continuationBody: Record<string, unknown> = {\n ...opts.requestBody,\n internalContinuation: true,\n };\n delete continuationBody[AGENT_CHAT_BACKGROUND_RUN_FIELD];\n try {\n await d\n .recordRunDiagnostic(\n runId,\n RUN_DIAG_STAGE.workerSetupStep,\n `chain_dispatch_start nextRunId=${nextRunId} reason=${continuationReason} path=${continuationDispatchPath}`,\n )\n .catch(() => {});\n // ── TRANSACTIONAL HANDOFF ──────────────────────────────────────────────\n // 1. Insert the successor row (with its rehydration payload) BEFORE\n // firing the dispatch, so:\n // - /runs/active shows an active run continuously across the chunk\n // boundary (no idle gap for the client to misread as \"the turn\n // ended\"), and\n // - a lost dispatch leaves a row the unclaimed-run sweep reaps into a\n // LOUD error instead of a silent hang.\n // 2. Await the dispatch response fully (`awaitResponse`) — this\n // invocation is about to finish, and the old 250ms settle race let a\n // still-in-flight handoff fetch be killed by the post-return freeze\n // WITHOUT rejecting: the turn just stopped, silently. A Netlify\n // background function 202s on enqueue (normally well under a second);\n // a regular-function target instead responds only after the successor\n // chunk finishes, so its timeout falls back to the claim check below.\n // Retried with backoff for transient network blips.\n let nextRowInserted = false;\n try {\n await d.insertRun(nextRunId, effectiveThreadId, effectiveTurnId, {\n dispatchMode: \"background\",\n dispatchPayload: JSON.stringify(continuationBody),\n });\n nextRowInserted = true;\n } catch (insertErr) {\n await d\n .recordRunDiagnostic(\n runId,\n RUN_DIAG_STAGE.workerSetupStep,\n `chain_successor_insert_failed nextRunId=${nextRunId} ${\n insertErr instanceof Error ? insertErr.message : String(insertErr)\n }`,\n )\n .catch(() => {});\n console.error(\n \"[agent-chat] continuation insertRun failed; dispatching with inline body:\",\n insertErr instanceof Error ? insertErr.message : insertErr,\n );\n }\n const dispatchBody = nextRowInserted\n ? {\n internalContinuation: true,\n [AGENT_CHAT_BACKGROUND_RUN_FIELD]: {\n ...continuationMarker,\n payloadRef: true,\n },\n }\n : {\n ...continuationBody,\n [AGENT_CHAT_BACKGROUND_RUN_FIELD]: continuationMarker,\n };\n let dispatched = false;\n let lastDispatchErr: unknown;\n for (\n let attempt = 0;\n attempt < maxDispatchAttempts && !dispatched;\n attempt++\n ) {\n try {\n if (attempt > 0) {\n // Uncapped budgets (durable-background and true-foreground) keep\n // the original `500 * 2 ** attempt` schedule unchanged. The capped\n // budget (proven-in-background-function) instead uses a schedule\n // starting at 500ms and doubling per gap, capped at\n // `backoffCapMs` — see `resolveContinuationDispatchBudget` for why\n // this stays well inside the worker's remaining wall clock even\n // with 5 attempts.\n const backoffMs = Number.isFinite(dispatchBudget.backoffCapMs)\n ? Math.min(500 * 2 ** (attempt - 1), dispatchBudget.backoffCapMs)\n : 500 * 2 ** attempt;\n await d.sleep(backoffMs);\n // Keep the pre-inserted successor row visibly alive while we\n // retry: the awaited attempts + backoff can outlast\n // UNCLAIMED_BACKGROUND_RUN_GRACE_MS (25s), and without a fresh\n // heartbeat the unclaimed-run reaper / sweep could error a handoff\n // we are still delivering.\n if (nextRowInserted) {\n await d.updateRunHeartbeat(nextRunId).catch(() => {});\n }\n }\n await d.fireInternalDispatch({\n event: opts.event,\n // Durable chain: same path resolution as the initial dispatch —\n // on hosted Netlify the background function's DEFAULT url (no\n // custom config.path; async via background:true; never shadowed\n // because /.netlify/* is excluded from the /* catch-all) so each\n // chunk keeps the 15-min budget; off-Netlify the in-process\n // framework route. Foreground self-chain: always the framework\n // `_process-run` route on the regular function (see the fn doc).\n path: continuationDispatchPath,\n taskId: nextRunId,\n body: dispatchBody,\n awaitResponse: true,\n responseTimeoutMs: dispatchResponseTimeoutMs,\n });\n dispatched = true;\n } catch (dispatchErr) {\n lastDispatchErr = dispatchErr;\n // Regular-function targets (foreground self-chain) respond only\n // after the successor chunk FINISHES, so an await timeout is not\n // proof of a dead handoff. The successor's ATOMIC CLAIM is: a row\n // that left `dispatch_mode='background'` (claimed) or is already\n // terminal proves the handoff landed — stop retrying. A duplicate\n // delivery would lose the claim and no-op anyway; skipping it saves\n // wall-clock this close to the invocation deadline.\n if (!opts.chainViaDurableBackground && nextRowInserted) {\n const claim = await d\n .readBackgroundRunClaim(nextRunId)\n .catch(() => null);\n if (\n claim &&\n ((claim.dispatchMode && claim.dispatchMode !== \"background\") ||\n (claim.status && claim.status !== \"running\"))\n ) {\n dispatched = true;\n break;\n }\n }\n console.error(\n `[agent-chat] background continuation dispatch attempt ${attempt + 1} failed:`,\n dispatchErr instanceof Error ? dispatchErr.message : dispatchErr,\n );\n }\n }\n if (!dispatched) {\n // The pre-inserted successor row would otherwise sit unclaimed until\n // the sweep reaps it — error it now so the failure is immediate and\n // truthful.\n if (nextRowInserted) {\n const nextStatusUpdated = await d\n .updateRunStatusIfRunning(nextRunId, \"errored\")\n .catch(() => false);\n if (nextStatusUpdated) {\n await d\n .setRunTerminalReason(\n nextRunId,\n \"background_continuation_dispatch_failed\",\n )\n .catch(() => {});\n }\n }\n throw lastDispatchErr instanceof Error\n ? lastDispatchErr\n : new Error(String(lastDispatchErr));\n }\n await d\n .recordRunDiagnostic(\n runId,\n RUN_DIAG_STAGE.workerSetupStep,\n `chain_dispatch_sent nextRunId=${nextRunId} reason=${continuationReason}`,\n )\n .catch(() => {});\n await d\n .markBackgroundContinuationChunkTerminal({\n runId,\n continuationReason,\n })\n .catch(() => {});\n } catch (chainErr) {\n // Chain dispatch failed — fail loud so the held row goes terminal\n // instead of spinning. The reaper would also catch it, but this is\n // immediate and truthful. (Foreground self-chain: the client still\n // receives the terminal auto_continue after this returns, so its\n // existing re-POST continuation path takes over.)\n await d\n .recordRunDiagnostic(\n runId,\n RUN_DIAG_STAGE.workerThrew,\n `chain_dispatch_failed nextRunId=${nextRunId} ${\n chainErr instanceof Error ? chainErr.message : String(chainErr)\n }`,\n )\n .catch(() => {});\n console.error(\n \"[agent-chat] background continuation dispatch failed:\",\n chainErr instanceof Error ? chainErr.message : chainErr,\n );\n const statusUpdated = await d\n .updateRunStatusIfRunning(runId, \"errored\")\n .catch(() => false);\n if (statusUpdated) {\n await d\n .setRunTerminalReason(runId, \"background_continuation_dispatch_failed\")\n .catch(() => {});\n }\n }\n}\n\nfunction progressStepFromAgentChatEvent(event: AgentChatEvent): string | null {\n switch (event.type) {\n case \"activity\":\n return event.label;\n case \"tool_start\":\n return `Using ${event.tool}.`;\n case \"tool_done\":\n return `Finished ${event.tool}.`;\n case \"agent_call\":\n return event.status === \"start\"\n ? `Calling ${event.agent}.`\n : event.status === \"done\"\n ? `Finished ${event.agent}.`\n : `${event.agent} failed.`;\n case \"agent_task\":\n return event.status === \"running\"\n ? \"Started background task.\"\n : event.status === \"completed\"\n ? \"Background task completed.\"\n : \"Background task failed.\";\n case \"agent_task_update\":\n return event.currentStep || event.preview || \"Background task updated.\";\n case \"text\":\n return \"Agent is responding.\";\n default:\n return null;\n }\n}\n\nexport function createProductionAgentHandler(\n options: ProductionAgentOptions,\n): H3EventHandler {\n // Undefined = let each engine pick its own defaultModel at request time.\n const configuredModel = options.model;\n\n // Resolve actions — prefer `actions`, fall back to deprecated `scripts`\n const resolvedActions = options.actions ?? options.scripts ?? {};\n\n // Engine tools are derived from the action registry at request time so that\n // registries which mutate after handler creation (e.g. MCP servers added via\n // the settings UI) show up to the LLM without a process restart. MCP tools\n // are also scope-filtered per request — a user-scope server added by Alice\n // must not appear in Bob's tool list in a shared-process deployment.\n const getEngineTools = (\n actions: Record<string, ActionEntry> = resolvedActions,\n ) => {\n const filtered: Record<string, ActionEntry> = {};\n for (const [name, entry] of Object.entries(actions)) {\n if (name.startsWith(\"mcp__\") && !isMcpToolAllowedForRequest(name)) {\n continue;\n }\n filtered[name] = entry;\n }\n return actionsToEngineTools(filtered);\n };\n\n return defineEventHandler(async (event) => {\n // Diagnostic-only setup-timing instrumentation. Captures wall-clock offsets\n // from handler entry through the work done BEFORE startRun so a slow pre-run\n // setup phase is visible in the run diagnostics. Never alters control flow.\n const setupT0 = Date.now();\n const setupMarks: Record<string, number> = {};\n const setupMark = (k: string) => {\n setupMarks[k] = Date.now() - setupT0;\n };\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n let body: AgentChatRequest;\n // The durable-background `_process-run` route already consumed and verified\n // the request body (h3 v2's web Request body stream is single-use, so a\n // second readBody would fail). It stashes the verified+augmented body here\n // so this re-entered handler reads it instead of the spent stream.\n const preInjectedBody = (event as any)?.context\n ?.__agentChatBackgroundBody as AgentChatRequest | undefined;\n if (preInjectedBody && typeof preInjectedBody === \"object\") {\n body = preInjectedBody;\n } else {\n try {\n body = await readBody(event);\n } catch {\n setResponseStatus(event, 400);\n return { error: \"Invalid request body\" };\n }\n }\n\n const {\n message,\n history = [],\n structuredHistory,\n references = [],\n threadId,\n attachments,\n displayMessage,\n internalContinuation,\n turnId: requestTurnId,\n model: requestModel,\n engine: requestEngine,\n effort: requestEffort,\n browserTabId,\n scope,\n trackInRunsTray,\n } = body;\n setupMark(\"bodyParsed\");\n\n // Durable-background marker. Present ONLY when this handler was re-entered\n // as the Netlify background worker via the `_process-run` self-dispatch\n // (the route HMAC-verifies the dispatch before invoking us). When set, we\n // run the loop inline with the background soft-timeout, reusing the\n // pre-claimed runId/turnId — we must NOT re-claim the slot or re-dispatch.\n const backgroundRunMarker =\n body[AGENT_CHAT_BACKGROUND_RUN_FIELD] &&\n typeof body[AGENT_CHAT_BACKGROUND_RUN_FIELD] === \"object\" &&\n typeof body[AGENT_CHAT_BACKGROUND_RUN_FIELD]!.runId === \"string\"\n ? body[AGENT_CHAT_BACKGROUND_RUN_FIELD]!\n : null;\n const isBackgroundWorker = backgroundRunMarker !== null;\n // DIAGNOSTIC-ONLY: progressive per-stage hang localizer for the bg worker.\n // The worker's runId is available EARLY on the marker (the general `runId`\n // var resolves much later), so capture it now and emit the LAST setup stage\n // reached as the run's `diag_stage`. Best-effort, gated on the worker, never\n // blocks or alters control flow.\n const bgRunId = isBackgroundWorker\n ? (backgroundRunMarker?.runId as string)\n : null;\n const workerStep = (s: string) => {\n if (bgRunId)\n void recordRunDiagnostic(\n bgRunId,\n RUN_DIAG_STAGE.workerSetupStep,\n `${s}=${Date.now() - setupT0}ms`,\n ).catch(() => {});\n };\n // Whether this worker is REALLY executing inside a 15-min Netlify\n // `-background` function (proven by the runtime function name), not merely a\n // `_process-run` re-entry that may have landed on the ~60s synchronous\n // function. Only a true value unlocks the ~13-min soft-timeout budget; a\n // worker on the 60s function keeps the 40s clamp and checkpoints cleanly.\n const runsInBackgroundFunction =\n isBackgroundWorker &&\n shouldUseBackgroundFunctionTimeoutForWorker(backgroundRunMarker);\n const backgroundRuntimeDetail = isBackgroundWorker\n ? backgroundRuntimeDiagnosticDetail(backgroundRunMarker)\n : \"\";\n // How many server-driven background continuations have already chained into\n // this logical turn (0 on the first chunk). Used to bound the chain.\n const backgroundContinuationCount =\n isBackgroundWorker &&\n typeof backgroundRunMarker?.continuationCount === \"number\" &&\n Number.isFinite(backgroundRunMarker.continuationCount)\n ? Math.max(0, Math.floor(backgroundRunMarker.continuationCount))\n : 0;\n let backgroundRunClaimedEarly = false;\n if (isBackgroundWorker && bgRunId) {\n const earlyClaim = await claimBackgroundWorkerRunEarly({\n runId: bgRunId,\n threadId,\n markerTurnId:\n typeof backgroundRunMarker?.turnId === \"string\"\n ? backgroundRunMarker.turnId\n : null,\n requestTurnId,\n continuationCount: backgroundContinuationCount,\n runsInBackgroundFunction,\n backgroundRuntimeDetail,\n });\n if (!earlyClaim.claimed) {\n return { ok: true, skipped: earlyClaim.skipped };\n }\n backgroundRunClaimedEarly = true;\n }\n // The foreground POST decides whether to dispatch into a background\n // function. The background worker itself never re-dispatches.\n const dispatchToBackground =\n !isBackgroundWorker &&\n isAgentChatDurableBackgroundEnabled({\n appOptIn: options.durableBackgroundRuns === true,\n });\n const requestBrowserTabId = normalizeBrowserTabId(browserTabId);\n const requestChatScope = normalizeChatScope(scope);\n const requestRunCtx = ensureRequestRunContext();\n if (requestRunCtx) {\n requestRunCtx.browserTabId = requestBrowserTabId;\n requestRunCtx.chatScope = requestChatScope;\n // Let template extraContext / system-prompt builders detect the durable\n // background worker so they can skip heavy hang-prone enrichment (e.g. the\n // analytics data-dictionary read) that otherwise stalls the worker before\n // it claims its run. Set early — before the system-prompt build runs.\n requestRunCtx.isBackgroundWorker = isBackgroundWorker;\n }\n const requestMode: AgentExecutionMode =\n body.mode === \"plan\" ? \"plan\" : \"act\";\n const hasMessageText =\n typeof message === \"string\" && message.trim().length > 0;\n const hasAttachments = Array.isArray(attachments) && attachments.length > 0;\n if (!hasMessageText && !hasAttachments) {\n setResponseStatus(event, 400);\n return { error: \"message is required\" };\n }\n let requestMessage = hasMessageText ? message : \"Use the attached context.\";\n let requestAttachments = Array.isArray(attachments) ? attachments : [];\n let requestDisplayMessage = displayMessage;\n\n // Resolve owner first so we can look up a per-owner API key. Users\n // who bring their own key use their key for this request (durable\n // across serverless cold starts via the settings table).\n const ownerEmail = await resolveAgentOwnerEmail(options, event);\n const preparedRequest = await options.prepareRequest?.({\n event,\n ownerEmail,\n message: requestMessage,\n displayMessage: requestDisplayMessage,\n attachments: requestAttachments,\n references,\n threadId,\n internalContinuation: Boolean(internalContinuation),\n mode: requestMode,\n });\n if (preparedRequest) {\n if (\n typeof preparedRequest.message === \"string\" &&\n preparedRequest.message.trim().length > 0\n ) {\n requestMessage = preparedRequest.message;\n }\n if (typeof preparedRequest.displayMessage === \"string\") {\n requestDisplayMessage = preparedRequest.displayMessage;\n }\n if (Array.isArray(preparedRequest.attachments)) {\n requestAttachments = preparedRequest.attachments;\n }\n }\n // DIAGNOSTIC-ONLY: owner/request context prep (resolveAgentOwnerEmail +\n // prepareRequest) finished. A worker stuck before this points at the\n // owner/request-context awaits.\n workerStep(\"db_request_ctx\");\n\n // DIAGNOSTIC-ONLY: bracket attachment upload + text-attachment persistence.\n workerStep(\"attach_start\");\n // Pre-upload chat attachments (images AND files/PDFs) through the framework\n // file-upload provider (Builder.io by default). The model still sees the\n // base64 multimodal content for the current turn; each uploaded attachment\n // also gets a hosted `url` injected so the agent can embed it in slides,\n // docs, or outbound messages, and callers can persist a URL reference\n // instead of the raw base64.\n //\n // When no provider is configured, leave attachments untouched and inject a\n // hint recommending Builder.io connect — the model can still see images via\n // base64, and files via their data URL / text, but has no hosted URL.\n if (\n hasAttachments &&\n requestAttachments.some(\n (a) => a.type === \"image\" || a.type === \"file\" || a.type === \"document\",\n )\n ) {\n try {\n const preUpload = await preUploadAttachments({\n attachments: requestAttachments,\n ownerEmail,\n includeFiles: true,\n });\n if (preUpload.injectedText) {\n requestMessage = requestMessage\n ? `${requestMessage}\\n\\n${preUpload.injectedText}`\n : preUpload.injectedText;\n }\n } catch (err) {\n console.warn(\n \"[agent-native] preUploadAttachments failed:\",\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n\n // Persist text-ish attachments as thread-scoped agent_scratch resources so\n // the model can page through them with the `read-attachment` tool. We do\n // this here — before buildUserContentWithAttachments — so the resource IDs\n // are available when we inject the truncation notice into the text content.\n const textAttachmentResourceMap = new Map<\n number,\n { resourceId: string; path: string; totalChars: number }\n >();\n if (hasAttachments && threadId) {\n try {\n const { persistTextAttachmentsAsResources } =\n await import(\"../server/attachment-actions.js\");\n const stored = await persistTextAttachmentsAsResources({\n attachments: requestAttachments,\n threadId,\n ownerEmail,\n });\n for (const [k, v] of stored) {\n textAttachmentResourceMap.set(k, v);\n }\n } catch (err) {\n console.warn(\n \"[agent-native] persistTextAttachmentsAsResources failed:\",\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n // DIAGNOSTIC-ONLY: attachment upload + persistence finished.\n workerStep(\"attach_done\");\n\n // When a per-request engine override is specified, resolve the API key\n // for that provider instead of the global active engine's provider.\n // DIAGNOSTIC-ONLY: bracket per-owner API-key resolution (settings/app_secrets reads).\n workerStep(\"apikey_start\");\n let userApiKey: string | undefined;\n if (requestEngine) {\n const provider = engineToProvider(requestEngine);\n userApiKey = await getOwnerApiKey(provider, ownerEmail);\n const envVar = PROVIDER_TO_ENV[provider];\n if (\n !userApiKey &&\n envVar &&\n canUseDeployCredentialFallbackForRequest(envVar)\n ) {\n // Read-only env fallback for the requested provider.\n userApiKey = envVar ? readDeployCredentialEnv(envVar) : undefined;\n }\n } else {\n userApiKey = await getOwnerActiveApiKey(ownerEmail);\n }\n // DIAGNOSTIC-ONLY: API-key resolution finished.\n workerStep(\"apikey_done\");\n\n // `options.apiKey` is the value the template constructed the plugin with\n // (often wired from a deployment env var). Honor it as host-provided\n // read-only configuration after scoped keys when deploy fallback is safe.\n const hostApiKey = canUseDeployCredentialFallbackForRequest(\n \"ANTHROPIC_API_KEY\",\n )\n ? (options.apiKey ?? readDeployCredentialEnv(\"ANTHROPIC_API_KEY\"))\n : undefined;\n const effectiveApiKey = userApiKey ?? hostApiKey;\n\n // Resolve engine — per-request engine override takes priority\n // DIAGNOSTIC-ONLY: bracket engine resolution (Builder credential / app-default\n // settings reads inside resolveEngine).\n workerStep(\"engine_start\");\n let engine: AgentEngine;\n try {\n engine = await resolveEngine({\n engineOption: requestEngine ?? options.engine,\n apiKey: effectiveApiKey,\n model: configuredModel,\n appId: options.appId,\n });\n } catch {\n engine = await resolveEngine({\n apiKey: effectiveApiKey,\n appId: options.appId,\n });\n }\n // DIAGNOSTIC-ONLY: engine resolution finished.\n workerStep(\"engine_done\");\n\n // Honor the model the user picked in the settings UI (written via\n // `manage-agent-engine` action=\"set\"), but only when the caller hasn't overridden it for\n // this request or at plugin construction time. Read per-request so a\n // dropdown change in the UI takes effect without a server restart. Skip\n // the DB read entirely when a higher-precedence value is set.\n // DIAGNOSTIC-ONLY: bracket stored-model resolution (getStoredModelForEngine\n // settings read).\n workerStep(\"model_start\");\n const modelCandidate =\n requestModel ??\n configuredModel ??\n (await getStoredModelForEngine(engine, { appId: options.appId })) ??\n engine.defaultModel;\n // DIAGNOSTIC-ONLY: stored-model resolution finished.\n workerStep(\"model_done\");\n const model = normalizeModelForEngine(engine, modelCandidate);\n const reasoningEffort = normalizeReasoningEffortForModel(\n model,\n isReasoningEffort(requestEffort)\n ? requestEffort\n : options.reasoningEffort,\n );\n\n options.onEngineResolved?.(engine, model);\n\n // One-line per-turn resolution log so it's obvious in dev which engine\n // is actually handling the request. `requestEngine` is what the client\n // sent from the model picker; `engine.name` is what resolveEngine picked.\n // Divergence between them is the usual cause of \"status says builder but\n // no [builder-engine] log lines appear\" confusion.\n console.log(\n `[agent-chat] resolved engine=${engine.name} model=${model} requestEngine=${requestEngine ?? \"(none)\"}`,\n );\n\n if (\n !(await isResolvedEngineUsableForRequest(engine, {\n apiKey: effectiveApiKey,\n }))\n ) {\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n setResponseHeader(event, \"Connection\", \"keep-alive\");\n const encoder = new TextEncoder();\n return new ReadableStream({\n start(controller) {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({\n type: \"error\",\n error: LLM_MISSING_CREDENTIALS_MESSAGE,\n errorCode: LLM_MISSING_CREDENTIALS_ERROR_CODE,\n })}\\n\\n`,\n ),\n );\n controller.close();\n },\n });\n }\n\n setupMark(\"prepDone\");\n // DIAGNOSTIC-ONLY: engine/model/api-key resolution finished. A worker that\n // reached db_request_ctx but not env_config hung in attachment upload or\n // engine/model resolution.\n workerStep(\"env_config\");\n // Run all independent pre-send steps in parallel. Each of these hits\n // the DB or invokes an action; running them sequentially was the\n // single biggest contributor to pre-LLM latency.\n const enrichedMessageThunk = () =>\n enrichMessage(requestMessage, references);\n const loopSettingsThunk = () =>\n readAgentLoopSettings({\n userEmail: ownerEmail ?? getRequestUserEmail() ?? null,\n orgId: getRequestOrgId() ?? null,\n }).catch(() => readAgentLoopSettings({}));\n\n let systemPromptError: any = null;\n const systemPromptThunk = (): Promise<string> =>\n (async (): Promise<string> => {\n const sysPromptStart = Date.now();\n try {\n const built =\n typeof options.systemPrompt === \"function\"\n ? await options.systemPrompt(event)\n : options.systemPrompt;\n return built;\n } catch (error) {\n systemPromptError = error;\n return \"\";\n } finally {\n setupMarks.sysPromptMs = Date.now() - sysPromptStart;\n }\n })();\n\n // Precise current time is volatile (changes every request) and must never\n // live in the cached system-prompt prefix — see buildRuntimeContextPrompt\n // in runtime-context.ts. It is injected here, per-turn, into the user\n // message instead, following the same pattern as the screen/url/selection\n // context below. This keeps \"what time is it\" answerable while leaving\n // the system prompt's runtime-context block stable at day granularity.\n const timeContextThunk = (): Promise<string> =>\n (async (): Promise<string> => {\n try {\n const tzRaw = getHeader(event, \"x-user-timezone\");\n const timezone =\n typeof tzRaw === \"string\" &&\n tzRaw.trim().length > 0 &&\n tzRaw.trim().length < 64\n ? tzRaw.trim()\n : undefined;\n return buildCurrentTimeUserContext({ timezone });\n } catch {\n return buildCurrentTimeUserContext();\n }\n })();\n\n const screenContextThunk = (): Promise<string> =>\n (async (): Promise<string> => {\n const screenStart = Date.now();\n try {\n const viewScreenAction = resolvedActions[\"view-screen\"];\n if (viewScreenAction) {\n const result = await viewScreenAction.run(\n {},\n {\n userEmail: getRequestUserEmail(),\n orgId: getRequestOrgId() ?? null,\n caller: \"tool\",\n },\n );\n if (result && result !== \"(no output)\") {\n const screenText =\n typeof result === \"string\"\n ? result\n : JSON.stringify(result, null, 2);\n return `\\n\\n<current-screen>\\n${capScreenContext(screenText)}\\n</current-screen>`;\n }\n } else {\n const navigation = await readAppStateForBrowserTab(\n \"navigation\",\n requestBrowserTabId,\n );\n if (navigation) {\n return `\\n\\n<current-screen>\\n${capScreenContext(JSON.stringify(navigation, null, 2))}\\n</current-screen>`;\n }\n }\n } catch {\n // DB not ready or no navigation state — skip silently\n } finally {\n setupMarks.screenMs = Date.now() - screenStart;\n }\n return \"\";\n })();\n\n const urlContextThunk = (): Promise<string> =>\n (async (): Promise<string> => {\n try {\n const url = (await readAppStateForBrowserTab(\n \"__url__\",\n requestBrowserTabId,\n )) as {\n pathname?: string;\n search?: string;\n hash?: string;\n searchParams?: Record<string, string>;\n } | null;\n if (url && (url.pathname || url.search || url.hash)) {\n const lines: string[] = [];\n if (url.pathname) lines.push(`pathname: ${url.pathname}`);\n const extensionId = url.pathname\n ? extensionIdFromPathname(url.pathname)\n : null;\n if (extensionId) lines.push(`extensionId: ${extensionId}`);\n if (url.search) lines.push(`search: ${url.search}`);\n if (url.hash) lines.push(`hash: ${url.hash}`);\n if (url.searchParams && Object.keys(url.searchParams).length > 0) {\n lines.push(\"searchParams:\");\n for (const [k, v] of Object.entries(url.searchParams)) {\n lines.push(` ${k}: ${v}`);\n }\n }\n return `\\n\\n<current-url>\\n${lines.join(\"\\n\")}\\n</current-url>`;\n }\n } catch {\n // DB not ready — skip silently\n }\n return \"\";\n })();\n\n // Selection context: written by the client when the user presses Cmd+I\n // with text selected on the page. Treat anything older than 5 minutes\n // as stale and ignore it.\n const SELECTION_TTL_MS = 5 * 60 * 1000;\n const selectionContextThunk = (): Promise<string> =>\n (async (): Promise<string> => {\n try {\n const sel = (await readAppState(\"pending-selection-context\")) as {\n text?: string;\n capturedAt?: number;\n } | null;\n if (!sel?.text) return \"\";\n const capturedAt =\n typeof sel.capturedAt === \"number\" ? sel.capturedAt : 0;\n if (Date.now() - capturedAt > SELECTION_TTL_MS) return \"\";\n return (\n `\\n\\nThe user has selected the following text and pressed Cmd+I to focus the agent. ` +\n `Treat this as the immediate context to act on:\\n` +\n `<selection>\\n${capSelectionContext(sel.text)}\\n</selection>`\n );\n } catch {\n // DB not ready — skip silently\n }\n return \"\";\n })();\n\n // On the first message of a conversation, inject workspace inventory\n // so the agent knows what files, skills, jobs, and custom agents exist.\n // Templates can opt out via `skipFilesContext: true` when the inventory\n // is unrelated to the app's job (e.g. a voice-first macro tracker).\n const filesContextThunk = (): Promise<string> =>\n (async (): Promise<string> => {\n let filesContext = \"\";\n if (options.skipFilesContext) return filesContext;\n if (history.length === 0) {\n try {\n const {\n resourceListAccessible,\n SHARED_OWNER,\n WORKSPACE_OWNER,\n resourceGet,\n } = await import(\"../resources/store.js\");\n const {\n getResourceKind,\n parseCustomAgentProfile,\n parseRemoteAgentManifest,\n parseSkillMetadata,\n } = await import(\"../resources/metadata.js\");\n const ownerEmail = getRequestUserEmail();\n const orgId = getRequestOrgId();\n if (!ownerEmail) throw new Error(\"no authenticated user\");\n const allResources = await resourceListAccessible(\n ownerEmail,\n undefined,\n { userEmail: ownerEmail, orgId },\n );\n\n if (allResources.length > 0) {\n const fileLines: string[] = [];\n const skillLines: string[] = [];\n const agentLines: string[] = [];\n const jobLines: string[] = [];\n for (const r of allResources) {\n const scope =\n r.owner === WORKSPACE_OWNER\n ? \"workspace\"\n : r.owner === SHARED_OWNER\n ? \"shared\"\n : \"personal\";\n const kind = getResourceKind(r.path);\n if (kind === \"file\") {\n fileLines.push(` ${r.path} (${scope})`);\n continue;\n }\n\n if (kind === \"job\") {\n jobLines.push(` ${r.path} (${scope})`);\n continue;\n }\n\n if (\n kind === \"skill\" ||\n kind === \"agent\" ||\n kind === \"remote-agent\"\n ) {\n const full = await resourceGet(r.id, {\n userEmail: ownerEmail,\n orgId,\n });\n if (!full) continue;\n if (kind === \"skill\") {\n const skill = parseSkillMetadata(full.content, r.path);\n skillLines.push(\n ` ${skill?.name || r.path} — ${compactInventoryDescription(skill?.description || r.path)} (${scope}, ${r.path})`,\n );\n } else if (kind === \"agent\") {\n const agent = parseCustomAgentProfile(full.content, r.path);\n agentLines.push(\n ` ${agent?.name || r.path} — ${compactInventoryDescription(agent?.description || \"Custom workspace agent\")} (${scope}, ${r.path}${agent?.model ? `, model: ${agent.model}` : \"\"})`,\n );\n } else {\n const agent = parseRemoteAgentManifest(\n full.content,\n r.path,\n );\n agentLines.push(\n ` ${agent?.name || r.path} — ${compactInventoryDescription(agent?.description || \"Connected A2A agent\")} (${scope}, remote via ${r.path})`,\n );\n }\n }\n }\n const blocks: string[] = [];\n if (fileLines.length > 0) {\n const lines = limitInventoryLines(fileLines, \"files\");\n blocks.push(\n `<available-files>\\nFiles in the workspace:\\n${lines.join(\"\\n\")}\\n\\nTo read a resource file's contents, use the resources tool with action \"read\" and the file path.\\n</available-files>`,\n );\n }\n if (skillLines.length > 0) {\n const lines = limitInventoryLines(skillLines, \"skills\");\n blocks.push(\n `<available-skills>\\nSkills in the workspace:\\n${lines.join(\"\\n\")}\\n\\nBefore using a matching workspace skill, read its path with the resources tool using action \"read\"; slash-selected skills are inlined automatically when available.\\n</available-skills>`,\n );\n }\n if (agentLines.length > 0) {\n const lines = limitInventoryLines(agentLines, \"agents\");\n blocks.push(\n `<available-agents>\\nCustom and connected agents in the workspace:\\n${lines.join(\"\\n\")}\\n\\nCustom agents under agents/*.md can be mentioned or used via agent-teams (action: \"spawn\") with the agent parameter.\\n</available-agents>`,\n );\n }\n if (jobLines.length > 0) {\n const lines = limitInventoryLines(jobLines, \"jobs\");\n blocks.push(\n `<available-jobs>\\nScheduled tasks in the workspace:\\n${lines.join(\"\\n\")}\\n</available-jobs>`,\n );\n }\n filesContext =\n blocks.length > 0 ? `\\n\\n${blocks.join(\"\\n\\n\")}` : \"\";\n }\n } catch {\n // Resources not available — skip silently\n }\n }\n return filesContext;\n })();\n\n // Durable bg worker: a pre-send step that HANGS (rather than erroring) would\n // otherwise stall the worker until the foreground inline-recovery grace\n // (~16s) — wasting the entire 15-min durable budget and leaving the run\n // un-claimed (the exact analytics symptom: diag stuck at model_done,\n // preStart≈18s). `presendCap` takes a THUNK (not an eagerly-started promise):\n // the work runs INSIDE the cap, after the timer is armed, so a step whose\n // own synchronous prefix is heavy can still be timed out — an eagerly-created\n // promise would start (and could block the loop) before the cap ever wrapped\n // it. On timeout it records `presend_timeout:<label>` so a stalled phase is\n // attributable, then degrades to the fallback so the worker proceeds to\n // claim. Foreground keeps the un-capped path (thunk invoked immediately), so\n // its behaviour is unchanged. A rejected step (e.g. enrichMessage has no\n // .catch) resolves to the fallback instead of rejecting the whole batch.\n const presendCap = <T>(\n label: string,\n thunk: () => Promise<T>,\n fallback: T,\n ms: number,\n ): Promise<T> => {\n if (!isBackgroundWorker) return thunk();\n return new Promise<T>((resolve) => {\n const timer = setTimeout(() => {\n workerStep(`presend_timeout:${label}`);\n resolve(fallback);\n }, ms);\n // Defer invocation one microtask so every sibling cap arms its timer\n // before any thunk's synchronous prefix runs.\n void Promise.resolve()\n .then(thunk)\n .then(\n (v) => {\n clearTimeout(timer);\n resolve(v);\n },\n () => {\n clearTimeout(timer);\n resolve(fallback);\n },\n );\n });\n };\n const fallbackLoopSettings: AgentLoopSettings = {\n maxIterations: getDefaultMaxIterations(),\n defaultMaxIterations: getDefaultMaxIterations(),\n minMaxIterations: MIN_AGENT_MAX_ITERATIONS,\n maxMaxIterations: MAX_AGENT_MAX_ITERATIONS,\n scope: \"default\",\n source: \"default\",\n };\n const [\n systemPrompt,\n timeBlock,\n screenBlock,\n urlBlock,\n selectionBlock,\n filesContext,\n loopSettings,\n enrichedMessage,\n ] = await Promise.all([\n presendCap(\"systemPrompt\", systemPromptThunk, \"\", 13000),\n presendCap(\"time\", timeContextThunk, \"\", 9000),\n presendCap(\"screen\", screenContextThunk, \"\", 9000),\n presendCap(\"url\", urlContextThunk, \"\", 9000),\n presendCap(\"selection\", selectionContextThunk, \"\", 9000),\n presendCap(\"files\", filesContextThunk, \"\", 12000),\n presendCap(\"loopSettings\", loopSettingsThunk, fallbackLoopSettings, 9000),\n presendCap(\"enrichedMessage\", enrichedMessageThunk, requestMessage, 9000),\n ]);\n setupMark(\"ctxAll\");\n // DIAGNOSTIC-ONLY: all parallel context gathering (system prompt, screen,\n // files, loop settings, enriched message) resolved.\n workerStep(\"context_all\");\n\n if (systemPromptError) {\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n const encoder = new TextEncoder();\n const err = systemPromptError;\n return new ReadableStream({\n start(controller) {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ type: \"error\", error: `Failed to load system prompt: ${err?.message ?? String(err)}` })}\\n\\n`,\n ),\n );\n controller.close();\n },\n });\n }\n const screenContext = timeBlock + screenBlock + urlBlock + selectionBlock;\n const requestActions =\n requestMode === \"plan\"\n ? createPlanModeActionRegistry(resolvedActions)\n : resolvedActions;\n const availableRequestTools = getEngineTools(requestActions);\n const requestTools = filterInitialEngineTools(\n availableRequestTools,\n options.initialToolNames,\n );\n setupMark(\"actions\");\n // DIAGNOSTIC-ONLY: action/tool resolution + engine-tool filtering finished.\n workerStep(\"action_tool_setup\");\n const requestSystemPrompt =\n requestMode === \"plan\"\n ? `${systemPrompt}\\n\\n${PLAN_MODE_SYSTEM_PROMPT}`\n : systemPrompt;\n\n // Pre-compute agent references for A2A resolution inside the run\n const agentRefs = references.filter((r) => r.type === \"agent\");\n const customAgentRefs = references.filter((r) => r.type === \"custom-agent\");\n const planModeAgentNote =\n requestMode === \"plan\" && agentRefs.length > 0\n ? \"\\n\\n<plan-mode-note>Connected external agent mentions were not called because Plan mode is read-only. Mention that they can be called after the user switches to Act mode if the plan needs them.</plan-mode-note>\"\n : \"\";\n\n const userContent = buildUserContentWithAttachments({\n text: enrichedMessage + screenContext + filesContext + planModeAgentNote,\n attachments: requestAttachments,\n });\n\n const historyMessages =\n structuredHistoryToEngineMessages(structuredHistory) ??\n history\n .filter((m) => m.content.trim())\n .map(\n (m): EngineMessage => ({\n role: m.role as \"user\" | \"assistant\",\n content: [{ type: \"text\" as const, text: m.content }],\n }),\n );\n\n const messages: EngineMessage[] = [\n ...historyMessages,\n { role: \"user\" as const, content: userContent },\n ];\n\n // Atomically claim the run slot for this thread. The claim checks SQL for\n // a live (non-stale) running row so two near-simultaneous POSTs on\n // different serverless isolates both see the correct state — a plain\n // read-then-act check races on multi-isolate deployments because both\n // reads see no running row before either insert commits.\n //\n // The background worker SKIPS this: the foreground POST already claimed the\n // slot and inserted the run row before dispatching, so re-claiming here\n // would falsely 409 against the row the foreground holds.\n if (threadId && !isBackgroundWorker) {\n const slot = await tryClaimRunSlot(threadId);\n if (!slot.claimed) {\n setResponseStatus(event, 409);\n return {\n error: \"Run already in progress for this thread\",\n activeRunId: slot.activeRunId,\n };\n }\n }\n\n // Start agent loop in background via run-manager. The background worker\n // reuses the runId carried in the marker (signed into the dispatch token):\n // - First background chunk (count 0): the foreground generated + INSERTED\n // this runId, so the event stream the client is already subscribed to is\n // the one we write to.\n // - Chained continuation chunk (count > 0): the prior chunk minted a FRESH\n // runId for this one (a reused runId would restart `startRun`'s in-memory\n // seq log at 0 and collide with the prior chunk's persisted seqs, which\n // insertRunEvent's ON CONFLICT would drop — making the continuation\n // invisible). A fresh runId on the SAME thread + SAME turnId folds onto\n // one assistant message and is surfaced by the existing\n // `/runs/active?threadId` reconnect path. The continuation worker inserts\n // its own background row below (the foreground only inserted chunk-0's).\n const isChainedBackgroundContinuation =\n isBackgroundWorker && backgroundContinuationCount > 0;\n const runId = backgroundRunMarker?.runId ?? generateRunId();\n const effectiveThreadId = threadId ?? runId;\n const effectiveTurnId =\n typeof backgroundRunMarker?.turnId === \"string\" &&\n backgroundRunMarker.turnId.trim()\n ? backgroundRunMarker.turnId.trim()\n : typeof requestTurnId === \"string\" && requestTurnId.trim()\n ? requestTurnId.trim()\n : runId;\n const messageToPersist =\n typeof requestDisplayMessage === \"string\" &&\n requestDisplayMessage.trim().length > 0\n ? requestDisplayMessage\n : requestMessage;\n\n // Server-driven background continuation: when the background worker re-fired\n // itself at a soft-timeout boundary (a chained continuation chunk), rebuild\n // the conversation from the persisted thread_data so the next chunk resumes\n // from committed progress instead of restarting from the original user\n // message (which would re-do work — the re-hydration thrash the design doc\n // calls out). Mirrors the agent-teams continuation, which seeds from\n // thread_data + appends a continuation nudge. Falls back to the body-derived\n // `messages` if thread_data is empty/unreadable — a continuation that\n // restarts is worse than one that resumes, but both are correct.\n if (isChainedBackgroundContinuation && effectiveThreadId) {\n try {\n const { getThread } = await import(\"../chat-threads/store.js\");\n const { threadDataToEngineMessages } =\n await import(\"./thread-data-builder.js\");\n const priorThreadData = (await getThread(effectiveThreadId))\n ?.threadData;\n const resumed = threadDataToEngineMessages(priorThreadData);\n if (resumed.length > 0) {\n const actionPreparationTool =\n typeof backgroundRunMarker?.actionPreparationTool === \"string\" &&\n backgroundRunMarker.actionPreparationTool.trim()\n ? backgroundRunMarker.actionPreparationTool.trim()\n : undefined;\n const continuationReason = isAgentLoopContinuationReason(\n backgroundRunMarker?.continuationReason,\n )\n ? backgroundRunMarker.continuationReason\n : \"run_timeout\";\n appendAgentLoopContinuation(resumed, continuationReason, {\n ...(actionPreparationTool ? { actionPreparationTool } : {}),\n });\n messages.length = 0;\n messages.push(...resumed);\n }\n } catch {\n // Keep the body-derived messages — never drop the run.\n }\n }\n setupMark(\"depsThread\");\n // DIAGNOSTIC-ONLY: owner/thread resolution + runId/effectiveThreadId +\n // chained-continuation thread fetch finished.\n workerStep(\"owner_thread\");\n\n // Persist the user's turn exactly once. The foreground POST does this\n // before dispatching; the background worker must NOT repeat it (it re-enters\n // with the same body, which would double-persist the user message).\n if (options.onRunPrepared && !internalContinuation && !isBackgroundWorker) {\n await options.onRunPrepared({\n runId,\n threadId,\n message: messageToPersist,\n attachments: requestAttachments,\n });\n }\n\n // ─── Durable-background dispatch decision ──────────────────────────────\n // Flag active (hosted + A2A_SECRET + AGENT_CHAT_DURABLE_BACKGROUND) and we\n // are the FOREGROUND POST: insert the run row (marked background), fire an\n // HMAC-signed self-dispatch into the Netlify background function (15-min\n // budget), and return the SSE subscription immediately. The client streams\n // the same events via the cross-isolate SQL-poll path with no client\n // change. With the flag OFF this whole branch is skipped and the inline\n // `startRun` path below runs exactly as before (byte-for-byte).\n if (dispatchToBackground) {\n let backgroundRowInserted = false;\n try {\n // Insert the run row up front so /runs/active sees it immediately and\n // the slot stays held while the background function cold-starts. Mark\n // it background-dispatched so the stale reaper uses the wider window.\n // The full request body is persisted ON the row (dispatch_payload) so\n // the self-POST below can carry only the tiny marker — Netlify caps\n // background-function request bodies at 256KB, and a large chat\n // history (inline attachments especially) silently exceeded that.\n await insertRun(runId, effectiveThreadId, effectiveTurnId, {\n dispatchMode: \"background\",\n dispatchPayload: JSON.stringify(body),\n });\n backgroundRowInserted = true;\n } catch (err) {\n // A duplicate-PK collision means the row already exists (ret­ried POST);\n // any other failure means we can't safely hand off — fall back to the\n // inline path rather than dropping the turn.\n console.error(\n \"[agent-chat] background insertRun failed; falling back to inline:\",\n err instanceof Error ? err.message : err,\n );\n }\n\n let dispatched = false;\n const backgroundDispatchPath = resolveAgentChatProcessRunDispatchPath();\n const expectsNetlifyBackgroundFunction =\n dispatchPathTargetsNetlifyBackgroundFunction(backgroundDispatchPath);\n try {\n await fireInternalDispatch({\n event,\n // On hosted Netlify this resolves to the background function's DEFAULT\n // url (/.netlify/functions/<name>, or per-app <app>-agent-background for\n // workspaces) — the function declares NO custom config.path, so it keeps\n // its default url, and `background: true` makes that url async (202,\n // 15-min budget). The `server` /* catch-all already excludes /.netlify/*\n // so it never shadows it. Off-Netlify this resolves to the framework\n // `_process-run` route and the same in-process catch-all handles it\n // inline. `fireInternalDispatch` strips the app base path for\n // /.netlify/* targets so the request reaches the host-root function url;\n // the Authorization Bearer HMAC is preserved either way.\n path: backgroundDispatchPath,\n taskId: runId,\n // When the row (and its persisted payload) landed, send only the\n // marker — the worker rehydrates the body from dispatch_payload\n // (`payloadRef`), keeping the self-POST far under Netlify's 256KB\n // background-function body cap. If the insert failed we fall back to\n // carrying the full body inline, exactly as before.\n body: backgroundRowInserted\n ? {\n [AGENT_CHAT_BACKGROUND_RUN_FIELD]: {\n runId,\n turnId: effectiveTurnId,\n backgroundFunctionRuntimeExpected:\n expectsNetlifyBackgroundFunction,\n payloadRef: true,\n },\n }\n : {\n ...body,\n // Carry the pre-claimed identity so the worker reuses this run.\n [AGENT_CHAT_BACKGROUND_RUN_FIELD]: {\n runId,\n turnId: effectiveTurnId,\n backgroundFunctionRuntimeExpected:\n expectsNetlifyBackgroundFunction,\n },\n },\n });\n dispatched = true;\n } catch (err) {\n console.error(\n \"[agent-chat] background dispatch failed; falling back to inline:\",\n err instanceof Error ? err.message : err,\n );\n }\n\n // ─── Circuit-breaker: a 202 only ENQUEUES the background invocation ─────\n // It is NOT proof the worker executed. If the generated background-function\n // wrapper fails to import `./main.mjs` or hand off to the Nitro\n // `_process-run` route, the worker never reaches `claimBackgroundRun`: the\n // row sits at `dispatch_mode='background'` until the reaper errors it\n // (\"worker never claimed the run\"). `resolveBackgroundDispatchOutcome`\n // polls briefly for the claim and decides:\n // - \"stream\": a worker claimed the run → subscribe to it.\n // - \"subscribe\": a (delayed) worker already owns it → subscribe, NEVER\n // run a second copy.\n // - \"inline\": dispatch failed OR no worker claimed within grace → we\n // atomically own the run; recover by running it inline so a\n // dead worker degrades to a working synchronous turn.\n const backgroundOutcome = await resolveBackgroundDispatchOutcome({\n dispatched,\n backgroundRowInserted,\n runId,\n graceMs: BACKGROUND_CLAIM_GRACE_MS,\n reaperGraceMs: UNCLAIMED_BACKGROUND_RUN_GRACE_MS,\n pollIntervalMs: BACKGROUND_CLAIM_POLL_MS,\n readClaim: readBackgroundRunClaim,\n claim: claimBackgroundRun,\n });\n\n if (\n backgroundOutcome.action === \"stream\" ||\n backgroundOutcome.action === \"subscribe\"\n ) {\n const stream = subscribeToRun(runId, 0);\n if (stream) {\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n setResponseHeader(event, \"Connection\", \"keep-alive\");\n setResponseHeader(event, \"X-Run-Id\", runId);\n setResponseHeader(event, \"X-Dispatch-Mode\", \"background\");\n return stream;\n }\n // A background worker owns this run but we cannot subscribe — surface an\n // error rather than risk a double-run by falling through to inline.\n const terminalReason =\n backgroundOutcome.action === \"stream\"\n ? \"background_subscribe_failed\"\n : \"background_dispatch_failed\";\n const statusUpdated = await updateRunStatusIfRunning(\n runId,\n \"errored\",\n ).catch(() => false);\n if (statusUpdated) {\n await setRunTerminalReason(runId, terminalReason).catch(() => {});\n }\n setResponseStatus(event, 500);\n return {\n error:\n backgroundOutcome.action === \"stream\"\n ? \"Failed to subscribe to background run\"\n : \"Failed to dispatch background run\",\n };\n }\n\n // backgroundOutcome.action === \"inline\": we atomically own the run (or\n // there was no row to reconcile), so falling through to the inline\n // `startRun` path below cannot double-execute. `startRun` calls `insertRun`\n // again, but its duplicate-PK collision is swallowed, so an existing\n // `background-processing` row is reused — no double row.\n if (backgroundOutcome.reason === \"worker-never-claimed\") {\n // The async 202 landed but no worker claimed within grace. PRESERVE the\n // bg-fn's last-recorded diag_stage (route_entered / auth_failed / ... or\n // \"none\" if it never reached the route) in the recovery detail BEFORE we\n // overwrite diag_stage — otherwise foreground_inline_recovery clobbers\n // the only clue to WHY the worker died (its own logs are unreadable).\n const priorClaim = await readBackgroundRunClaim(runId).catch(\n () => null,\n );\n const priorDiag = priorClaim?.diagStage ?? \"none\";\n console.error(\n \"[agent-chat] background worker did not claim the 202-dispatched run \" +\n `within grace; recovering inline. bgFnPriorDiag=${priorDiag}`,\n runId,\n );\n await recordRunDiagnostic(\n runId,\n RUN_DIAG_STAGE.foregroundInlineRecovery,\n `202 dispatched but no worker claimed within grace; bgFnPriorDiag=${priorDiag}`,\n ).catch(() => {});\n }\n // Fall through to the inline `startRun` path below.\n }\n\n const trackedProgressOwner =\n trackInRunsTray === true && ownerEmail ? ownerEmail : null;\n const trackedProgressRunId = trackedProgressOwner\n ? backgroundChatProgressRunId(effectiveTurnId)\n : null;\n const trackedProgressMetadata = trackedProgressRunId\n ? {\n kind: \"agent-chat-background\",\n threadId: effectiveThreadId,\n surfaceUrl: `agent-native://threads/${encodeURIComponent(effectiveThreadId)}`,\n turnId: effectiveTurnId,\n }\n : null;\n // Foreground self-chain: gated on hosted runtime + A2A_SECRET, with an\n // explicit env opt-out, AND this specific run never having been routed to\n // the durable background worker. A run that WAS dispatched to background\n // (`dispatchToBackground`) already has its recovery owned by the background\n // circuit-breaker / `isBackgroundWorker` chain above — this flag must never\n // double up with that path, only stand in for it on plain foreground turns. A persistent\n // threadId is required: the client discovers the pre-inserted successor\n // via `/runs/active?threadId` and the successor chunk resumes from the\n // thread's persisted thread_data — without a thread there is neither a\n // discovery channel nor durable progress to resume from.\n const foregroundSelfChainEligible =\n !isBackgroundWorker &&\n !dispatchToBackground &&\n typeof threadId === \"string\" &&\n threadId.trim().length > 0 &&\n isAgentChatForegroundSelfChainEnabled();\n const willChainBackgroundContinuation = (run: ActiveRun) =>\n shouldChainBackgroundContinuation({\n isBackgroundWorker,\n run,\n continuationCount: backgroundContinuationCount,\n foregroundSelfChainEligible,\n dispatchedToBackground: dispatchToBackground,\n });\n\n const completeTrackedProgressRun = async (\n run: ActiveRun,\n completionError?: unknown,\n ) => {\n if (!trackedProgressRunId || !trackedProgressOwner) return;\n if (!completionError && willChainBackgroundContinuation(run)) {\n return;\n }\n const terminalStatus =\n run.status === \"aborted\"\n ? \"cancelled\"\n : run.status === \"errored\" || completionError\n ? \"failed\"\n : \"succeeded\";\n const step =\n terminalStatus === \"succeeded\"\n ? \"Agent finished.\"\n : terminalStatus === \"cancelled\"\n ? \"Agent run was cancelled.\"\n : \"Agent stopped with an error.\";\n await completeProgressRun(\n trackedProgressRunId,\n trackedProgressOwner,\n terminalStatus,\n {\n step,\n metadata: {\n ...(trackedProgressMetadata ?? {}),\n runId: run.runId,\n },\n },\n ).catch(() => {});\n };\n\n let lastTrackedProgressUpdateAt = 0;\n const updateTrackedProgressFromEvent = (event: AgentChatEvent) => {\n if (!trackedProgressRunId || !trackedProgressOwner) return;\n const step = progressStepFromAgentChatEvent(event);\n if (!step) return;\n const now = Date.now();\n if (now - lastTrackedProgressUpdateAt < 15_000) return;\n lastTrackedProgressUpdateAt = now;\n void updateRunProgress(trackedProgressRunId, trackedProgressOwner, {\n step,\n metadata: {\n ...(trackedProgressMetadata ?? {}),\n runId,\n },\n }).catch(() => {});\n };\n\n if (trackedProgressRunId && trackedProgressOwner && !internalContinuation) {\n await startProgressRun({\n id: trackedProgressRunId,\n owner: trackedProgressOwner,\n title: messageToPersist,\n step: \"Starting agent.\",\n metadata: trackedProgressMetadata ?? undefined,\n }).catch(() => {});\n }\n\n // The background worker must AWAIT the run to completion before returning,\n // or Netlify freezes/kills the function the instant the handler returns and\n // the detached run dies mid-turn (mirrors the agent-teams processor, which\n // wraps startRun in `await new Promise(resolve => startRun(..., onComplete:\n // () => resolve()))`). We resolve this when the run's onComplete fires.\n let resolveBackgroundRunDone: (() => void) | null = null;\n const backgroundRunDone = isBackgroundWorker\n ? new Promise<void>((resolve) => {\n resolveBackgroundRunDone = resolve;\n })\n : null;\n\n const baseHandleRunComplete =\n options.onRunComplete || trackedProgressRunId\n ? async (run: ActiveRun) => {\n try {\n await options.onRunComplete?.(run, threadId);\n } catch (err) {\n await completeTrackedProgressRun(run, err);\n throw err;\n }\n await completeTrackedProgressRun(run);\n }\n : undefined;\n\n // Wrap so the background worker is unblocked even when there is no app\n // onRunComplete / tracked-progress callback configured. Also installed for\n // a foreground run eligible for self-chain — that path needs this same\n // wrapper to fire the continuation dispatch below.\n const handleRunComplete =\n isBackgroundWorker || foregroundSelfChainEligible || baseHandleRunComplete\n ? async (run: ActiveRun) => {\n try {\n // DIAGNOSTIC: a background worker that completed in an errored\n // state threw inside the loop. Record it (with the last error\n // event's message when available) so the failure cause is\n // readable from the client. Skipped for clean completions and for\n // recoverable soft-timeout boundaries (those chain a continuation\n // below, they did not \"throw\").\n if (\n isBackgroundWorker &&\n run.status === \"errored\" &&\n !willChainBackgroundContinuation(run)\n ) {\n const errEvent = [...run.events]\n .reverse()\n .find((e) => e.event.type === \"error\")?.event as\n | { error?: string; errorCode?: string }\n | undefined;\n await recordRunDiagnostic(\n run.runId,\n RUN_DIAG_STAGE.workerThrew,\n errEvent?.errorCode || errEvent?.error\n ? `${errEvent.errorCode ?? \"\"} ${errEvent.error ?? \"\"}`.trim()\n : \"run ended in errored state\",\n ).catch(() => {});\n }\n // Persist the (partial) assistant turn to thread_data FIRST — the\n // server-driven continuation below rebuilds from it, so it must be\n // committed before we re-fire.\n await baseHandleRunComplete?.(run);\n\n // Server-driven background→background continuation. If this chunk\n // hit its soft-timeout still unfinished (ended at an auto_continue\n // / loop_limit / recoverable boundary), chain the next chunk by\n // re-firing the `_process-run` self-dispatch with mode \"continue\"\n // (carried as internalContinuation + an incremented count),\n // instead of relying on the client to re-POST. Mirrors the\n // agent-teams `fireInternalDispatch({ body: { mode: \"continue\" }})`\n // chain. Bounded by MAX_BACKGROUND_RUN_CONTINUATIONS. Aborted /\n // user-stopped runs do NOT chain.\n // Self-chain server-side for EVERY durable worker, not only the\n // ones inside a `-background` function. Server-driven\n // continuation is the whole point of durable background: the run\n // must survive the client disconnecting (closed tab), so it\n // cannot depend on the browser re-POSTing `auto_continue`. A\n // worker on the regular ~60s function — a Netlify routing miss,\n // or a non-Netlify host (Vercel/Cloudflare/Render/Fly) that\n // never emits a `-background` function — checkpoints at the 40s\n // soft-timeout and self-dispatches the next 40s chunk; a worker\n // in a real `-background` function chains ~13-min chunks. Only\n // the per-chunk BUDGET differs by function type (gated by\n // `runsInBackgroundFunction` at the startRun call below); the\n // continuation itself must stay server-driven on both. (The\n // self-chain is only reachable when the initial dispatch already\n // succeeded — a dispatch fast-fail degrades to the inline\n // foreground fallback, which is not a worker and rides the\n // connected client's auto_continue instead.)\n if (willChainBackgroundContinuation(run)) {\n // Full handoff discipline lives in\n // `chainServerDrivenContinuation` (exported + unit-tested):\n // per-turn SQL run budget, successor row PRE-INSERTED before\n // the dispatch, fully awaited dispatch with retries, loud\n // diag/terminal marking on failure. Never throws.\n await chainServerDrivenContinuation({\n event,\n run,\n effectiveThreadId,\n effectiveTurnId,\n requestBody: body as unknown as Record<string, unknown>,\n backgroundContinuationCount,\n // Re-evaluate the durable gate rather than keying off\n // isBackgroundWorker: a successor chunk of a FOREGROUND\n // self-chain re-enters as a worker too, and must keep\n // chaining via the regular function — the Netlify\n // `-background` function is only emitted into the deploy\n // output when the durable flag is on.\n //\n // `&& !runsInBackgroundFunction`: a worker PROVEN to already\n // be executing inside the real `-background` function must\n // never dispatch back to that same function's own URL — a\n // background function invoking itself by URL from inside a\n // live invocation is a documented Netlify platform\n // limitation (404), unlike the initial foreground→background\n // dispatch or a worker that landed on the regular function\n // (a genuinely different function calling the background\n // one, which works). This only changes the dispatch TARGET\n // for that one proven-in-bg-function case — by this point\n // (with the in-process resumable-error resume above) it is\n // reached only when the chunk genuinely exhausted its\n // budget, so falling back to the regular `_process-run`\n // function (40s clamp) here is the correct, safe target.\n chainViaDurableBackground:\n isAgentChatDurableBackgroundEnabled({\n appOptIn: options.durableBackgroundRuns === true,\n }) && !runsInBackgroundFunction,\n // Only changes the retry BUDGET, never the dispatch target\n // above: a worker proven in a real background function has\n // minutes of remaining wall clock and no connected-client\n // fallback, so it must not be demoted to the foreground's\n // 2-attempt budget just because it was forced onto the\n // regular-function dispatch target. See\n // `resolveContinuationDispatchBudget`.\n workerProvenInBackgroundFunction: runsInBackgroundFunction,\n });\n }\n } finally {\n resolveBackgroundRunDone?.();\n }\n }\n : undefined;\n\n // Background worker: the run was claimed immediately after the authenticated\n // `_process-run` body was parsed, before owner/model/prompt/tool setup. That\n // early claim is what lets the foreground subscribe to the real background\n // worker instead of racing slow setup and falling back to the 40s inline\n // path. This late block is a defensive fallback for older/custom callers\n // that somehow reach here without the early claim.\n if (isBackgroundWorker) {\n if (!backgroundRunClaimedEarly) {\n await recordRunDiagnostic(\n runId,\n RUN_DIAG_STAGE.workerEntered,\n [\n `runsInBackgroundFunction=${runsInBackgroundFunction}`,\n `continuationCount=${backgroundContinuationCount}`,\n backgroundRuntimeDetail,\n ]\n .filter(Boolean)\n .join(\" \"),\n ).catch(() => {});\n if (isChainedBackgroundContinuation) {\n await insertRun(runId, effectiveThreadId, effectiveTurnId, {\n dispatchMode: \"background\",\n }).catch(() => {});\n }\n const won = await claimBackgroundRun(runId);\n if (!won) {\n await recordRunDiagnostic(\n runId,\n RUN_DIAG_STAGE.workerClaimLost,\n ).catch(() => {});\n return { ok: true, skipped: \"already-claimed\" };\n }\n await recordRunDiagnostic(runId, RUN_DIAG_STAGE.workerClaimed).catch(\n () => {},\n );\n await updateRunHeartbeat(runId).catch(() => {});\n }\n }\n\n // DIAGNOSTIC-ONLY: build the pre-startRun setup-timing breakdown now (so the\n // marks reflect the work done BEFORE the loop), but EMIT it from inside\n // startRun's callback below — the run row does not exist until startRun\n // inserts it, so a pre-startRun write would no-op on the inline path.\n setupMark(\"preStart\");\n // DIAGNOSTIC-ONLY: last stage before startRun fires. A worker that reaches\n // prestart but never workerStarted is hanging inside startRun itself.\n workerStep(\"prestart\");\n const setupDetail =\n Object.entries(setupMarks)\n .map(([k, v]) => `${k}=${v}`)\n .join(\" \") +\n ` total=${Date.now() - setupT0}` +\n (backgroundRuntimeDetail ? ` ${backgroundRuntimeDetail}` : \"\");\n\n startRun(\n runId,\n effectiveThreadId,\n async (rawSend, signal) => {\n const send = (event: AgentChatEvent) => {\n rawSend(event);\n updateTrackedProgressFromEvent(event);\n };\n\n send({ type: \"activity\", label: \"Starting agent\" });\n\n // DIAGNOSTIC: the agent loop body actually started running. For a\n // background worker, a run that is claimed but never reaches this stage\n // died between claiming and loop start. The pre-startRun setup-timing\n // breakdown rides along here so it persists now that the run row exists\n // (startRun inserted it), WITHOUT adding a separate DB hop to the\n // run-start path: on the worker it is folded into this same\n // already-awaited worker_started write (one hop, correctly ordered, no\n // clobber); on the inline path there is no later diag stage to overwrite,\n // so it is fire-and-forget to keep run-start non-blocking. Best-effort.\n if (isBackgroundWorker) {\n await recordRunDiagnostic(\n runId,\n RUN_DIAG_STAGE.workerStarted,\n setupDetail,\n ).catch(() => {});\n } else {\n void recordRunDiagnostic(\n runId,\n RUN_DIAG_STAGE.setupTimings,\n setupDetail,\n ).catch(() => {});\n }\n\n // Notify listeners that a run has started (used by agent teams)\n if (options.onRunStart) {\n await options.onRunStart(send, threadId ?? runId);\n }\n\n // Resolve custom workspace agent mentions first.\n if (customAgentRefs.length > 0) {\n const ownerEmail = getRequestUserEmail();\n if (!ownerEmail) throw new Error(\"no authenticated user\");\n const { findAccessibleCustomAgent } =\n await import(\"../resources/agents.js\");\n const customResults = await Promise.allSettled(\n customAgentRefs.map(async (ref) => {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"start\",\n });\n try {\n const profile = await findAccessibleCustomAgent(\n ownerEmail,\n ref.refId || ref.path || ref.name,\n );\n if (!profile) {\n throw new Error(\"Profile not found\");\n }\n\n const profilePrompt =\n `${requestSystemPrompt}\\n\\n<custom-agent-profile name=\"${profile.name}\" path=\"${profile.path}\">\\n` +\n (profile.description ? `${profile.description}\\n\\n` : \"\") +\n `${profile.instructions}\\n</custom-agent-profile>`;\n\n let responseText = \"\";\n const subUsage = await runAgentLoop({\n engine,\n model: profile.model ?? model,\n systemPrompt: profilePrompt,\n tools: requestTools,\n availableTools: availableRequestTools,\n messages: [\n {\n role: \"user\",\n content: [\n { type: \"text\", text: enrichedMessage + screenContext },\n ],\n },\n ],\n actions: requestActions,\n send: (event) => {\n if (event.type === \"text\") {\n responseText += event.text;\n send({\n type: \"agent_call_text\",\n agent: ref.name,\n text: event.text,\n });\n }\n },\n signal,\n reasoningEffort,\n providerOptions: options.providerOptions,\n executionMode: requestMode,\n maxIterations: loopSettings.maxIterations,\n });\n\n // Attribute custom-agent sub-calls under their own label\n // so the Usage panel separates them from the main chat.\n try {\n const ownerEmail = options.resolveOwnerEmail\n ? await options.resolveOwnerEmail(event)\n : getRequestUserEmail();\n if (!ownerEmail) {\n // Skip usage recording for unauthenticated runs.\n return;\n }\n const { recordUsage } = await import(\"../usage/store.js\");\n await recordUsage({\n ownerEmail,\n inputTokens: subUsage.inputTokens,\n outputTokens: subUsage.outputTokens,\n cacheReadTokens: subUsage.cacheReadTokens,\n cacheWriteTokens: subUsage.cacheWriteTokens,\n model: subUsage.model,\n label: `custom-agent:${ref.name}`,\n });\n } catch {}\n\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"done\",\n });\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" type=\"custom-agent\">\\n${responseText}\\n</agent-response>`;\n } catch (err: any) {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"error\",\n });\n const message =\n userFacingLlmCredentialError(err, {\n agentName: ref.name,\n }) ?? `Failed to run ${ref.name}: ${err?.message}`;\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" type=\"custom-agent\" error=\"true\">\\n${message}\\n</agent-response>`;\n }\n }),\n );\n\n const customResponses = customResults\n .filter(\n (result): result is PromiseFulfilledResult<string> =>\n result.status === \"fulfilled\",\n )\n .map((result) => result.value);\n\n if (customResponses.length > 0) {\n const agentContext =\n \"Responses from custom workspace agents:\\n\\n\" +\n customResponses.join(\"\\n\\n\");\n const lastMsg = messages[messages.length - 1];\n if (lastMsg?.role === \"user\" && Array.isArray(lastMsg.content)) {\n const textPart = lastMsg.content.find(\n (p): p is import(\"./engine/types.js\").EngineTextPart =>\n p.type === \"text\",\n );\n if (textPart) {\n textPart.text = agentContext + \"\\n\\n\" + textPart.text;\n }\n }\n }\n }\n\n // Resolve connected agent @-mentions via A2A calls.\n if (agentRefs.length > 0 && requestMode !== \"plan\") {\n const [{ A2AClient, callAgent }, { resolveA2ACallerAuth }] =\n await Promise.all([\n import(\"../a2a/client.js\"),\n import(\"../a2a/caller-auth.js\"),\n ]);\n const results = await Promise.allSettled(\n agentRefs.map(async (ref) => {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"start\",\n });\n try {\n const callerAuth = await resolveA2ACallerAuth({\n includeGoogleToken: true,\n });\n const a2aClient = new A2AClient(ref.path, callerAuth.apiKey, {\n ...(callerAuth.apiKeyFallbacks\n ? { fallbackApiKeys: callerAuth.apiKeyFallbacks }\n : {}),\n });\n const a2aMetadata = callerAuth.metadata;\n\n let responseText = \"\";\n let lastSentLength = 0;\n\n try {\n for await (const task of a2aClient.stream(\n {\n role: \"user\",\n parts: [\n {\n type: \"text\",\n text: enrichedMessage + screenContext,\n },\n ],\n },\n Object.keys(a2aMetadata).length > 0\n ? { metadata: a2aMetadata }\n : undefined,\n )) {\n const newText =\n task.status?.message?.parts\n ?.filter(\n (p): p is { type: \"text\"; text: string } =>\n p.type === \"text\",\n )\n ?.map((p) => p.text)\n ?.join(\"\") ?? \"\";\n\n if (newText.length > lastSentLength) {\n send({\n type: \"agent_call_text\",\n agent: ref.name,\n text: newText.slice(lastSentLength),\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n }\n } catch {\n if (!responseText) {\n responseText = await callAgent(\n ref.path,\n enrichedMessage + screenContext,\n {\n apiKey: callerAuth.apiKey,\n userEmail: callerAuth.userEmail,\n orgDomain: callerAuth.orgDomain,\n orgSecret: callerAuth.orgSecret,\n },\n );\n }\n }\n responseText =\n userFacingLlmCredentialError(responseText, {\n agentName: ref.name,\n }) ?? responseText;\n\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"done\",\n });\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\">\\n${responseText}\\n</agent-response>`;\n } catch (err: any) {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"error\",\n });\n const message =\n userFacingLlmCredentialError(err, {\n agentName: ref.name,\n }) ?? `Failed to reach ${ref.name}: ${err?.message}`;\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" error=\"true\">\\n${message}\\n</agent-response>`;\n }\n }),\n );\n\n const agentResponses_local: string[] = [];\n for (const result of results) {\n if (result.status === \"fulfilled\") {\n agentResponses_local.push(result.value);\n }\n }\n\n if (agentResponses_local.length > 0) {\n const agentContext =\n \"Responses from other agents:\\n\\n\" +\n agentResponses_local.join(\"\\n\\n\");\n const lastMsg = messages[messages.length - 1];\n if (lastMsg?.role === \"user\" && Array.isArray(lastMsg.content)) {\n const textPart = lastMsg.content.find(\n (p): p is import(\"./engine/types.js\").EngineTextPart =>\n p.type === \"text\",\n );\n if (textPart) {\n textPart.text = agentContext + \"\\n\\n\" + textPart.text;\n }\n }\n }\n }\n\n // Apply experiment variant overrides (A/B testing)\n let effectiveModel = model;\n try {\n const { resolveActiveExperimentConfig } =\n await import(\"../observability/experiments.js\");\n if (!ownerEmail) {\n // Without an authenticated owner we can't resolve user-scoped experiments.\n throw new Error(\"no authenticated user\");\n }\n const expConfig = await resolveActiveExperimentConfig(ownerEmail);\n if (expConfig) {\n if (typeof expConfig.configs.model === \"string\") {\n effectiveModel = expConfig.configs.model;\n }\n }\n } catch {\n // Experiments module unavailable — use default model\n }\n\n // TODO(processor-seam): thread `processors` from ProductionAgentOptions\n // through to runAgentLoop here once the handler exposes a way to\n // configure them (e.g. a `processors` field on ProductionAgentOptions\n // or a per-request resolver). The loop-level seam (runAgentLoop's\n // `processors` opt + ProcessorChain/TripWire) is the deliverable and is\n // already callable directly by sub-agents, A2A, MCP, and tests; this is\n // only the HTTP-handler convenience plumbing.\n const agentLoopOpts = {\n engine,\n model: effectiveModel,\n systemPrompt: requestSystemPrompt,\n tools: requestTools,\n availableTools: availableRequestTools,\n messages,\n actions: requestActions,\n send,\n signal,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n attachments: requestAttachments,\n reasoningEffort,\n // The interactive chat turn needs real completion headroom — the\n // flat per-engine defaults (4096-8192) exist for internal/eval\n // callers and are far below what a hard, long-context turn needs\n // once extended thinking is in play. See output-tokens.ts.\n maxOutputTokens: resolveMainChatMaxOutputTokens(effectiveModel),\n providerOptions: options.providerOptions,\n executionMode: requestMode,\n maxIterations: loopSettings.maxIterations,\n finalResponseGuard: options.finalResponseGuard,\n ...(options.toolLimits ? { toolLimits: options.toolLimits } : {}),\n ...(threadId\n ? { threadId: effectiveThreadId, turnId: effectiveTurnId }\n : {}),\n // Human-in-the-loop approval grants for this turn (sanitized — the\n // request is untrusted; accept only a bounded list of string keys).\n ...(Array.isArray(body.approvedToolCalls) &&\n body.approvedToolCalls.length\n ? {\n approvedToolCalls: body.approvedToolCalls\n .filter((k: unknown): k is string => typeof k === \"string\")\n .slice(0, 200),\n }\n : {}),\n // A worker PROVEN to be running inside the real 15-min Netlify\n // `-background` function (`runsInBackgroundFunction`) has minutes of\n // budget left on THIS invocation. Let it catch a recoverable\n // transport/gateway error (isResumableEngineError) and resume the\n // agent loop in-process instead of unwinding out to `startRun`'s\n // outer catch, which would otherwise hand off to\n // `chainServerDrivenContinuation` — and for a worker already inside\n // the background function, that hand-off is a same-function\n // self-dispatch that 404s on Netlify (a background function cannot\n // invoke its own public URL from inside a live invocation). A\n // foreground turn or a worker that landed on the regular ~60s\n // function (runsInBackgroundFunction false) must NOT set this — it\n // keeps depending on the existing cross-invocation recovery\n // (foreground self-chain / client auto_continue re-POST), unchanged.\n ...(runsInBackgroundFunction\n ? {\n resumeResumableErrorsInProcess: true,\n maxContinuations: MAX_BACKGROUND_RUN_CONTINUATIONS,\n }\n : {}),\n };\n\n send({ type: \"activity\", label: \"Contacting model\" });\n\n // loopUsage is always assigned — either via instrumentAgentLoop or\n // runAgentLoop before use below. The definite-assignment guard is\n // conservative because the try/catch makes the control flow non-obvious.\n let loopUsage: AgentLoopUsage = undefined!;\n let instrumented = false;\n try {\n const { getObservabilityConfig, instrumentAgentLoop } =\n await import(\"../observability/traces.js\");\n const obsConfig = await getObservabilityConfig();\n if (obsConfig.enabled) {\n instrumented = true;\n loopUsage = await instrumentAgentLoop({\n runAgentLoop: runAgentLoopWithMainChatInternalContinuations,\n loopOpts: agentLoopOpts,\n runId,\n threadId: threadId ?? null,\n userId: ownerEmail,\n config: obsConfig,\n classifyError: () => {\n if (\n agentLoopOpts.signal.aborted &&\n agentLoopOpts.signal.reason === \"run_timeout\"\n ) {\n return {\n status: \"success\",\n errorMessage: null,\n metadata: {\n terminalReason: \"run_timeout\",\n recoverableContinuation: true,\n },\n };\n }\n return null;\n },\n });\n }\n } catch (err) {\n // If instrumentation setup failed, fall through to uninstrumented.\n // If the agent loop itself failed (via instrumentAgentLoop), re-throw.\n if (instrumented) throw err;\n }\n if (!instrumented) {\n loopUsage =\n await runAgentLoopWithMainChatInternalContinuations(agentLoopOpts);\n }\n\n // Record token usage for cost monitoring so the Usage panel in\n // settings works in every mode, including local dev.\n try {\n const ownerEmail = options.resolveOwnerEmail\n ? await options.resolveOwnerEmail(event)\n : getRequestUserEmail();\n if (\n ownerEmail &&\n (loopUsage.inputTokens > 0 ||\n loopUsage.outputTokens > 0 ||\n loopUsage.cacheReadTokens > 0 ||\n loopUsage.cacheWriteTokens > 0)\n ) {\n const { recordUsage } = await import(\"../usage/store.js\");\n await recordUsage({\n ownerEmail,\n inputTokens: loopUsage.inputTokens,\n outputTokens: loopUsage.outputTokens,\n cacheReadTokens: loopUsage.cacheReadTokens,\n cacheWriteTokens: loopUsage.cacheWriteTokens,\n model: loopUsage.model,\n label: body.usageLabel || \"chat\",\n });\n }\n } catch {\n // Usage recording failed — don't break the run\n }\n },\n handleRunComplete,\n {\n softTimeoutMs: options.runSoftTimeoutMs,\n useHostedSoftTimeoutDefault: true,\n // Lift the soft-timeout clamp to ~13min ONLY when this run is actually\n // executing inside a real Netlify `-background` function (15-min budget,\n // no ~60s wall). Being the `_process-run` worker (`isBackgroundWorker`)\n // is NOT sufficient: if the `-background` function wasn't emitted, or\n // Netlify routed the self-POST to the synchronous function, the worker\n // landed on the regular ~60s `server` function — there it MUST keep the\n // 40s clamp and checkpoint before the wall, or it overshoots the 60s\n // hard kill and re-dispatches in a loop. `runsInBackgroundFunction`\n // gates the 13-min budget on the proven runtime, not merely on \"I'm the\n // worker.\" Foreground runs never set this, so their 40s clamp is\n // unchanged.\n backgroundFunction: runsInBackgroundFunction,\n noProgressTimeoutMs: options.runNoProgressTimeoutMs,\n // Fold continuation runs of one logical turn onto a single durable\n // assistant message. Falls back to the runId (turn == run) when the\n // client doesn't supply a turnId.\n turnId: effectiveTurnId,\n dispatchMode: foregroundSelfChainEligible\n ? \"foreground-self-chain\"\n : \"foreground\",\n },\n );\n\n // Background worker: await the run to completion so Netlify keeps the\n // background function alive for the whole turn (the client is streaming the\n // same events via the foreground POST's cross-isolate SQL subscription).\n // The onComplete wrapper above resolves `backgroundRunDone`.\n if (isBackgroundWorker) {\n if (backgroundRunDone) await backgroundRunDone;\n return { ok: true, runId };\n }\n\n // Subscribe to the run and stream events to the client\n const stream = subscribeToRun(runId, 0);\n if (!stream) {\n setResponseStatus(event, 500);\n return { error: \"Failed to start agent run\" };\n }\n\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n setResponseHeader(event, \"Connection\", \"keep-alive\");\n setResponseHeader(event, \"X-Run-Id\", runId);\n setResponseHeader(\n event,\n \"X-Dispatch-Mode\",\n foregroundSelfChainEligible ? \"foreground-self-chain\" : \"foreground\",\n );\n\n return stream;\n });\n}\n\nexport {\n getActiveRunForThread,\n getActiveRunForThreadAsync,\n getRun,\n abortRun,\n subscribeToRun,\n};\n"]}