@agent-native/core 0.14.0 → 0.14.1

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":"builder-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EACV,WAAW,EACX,kBAAkB,EAInB,MAAM,YAAY,CAAC;AAqBpB,eAAO,MAAM,oBAAoB,EAAE,kBAUlC,CAAC;AAEF,eAAO,MAAM,wBAAwB,8RAAuC,CAAC;AAM7E,eAAO,MAAM,qBAAqB,qBAAoC,CAAC;AA2iBvE,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACpC,WAAW,CAEb"}
1
+ {"version":3,"file":"builder-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EACV,WAAW,EACX,kBAAkB,EAInB,MAAM,YAAY,CAAC;AAqBpB,eAAO,MAAM,oBAAoB,EAAE,kBAUlC,CAAC;AAEF,eAAO,MAAM,wBAAwB,8RAAuC,CAAC;AAU7E,eAAO,MAAM,qBAAqB,qBAAoC,CAAC;AA2iBvE,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACpC,WAAW,CAEb"}
@@ -30,7 +30,11 @@ export const BUILDER_CAPABILITIES = {
30
30
  parallelToolCalls: true,
31
31
  };
32
32
  export const BUILDER_SUPPORTED_MODELS = BUILDER_MODEL_CONFIG.supportedModels;
33
- const DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;
33
+ // Default to the max — design generation, multi-screen prototypes, and other
34
+ // large-output workloads need every second they can get inside Lambda's 75s
35
+ // function budget. The cap stays at 55s to leave ~20s headroom for response
36
+ // streaming + the soft-timeout continuation path in run-loop-with-resume.
37
+ const DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS = 55_000;
34
38
  const MAX_BUILDER_GATEWAY_TIMEOUT_MS = 55_000;
35
39
  const BUILDER_GATEWAY_NETWORK_ERROR_CODE = "builder_gateway_network_error";
36
40
  export const BUILDER_DEFAULT_MODEL = BUILDER_MODEL_CONFIG.defaultModel;
