@agent-native/core 0.14.5 → 0.14.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/engine/builder-engine.d.ts.map +1 -1
- package/dist/agent/engine/builder-engine.js +54 -0
- package/dist/agent/engine/builder-engine.js.map +1 -1
- package/dist/agent/thread-data-builder.d.ts +11 -1
- package/dist/agent/thread-data-builder.d.ts.map +1 -1
- package/dist/agent/thread-data-builder.js +120 -48
- package/dist/agent/thread-data-builder.js.map +1 -1
- package/dist/chat-threads/store.d.ts +6 -1
- package/dist/chat-threads/store.d.ts.map +1 -1
- package/dist/chat-threads/store.js +109 -40
- package/dist/chat-threads/store.js.map +1 -1
- package/dist/client/AgentPanel.d.ts.map +1 -1
- package/dist/client/AgentPanel.js +8 -1
- package/dist/client/AgentPanel.js.map +1 -1
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +110 -5
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/error-format.d.ts.map +1 -1
- package/dist/client/error-format.js +7 -1
- package/dist/client/error-format.js.map +1 -1
- package/dist/client/extensions/ExtensionsSidebarSection.d.ts.map +1 -1
- package/dist/client/extensions/ExtensionsSidebarSection.js +2 -2
- package/dist/client/extensions/ExtensionsSidebarSection.js.map +1 -1
- package/dist/mcp-client/manager.d.ts.map +1 -1
- package/dist/mcp-client/manager.js +10 -0
- package/dist/mcp-client/manager.js.map +1 -1
- package/dist/server/onboarding-html.d.ts.map +1 -1
- package/dist/server/onboarding-html.js +6 -0
- package/dist/server/onboarding-html.js.map +1 -1
- package/dist/server/sentry.d.ts.map +1 -1
- package/dist/server/sentry.js +20 -0
- package/dist/server/sentry.js.map +1 -1
- package/package.json +1 -1
|
@@ -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;AAU7E,eAAO,MAAM,qBAAqB,qBAAoC,CAAC;
|
|
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;AA4jBvE,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACpC,WAAW,CAEb"}
|
|
@@ -430,6 +430,22 @@ async function* parseJsonlStream(reader, model, captureContext = {}) {
|
|
|
430
430
|
event.code ??
|
|
431
431
|
(!explicitErrMsg ? "builder_gateway_error" : undefined);
|
|
432
432
|
console.error(`[builder-engine] stop reason=error model=${model} code=${errCode ?? "(none)"} error=${errMsg}`);
|
|
433
|
+
// No-detail gateway errors are opaque to the chat client — the
|
|
434
|
+
// only way to debug them is from the gateway side. Capture rich
|
|
435
|
+
// tags here (model, gatewayOrigin, requestId) so the gateway
|
|
436
|
+
// team can search Sentry by requestId or filter by model. The
|
|
437
|
+
// downstream run-manager will also capture the EngineError once
|
|
438
|
+
// it's thrown, but without these tags.
|
|
439
|
+
if (!explicitErrMsg) {
|
|
440
|
+
captureBuilderGatewayNoDetailError({
|
|
441
|
+
requestId: typeof event.requestId === "string"
|
|
442
|
+
? event.requestId
|
|
443
|
+
: undefined,
|
|
444
|
+
model,
|
|
445
|
+
gatewayUrl: captureContext.gatewayUrl,
|
|
446
|
+
rawEvent: event,
|
|
447
|
+
});
|
|
448
|
+
}
|
|
433
449
|
yield {
|
|
434
450
|
type: "stop",
|
|
435
451
|
reason: "error",
|
|
@@ -655,4 +671,42 @@ function captureBuilderGatewayTransportError(err, context) {
|
|
|
655
671
|
},
|
|
656
672
|
});
|
|
657
673
|
}
|
|
674
|
+
/**
|
|
675
|
+
* Capture a Builder-gateway no-detail stop event to Sentry with the request
|
|
676
|
+
* context the run-manager doesn't have. The gateway emits
|
|
677
|
+
* `{type:"stop",reason:"error",requestId:"..."}` with no diagnostic — the
|
|
678
|
+
* only way to debug it is from the gateway side, so we surface model,
|
|
679
|
+
* gatewayOrigin, and requestId as searchable tags.
|
|
680
|
+
*/
|
|
681
|
+
function captureBuilderGatewayNoDetailError(context) {
|
|
682
|
+
const err = new Error(context.requestId
|
|
683
|
+
? `Builder gateway stop reason=error with no detail (requestId=${context.requestId})`
|
|
684
|
+
: "Builder gateway stop reason=error with no detail");
|
|
685
|
+
err.name = "BuilderGatewayNoDetailError";
|
|
686
|
+
captureError(err, {
|
|
687
|
+
route: "/_agent-native/agent-chat",
|
|
688
|
+
tags: {
|
|
689
|
+
source: "builder-engine",
|
|
690
|
+
phase: "stream",
|
|
691
|
+
model: context.model,
|
|
692
|
+
errorCode: "builder_gateway_error",
|
|
693
|
+
...(context.requestId ? { gatewayRequestId: context.requestId } : {}),
|
|
694
|
+
},
|
|
695
|
+
extra: {
|
|
696
|
+
gatewayOrigin: context.gatewayUrl?.origin,
|
|
697
|
+
gatewayPath: context.gatewayUrl?.pathname,
|
|
698
|
+
rawEvent: context.rawEvent,
|
|
699
|
+
},
|
|
700
|
+
contexts: {
|
|
701
|
+
builderGateway: {
|
|
702
|
+
phase: "stream",
|
|
703
|
+
model: context.model,
|
|
704
|
+
gatewayOrigin: context.gatewayUrl?.origin,
|
|
705
|
+
gatewayPath: context.gatewayUrl?.pathname,
|
|
706
|
+
requestId: context.requestId,
|
|
707
|
+
errorCode: "builder_gateway_error",
|
|
708
|
+
},
|
|
709
|
+
},
|
|
710
|
+
});
|
|
711
|
+
}
|
|
658
712
|
//# sourceMappingURL=builder-engine.js.map
|
|
@@ -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,6EAA6E;AAC7E,4EAA4E;AAC5E,4EAA4E;AAC5E,0EAA0E;AAC1E,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;;;;;;;;;;;;;;GAcG;AACH,SAAS,kBAAkB,CAAC,YAAoB;IAC9C,IAAI,YAAY,GAAG,IAAI;Q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,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\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(/ /gi, \" \")\n .replace(/</gi, \"<\")\n .replace(/>/gi, \">\")\n .replace(/&/gi, \"&\")\n .replace(/"/gi, '\"')\n .replace(/'/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,6EAA6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c,EAAE;gBACd,KAAK,EAAE,QAAQ;gBACf,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,SAAS,EAAE,uBAAuB;aACnC;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 // No-detail gateway errors are opaque to the chat client — the\n // only way to debug them is from the gateway side. Capture rich\n // tags here (model, gatewayOrigin, requestId) so the gateway\n // team can search Sentry by requestId or filter by model. The\n // downstream run-manager will also capture the EngineError once\n // it's thrown, but without these tags.\n if (!explicitErrMsg) {\n captureBuilderGatewayNoDetailError({\n requestId:\n typeof event.requestId === \"string\"\n ? event.requestId\n : undefined,\n model,\n gatewayUrl: captureContext.gatewayUrl,\n rawEvent: event,\n });\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(/ /gi, \" \")\n .replace(/</gi, \"<\")\n .replace(/>/gi, \">\")\n .replace(/&/gi, \"&\")\n .replace(/"/gi, '\"')\n .replace(/'/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\n/**\n * Capture a Builder-gateway no-detail stop event to Sentry with the request\n * context the run-manager doesn't have. The gateway emits\n * `{type:\"stop\",reason:\"error\",requestId:\"...\"}` with no diagnostic — the\n * only way to debug it is from the gateway side, so we surface model,\n * gatewayOrigin, and requestId as searchable tags.\n */\nfunction captureBuilderGatewayNoDetailError(context: {\n requestId?: string;\n model: string;\n gatewayUrl?: URL;\n rawEvent: unknown;\n}): void {\n const err = new Error(\n context.requestId\n ? `Builder gateway stop reason=error with no detail (requestId=${context.requestId})`\n : \"Builder gateway stop reason=error with no detail\",\n );\n err.name = \"BuilderGatewayNoDetailError\";\n captureError(err, {\n route: \"/_agent-native/agent-chat\",\n tags: {\n source: \"builder-engine\",\n phase: \"stream\",\n model: context.model,\n errorCode: \"builder_gateway_error\",\n ...(context.requestId ? { gatewayRequestId: context.requestId } : {}),\n },\n extra: {\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n rawEvent: context.rawEvent,\n },\n contexts: {\n builderGateway: {\n phase: \"stream\",\n model: context.model,\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n requestId: context.requestId,\n errorCode: \"builder_gateway_error\",\n },\n },\n });\n}\n"]}
|
|
@@ -32,6 +32,12 @@ export declare function buildAssistantMessage(events: RunEvent[], runId?: string
|
|
|
32
32
|
};
|
|
33
33
|
metadata: Record<string, unknown>;
|
|
34
34
|
} | null;
|
|
35
|
+
/**
|
|
36
|
+
* Convert legacy/partially merged thread data into assistant-ui's exported
|
|
37
|
+
* repository shape and repair parent links so `threadRuntime.import()` cannot
|
|
38
|
+
* fail with "Parent message not found".
|
|
39
|
+
*/
|
|
40
|
+
export declare function normalizeThreadRepository(repo: any): any;
|
|
35
41
|
/**
|
|
36
42
|
* Merge an incoming client-side full-thread save over the current SQL copy.
|
|
37
43
|
*
|
|
@@ -41,7 +47,11 @@ export declare function buildAssistantMessage(events: RunEvent[], runId?: string
|
|
|
41
47
|
* reconstructed from run events. Preserve server-only messages while still
|
|
42
48
|
* accepting client-only messages and metadata.
|
|
43
49
|
*/
|
|
44
|
-
export
|
|
50
|
+
export interface MergeThreadDataOptions {
|
|
51
|
+
preserveExistingQueuedMessages?: boolean;
|
|
52
|
+
preserveExistingTopLevelKeys?: boolean;
|
|
53
|
+
}
|
|
54
|
+
export declare function mergeThreadDataForClientSave(existingRepo: any, incomingRepo: any, options?: MergeThreadDataOptions): any;
|
|
45
55
|
export declare function buildUserMessage(opts: {
|
|
46
56
|
text: string;
|
|
47
57
|
attachments?: AgentChatAttachment[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-data-builder.d.ts","sourceRoot":"","sources":["../../src/agent/thread-data-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEhE,UAAU,WAAW;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,UAAU,4BAA4B;IACpC,4BAA4B,CAAC,EAAE,OAAO,CAAC;CACxC;AAED,KAAK,gBAAgB,GAAG,WAAW,CAAC,UAAU,CAAC,OAAO,qBAAqB,CAAC,CAAC,CAAC;AAC9E,KAAK,WAAW,GAAG,UAAU,CAAC,OAAO,gBAAgB,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"thread-data-builder.d.ts","sourceRoot":"","sources":["../../src/agent/thread-data-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEhE,UAAU,WAAW;IAC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C1C,YAAY,EAAE,GAAG,EACjB,YAAY,EAAE,GAAG,EACjB,OAAO,GAAE,sBAA2B,OAkFrC;AAqFD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE;IACrC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,mBAAmB,EAAE,CAAC;IACpC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,IAAI,CAAC;CAClB,GAAG;IACF,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,IAAI,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,WAAW,EAAE,CAAC;IACvB,WAAW,CAAC,EAAE,GAAG,EAAE,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC,CAcA;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,WAAW,GAAG,GAAG,CAetE;AA+BD;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,GAAG,EACT,YAAY,EAAE,gBAAgB,GAC7B,GAAG,CA0BL;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,GAAG,GAAG;IAC5C,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CACjB,CAyBA"}
|
|
@@ -2,8 +2,9 @@ const MAX_STORED_ATTACHMENT_CHARS = 60_000;
|
|
|
2
2
|
function isInternalContinuationError(event) {
|
|
3
3
|
const code = String(event.errorCode ?? "").toLowerCase();
|
|
4
4
|
const msg = event.error.toLowerCase();
|
|
5
|
+
if (code === "builder_gateway_error")
|
|
6
|
+
return false;
|
|
5
7
|
return (event.recoverable === true ||
|
|
6
|
-
code === "builder_gateway_error" ||
|
|
7
8
|
code === "builder_gateway_timeout" ||
|
|
8
9
|
code === "stale_run" ||
|
|
9
10
|
code === "timeout" ||
|
|
@@ -18,7 +19,6 @@ function isInternalContinuationError(event) {
|
|
|
18
19
|
code === "too_many_concurrent_requests" ||
|
|
19
20
|
code === "overloaded_error" ||
|
|
20
21
|
msg.includes("timeout") ||
|
|
21
|
-
msg.includes("gateway error") ||
|
|
22
22
|
msg.includes("gateway timeout") ||
|
|
23
23
|
msg.includes("inactivity timeout") ||
|
|
24
24
|
msg.includes("stream ended") ||
|
|
@@ -143,6 +143,19 @@ export function buildAssistantMessage(events, runId, options = {}) {
|
|
|
143
143
|
function getStoredMessage(entry) {
|
|
144
144
|
return entry?.message ?? entry;
|
|
145
145
|
}
|
|
146
|
+
function getStoredParentId(entry) {
|
|
147
|
+
return typeof entry?.parentId === "string" || entry?.parentId === null
|
|
148
|
+
? entry.parentId
|
|
149
|
+
: undefined;
|
|
150
|
+
}
|
|
151
|
+
function getStoredRunConfig(entry) {
|
|
152
|
+
return entry && typeof entry === "object" && "runConfig" in entry
|
|
153
|
+
? entry.runConfig
|
|
154
|
+
: undefined;
|
|
155
|
+
}
|
|
156
|
+
function messageId(message) {
|
|
157
|
+
return typeof message?.id === "string" && message.id ? message.id : undefined;
|
|
158
|
+
}
|
|
146
159
|
function getMessageRunId(message) {
|
|
147
160
|
const meta = message?.metadata;
|
|
148
161
|
const direct = meta?.runId;
|
|
@@ -242,25 +255,92 @@ function chooseMergedMessageEntry(existingEntry, incomingEntry) {
|
|
|
242
255
|
}
|
|
243
256
|
return incomingEntry;
|
|
244
257
|
}
|
|
258
|
+
function normalizeMessageEntry(entry, parentId) {
|
|
259
|
+
const message = getStoredMessage(entry);
|
|
260
|
+
if (!messageId(message))
|
|
261
|
+
return null;
|
|
262
|
+
const runConfig = getStoredRunConfig(entry);
|
|
263
|
+
return {
|
|
264
|
+
message,
|
|
265
|
+
parentId,
|
|
266
|
+
...(runConfig !== undefined ? { runConfig } : {}),
|
|
267
|
+
};
|
|
268
|
+
}
|
|
245
269
|
/**
|
|
246
|
-
*
|
|
247
|
-
*
|
|
248
|
-
*
|
|
249
|
-
* completion save lands first, an older browser export can otherwise replace
|
|
250
|
-
* `thread_data` wholesale and delete the assistant message the server just
|
|
251
|
-
* reconstructed from run events. Preserve server-only messages while still
|
|
252
|
-
* accepting client-only messages and metadata.
|
|
270
|
+
* Convert legacy/partially merged thread data into assistant-ui's exported
|
|
271
|
+
* repository shape and repair parent links so `threadRuntime.import()` cannot
|
|
272
|
+
* fail with "Parent message not found".
|
|
253
273
|
*/
|
|
254
|
-
export function
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
274
|
+
export function normalizeThreadRepository(repo) {
|
|
275
|
+
const normalized = repo && typeof repo === "object" ? { ...repo } : {};
|
|
276
|
+
const sourceMessages = Array.isArray(repo?.messages) ? repo.messages : [];
|
|
277
|
+
const messages = [];
|
|
278
|
+
const seenIds = new Set();
|
|
279
|
+
let previousId = null;
|
|
280
|
+
for (const entry of sourceMessages) {
|
|
281
|
+
const message = getStoredMessage(entry);
|
|
282
|
+
const id = messageId(message);
|
|
283
|
+
if (!id)
|
|
284
|
+
continue;
|
|
285
|
+
const requestedParentId = getStoredParentId(entry);
|
|
286
|
+
const parentId = requestedParentId === null
|
|
287
|
+
? null
|
|
288
|
+
: requestedParentId && seenIds.has(requestedParentId)
|
|
289
|
+
? requestedParentId
|
|
290
|
+
: previousId;
|
|
291
|
+
const normalizedEntry = normalizeMessageEntry(entry, parentId);
|
|
292
|
+
if (!normalizedEntry)
|
|
293
|
+
continue;
|
|
294
|
+
messages.push(normalizedEntry);
|
|
295
|
+
seenIds.add(id);
|
|
296
|
+
previousId = id;
|
|
297
|
+
}
|
|
298
|
+
normalized.messages = messages;
|
|
299
|
+
const headId = typeof repo?.headId === "string" ? repo.headId : undefined;
|
|
300
|
+
normalized.headId =
|
|
301
|
+
headId && seenIds.has(headId) ? headId : (previousId ?? null);
|
|
302
|
+
return normalized;
|
|
303
|
+
}
|
|
304
|
+
function rewriteEntryParentId(entry, idRewrites) {
|
|
305
|
+
const parentId = getStoredParentId(entry);
|
|
306
|
+
if (!parentId)
|
|
307
|
+
return entry;
|
|
308
|
+
const rewritten = idRewrites.get(parentId);
|
|
309
|
+
if (!rewritten)
|
|
310
|
+
return entry;
|
|
311
|
+
return { ...entry, parentId: rewritten };
|
|
312
|
+
}
|
|
313
|
+
export function mergeThreadDataForClientSave(existingRepo, incomingRepo, options = {}) {
|
|
314
|
+
const preserveExistingQueuedMessages = options.preserveExistingQueuedMessages ?? true;
|
|
315
|
+
const preserveExistingTopLevelKeys = options.preserveExistingTopLevelKeys ?? true;
|
|
316
|
+
const existingNormalized = normalizeThreadRepository(existingRepo);
|
|
317
|
+
const incomingNormalized = normalizeThreadRepository(incomingRepo);
|
|
318
|
+
const merged = incomingNormalized && typeof incomingNormalized === "object"
|
|
319
|
+
? { ...incomingNormalized }
|
|
320
|
+
: {};
|
|
321
|
+
if (preserveExistingTopLevelKeys &&
|
|
322
|
+
existingNormalized &&
|
|
323
|
+
typeof existingNormalized === "object") {
|
|
324
|
+
for (const [key, value] of Object.entries(existingNormalized)) {
|
|
325
|
+
if (key === "messages" || key === "headId")
|
|
326
|
+
continue;
|
|
327
|
+
if (key === "queuedMessages" && !preserveExistingQueuedMessages) {
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
if (!(key in merged)) {
|
|
331
|
+
merged[key] = value;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
else if (preserveExistingQueuedMessages &&
|
|
336
|
+
existingNormalized &&
|
|
337
|
+
typeof existingNormalized === "object" &&
|
|
338
|
+
existingNormalized.queuedMessages !== undefined &&
|
|
259
339
|
merged.queuedMessages === undefined) {
|
|
260
|
-
merged.queuedMessages =
|
|
340
|
+
merged.queuedMessages = existingNormalized.queuedMessages;
|
|
261
341
|
}
|
|
262
|
-
const existingMessages = Array.isArray(
|
|
263
|
-
?
|
|
342
|
+
const existingMessages = Array.isArray(existingNormalized?.messages)
|
|
343
|
+
? existingNormalized.messages
|
|
264
344
|
: null;
|
|
265
345
|
const incomingMessages = Array.isArray(merged.messages)
|
|
266
346
|
? merged.messages
|
|
@@ -270,6 +350,7 @@ export function mergeThreadDataForClientSave(existingRepo, incomingRepo) {
|
|
|
270
350
|
const incomingKeySets = incomingMessages.map((entry) => new Set(messageIdentityKeys(getStoredMessage(entry))));
|
|
271
351
|
const usedIncoming = new Set();
|
|
272
352
|
const nextMessages = [];
|
|
353
|
+
const idRewrites = new Map();
|
|
273
354
|
for (const existingEntry of existingMessages) {
|
|
274
355
|
const existingKeys = messageIdentityKeys(getStoredMessage(existingEntry));
|
|
275
356
|
const incomingIndex = incomingKeySets.findIndex((keys, index) => !usedIncoming.has(index) && existingKeys.some((key) => keys.has(key)));
|
|
@@ -278,14 +359,21 @@ export function mergeThreadDataForClientSave(existingRepo, incomingRepo) {
|
|
|
278
359
|
continue;
|
|
279
360
|
}
|
|
280
361
|
usedIncoming.add(incomingIndex);
|
|
281
|
-
|
|
362
|
+
const incomingEntry = incomingMessages[incomingIndex];
|
|
363
|
+
const chosen = chooseMergedMessageEntry(existingEntry, incomingEntry);
|
|
364
|
+
const existingId = messageId(getStoredMessage(existingEntry));
|
|
365
|
+
const chosenId = messageId(getStoredMessage(chosen));
|
|
366
|
+
if (existingId && chosenId && existingId !== chosenId) {
|
|
367
|
+
idRewrites.set(existingId, chosenId);
|
|
368
|
+
}
|
|
369
|
+
nextMessages.push(chosen);
|
|
282
370
|
}
|
|
283
371
|
for (let index = 0; index < incomingMessages.length; index++) {
|
|
284
372
|
if (!usedIncoming.has(index))
|
|
285
373
|
nextMessages.push(incomingMessages[index]);
|
|
286
374
|
}
|
|
287
|
-
merged.messages = nextMessages;
|
|
288
|
-
return merged;
|
|
375
|
+
merged.messages = nextMessages.map((entry) => rewriteEntryParentId(entry, idRewrites));
|
|
376
|
+
return normalizeThreadRepository(merged);
|
|
289
377
|
}
|
|
290
378
|
function escapeAttachmentAttribute(value) {
|
|
291
379
|
return value.replace(/&/g, "&").replace(/"/g, """);
|
|
@@ -374,23 +462,16 @@ export function buildUserMessage(opts) {
|
|
|
374
462
|
};
|
|
375
463
|
}
|
|
376
464
|
export function upsertUserMessage(repo, userMsg) {
|
|
377
|
-
const nextRepo = repo
|
|
378
|
-
if (!Array.isArray(nextRepo.messages))
|
|
379
|
-
nextRepo.messages = [];
|
|
465
|
+
const nextRepo = normalizeThreadRepository(repo);
|
|
380
466
|
const lastIndex = nextRepo.messages.length - 1;
|
|
381
467
|
const lastEntry = lastIndex >= 0 ? nextRepo.messages[lastIndex] : undefined;
|
|
382
468
|
const lastMsg = getStoredMessage(lastEntry);
|
|
383
469
|
if (lastMsg?.role === "user" && messagesMatch(lastMsg, userMsg)) {
|
|
384
470
|
return nextRepo;
|
|
385
471
|
}
|
|
386
|
-
const
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
nextRepo.messages.push({ message: userMsg, parentId });
|
|
390
|
-
}
|
|
391
|
-
else {
|
|
392
|
-
nextRepo.messages.push(userMsg);
|
|
393
|
-
}
|
|
472
|
+
const parentId = lastIndex >= 0 ? (messageId(getStoredMessage(lastEntry)) ?? null) : null;
|
|
473
|
+
nextRepo.messages.push({ message: userMsg, parentId });
|
|
474
|
+
nextRepo.headId = userMsg.id;
|
|
394
475
|
return nextRepo;
|
|
395
476
|
}
|
|
396
477
|
function shouldReplaceLastAssistant(lastMessage, assistantMsg) {
|
|
@@ -431,31 +512,22 @@ function shouldReplaceLastAssistant(lastMessage, assistantMsg) {
|
|
|
431
512
|
* turn.
|
|
432
513
|
*/
|
|
433
514
|
export function upsertAssistantMessage(repo, assistantMsg) {
|
|
434
|
-
const nextRepo = repo
|
|
435
|
-
if (!Array.isArray(nextRepo.messages))
|
|
436
|
-
nextRepo.messages = [];
|
|
515
|
+
const nextRepo = normalizeThreadRepository(repo);
|
|
437
516
|
const lastIndex = nextRepo.messages.length - 1;
|
|
438
517
|
const lastEntry = lastIndex >= 0 ? nextRepo.messages[lastIndex] : undefined;
|
|
439
518
|
const lastMsg = getStoredMessage(lastEntry);
|
|
440
519
|
const lastRole = lastMsg?.role;
|
|
441
|
-
const isWrapped = Boolean(lastEntry && "message" in lastEntry);
|
|
442
520
|
if (lastRole === "assistant" &&
|
|
443
521
|
shouldReplaceLastAssistant(lastMsg, assistantMsg)) {
|
|
444
|
-
nextRepo.messages[lastIndex] =
|
|
445
|
-
|
|
446
|
-
: assistantMsg;
|
|
522
|
+
nextRepo.messages[lastIndex] = { ...lastEntry, message: assistantMsg };
|
|
523
|
+
nextRepo.headId = assistantMsg.id;
|
|
447
524
|
return nextRepo;
|
|
448
525
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
nextRepo.messages.push({ message: assistantMsg, parentId });
|
|
455
|
-
}
|
|
456
|
-
else {
|
|
457
|
-
nextRepo.messages.push(assistantMsg);
|
|
458
|
-
}
|
|
526
|
+
const parentId = nextRepo.messages.length > 0
|
|
527
|
+
? (messageId(getStoredMessage(nextRepo.messages[nextRepo.messages.length - 1])) ?? null)
|
|
528
|
+
: null;
|
|
529
|
+
nextRepo.messages.push({ message: assistantMsg, parentId });
|
|
530
|
+
nextRepo.headId = assistantMsg.id;
|
|
459
531
|
return nextRepo;
|
|
460
532
|
}
|
|
461
533
|
/**
|