@@ -1 +1 @@
1
- {"version":3,"file":"builder-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AASH,OAAO,EACL,yBAAyB,EACzB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACxB,wBAAwB,GACzB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,kCAAkC,EAClC,+BAA+B,GAChC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAE7D,MAAM,CAAC,MAAM,oBAAoB,GAAuB;IACtD,QAAQ,EAAE,IAAI;IACd,uEAAuE;IACvE,yEAAyE;IACzE,sEAAsE;IACtE,wEAAwE;IACxE,aAAa,EAAE,KAAK;IACpB,MAAM,EAAE,IAAI;IACZ,WAAW,EAAE,KAAK;IAClB,iBAAiB,EAAE,IAAI;CACxB,CAAC;AAEF,MAAM,CAAC,MAAM,wBAAwB,GAAG,oBAAoB,CAAC,eAAe,CAAC;AAE7E,MAAM,kCAAkC,GAAG,MAAM,CAAC;AAClD,MAAM,8BAA8B,GAAG,MAAM,CAAC;AAC9C,MAAM,kCAAkC,GAAG,+BAA+B,CAAC;AAE3E,MAAM,CAAC,MAAM,qBAAqB,GAAG,oBAAoB,CAAC,YAAY,CAAC;AAEvE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CAAC,mBAAmB,CAAC;QAClC,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC;QAC9B,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,CAC5B,CAAC;AACJ,CAAC;AAED,SAAS,mCAAmC,CAC1C,GAAY,EACZ,OAOC;IAED,YAAY,CAAC,GAAG,EAAE;QAChB,KAAK,EAAE,2BAA2B;QAClC,IAAI,EAAE;YACJ,MAAM,EAAE,gBAAgB;YACxB,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO;YAC7C,SAAS,EAAE,OAAO,CAAC,QAAQ;gBACzB,CAAC,CAAC,yBAAyB;gBAC3B,CAAC,CAAC,kCAAkC;SACvC;QACD,KAAK,EAAE;YACL,aAAa,EAAE,OAAO,CAAC,UAAU,EAAE,MAAM;YACzC,WAAW,EAAE,OAAO,CAAC,UAAU,EAAE,QAAQ;YACzC,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,SAAS,EAAE,OAAO,CAAC,SAAS;SAC7B;QACD,QAAQ,EAAE;YACR,cAAc,EAAE;gBACd,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,aAAa,EAAE,OAAO,CAAC,UAAU,EAAE,MAAM;gBACzC,WAAW,EAAE,OAAO,CAAC,UAAU,EAAE,QAAQ;gBACzC,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,QAAQ,EAAE,OAAO,CAAC,QAAQ;gBAC1B,SAAS,EAAE,OAAO,CAAC,SAAS;aAC7B;SACF;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * BuilderEngine — HTTP client for the Builder.io managed LLM gateway.\n *\n * The gateway accepts an Anthropic-shaped request body and streams events as\n * JSONL. This engine translates the framework's EngineStreamOptions into the\n * gateway request, parses the streamed events into EngineEvent items, and\n * maps gateway error responses (402 quota, 403 disabled, 401 auth, 429\n * concurrency) into structured stop events that carry an upgrade URL when\n * the chat UI needs to prompt the user to upgrade.\n *\n * Credentials come from BUILDER_PRIVATE_KEY + BUILDER_PUBLIC_KEY (set via the\n * Builder CLI-auth onboarding flow). Base URL is overridable via\n * BUILDER_GATEWAY_BASE_URL.\n */\n\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineContentPart,\n EngineEvent,\n EngineStreamOptions,\n} from \"./types.js\";\nimport {\n engineMessagesToAnthropic,\n engineToolsToAnthropic,\n} from \"./translate-anthropic.js\";\nimport {\n resolveBuilderAuthHeader,\n resolveBuilderCredential,\n getBuilderGatewayBaseUrl,\n} from \"../../server/credential-provider.js\";\nimport {\n normalizeReasoningEffortForModel,\n type ReasoningEffort,\n} from \"../../shared/reasoning-effort.js\";\nimport {\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n LLM_MISSING_CREDENTIALS_MESSAGE,\n} from \"./credential-errors.js\";\nimport { BUILDER_MODEL_CONFIG } from \"../model-config.js\";\nimport { captureError } from \"../../server/capture-error.js\";\n\nexport const BUILDER_CAPABILITIES: EngineCapabilities = {\n thinking: true,\n // TODO: flip to true once we forward `cache_control` blocks through to\n // the gateway request body. Today the engine builds the Anthropic-shaped\n // body without cache_control markers, and Anthropic caching is opt-in\n // (not automatic), so claiming `promptCaching: true` would overpromise.\n promptCaching: false,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n};\n\nexport const BUILDER_SUPPORTED_MODELS = BUILDER_MODEL_CONFIG.supportedModels;\n\nconst DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;\nconst MAX_BUILDER_GATEWAY_TIMEOUT_MS = 55_000;\nconst BUILDER_GATEWAY_NETWORK_ERROR_CODE = \"builder_gateway_network_error\";\n\nexport const BUILDER_DEFAULT_MODEL = BUILDER_MODEL_CONFIG.defaultModel;\n\n/**\n * Bucket an Anthropic `thinking.budgetTokens` value into the gateway's\n * legacy three-level `reasoning_effort` enum.\n *\n * The thresholds are chosen to align with typical Anthropic extended-thinking\n * budgets we see in the wild:\n * • < 2000 → short one-step reasoning (\"low\")\n * • 2000–8000 → multi-step thinking (\"medium\")\n * • ≥ 8000 → deep planning / long chains (\"high\")\n *\n * 8000 is Anthropic's documented default in our framework (see\n * engine/types.ts:195), so callers that don't explicitly set\n * `budgetTokens` map to \"high\" via the default. If the gateway later\n * exposes more granular knobs or different thresholds, revisit this map.\n */\nfunction mapReasoningEffort(budgetTokens: number): ReasoningEffort {\n if (budgetTokens < 2000) return \"low\";\n if (budgetTokens < 8000) return \"medium\";\n return \"high\";\n}\n\n/**\n * Build the URL the chat UI should link to when a user hits a quota error.\n * Deep-links to the connected org's billing page when BUILDER_ORG_NAME is\n * known, else falls back to the generic account billing page.\n */\nasync function buildUpgradeUrl(): Promise<string> {\n const orgName = await resolveBuilderCredential(\"BUILDER_ORG_NAME\");\n if (orgName) {\n return `https://builder.io/app/organizations/${encodeURIComponent(orgName)}/billing`;\n }\n return \"https://builder.io/account/billing\";\n}\n\ninterface GatewayErrorBody {\n code?: string;\n message?: string;\n usageInfo?: {\n plan?: string;\n limitExceeded?: string;\n isEnterprise?: boolean;\n };\n}\n\nclass BuilderEngine implements AgentEngine {\n readonly name = \"builder\";\n readonly label = \"Builder.io Gateway\";\n readonly defaultModel = BUILDER_DEFAULT_MODEL;\n readonly supportedModels = BUILDER_SUPPORTED_MODELS;\n readonly capabilities = BUILDER_CAPABILITIES;\n\n async *stream(opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n const [authHeader, spaceId, builderUserId] = await Promise.all([\n resolveBuilderAuthHeader(),\n resolveBuilderCredential(\"BUILDER_PUBLIC_KEY\"),\n resolveBuilderCredential(\"BUILDER_USER_ID\"),\n ]);\n if (!authHeader || !spaceId) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: LLM_MISSING_CREDENTIALS_MESSAGE,\n errorCode: LLM_MISSING_CREDENTIALS_ERROR_CODE,\n };\n return;\n }\n\n const messages = engineMessagesToAnthropic(opts.messages);\n const tools = engineToolsToAnthropic(opts.tools);\n const thinkingBudget =\n opts.providerOptions?.anthropic?.thinking?.budgetTokens;\n const explicitReasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort,\n );\n const reasoningEffort =\n explicitReasoningEffort ??\n (typeof thinkingBudget === \"number\"\n ? mapReasoningEffort(thinkingBudget)\n : undefined);\n\n const body: Record<string, unknown> = {\n model: opts.model,\n messages,\n ...(opts.systemPrompt ? { system: opts.systemPrompt } : {}),\n ...(tools.length > 0 ? { tools } : {}),\n ...(opts.maxOutputTokens !== undefined\n ? { max_tokens: opts.maxOutputTokens }\n : {}),\n ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),\n };\n\n const gatewayBaseUrl = getBuilderGatewayBaseUrl();\n const gatewayUrl = new URL(\n \"messages\",\n gatewayBaseUrl.endsWith(\"/\") ? gatewayBaseUrl : `${gatewayBaseUrl}/`,\n );\n gatewayUrl.searchParams.set(\"apiKey\", spaceId);\n const orgLabel =\n (await resolveBuilderCredential(\"BUILDER_ORG_NAME\")) || \"unknown-org\";\n const tStart = Date.now();\n console.log(\n `[builder-engine] → POST ${gatewayUrl.origin}${gatewayUrl.pathname} model=${opts.model} tools=${tools.length} org=${orgLabel}`,\n );\n\n const gatewayTimeoutMs = getBuilderGatewayTimeoutMs();\n const gatewayAbort = createGatewayAbortSignal(\n opts.abortSignal,\n gatewayTimeoutMs,\n );\n try {\n let response: Response;\n try {\n response = await fetch(gatewayUrl.toString(), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n \"x-builder-api-key\": spaceId,\n ...(builderUserId ? { \"x-builder-user-id\": builderUserId } : {}),\n },\n body: JSON.stringify(body),\n signal: gatewayAbort.signal,\n });\n } catch (err) {\n const timedOut = gatewayAbort.didTimeout();\n if (gatewayAbort.didTimeout()) {\n console.warn(\n `[builder-engine] gateway timed out after ${Date.now() - tStart}ms`,\n );\n }\n if (timedOut || isBuilderGatewayNetworkError(err)) {\n captureBuilderGatewayTransportError(err, {\n phase: \"request\",\n model: opts.model,\n gatewayUrl,\n timeoutMs: gatewayTimeoutMs,\n timedOut,\n elapsedMs: Date.now() - tStart,\n });\n }\n yield createBuilderGatewayTimeoutStop(err, timedOut, gatewayTimeoutMs);\n return;\n }\n\n console.log(\n `[builder-engine] ← ${response.status} ${response.statusText} in ${Date.now() - tStart}ms`,\n );\n\n if (!response.ok) {\n yield* emitHttpError(response);\n return;\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"text/html\")) {\n const rawText = await response.text().catch(() => \"\");\n yield {\n type: \"stop\",\n reason: \"error\",\n error: normalizeGatewayErrorText(rawText, response.status || 502),\n errorCode: `http_${response.status || 502}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder gateway response has no body\",\n };\n return;\n }\n\n yield* parseJsonlStream(reader, opts.model, {\n didGatewayTimeout: gatewayAbort.didTimeout,\n gatewayTimeoutMs,\n gatewayUrl,\n requestStartedAt: tStart,\n });\n } finally {\n gatewayAbort.cleanup();\n }\n }\n}\n\nasync function* emitHttpError(response: Response): AsyncIterable<EngineEvent> {\n const status = response.status;\n // Read the body once as text and then try to parse — calling `.json()`\n // and then `.text()` as a fallback fails because the body stream is\n // already consumed (TypeError: Body has already been read), so we'd\n // silently lose non-JSON error payloads like HTML proxy 502s.\n let errBody: GatewayErrorBody = {};\n const rawText = await response.text().catch(() => \"\");\n if (rawText) {\n try {\n errBody = JSON.parse(rawText) as GatewayErrorBody;\n } catch {\n errBody.message = normalizeGatewayErrorText(rawText, status);\n }\n }\n const code = errBody.code ?? `http_${status}`;\n const message = errBody.message ?? `Builder gateway returned ${status}`;\n\n // Belt-and-suspenders: 402 without a structured `credits-limit` code\n // (e.g. bare proxy response) still means quota → show upgrade CTA.\n if (code.startsWith(\"credits-limit\") || status === 402) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n upgradeUrl: await buildUpgradeUrl(),\n };\n return;\n }\n if (code === \"gateway_not_enabled\") {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n return;\n }\n if (status === 401 || code === \"unauthorized\") {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder authentication failed. Reconnect Builder via Settings.\",\n errorCode: \"builder_auth_error\",\n };\n return;\n }\n const lowerMessage = message.toLowerCase();\n if (\n status === 403 &&\n (lowerMessage.includes(\"unauthorized\") ||\n lowerMessage.includes(\"private key\") ||\n lowerMessage.includes(\"invalid token\") ||\n lowerMessage.includes(\"invalid_token\") ||\n lowerMessage.includes(\"token invalid\"))\n ) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder authentication failed. Reconnect Builder via Settings.\",\n errorCode: \"builder_auth_error\",\n };\n return;\n }\n if (status === 403) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n return;\n }\n if (status === 429 || code === \"too_many_concurrent_requests\") {\n // Include \"too many requests\" in the message so production-agent's\n // isRetryableError picks it up and retries the turn.\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `${message} (too many requests)`,\n errorCode: code,\n };\n return;\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n}\n\n// Yields one non-empty JSONL line at a time. Flushes any trailing content\n// after the stream ends so a final event without a newline terminator\n// isn't silently dropped — some gateway proxies close the connection on\n// a complete line and the client must still process it.\nasync function* readJsonlLines(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n): AsyncIterable<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let newlineIdx = buffer.indexOf(\"\\n\");\n while (newlineIdx !== -1) {\n const line = buffer.slice(0, newlineIdx).trim();\n buffer = buffer.slice(newlineIdx + 1);\n newlineIdx = buffer.indexOf(\"\\n\");\n if (line) yield line;\n }\n }\n const tail = buffer.trim();\n if (tail) yield tail;\n}\n\nasync function* parseJsonlStream(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n model: string,\n captureContext: {\n didGatewayTimeout?: () => boolean;\n gatewayTimeoutMs?: number;\n gatewayUrl?: URL;\n requestStartedAt?: number;\n } = {},\n): AsyncIterable<EngineEvent> {\n const gatewayTimeoutMs =\n captureContext.gatewayTimeoutMs ?? DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;\n const parts: EngineContentPart[] = [];\n let pendingText = \"\";\n let pendingThinking: { text: string; signature?: string } | null = null;\n\n const flushPending = () => {\n if (pendingText) {\n parts.push({ type: \"text\", text: pendingText });\n pendingText = \"\";\n }\n if (pendingThinking) {\n parts.push({\n type: \"thinking\",\n text: pendingThinking.text,\n ...(pendingThinking.signature !== undefined\n ? { signature: pendingThinking.signature }\n : {}),\n });\n pendingThinking = null;\n }\n };\n\n try {\n for await (const line of readJsonlLines(reader)) {\n let event: any;\n try {\n event = JSON.parse(line);\n } catch {\n const normalized = normalizeGatewayErrorText(line, 502);\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `Builder gateway returned invalid JSONL: ${normalized.slice(\n 0,\n 240,\n )}`,\n errorCode: \"http_502\",\n };\n return;\n }\n\n switch (event.type) {\n case \"text-delta\": {\n const text = event.text ?? \"\";\n pendingText += text;\n yield { type: \"text-delta\", text };\n break;\n }\n\n case \"thinking-delta\": {\n const text = event.text ?? \"\";\n if (!pendingThinking) pendingThinking = { text: \"\" };\n pendingThinking.text += text;\n if (event.signature) pendingThinking.signature = event.signature;\n yield {\n type: \"thinking-delta\",\n text,\n ...(event.signature ? { signature: event.signature } : {}),\n };\n break;\n }\n\n case \"tool-call-delta\":\n yield {\n type: \"tool-input-delta\",\n id: event.id,\n name: event.name,\n text:\n typeof event.argsTextDelta === \"string\"\n ? event.argsTextDelta\n : typeof event.delta === \"string\"\n ? event.delta\n : \"\",\n };\n break;\n\n case \"tool-call\": {\n flushPending();\n parts.push({\n type: \"tool-call\",\n id: event.id,\n name: event.name,\n input: event.input,\n });\n yield {\n type: \"tool-call\",\n id: event.id,\n name: event.name,\n input: event.input,\n };\n break;\n }\n\n case \"usage\": {\n const cacheWrite =\n (event.cacheCreatedTokens ?? 0) + (event.cacheCreated1hTokens ?? 0);\n yield {\n type: \"usage\",\n inputTokens: event.inputTokens ?? 0,\n outputTokens: event.outputTokens ?? 0,\n ...(event.cacheInputTokens !== undefined\n ? { cacheReadTokens: event.cacheInputTokens }\n : {}),\n ...(cacheWrite > 0 ? { cacheWriteTokens: cacheWrite } : {}),\n };\n break;\n }\n\n case \"stop\": {\n flushPending();\n yield { type: \"assistant-content\", parts };\n\n const reason = event.reason ?? \"end_turn\";\n if (reason === \"rate_limited\") {\n // Include \"rate_limit\" in the message so production-agent's\n // isRetryableError picks it up and retries.\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `rate_limit exceeded: ${event.error ?? \"upstream provider rate limited\"}`,\n errorCode: \"rate_limited\",\n };\n } else if (reason === \"error\") {\n // Surface every diagnostic the gateway gave us so the user (and\n // our logs) get more than a bare \"Gateway error\". The gateway\n // sometimes emits an error stop event with no message — most\n // commonly when the upstream provider rejects the model for\n // this account (Opus quotas have hit this in practice).\n const explicitErrMsg = event.error || event.message || event.detail;\n const errMsg =\n explicitErrMsg ??\n `Gateway error (no detail; raw event: ${JSON.stringify(event)})`;\n const errCode =\n event.errorCode ??\n event.code ??\n (!explicitErrMsg ? \"builder_gateway_error\" : undefined);\n console.error(\n `[builder-engine] stop reason=error model=${model} code=${errCode ?? \"(none)\"} error=${errMsg}`,\n );\n yield {\n type: \"stop\",\n reason: \"error\",\n error: errMsg,\n ...(errCode ? { errorCode: errCode } : {}),\n };\n } else if (\n reason === \"end_turn\" ||\n reason === \"tool_use\" ||\n reason === \"max_tokens\" ||\n reason === \"stop_sequence\"\n ) {\n yield { type: \"stop\", reason };\n } else {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `Unknown stop reason: ${reason}`,\n };\n }\n return;\n }\n\n default:\n // Unknown event type — ignore for forward compat.\n break;\n }\n }\n\n // Stream ended without a stop event — synthesize one so callers don't hang.\n flushPending();\n yield { type: \"assistant-content\", parts };\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder gateway stream ended without a stop event\",\n };\n } catch (err) {\n const timedOut = captureContext.didGatewayTimeout?.() ?? false;\n if (timedOut || isBuilderGatewayNetworkError(err)) {\n captureBuilderGatewayTransportError(err, {\n phase: \"stream\",\n model,\n gatewayUrl: captureContext.gatewayUrl,\n timeoutMs: gatewayTimeoutMs,\n timedOut,\n elapsedMs:\n typeof captureContext.requestStartedAt === \"number\"\n ? Date.now() - captureContext.requestStartedAt\n : undefined,\n });\n }\n yield createBuilderGatewayTimeoutStop(err, timedOut, gatewayTimeoutMs);\n } finally {\n // Release the reader on every exit path — early returns (invalid JSONL,\n // stop event) and generator abandonment both leave the underlying\n // Response body locked otherwise. cancel() also closes the socket.\n try {\n await reader.cancel();\n } catch {\n // Already cancelled or closed\n }\n }\n}\n\nfunction normalizeGatewayErrorText(raw: string, status: number): string {\n const text = raw.trim();\n const looksHtml = /<html[\\s>]|<body[\\s>]|<head[\\s>]/i.test(text);\n const readable = looksHtml ? htmlToText(text) : text;\n if (/inactivity timeout/i.test(readable)) {\n return `Builder gateway returned ${status}: Inactivity Timeout. The upstream connection was idle too long before sending data.`;\n }\n if (looksHtml) {\n return `Builder gateway returned ${status}: ${readable.slice(0, 240)}`;\n }\n return readable;\n}\n\nfunction htmlToText(html: string): string {\n return html\n .replace(/<script[\\s\\S]*?<\\/script>/gi, \" \")\n .replace(/<style[\\s\\S]*?<\\/style>/gi, \" \")\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/(p|div|h1|h2|h3|li|tr)>/gi, \"\\n\")\n .replace(/<[^>]+>/g, \" \")\n .replace(/&nbsp;/gi, \" \")\n .replace(/&lt;/gi, \"<\")\n .replace(/&gt;/gi, \">\")\n .replace(/&amp;/gi, \"&\")\n .replace(/&quot;/gi, '\"')\n .replace(/&#39;/gi, \"'\")\n .replace(/[ \\t]+/g, \" \")\n .replace(/\\n\\s+/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\nexport function createBuilderEngine(\n _config: Record<string, unknown> = {},\n): AgentEngine {\n return new BuilderEngine();\n}\n\nfunction getBuilderGatewayTimeoutMs(): number {\n const raw = process.env.AGENT_NATIVE_BUILDER_GATEWAY_TIMEOUT_MS;\n if (!raw) return DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;\n const parsed = Number(raw);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n return Math.min(parsed, MAX_BUILDER_GATEWAY_TIMEOUT_MS);\n}\n\nfunction createGatewayAbortSignal(\n parentSignal: AbortSignal,\n timeoutMs: number,\n): {\n signal: AbortSignal;\n didTimeout: () => boolean;\n cleanup: () => void;\n} {\n const controller = new AbortController();\n let timedOut = false;\n\n const abortFromParent = () => {\n if (!controller.signal.aborted) {\n controller.abort(parentSignal.reason);\n }\n };\n\n const timeout = setTimeout(() => {\n timedOut = true;\n if (!controller.signal.aborted) {\n controller.abort(new Error(\"Builder gateway request timed out\"));\n }\n }, timeoutMs);\n\n if (parentSignal.aborted) abortFromParent();\n parentSignal.addEventListener(\"abort\", abortFromParent, { once: true });\n\n return {\n signal: controller.signal,\n didTimeout: () => timedOut,\n cleanup: () => {\n clearTimeout(timeout);\n parentSignal.removeEventListener(\"abort\", abortFromParent);\n },\n };\n}\n\nfunction normalizeBuilderGatewayFetchError(\n err: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): string {\n if (timedOut) {\n return `Builder gateway timed out after ${formatTimeoutMs(\n timeoutMs,\n )} before the hosting function limit. Please retry; if this keeps happening, reduce the prompt size or try again when the gateway is less busy.`;\n }\n const message = errorMessage(err);\n if (isBuilderGatewayNetworkError(err)) {\n return `Builder gateway network error: ${message}`;\n }\n return message;\n}\n\nfunction createBuilderGatewayTimeoutStop(\n err: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): EngineEvent {\n const networkError = !timedOut && isBuilderGatewayNetworkError(err);\n return {\n type: \"stop\",\n reason: \"error\",\n error: normalizeBuilderGatewayFetchError(err, timedOut, timeoutMs),\n ...(timedOut\n ? { errorCode: \"builder_gateway_timeout\" }\n : networkError\n ? { errorCode: BUILDER_GATEWAY_NETWORK_ERROR_CODE }\n : {}),\n };\n}\n\nfunction formatTimeoutMs(timeoutMs: number): string {\n if (timeoutMs < 1000) return `${timeoutMs}ms`;\n return `${Math.round(timeoutMs / 1000)}s`;\n}\n\nfunction errorMessage(err: unknown): string {\n if (err instanceof Error) return err.message;\n return String(err);\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 & {\n code?: unknown;\n cause?: unknown;\n };\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 isBuilderGatewayNetworkError(err: unknown): boolean {\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 reset\") ||\n text.includes(\"connection closed\") ||\n text.includes(\"stream closed\") ||\n text.includes(\"terminated\")\n );\n}\n\nfunction captureBuilderGatewayTransportError(\n err: unknown,\n context: {\n phase: \"request\" | \"stream\";\n model: string;\n gatewayUrl?: URL;\n timeoutMs: number;\n timedOut: boolean;\n elapsedMs?: number;\n },\n): void {\n captureError(err, {\n route: \"/_agent-native/agent-chat\",\n tags: {\n source: \"builder-engine\",\n phase: context.phase,\n model: context.model,\n timedOut: context.timedOut ? \"true\" : \"false\",\n errorCode: context.timedOut\n ? \"builder_gateway_timeout\"\n : BUILDER_GATEWAY_NETWORK_ERROR_CODE,\n },\n extra: {\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n timeoutMs: context.timeoutMs,\n elapsedMs: context.elapsedMs,\n },\n contexts: {\n builderGateway: {\n phase: context.phase,\n model: context.model,\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n timeoutMs: context.timeoutMs,\n timedOut: context.timedOut,\n elapsedMs: context.elapsedMs,\n },\n },\n });\n}\n"]}
1
+ {"version":3,"file":"builder-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AASH,OAAO,EACL,yBAAyB,EACzB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACxB,wBAAwB,GACzB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,kCAAkC,EAClC,+BAA+B,GAChC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAE7D,MAAM,CAAC,MAAM,oBAAoB,GAAuB;IACtD,QAAQ,EAAE,IAAI;IACd,uEAAuE;IACvE,yEAAyE;IACzE,sEAAsE;IACtE,wEAAwE;IACxE,aAAa,EAAE,KAAK;IACpB,MAAM,EAAE,IAAI;IACZ,WAAW,EAAE,KAAK;IAClB,iBAAiB,EAAE,IAAI;CACxB,CAAC;AAEF,MAAM,CAAC,MAAM,wBAAwB,GAAG,oBAAoB,CAAC,eAAe,CAAC;AAE7E,6EAA6E;AAC7E,4EAA4E;AAC5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AQ;gBAC1B,SAAS,EAAE,OAAO,CAAC,SAAS;aAC7B;SACF;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * BuilderEngine — HTTP client for the Builder.io managed LLM gateway.\n *\n * The gateway accepts an Anthropic-shaped request body and streams events as\n * JSONL. This engine translates the framework's EngineStreamOptions into the\n * gateway request, parses the streamed events into EngineEvent items, and\n * maps gateway error responses (402 quota, 403 disabled, 401 auth, 429\n * concurrency) into structured stop events that carry an upgrade URL when\n * the chat UI needs to prompt the user to upgrade.\n *\n * Credentials come from BUILDER_PRIVATE_KEY + BUILDER_PUBLIC_KEY (set via the\n * Builder CLI-auth onboarding flow). Base URL is overridable via\n * BUILDER_GATEWAY_BASE_URL.\n */\n\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineContentPart,\n EngineEvent,\n EngineStreamOptions,\n} from \"./types.js\";\nimport {\n engineMessagesToAnthropic,\n engineToolsToAnthropic,\n} from \"./translate-anthropic.js\";\nimport {\n resolveBuilderAuthHeader,\n resolveBuilderCredential,\n getBuilderGatewayBaseUrl,\n} from \"../../server/credential-provider.js\";\nimport {\n normalizeReasoningEffortForModel,\n type ReasoningEffort,\n} from \"../../shared/reasoning-effort.js\";\nimport {\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n LLM_MISSING_CREDENTIALS_MESSAGE,\n} from \"./credential-errors.js\";\nimport { BUILDER_MODEL_CONFIG } from \"../model-config.js\";\nimport { captureError } from \"../../server/capture-error.js\";\n\nexport const BUILDER_CAPABILITIES: EngineCapabilities = {\n thinking: true,\n // TODO: flip to true once we forward `cache_control` blocks through to\n // the gateway request body. Today the engine builds the Anthropic-shaped\n // body without cache_control markers, and Anthropic caching is opt-in\n // (not automatic), so claiming `promptCaching: true` would overpromise.\n promptCaching: false,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n};\n\nexport const BUILDER_SUPPORTED_MODELS = BUILDER_MODEL_CONFIG.supportedModels;\n\n// Default to the max — design generation, multi-screen prototypes, and other\n// large-output workloads need every second they can get inside Lambda's 75s\n// function budget. The cap stays at 55s to leave ~20s headroom for response\n// streaming + the soft-timeout continuation path in run-loop-with-resume.\nconst DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS = 55_000;\nconst MAX_BUILDER_GATEWAY_TIMEOUT_MS = 55_000;\nconst BUILDER_GATEWAY_NETWORK_ERROR_CODE = \"builder_gateway_network_error\";\n\nexport const BUILDER_DEFAULT_MODEL = BUILDER_MODEL_CONFIG.defaultModel;\n\n/**\n * Bucket an Anthropic `thinking.budgetTokens` value into the gateway's\n * legacy three-level `reasoning_effort` enum.\n *\n * The thresholds are chosen to align with typical Anthropic extended-thinking\n * budgets we see in the wild:\n * • < 2000 → short one-step reasoning (\"low\")\n * • 2000–8000 → multi-step thinking (\"medium\")\n * • ≥ 8000 → deep planning / long chains (\"high\")\n *\n * 8000 is Anthropic's documented default in our framework (see\n * engine/types.ts:195), so callers that don't explicitly set\n * `budgetTokens` map to \"high\" via the default. If the gateway later\n * exposes more granular knobs or different thresholds, revisit this map.\n */\nfunction mapReasoningEffort(budgetTokens: number): ReasoningEffort {\n if (budgetTokens < 2000) return \"low\";\n if (budgetTokens < 8000) return \"medium\";\n return \"high\";\n}\n\n/**\n * Build the URL the chat UI should link to when a user hits a quota error.\n * Deep-links to the connected org's billing page when BUILDER_ORG_NAME is\n * known, else falls back to the generic account billing page.\n */\nasync function buildUpgradeUrl(): Promise<string> {\n const orgName = await resolveBuilderCredential(\"BUILDER_ORG_NAME\");\n if (orgName) {\n return `https://builder.io/app/organizations/${encodeURIComponent(orgName)}/billing`;\n }\n return \"https://builder.io/account/billing\";\n}\n\ninterface GatewayErrorBody {\n code?: string;\n message?: string;\n usageInfo?: {\n plan?: string;\n limitExceeded?: string;\n isEnterprise?: boolean;\n };\n}\n\nclass BuilderEngine implements AgentEngine {\n readonly name = \"builder\";\n readonly label = \"Builder.io Gateway\";\n readonly defaultModel = BUILDER_DEFAULT_MODEL;\n readonly supportedModels = BUILDER_SUPPORTED_MODELS;\n readonly capabilities = BUILDER_CAPABILITIES;\n\n async *stream(opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n const [authHeader, spaceId, builderUserId] = await Promise.all([\n resolveBuilderAuthHeader(),\n resolveBuilderCredential(\"BUILDER_PUBLIC_KEY\"),\n resolveBuilderCredential(\"BUILDER_USER_ID\"),\n ]);\n if (!authHeader || !spaceId) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: LLM_MISSING_CREDENTIALS_MESSAGE,\n errorCode: LLM_MISSING_CREDENTIALS_ERROR_CODE,\n };\n return;\n }\n\n const messages = engineMessagesToAnthropic(opts.messages);\n const tools = engineToolsToAnthropic(opts.tools);\n const thinkingBudget =\n opts.providerOptions?.anthropic?.thinking?.budgetTokens;\n const explicitReasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort,\n );\n const reasoningEffort =\n explicitReasoningEffort ??\n (typeof thinkingBudget === \"number\"\n ? mapReasoningEffort(thinkingBudget)\n : undefined);\n\n const body: Record<string, unknown> = {\n model: opts.model,\n messages,\n ...(opts.systemPrompt ? { system: opts.systemPrompt } : {}),\n ...(tools.length > 0 ? { tools } : {}),\n ...(opts.maxOutputTokens !== undefined\n ? { max_tokens: opts.maxOutputTokens }\n : {}),\n ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),\n };\n\n const gatewayBaseUrl = getBuilderGatewayBaseUrl();\n const gatewayUrl = new URL(\n \"messages\",\n gatewayBaseUrl.endsWith(\"/\") ? gatewayBaseUrl : `${gatewayBaseUrl}/`,\n );\n gatewayUrl.searchParams.set(\"apiKey\", spaceId);\n const orgLabel =\n (await resolveBuilderCredential(\"BUILDER_ORG_NAME\")) || \"unknown-org\";\n const tStart = Date.now();\n console.log(\n `[builder-engine] → POST ${gatewayUrl.origin}${gatewayUrl.pathname} model=${opts.model} tools=${tools.length} org=${orgLabel}`,\n );\n\n const gatewayTimeoutMs = getBuilderGatewayTimeoutMs();\n const gatewayAbort = createGatewayAbortSignal(\n opts.abortSignal,\n gatewayTimeoutMs,\n );\n try {\n let response: Response;\n try {\n response = await fetch(gatewayUrl.toString(), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n \"x-builder-api-key\": spaceId,\n ...(builderUserId ? { \"x-builder-user-id\": builderUserId } : {}),\n },\n body: JSON.stringify(body),\n signal: gatewayAbort.signal,\n });\n } catch (err) {\n const timedOut = gatewayAbort.didTimeout();\n if (gatewayAbort.didTimeout()) {\n console.warn(\n `[builder-engine] gateway timed out after ${Date.now() - tStart}ms`,\n );\n }\n if (timedOut || isBuilderGatewayNetworkError(err)) {\n captureBuilderGatewayTransportError(err, {\n phase: \"request\",\n model: opts.model,\n gatewayUrl,\n timeoutMs: gatewayTimeoutMs,\n timedOut,\n elapsedMs: Date.now() - tStart,\n });\n }\n yield createBuilderGatewayTimeoutStop(err, timedOut, gatewayTimeoutMs);\n return;\n }\n\n console.log(\n `[builder-engine] ← ${response.status} ${response.statusText} in ${Date.now() - tStart}ms`,\n );\n\n if (!response.ok) {\n yield* emitHttpError(response);\n return;\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"text/html\")) {\n const rawText = await response.text().catch(() => \"\");\n yield {\n type: \"stop\",\n reason: \"error\",\n error: normalizeGatewayErrorText(rawText, response.status || 502),\n errorCode: `http_${response.status || 502}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder gateway response has no body\",\n };\n return;\n }\n\n yield* parseJsonlStream(reader, opts.model, {\n didGatewayTimeout: gatewayAbort.didTimeout,\n gatewayTimeoutMs,\n gatewayUrl,\n requestStartedAt: tStart,\n });\n } finally {\n gatewayAbort.cleanup();\n }\n }\n}\n\nasync function* emitHttpError(response: Response): AsyncIterable<EngineEvent> {\n const status = response.status;\n // Read the body once as text and then try to parse — calling `.json()`\n // and then `.text()` as a fallback fails because the body stream is\n // already consumed (TypeError: Body has already been read), so we'd\n // silently lose non-JSON error payloads like HTML proxy 502s.\n let errBody: GatewayErrorBody = {};\n const rawText = await response.text().catch(() => \"\");\n if (rawText) {\n try {\n errBody = JSON.parse(rawText) as GatewayErrorBody;\n } catch {\n errBody.message = normalizeGatewayErrorText(rawText, status);\n }\n }\n const code = errBody.code ?? `http_${status}`;\n const message = errBody.message ?? `Builder gateway returned ${status}`;\n\n // Belt-and-suspenders: 402 without a structured `credits-limit` code\n // (e.g. bare proxy response) still means quota → show upgrade CTA.\n if (code.startsWith(\"credits-limit\") || status === 402) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n upgradeUrl: await buildUpgradeUrl(),\n };\n return;\n }\n if (code === \"gateway_not_enabled\") {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n return;\n }\n if (status === 401 || code === \"unauthorized\") {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder authentication failed. Reconnect Builder via Settings.\",\n errorCode: \"builder_auth_error\",\n };\n return;\n }\n const lowerMessage = message.toLowerCase();\n if (\n status === 403 &&\n (lowerMessage.includes(\"unauthorized\") ||\n lowerMessage.includes(\"private key\") ||\n lowerMessage.includes(\"invalid token\") ||\n lowerMessage.includes(\"invalid_token\") ||\n lowerMessage.includes(\"token invalid\"))\n ) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder authentication failed. Reconnect Builder via Settings.\",\n errorCode: \"builder_auth_error\",\n };\n return;\n }\n if (status === 403) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n return;\n }\n if (status === 429 || code === \"too_many_concurrent_requests\") {\n // Include \"too many requests\" in the message so production-agent's\n // isRetryableError picks it up and retries the turn.\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `${message} (too many requests)`,\n errorCode: code,\n };\n return;\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n}\n\n// Yields one non-empty JSONL line at a time. Flushes any trailing content\n// after the stream ends so a final event without a newline terminator\n// isn't silently dropped — some gateway proxies close the connection on\n// a complete line and the client must still process it.\nasync function* readJsonlLines(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n): AsyncIterable<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let newlineIdx = buffer.indexOf(\"\\n\");\n while (newlineIdx !== -1) {\n const line = buffer.slice(0, newlineIdx).trim();\n buffer = buffer.slice(newlineIdx + 1);\n newlineIdx = buffer.indexOf(\"\\n\");\n if (line) yield line;\n }\n }\n const tail = buffer.trim();\n if (tail) yield tail;\n}\n\nasync function* parseJsonlStream(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n model: string,\n captureContext: {\n didGatewayTimeout?: () => boolean;\n gatewayTimeoutMs?: number;\n gatewayUrl?: URL;\n requestStartedAt?: number;\n } = {},\n): AsyncIterable<EngineEvent> {\n const gatewayTimeoutMs =\n captureContext.gatewayTimeoutMs ?? DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;\n const parts: EngineContentPart[] = [];\n let pendingText = \"\";\n let pendingThinking: { text: string; signature?: string } | null = null;\n\n const flushPending = () => {\n if (pendingText) {\n parts.push({ type: \"text\", text: pendingText });\n pendingText = \"\";\n }\n if (pendingThinking) {\n parts.push({\n type: \"thinking\",\n text: pendingThinking.text,\n ...(pendingThinking.signature !== undefined\n ? { signature: pendingThinking.signature }\n : {}),\n });\n pendingThinking = null;\n }\n };\n\n try {\n for await (const line of readJsonlLines(reader)) {\n let event: any;\n try {\n event = JSON.parse(line);\n } catch {\n const normalized = normalizeGatewayErrorText(line, 502);\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `Builder gateway returned invalid JSONL: ${normalized.slice(\n 0,\n 240,\n )}`,\n errorCode: \"http_502\",\n };\n return;\n }\n\n switch (event.type) {\n case \"text-delta\": {\n const text = event.text ?? \"\";\n pendingText += text;\n yield { type: \"text-delta\", text };\n break;\n }\n\n case \"thinking-delta\": {\n const text = event.text ?? \"\";\n if (!pendingThinking) pendingThinking = { text: \"\" };\n pendingThinking.text += text;\n if (event.signature) pendingThinking.signature = event.signature;\n yield {\n type: \"thinking-delta\",\n text,\n ...(event.signature ? { signature: event.signature } : {}),\n };\n break;\n }\n\n case \"tool-call-delta\":\n yield {\n type: \"tool-input-delta\",\n id: event.id,\n name: event.name,\n text:\n typeof event.argsTextDelta === \"string\"\n ? event.argsTextDelta\n : typeof event.delta === \"string\"\n ? event.delta\n : \"\",\n };\n break;\n\n case \"tool-call\": {\n flushPending();\n parts.push({\n type: \"tool-call\",\n id: event.id,\n name: event.name,\n input: event.input,\n });\n yield {\n type: \"tool-call\",\n id: event.id,\n name: event.name,\n input: event.input,\n };\n break;\n }\n\n case \"usage\": {\n const cacheWrite =\n (event.cacheCreatedTokens ?? 0) + (event.cacheCreated1hTokens ?? 0);\n yield {\n type: \"usage\",\n inputTokens: event.inputTokens ?? 0,\n outputTokens: event.outputTokens ?? 0,\n ...(event.cacheInputTokens !== undefined\n ? { cacheReadTokens: event.cacheInputTokens }\n : {}),\n ...(cacheWrite > 0 ? { cacheWriteTokens: cacheWrite } : {}),\n };\n break;\n }\n\n case \"stop\": {\n flushPending();\n yield { type: \"assistant-content\", parts };\n\n const reason = event.reason ?? \"end_turn\";\n if (reason === \"rate_limited\") {\n // Include \"rate_limit\" in the message so production-agent's\n // isRetryableError picks it up and retries.\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `rate_limit exceeded: ${event.error ?? \"upstream provider rate limited\"}`,\n errorCode: \"rate_limited\",\n };\n } else if (reason === \"error\") {\n // Surface every diagnostic the gateway gave us so the user (and\n // our logs) get more than a bare \"Gateway error\". The gateway\n // sometimes emits an error stop event with no message — most\n // commonly when the upstream provider rejects the model for\n // this account (Opus quotas have hit this in practice).\n const explicitErrMsg = event.error || event.message || event.detail;\n const errMsg =\n explicitErrMsg ??\n `Gateway error (no detail; raw event: ${JSON.stringify(event)})`;\n const errCode =\n event.errorCode ??\n event.code ??\n (!explicitErrMsg ? \"builder_gateway_error\" : undefined);\n console.error(\n `[builder-engine] stop reason=error model=${model} code=${errCode ?? \"(none)\"} error=${errMsg}`,\n );\n yield {\n type: \"stop\",\n reason: \"error\",\n error: errMsg,\n ...(errCode ? { errorCode: errCode } : {}),\n };\n } else if (\n reason === \"end_turn\" ||\n reason === \"tool_use\" ||\n reason === \"max_tokens\" ||\n reason === \"stop_sequence\"\n ) {\n yield { type: \"stop\", reason };\n } else {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `Unknown stop reason: ${reason}`,\n };\n }\n return;\n }\n\n default:\n // Unknown event type — ignore for forward compat.\n break;\n }\n }\n\n // Stream ended without a stop event — synthesize one so callers don't hang.\n flushPending();\n yield { type: \"assistant-content\", parts };\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder gateway stream ended without a stop event\",\n };\n } catch (err) {\n const timedOut = captureContext.didGatewayTimeout?.() ?? false;\n if (timedOut || isBuilderGatewayNetworkError(err)) {\n captureBuilderGatewayTransportError(err, {\n phase: \"stream\",\n model,\n gatewayUrl: captureContext.gatewayUrl,\n timeoutMs: gatewayTimeoutMs,\n timedOut,\n elapsedMs:\n typeof captureContext.requestStartedAt === \"number\"\n ? Date.now() - captureContext.requestStartedAt\n : undefined,\n });\n }\n yield createBuilderGatewayTimeoutStop(err, timedOut, gatewayTimeoutMs);\n } finally {\n // Release the reader on every exit path — early returns (invalid JSONL,\n // stop event) and generator abandonment both leave the underlying\n // Response body locked otherwise. cancel() also closes the socket.\n try {\n await reader.cancel();\n } catch {\n // Already cancelled or closed\n }\n }\n}\n\nfunction normalizeGatewayErrorText(raw: string, status: number): string {\n const text = raw.trim();\n const looksHtml = /<html[\\s>]|<body[\\s>]|<head[\\s>]/i.test(text);\n const readable = looksHtml ? htmlToText(text) : text;\n if (/inactivity timeout/i.test(readable)) {\n return `Builder gateway returned ${status}: Inactivity Timeout. The upstream connection was idle too long before sending data.`;\n }\n if (looksHtml) {\n return `Builder gateway returned ${status}: ${readable.slice(0, 240)}`;\n }\n return readable;\n}\n\nfunction htmlToText(html: string): string {\n return html\n .replace(/<script[\\s\\S]*?<\\/script>/gi, \" \")\n .replace(/<style[\\s\\S]*?<\\/style>/gi, \" \")\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/(p|div|h1|h2|h3|li|tr)>/gi, \"\\n\")\n .replace(/<[^>]+>/g, \" \")\n .replace(/&nbsp;/gi, \" \")\n .replace(/&lt;/gi, \"<\")\n .replace(/&gt;/gi, \">\")\n .replace(/&amp;/gi, \"&\")\n .replace(/&quot;/gi, '\"')\n .replace(/&#39;/gi, \"'\")\n .replace(/[ \\t]+/g, \" \")\n .replace(/\\n\\s+/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\nexport function createBuilderEngine(\n _config: Record<string, unknown> = {},\n): AgentEngine {\n return new BuilderEngine();\n}\n\nfunction getBuilderGatewayTimeoutMs(): number {\n const raw = process.env.AGENT_NATIVE_BUILDER_GATEWAY_TIMEOUT_MS;\n if (!raw) return DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;\n const parsed = Number(raw);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n return Math.min(parsed, MAX_BUILDER_GATEWAY_TIMEOUT_MS);\n}\n\nfunction createGatewayAbortSignal(\n parentSignal: AbortSignal,\n timeoutMs: number,\n): {\n signal: AbortSignal;\n didTimeout: () => boolean;\n cleanup: () => void;\n} {\n const controller = new AbortController();\n let timedOut = false;\n\n const abortFromParent = () => {\n if (!controller.signal.aborted) {\n controller.abort(parentSignal.reason);\n }\n };\n\n const timeout = setTimeout(() => {\n timedOut = true;\n if (!controller.signal.aborted) {\n controller.abort(new Error(\"Builder gateway request timed out\"));\n }\n }, timeoutMs);\n\n if (parentSignal.aborted) abortFromParent();\n parentSignal.addEventListener(\"abort\", abortFromParent, { once: true });\n\n return {\n signal: controller.signal,\n didTimeout: () => timedOut,\n cleanup: () => {\n clearTimeout(timeout);\n parentSignal.removeEventListener(\"abort\", abortFromParent);\n },\n };\n}\n\nfunction normalizeBuilderGatewayFetchError(\n err: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): string {\n if (timedOut) {\n return `Builder gateway timed out after ${formatTimeoutMs(\n timeoutMs,\n )} before the hosting function limit. Please retry; if this keeps happening, reduce the prompt size or try again when the gateway is less busy.`;\n }\n const message = errorMessage(err);\n if (isBuilderGatewayNetworkError(err)) {\n return `Builder gateway network error: ${message}`;\n }\n return message;\n}\n\nfunction createBuilderGatewayTimeoutStop(\n err: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): EngineEvent {\n const networkError = !timedOut && isBuilderGatewayNetworkError(err);\n return {\n type: \"stop\",\n reason: \"error\",\n error: normalizeBuilderGatewayFetchError(err, timedOut, timeoutMs),\n ...(timedOut\n ? { errorCode: \"builder_gateway_timeout\" }\n : networkError\n ? { errorCode: BUILDER_GATEWAY_NETWORK_ERROR_CODE }\n : {}),\n };\n}\n\nfunction formatTimeoutMs(timeoutMs: number): string {\n if (timeoutMs < 1000) return `${timeoutMs}ms`;\n return `${Math.round(timeoutMs / 1000)}s`;\n}\n\nfunction errorMessage(err: unknown): string {\n if (err instanceof Error) return err.message;\n return String(err);\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 & {\n code?: unknown;\n cause?: unknown;\n };\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 isBuilderGatewayNetworkError(err: unknown): boolean {\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 reset\") ||\n text.includes(\"connection closed\") ||\n text.includes(\"stream closed\") ||\n text.includes(\"terminated\")\n );\n}\n\nfunction captureBuilderGatewayTransportError(\n err: unknown,\n context: {\n phase: \"request\" | \"stream\";\n model: string;\n gatewayUrl?: URL;\n timeoutMs: number;\n timedOut: boolean;\n elapsedMs?: number;\n },\n): void {\n captureError(err, {\n route: \"/_agent-native/agent-chat\",\n tags: {\n source: \"builder-engine\",\n phase: context.phase,\n model: context.model,\n timedOut: context.timedOut ? \"true\" : \"false\",\n errorCode: context.timedOut\n ? \"builder_gateway_timeout\"\n : BUILDER_GATEWAY_NETWORK_ERROR_CODE,\n },\n extra: {\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n timeoutMs: context.timeoutMs,\n elapsedMs: context.elapsedMs,\n },\n contexts: {\n builderGateway: {\n phase: context.phase,\n model: context.model,\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n timeoutMs: context.timeoutMs,\n timedOut: context.timedOut,\n elapsedMs: context.elapsedMs,\n },\n },\n });\n}\n"]}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Wraps `runAgentLoop` with two layered recovery mechanisms so a single hosted
3
+ * invocation can survive interruptions without showing the user a dead chat:
4
+ *
5
+ * 1. **Soft timeout** — an inner timer that aborts the LLM call before the
6
+ * hosting function's hard limit (Lambda 75s, Vercel 60s, etc.) so we have a
7
+ * chance to gracefully wind down and append a continuation nudge. Without
8
+ * this the function gets killed mid-stream and the user sees a frozen
9
+ * spinner.
10
+ *
11
+ * 2. **Resumable-error continuation** — when the LLM call errors with a
12
+ * transport- or gateway-level interruption (Builder gateway 45s timeout,
13
+ * socket hang up, ECONNRESET, upstream 5xx that survived engine retries),
14
+ * we save the conversation prefix, append a "continue from where you left
15
+ * off" message, and run another LLM call. Anthropic's prompt cache makes
16
+ * the resume call dramatically faster than the cold first attempt, and the
17
+ * agent gets explicit context that it was cut off so it doesn't re-do
18
+ * completed work.
19
+ *
20
+ * Both paths route through `appendAgentLoopContinuation` so the agent sees a
21
+ * uniform "continue" instruction regardless of which recovery fired.
22
+ */
23
+ import { runAgentLoop } from "./production-agent.js";
24
+ /**
25
+ * Cap on continuation iterations inside a single
26
+ * `runAgentLoopDirectWithSoftTimeout` invocation. The host's hard function
27
+ * timeout usually bounds this naturally — but a defensive cap prevents an
28
+ * instant-error spiral from looping forever inside hosting environments with a
29
+ * generous budget.
30
+ *
31
+ * 6 leaves room for: 1 normal completion + a few resume rounds for design
32
+ * generation (prompt + 3 variants ≈ 4 LLM calls), with a small safety margin.
33
+ */
34
+ export declare const MAX_RUN_LOOP_CONTINUATIONS = 6;
35
+ /**
36
+ * Internal entry point used by the agent-chat plugin's run handler. Wraps
37
+ * `runAgentLoop` with soft-timeout + resumable-error continuation recovery.
38
+ *
39
+ * The `softTimeoutMs` argument falls back to `resolveRunSoftTimeoutMs(...)` so
40
+ * different hosting environments (Lambda, Vercel, Cloudflare, local dev) get
41
+ * an appropriate inner budget. Setting it to <= 0 disables both layers — the
42
+ * call goes straight to `runAgentLoop` with no wrapping.
43
+ */
44
+ export declare function runAgentLoopDirectWithSoftTimeout(opts: Parameters<typeof runAgentLoop>[0], softTimeoutMs?: number): Promise<Awaited<ReturnType<typeof runAgentLoop>>>;
45
+ //# sourceMappingURL=run-loop-with-resume.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-loop-with-resume.d.ts","sourceRoot":"","sources":["../../src/agent/run-loop-with-resume.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EACL,YAAY,EAIb,MAAM,uBAAuB,CAAC;AAG/B;;;;;;;;;GASG;AACH,eAAO,MAAM,0BAA0B,IAAI,CAAC;AAE5C;;;;;;;;GAQG;AACH,wBAAsB,iCAAiC,CACrD,IAAI,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,EACxC,aAAa,CAAC,EAAE,MAAM,GACrB,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CA+EnD"}
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Wraps `runAgentLoop` with two layered recovery mechanisms so a single hosted
3
+ * invocation can survive interruptions without showing the user a dead chat:
4
+ *
5
+ * 1. **Soft timeout** — an inner timer that aborts the LLM call before the
6
+ * hosting function's hard limit (Lambda 75s, Vercel 60s, etc.) so we have a
7
+ * chance to gracefully wind down and append a continuation nudge. Without
8
+ * this the function gets killed mid-stream and the user sees a frozen
9
+ * spinner.
10
+ *
11
+ * 2. **Resumable-error continuation** — when the LLM call errors with a
12
+ * transport- or gateway-level interruption (Builder gateway 45s timeout,
13
+ * socket hang up, ECONNRESET, upstream 5xx that survived engine retries),
14
+ * we save the conversation prefix, append a "continue from where you left
15
+ * off" message, and run another LLM call. Anthropic's prompt cache makes
16
+ * the resume call dramatically faster than the cold first attempt, and the
17
+ * agent gets explicit context that it was cut off so it doesn't re-do
18
+ * completed work.
19
+ *
20
+ * Both paths route through `appendAgentLoopContinuation` so the agent sees a
21
+ * uniform "continue" instruction regardless of which recovery fired.
22
+ */
23
+ import { runAgentLoop, appendAgentLoopContinuation, isResumableEngineError, continuationReasonForResumableError, } from "./production-agent.js";
24
+ import { resolveRunSoftTimeoutMs } from "./run-manager.js";
25
+ /**
26
+ * Cap on continuation iterations inside a single
27
+ * `runAgentLoopDirectWithSoftTimeout` invocation. The host's hard function
28
+ * timeout usually bounds this naturally — but a defensive cap prevents an
29
+ * instant-error spiral from looping forever inside hosting environments with a
30
+ * generous budget.
31
+ *
32
+ * 6 leaves room for: 1 normal completion + a few resume rounds for design
33
+ * generation (prompt + 3 variants ≈ 4 LLM calls), with a small safety margin.
34
+ */
35
+ export const MAX_RUN_LOOP_CONTINUATIONS = 6;
36
+ /**
37
+ * Internal entry point used by the agent-chat plugin's run handler. Wraps
38
+ * `runAgentLoop` with soft-timeout + resumable-error continuation recovery.
39
+ *
40
+ * The `softTimeoutMs` argument falls back to `resolveRunSoftTimeoutMs(...)` so
41
+ * different hosting environments (Lambda, Vercel, Cloudflare, local dev) get
42
+ * an appropriate inner budget. Setting it to <= 0 disables both layers — the
43
+ * call goes straight to `runAgentLoop` with no wrapping.
44
+ */
45
+ export async function runAgentLoopDirectWithSoftTimeout(opts, softTimeoutMs) {
46
+ const timeoutMs = resolveRunSoftTimeoutMs(softTimeoutMs);
47
+ if (timeoutMs <= 0)
48
+ return runAgentLoop(opts);
49
+ const upstreamSignal = opts.signal;
50
+ const usage = {
51
+ inputTokens: 0,
52
+ outputTokens: 0,
53
+ cacheReadTokens: 0,
54
+ cacheWriteTokens: 0,
55
+ model: opts.model,
56
+ };
57
+ const addUsage = (next) => {
58
+ usage.inputTokens += next.inputTokens;
59
+ usage.outputTokens += next.outputTokens;
60
+ usage.cacheReadTokens += next.cacheReadTokens;
61
+ usage.cacheWriteTokens += next.cacheWriteTokens;
62
+ usage.model = next.model;
63
+ };
64
+ let attempts = 0;
65
+ while (!upstreamSignal.aborted && attempts < MAX_RUN_LOOP_CONTINUATIONS) {
66
+ attempts++;
67
+ const controller = new AbortController();
68
+ const abortFromUpstream = () => controller.abort();
69
+ if (upstreamSignal.aborted) {
70
+ controller.abort();
71
+ }
72
+ else {
73
+ upstreamSignal.addEventListener("abort", abortFromUpstream, {
74
+ once: true,
75
+ });
76
+ }
77
+ let softTimedOut = false;
78
+ const timer = setTimeout(() => {
79
+ if (controller.signal.aborted)
80
+ return;
81
+ softTimedOut = true;
82
+ controller.abort();
83
+ }, timeoutMs);
84
+ try {
85
+ const nextUsage = await runAgentLoop({
86
+ ...opts,
87
+ signal: controller.signal,
88
+ });
89
+ addUsage(nextUsage);
90
+ if (softTimedOut && !upstreamSignal.aborted) {
91
+ appendAgentLoopContinuation(opts.messages, "run_timeout");
92
+ continue;
93
+ }
94
+ return usage;
95
+ }
96
+ catch (err) {
97
+ if (softTimedOut && !upstreamSignal.aborted) {
98
+ appendAgentLoopContinuation(opts.messages, "run_timeout");
99
+ continue;
100
+ }
101
+ // Resumable transport / gateway interruptions: the LLM call was cut off
102
+ // mid-stream (gateway 45s timeout, socket hang up, function-level
103
+ // timeout that didn't trip our soft timer first). Treat it the same way
104
+ // as a soft timeout — append a "continue from where you left off" nudge
105
+ // and let the loop run another LLM call. The conversation prefix up to
106
+ // the cut-off is preserved in opts.messages, and Anthropic's prompt
107
+ // cache makes the resume call much faster.
108
+ if (!upstreamSignal.aborted && isResumableEngineError(err)) {
109
+ appendAgentLoopContinuation(opts.messages, continuationReasonForResumableError(err));
110
+ continue;
111
+ }
112
+ throw err;
113
+ }
114
+ finally {
115
+ clearTimeout(timer);
116
+ upstreamSignal.removeEventListener("abort", abortFromUpstream);
117
+ }
118
+ }
119
+ return usage;
120
+ }
121
+ //# sourceMappingURL=run-loop-with-resume.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-loop-with-resume.js","sourceRoot":"","sources":["../../src/agent/run-loop-with-resume.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EACL,YAAY,EACZ,2BAA2B,EAC3B,sBAAsB,EACtB,mCAAmC,GACpC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAE3D;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AAE5C;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,IAAwC,EACxC,aAAsB;IAEtB,MAAM,SAAS,GAAG,uBAAuB,CAAC,aAAa,CAAC,CAAC;IACzD,IAAI,SAAS,IAAI,CAAC;QAAE,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC;IAE9C,MAAM,cAAc,GAAG,IAAI,CAAC,MAAM,CAAC;IAC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AEd,IAAI,CAAC;YACH,MAAM,SAAS,GAAG,MAAM,YAAY,CAAC;gBACnC,GAAG,IAAI;gBACP,MAAM,EAAE,UAAU,CAAC,MAAM;aAC1B,CAAC,CAAC;YACH,QAAQ,CAAC,SAAS,CAAC,CAAC;YACpB,IAAI,YAAY,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,CAAC;gBAC5C,2BAA2B,CAAC,IAAI,CAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;gBAC1D,SAAS;YACX,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,YAAY,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,CAAC;gBAC5C,2BAA2B,CAAC,IAAI,CAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;gBAC1D,SAAS;YACX,CAAC;YACD,wEAAwE;YACxE,kEAAkE;YAClE,wEAAwE;YACxE,wEAAwE;YACxE,uEAAuE;YACvE,oEAAoE;YACpE,2CAA2C;YAC3C,IAAI,CAAC,cAAc,CAAC,OAAO,IAAI,sBAAsB,CAAC,GAAG,CAAC,EAAE,CAAC;gBAC3D,2BAA2B,CACzB,IAAI,CAAC,QAAQ,EACb,mCAAmC,CAAC,GAAG,CAAC,CACzC,CAAC;gBACF,SAAS;YACX,CAAC;YACD,MAAM,GAAG,CAAC;QACZ,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,cAAc,CAAC,mBAAmB,CAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC;QACjE,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * Wraps `runAgentLoop` with two layered recovery mechanisms so a single hosted\n * invocation can survive interruptions without showing the user a dead chat:\n *\n * 1. **Soft timeout** — an inner timer that aborts the LLM call before the\n * hosting function's hard limit (Lambda 75s, Vercel 60s, etc.) so we have a\n * chance to gracefully wind down and append a continuation nudge. Without\n * this the function gets killed mid-stream and the user sees a frozen\n * spinner.\n *\n * 2. **Resumable-error continuation** — when the LLM call errors with a\n * transport- or gateway-level interruption (Builder gateway 45s timeout,\n * socket hang up, ECONNRESET, upstream 5xx that survived engine retries),\n * we save the conversation prefix, append a \"continue from where you left\n * off\" message, and run another LLM call. Anthropic's prompt cache makes\n * the resume call dramatically faster than the cold first attempt, and the\n * agent gets explicit context that it was cut off so it doesn't re-do\n * completed work.\n *\n * Both paths route through `appendAgentLoopContinuation` so the agent sees a\n * uniform \"continue\" instruction regardless of which recovery fired.\n */\n\nimport {\n runAgentLoop,\n appendAgentLoopContinuation,\n isResumableEngineError,\n continuationReasonForResumableError,\n} from \"./production-agent.js\";\nimport { resolveRunSoftTimeoutMs } from \"./run-manager.js\";\n\n/**\n * Cap on continuation iterations inside a single\n * `runAgentLoopDirectWithSoftTimeout` invocation. The host's hard function\n * timeout usually bounds this naturally — but a defensive cap prevents an\n * instant-error spiral from looping forever inside hosting environments with a\n * generous budget.\n *\n * 6 leaves room for: 1 normal completion + a few resume rounds for design\n * generation (prompt + 3 variants ≈ 4 LLM calls), with a small safety margin.\n */\nexport const MAX_RUN_LOOP_CONTINUATIONS = 6;\n\n/**\n * Internal entry point used by the agent-chat plugin's run handler. Wraps\n * `runAgentLoop` with soft-timeout + resumable-error continuation recovery.\n *\n * The `softTimeoutMs` argument falls back to `resolveRunSoftTimeoutMs(...)` so\n * different hosting environments (Lambda, Vercel, Cloudflare, local dev) get\n * an appropriate inner budget. Setting it to <= 0 disables both layers — the\n * call goes straight to `runAgentLoop` with no wrapping.\n */\nexport async function runAgentLoopDirectWithSoftTimeout(\n opts: Parameters<typeof runAgentLoop>[0],\n softTimeoutMs?: number,\n): Promise<Awaited<ReturnType<typeof runAgentLoop>>> {\n const timeoutMs = resolveRunSoftTimeoutMs(softTimeoutMs);\n if (timeoutMs <= 0) return runAgentLoop(opts);\n\n const upstreamSignal = opts.signal;\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\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 let attempts = 0;\n while (!upstreamSignal.aborted && attempts < MAX_RUN_LOOP_CONTINUATIONS) {\n attempts++;\n const controller = new AbortController();\n const abortFromUpstream = () => controller.abort();\n if (upstreamSignal.aborted) {\n controller.abort();\n } else {\n upstreamSignal.addEventListener(\"abort\", abortFromUpstream, {\n once: true,\n });\n }\n\n let softTimedOut = false;\n const timer = setTimeout(() => {\n if (controller.signal.aborted) return;\n softTimedOut = true;\n controller.abort();\n }, timeoutMs);\n\n try {\n const nextUsage = await runAgentLoop({\n ...opts,\n signal: controller.signal,\n });\n addUsage(nextUsage);\n if (softTimedOut && !upstreamSignal.aborted) {\n appendAgentLoopContinuation(opts.messages, \"run_timeout\");\n continue;\n }\n return usage;\n } catch (err) {\n if (softTimedOut && !upstreamSignal.aborted) {\n appendAgentLoopContinuation(opts.messages, \"run_timeout\");\n continue;\n }\n // Resumable transport / gateway interruptions: the LLM call was cut off\n // mid-stream (gateway 45s timeout, socket hang up, function-level\n // timeout that didn't trip our soft timer first). Treat it the same way\n // as a soft timeout — append a \"continue from where you left off\" nudge\n // and let the loop run another LLM call. The conversation prefix up to\n // the cut-off is preserved in opts.messages, and Anthropic's prompt\n // cache makes the resume call much faster.\n if (!upstreamSignal.aborted && isResumableEngineError(err)) {\n appendAgentLoopContinuation(\n opts.messages,\n continuationReasonForResumableError(err),\n );\n continue;\n }\n throw err;\n } finally {\n clearTimeout(timer);\n upstreamSignal.removeEventListener(\"abort\", abortFromUpstream);\n }\n }\n\n return usage;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantChat.d.ts","sourceRo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AAC;QACd,MAAM,EAAE,MAAM,EAAE,CAAC;QACjB,UAAU,EAAE,OAAO,CAAC;KACrB,CAAC,CAAC;IACH,uDAAuD;IACvD,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACxD,kEAAkE;IAClE,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,CAAC;IACnD,wEAAwE;IACxE,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;CACzB;AAED,eAAO,MAAM,mBAAmB,gBAAgB,CAAC;AAEjD,8DAA8D;AAC9D,wBAAgB,gBAAgB,CAAC,KAAK,CAAC,EAAE,MAAM,QAI9C;AAqCD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,iBAAiB,EAAE,CAAC;AA69C7B,eAAO,MAAM,aAAa,gGA4DxB,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import React, { useState, useRef, useEffect, useLayoutEffect, useCallback, useMemo, forwardRef, useImperativeHandle, } from "react";
2
+ import React, { useState, useRef, useEffect, useCallback, useMemo, forwardRef, useImperativeHandle, } from "react";
3
3
  import { AssistantRuntimeProvider, useLocalRuntime, useThreadRuntime, useThread, useAui, useComposer, useMessageRuntime, ThreadPrimitive, ComposerPrimitive, MessagePrimitive, } from "@assistant-ui/react";
4
4
  import { SimpleImageAttachmentAdapter, CompositeAttachmentAdapter, } from "@assistant-ui/react";
5
5
  import { MarkdownTextPrimitive } from "@assistant-ui/react-markdown";
@@ -18,7 +18,6 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel,
18
18
  import { IframeEmbed, parseEmbedBody } from "./IframeEmbed.js";
19
19
  import { useDevMode } from "./use-dev-mode.js";
20
20
  import { agentNativePath } from "./api-path.js";
21
- import { getThreadCacheKey } from "./use-chat-threads.js";
22
21
  import { BUILDER_SPACE_SETTINGS_URL } from "./error-format.js";
23
22
  import { ThumbsFeedback } from "./observability/ThumbsFeedback.js";
24
23
  import { TiptapComposer, } from "./composer/TiptapComposer.js";
@@ -1492,22 +1491,7 @@ const AssistantChatInner = forwardRef(function AssistantChatInner({ emptyStateTe
1492
1491
  }, [isRunning, tabId, threadId]);
1493
1492
  // ─── Chat persistence ──────────────────────────────────────────────
1494
1493
  const hasRestoredRef = useRef(false);
1495
- // Cached thread data from a prior session, read synchronously so existing
1496
- // chats can paint their messages on first commit instead of after the server
1497
- // round-trip. The server fetch still runs to refresh with the latest.
1498
- const [cachedThreadData] = useState(() => {
1499
- if (typeof window === "undefined")
1500
- return null;
1501
- if (!threadId || isNewThread)
1502
- return null;
1503
- try {
1504
- return localStorage.getItem(getThreadCacheKey(threadId));
1505
- }
1506
- catch {
1507
- return null;
1508
- }
1509
- });
1510
- const [isRestoring, setIsRestoring] = useState(!!threadId && !isNewThread && !cachedThreadData);
1494
+ const [isRestoring, setIsRestoring] = useState(!!threadId && !isNewThread);
1511
1495
  const onSaveThreadRef = useRef(onSaveThread);
1512
1496
  onSaveThreadRef.current = onSaveThread;
1513
1497
  const onGenerateTitleRef = useRef(onGenerateTitle);
@@ -1708,30 +1692,15 @@ const AssistantChatInner = forwardRef(function AssistantChatInner({ emptyStateTe
1708
1692
  return false;
1709
1693
  }
1710
1694
  }, [apiUrl, refreshThreadFromServer, startReconnectToRun, threadId]);
1711
- // Hydrate from the localStorage cache synchronously so the message bubbles
1712
- // paint on the first commit instead of after the server round-trip. The
1713
- // server fetch below still runs to refresh with the latest content.
1714
- const hydratedFromCacheRef = useRef(false);
1715
- useLayoutEffect(() => {
1716
- if (hydratedFromCacheRef.current)
1717
- return;
1718
- if (!cachedThreadData)
1719
- return;
1720
- hydratedFromCacheRef.current = true;
1721
- try {
1722
- importThreadData(cachedThreadData, { markTitleGenerated: true });
1723
- }
1724
- catch {
1725
- // Corrupt cache entry — ignore and let the server fetch repopulate.
1726
- }
1727
- }, [cachedThreadData, importThreadData]);
1728
- // Restore messages from server on mount (when threadId is set)
1695
+ // Restore messages from server on mount (when threadId is set). The
1696
+ // server is the single source of truth we don't hydrate from localStorage
1697
+ // first, so what the user sees in the chat panel always matches what the
1698
+ // history list (and the agent) sees on disk.
1729
1699
  useEffect(() => {
1730
1700
  if (hasRestoredRef.current)
1731
1701
  return;
1732
1702
  hasRestoredRef.current = true;
1733
1703
  if (threadId) {
1734
- // Load from server
1735
1704
  (async () => {
1736
1705
  try {
1737
1706
  const res = await fetch(`${apiUrl}/threads/${encodeURIComponent(threadId)}`);
@@ -1739,12 +1708,7 @@ const AssistantChatInner = forwardRef(function AssistantChatInner({ emptyStateTe
1739
1708
  return;
1740
1709
  const data = await res.json();
1741
1710
  if (data.threadData) {
1742
- // Skip the re-import if the server data matches what we already
1743
- // hydrated from cache — avoids a second runtime.import that would
1744
- // briefly flicker the message list.
1745
- if (data.threadData !== cachedThreadData) {
1746
- importThreadData(data.threadData, { markTitleGenerated: true });
1747
- }
1711
+ importThreadData(data.threadData, { markTitleGenerated: true });
1748
1712
  }
1749
1713
  // Also skip title generation if thread already has a title
1750
1714
  if (data.title) {
@@ -1784,7 +1748,6 @@ const AssistantChatInner = forwardRef(function AssistantChatInner({ emptyStateTe
1784
1748
  threadRuntime,
1785
1749
  importThreadData,
1786
1750
  reconnectActiveRunForThread,
1787
- cachedThreadData,
1788
1751
  ]);
1789
1752
  // If assistant-ui stops the local runtime while the background server run is
1790
1753
  // still alive, immediately switch into the same reconnect path used after a