@agent-native/core 0.7.64 → 0.7.66
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/a2a/handlers.d.ts.map +1 -1
- package/dist/a2a/handlers.js +18 -8
- package/dist/a2a/handlers.js.map +1 -1
- package/dist/a2a/task-store.d.ts +1 -0
- package/dist/a2a/task-store.d.ts.map +1 -1
- package/dist/a2a/task-store.js +23 -0
- package/dist/a2a/task-store.js.map +1 -1
- package/dist/agent/engine/builder-engine.d.ts.map +1 -1
- package/dist/agent/engine/builder-engine.js +108 -49
- package/dist/agent/engine/builder-engine.js.map +1 -1
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +6 -0
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/integrations/a2a-continuation-processor.d.ts.map +1 -1
- package/dist/integrations/a2a-continuation-processor.js +9 -13
- package/dist/integrations/a2a-continuation-processor.js.map +1 -1
- package/dist/integrations/a2a-continuations-store.d.ts +1 -0
- package/dist/integrations/a2a-continuations-store.d.ts.map +1 -1
- package/dist/integrations/a2a-continuations-store.js +13 -0
- package/dist/integrations/a2a-continuations-store.js.map +1 -1
- package/dist/integrations/webhook-handler.d.ts.map +1 -1
- package/dist/integrations/webhook-handler.js +6 -0
- package/dist/integrations/webhook-handler.js.map +1 -1
- package/dist/scripts/call-agent.d.ts.map +1 -1
- package/dist/scripts/call-agent.js +17 -2
- package/dist/scripts/call-agent.js.map +1 -1
- package/dist/templates/workspace-core/src/server/index.ts +6 -2
- package/package.json +1 -1
- package/src/templates/workspace-core/src/server/index.ts +6 -2
|
@@ -43,6 +43,8 @@ export const BUILDER_SUPPORTED_MODELS = [
|
|
|
43
43
|
"z-ai-glm-4-5",
|
|
44
44
|
"z-ai-glm-5-1",
|
|
45
45
|
];
|
|
46
|
+
const DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;
|
|
47
|
+
const MAX_BUILDER_GATEWAY_TIMEOUT_MS = 55_000;
|
|
46
48
|
// Inherits from agent/default-model.ts — single source of truth so a
|
|
47
49
|
// new model release is a one-line bump.
|
|
48
50
|
import { DEFAULT_MODEL } from "../default-model.js";
|
|
@@ -120,52 +122,58 @@ class BuilderEngine {
|
|
|
120
122
|
const orgLabel = (await resolveBuilderCredential("BUILDER_ORG_NAME")) || "unknown-org";
|
|
121
123
|
const tStart = Date.now();
|
|
122
124
|
console.log(`[builder-engine] → POST ${gatewayBaseUrl}/messages model=${opts.model} tools=${tools.length} org=${orgLabel}`);
|
|
123
|
-
|
|
125
|
+
const gatewayTimeoutMs = getBuilderGatewayTimeoutMs();
|
|
126
|
+
const gatewayAbort = createGatewayAbortSignal(opts.abortSignal, gatewayTimeoutMs);
|
|
124
127
|
try {
|
|
125
|
-
response
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
128
|
+
let response;
|
|
129
|
+
try {
|
|
130
|
+
response = await fetch(`${gatewayBaseUrl}/messages`, {
|
|
131
|
+
method: "POST",
|
|
132
|
+
headers: {
|
|
133
|
+
"Content-Type": "application/json",
|
|
134
|
+
Authorization: authHeader,
|
|
135
|
+
},
|
|
136
|
+
body: JSON.stringify(body),
|
|
137
|
+
signal: gatewayAbort.signal,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
catch (err) {
|
|
141
|
+
if (gatewayAbort.didTimeout()) {
|
|
142
|
+
console.warn(`[builder-engine] gateway timed out after ${Date.now() - tStart}ms`);
|
|
143
|
+
}
|
|
144
|
+
yield createBuilderGatewayTimeoutStop(err, gatewayAbort.didTimeout(), gatewayTimeoutMs);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
console.log(`[builder-engine] ← ${response.status} ${response.statusText} in ${Date.now() - tStart}ms`);
|
|
148
|
+
if (!response.ok) {
|
|
149
|
+
yield* emitHttpError(response);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
153
|
+
if (contentType.includes("text/html")) {
|
|
154
|
+
const rawText = await response.text().catch(() => "");
|
|
155
|
+
yield {
|
|
156
|
+
type: "stop",
|
|
157
|
+
reason: "error",
|
|
158
|
+
error: normalizeGatewayErrorText(rawText, response.status || 502),
|
|
159
|
+
errorCode: `http_${response.status || 502}`,
|
|
160
|
+
};
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const reader = response.body?.getReader();
|
|
164
|
+
if (!reader) {
|
|
165
|
+
yield {
|
|
166
|
+
type: "stop",
|
|
167
|
+
reason: "error",
|
|
168
|
+
error: "Builder gateway response has no body",
|
|
169
|
+
};
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
yield* parseJsonlStream(reader, opts.model, gatewayAbort.didTimeout, gatewayTimeoutMs);
|
|
158
173
|
}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
yield {
|
|
162
|
-
type: "stop",
|
|
163
|
-
reason: "error",
|
|
164
|
-
error: "Builder gateway response has no body",
|
|
165
|
-
};
|
|
166
|
-
return;
|
|
174
|
+
finally {
|
|
175
|
+
gatewayAbort.cleanup();
|
|
167
176
|
}
|
|
168
|
-
yield* parseJsonlStream(reader, opts.model);
|
|
169
177
|
}
|
|
170
178
|
}
|
|
171
179
|
async function* emitHttpError(response) {
|
|
@@ -269,7 +277,7 @@ async function* readJsonlLines(reader) {
|
|
|
269
277
|
if (tail)
|
|
270
278
|
yield tail;
|
|
271
279
|
}
|
|
272
|
-
async function* parseJsonlStream(reader, model) {
|
|
280
|
+
async function* parseJsonlStream(reader, model, didGatewayTimeout, gatewayTimeoutMs = DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS) {
|
|
273
281
|
const parts = [];
|
|
274
282
|
let pendingText = "";
|
|
275
283
|
let pendingThinking = null;
|
|
@@ -422,11 +430,7 @@ async function* parseJsonlStream(reader, model) {
|
|
|
422
430
|
};
|
|
423
431
|
}
|
|
424
432
|
catch (err) {
|
|
425
|
-
yield
|
|
426
|
-
type: "stop",
|
|
427
|
-
reason: "error",
|
|
428
|
-
error: err instanceof Error ? err.message : String(err),
|
|
429
|
-
};
|
|
433
|
+
yield createBuilderGatewayTimeoutStop(err, didGatewayTimeout?.() ?? false, gatewayTimeoutMs);
|
|
430
434
|
}
|
|
431
435
|
finally {
|
|
432
436
|
// Release the reader on every exit path — early returns (invalid JSONL,
|
|
@@ -473,4 +477,59 @@ function htmlToText(html) {
|
|
|
473
477
|
export function createBuilderEngine(_config = {}) {
|
|
474
478
|
return new BuilderEngine();
|
|
475
479
|
}
|
|
480
|
+
function getBuilderGatewayTimeoutMs() {
|
|
481
|
+
const raw = process.env.AGENT_NATIVE_BUILDER_GATEWAY_TIMEOUT_MS;
|
|
482
|
+
if (!raw)
|
|
483
|
+
return DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;
|
|
484
|
+
const parsed = Number(raw);
|
|
485
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
486
|
+
return DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;
|
|
487
|
+
}
|
|
488
|
+
return Math.min(parsed, MAX_BUILDER_GATEWAY_TIMEOUT_MS);
|
|
489
|
+
}
|
|
490
|
+
function createGatewayAbortSignal(parentSignal, timeoutMs) {
|
|
491
|
+
const controller = new AbortController();
|
|
492
|
+
let timedOut = false;
|
|
493
|
+
const abortFromParent = () => {
|
|
494
|
+
if (!controller.signal.aborted) {
|
|
495
|
+
controller.abort(parentSignal.reason);
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
const timeout = setTimeout(() => {
|
|
499
|
+
timedOut = true;
|
|
500
|
+
if (!controller.signal.aborted) {
|
|
501
|
+
controller.abort(new Error("Builder gateway request timed out"));
|
|
502
|
+
}
|
|
503
|
+
}, timeoutMs);
|
|
504
|
+
if (parentSignal.aborted)
|
|
505
|
+
abortFromParent();
|
|
506
|
+
parentSignal.addEventListener("abort", abortFromParent, { once: true });
|
|
507
|
+
return {
|
|
508
|
+
signal: controller.signal,
|
|
509
|
+
didTimeout: () => timedOut,
|
|
510
|
+
cleanup: () => {
|
|
511
|
+
clearTimeout(timeout);
|
|
512
|
+
parentSignal.removeEventListener("abort", abortFromParent);
|
|
513
|
+
},
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
function normalizeBuilderGatewayFetchError(err, timedOut, timeoutMs) {
|
|
517
|
+
if (timedOut) {
|
|
518
|
+
return `Builder gateway timed out after ${formatTimeoutMs(timeoutMs)} before the hosting function limit. Please retry; if this keeps happening, reduce the prompt size or try again when the gateway is less busy.`;
|
|
519
|
+
}
|
|
520
|
+
return err instanceof Error ? err.message : String(err);
|
|
521
|
+
}
|
|
522
|
+
function createBuilderGatewayTimeoutStop(err, timedOut, timeoutMs) {
|
|
523
|
+
return {
|
|
524
|
+
type: "stop",
|
|
525
|
+
reason: "error",
|
|
526
|
+
error: normalizeBuilderGatewayFetchError(err, timedOut, timeoutMs),
|
|
527
|
+
...(timedOut ? { errorCode: "builder_gateway_timeout" } : {}),
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
function formatTimeoutMs(timeoutMs) {
|
|
531
|
+
if (timeoutMs < 1000)
|
|
532
|
+
return `${timeoutMs}ms`;
|
|
533
|
+
return `${Math.round(timeoutMs / 1000)}s`;
|
|
534
|
+
}
|
|
476
535
|
//# sourceMappingURL=builder-engine.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builder-engine.js","sourceRoot":"","s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,CAAC;IACzE,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,SAAS,UAAU,CAAC,IAAY;IAC9B,OAAO,IAAI;SACR,OAAO,CAAC,6BAA6B,EAAE,GAAG,CAAC;SAC3C,OAAO,CAAC,2BAA2B,EAAE,GAAG,CAAC;SACzC,OAAO,CAAC,cAAc,EAAE,IAAI,CAAC;SAC7B,OAAO,CAAC,8BAA8B,EAAE,IAAI,CAAC;SAC7C,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC;SACxB,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC;SACxB,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;SACtB,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;SACtB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC;SACxB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC;SACvB,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC;SAC1B,IAAI,EAAE,CAAC;AACZ,CAAC;AAED,MAAM,UAAU,mBAAmB,CACjC,UAAmC,EAAE;IAErC,OAAO,IAAI,aAAa,EAAE,CAAC;AAC7B,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 (set via the Builder CLI-auth\n * onboarding flow). Base URL is overridable via 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\";\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 = [\n \"claude-opus-4-7\",\n \"claude-sonnet-4-6\",\n \"claude-haiku-4-5\",\n \"gpt-5-4\",\n \"gpt-5-4-mini\",\n \"gpt-5-1-codex-mini\",\n \"gemini-3-1-pro\",\n \"gemini-3-0-flash\",\n \"gemini-3-1-flash-lite\",\n \"grok-code-fast\",\n \"qwen3-coder\",\n \"kimi-k2-5\",\n \"deepseek-v3-1\",\n \"z-ai-glm-4-5\",\n \"z-ai-glm-5-1\",\n] as const;\n\n// Inherits from agent/default-model.ts — single source of truth so a\n// new model release is a one-line bump.\nimport { DEFAULT_MODEL } from \"../default-model.js\";\nexport const BUILDER_DEFAULT_MODEL = DEFAULT_MODEL;\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 = await resolveBuilderAuthHeader();\n if (!authHeader) {\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 orgLabel =\n (await resolveBuilderCredential(\"BUILDER_ORG_NAME\")) || \"unknown-org\";\n const tStart = Date.now();\n console.log(\n `[builder-engine] → POST ${gatewayBaseUrl}/messages model=${opts.model} tools=${tools.length} org=${orgLabel}`,\n );\n\n let response: Response;\n try {\n response = await fetch(`${gatewayBaseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n },\n body: JSON.stringify(body),\n signal: opts.abortSignal,\n });\n } catch (err) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: err instanceof Error ? err.message : String(err),\n };\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 }\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:\n message ||\n \"Builder authentication failed. Reconnect Builder via Settings → LLM.\",\n errorCode: \"unauthorized\",\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): AsyncIterable<EngineEvent> {\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 // Engine contract has no equivalent; drop. The authoritative\n // `tool-call` event follows with the fully-parsed input.\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 errMsg =\n event.error ??\n event.message ??\n event.detail ??\n `Gateway error (no detail; raw event: ${JSON.stringify(event)})`;\n const errCode = event.errorCode ?? event.code;\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 yield {\n type: \"stop\",\n reason: \"error\",\n error: err instanceof Error ? err.message : String(err),\n };\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"]}
|
|
1
|
+
{"version":3,"file":"builder-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;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,g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C,eAAe,CACvD,SAAS,CACV,+IAA+I,CAAC;IACnJ,CAAC;IACD,OAAO,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1D,CAAC;AAED,SAAS,+BAA+B,CACtC,GAAY,EACZ,QAAiB,EACjB,SAAiB;IAEjB,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,MAAM,EAAE,OAAO;QACf,KAAK,EAAE,iCAAiC,CAAC,GAAG,EAAE,QAAQ,EAAE,SAAS,CAAC;QAClE,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,yBAAyB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC9D,CAAC;AACJ,CAAC;AAED,SAAS,eAAe,CAAC,SAAiB;IACxC,IAAI,SAAS,GAAG,IAAI;QAAE,OAAO,GAAG,SAAS,IAAI,CAAC;IAC9C,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC;AAC5C,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 (set via the Builder CLI-auth\n * onboarding flow). Base URL is overridable via 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\";\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 = [\n \"claude-opus-4-7\",\n \"claude-sonnet-4-6\",\n \"claude-haiku-4-5\",\n \"gpt-5-4\",\n \"gpt-5-4-mini\",\n \"gpt-5-1-codex-mini\",\n \"gemini-3-1-pro\",\n \"gemini-3-0-flash\",\n \"gemini-3-1-flash-lite\",\n \"grok-code-fast\",\n \"qwen3-coder\",\n \"kimi-k2-5\",\n \"deepseek-v3-1\",\n \"z-ai-glm-4-5\",\n \"z-ai-glm-5-1\",\n] as const;\n\nconst DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;\nconst MAX_BUILDER_GATEWAY_TIMEOUT_MS = 55_000;\n\n// Inherits from agent/default-model.ts — single source of truth so a\n// new model release is a one-line bump.\nimport { DEFAULT_MODEL } from \"../default-model.js\";\nexport const BUILDER_DEFAULT_MODEL = DEFAULT_MODEL;\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 = await resolveBuilderAuthHeader();\n if (!authHeader) {\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 orgLabel =\n (await resolveBuilderCredential(\"BUILDER_ORG_NAME\")) || \"unknown-org\";\n const tStart = Date.now();\n console.log(\n `[builder-engine] → POST ${gatewayBaseUrl}/messages 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(`${gatewayBaseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n },\n body: JSON.stringify(body),\n signal: gatewayAbort.signal,\n });\n } catch (err) {\n if (gatewayAbort.didTimeout()) {\n console.warn(\n `[builder-engine] gateway timed out after ${Date.now() - tStart}ms`,\n );\n }\n yield createBuilderGatewayTimeoutStop(\n err,\n gatewayAbort.didTimeout(),\n gatewayTimeoutMs,\n );\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(\n reader,\n opts.model,\n gatewayAbort.didTimeout,\n gatewayTimeoutMs,\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:\n message ||\n \"Builder authentication failed. Reconnect Builder via Settings → LLM.\",\n errorCode: \"unauthorized\",\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 didGatewayTimeout?: () => boolean,\n gatewayTimeoutMs = DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS,\n): AsyncIterable<EngineEvent> {\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 // Engine contract has no equivalent; drop. The authoritative\n // `tool-call` event follows with the fully-parsed input.\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 errMsg =\n event.error ??\n event.message ??\n event.detail ??\n `Gateway error (no detail; raw event: ${JSON.stringify(event)})`;\n const errCode = event.errorCode ?? event.code;\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 yield createBuilderGatewayTimeoutStop(\n err,\n didGatewayTimeout?.() ?? false,\n gatewayTimeoutMs,\n );\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 return err instanceof Error ? err.message : String(err);\n}\n\nfunction createBuilderGatewayTimeoutStop(\n err: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): EngineEvent {\n return {\n type: \"stop\",\n reason: \"error\",\n error: normalizeBuilderGatewayFetchError(err, timedOut, timeoutMs),\n ...(timedOut ? { errorCode: \"builder_gateway_timeout\" } : {}),\n };\n}\n\nfunction formatTimeoutMs(timeoutMs: number): string {\n if (timeoutMs < 1000) return `${timeoutMs}ms`;\n return `${Math.round(timeoutMs / 1000)}s`;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"production-agent.d.ts","sourceRoot":"","sources":["../../src/agent/production-agent.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,YAAY,IAAI,cAAc,EAAE,MAAM,IAAI,CAAC;AACzD,OAAO,KAAK,EACV,UAAU,EACV,mBAAmB,EAEnB,cAAc,EAEf,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,aAAa,EACb,iBAAiB,EAClB,MAAM,mBAAmB,CAAC;AAQ3B,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAEhE,OAAO,EAEL,cAAc,EACd,qBAAqB,EACrB,0BAA0B,EAC1B,MAAM,EACN,QAAQ,EACT,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAgBlD,OAAO,EAGL,KAAK,eAAe,EACrB,MAAM,+BAA+B,CAAC;AAKvC,OAAO,EAAE,eAAe,EAAE,CAAC;AAE3B;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACpC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA+B7B;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE3D;AAuBD;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,oBAAoB,CACxC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACpC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAqB7B;AAED,sEAAsE;AACtE,wBAAsB,uBAAuB,CAC3C,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACpC,OAAO,CAAC,MAAM,GAAG,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AAC;IACpB,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IACrC,IAAI,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,CAAC;IACtC,MAAM,EAAE,WAAW,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,eAAe,CAAC,EAAE,GAAG,CAAC;IACtB,aAAa,CAAC,EAAE,kBAAkB,CAAC;IACnC,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,GAAG,OAAO,CAAC,cAAc,CAAC,CA6S1B;AAED,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,sBAAsB,GAC9B,cAAc,CA4xBhB;AAED,OAAO,EACL,qBAAqB,EACrB,0BAA0B,EAC1B,MAAM,EACN,QAAQ,EACR,cAAc,GACf,CAAC"}
|
|
@@ -314,6 +314,8 @@ function isRetryableError(err) {
|
|
|
314
314
|
return false;
|
|
315
315
|
const msg = err.message.toLowerCase();
|
|
316
316
|
const code = err instanceof EngineError ? (err.errorCode ?? "").toLowerCase() : "";
|
|
317
|
+
if (code === "builder_gateway_timeout")
|
|
318
|
+
return false;
|
|
317
319
|
return (code === "http_502" ||
|
|
318
320
|
code === "http_503" ||
|
|
319
321
|
code === "http_504" ||
|
|
@@ -1278,6 +1280,10 @@ export function createProductionAgentHandler(options) {
|
|
|
1278
1280
|
responseText = await callAgent(ref.path, enrichedMessage + screenContext);
|
|
1279
1281
|
}
|
|
1280
1282
|
}
|
|
1283
|
+
responseText =
|
|
1284
|
+
userFacingLlmCredentialError(responseText, {
|
|
1285
|
+
agentName: ref.name,
|
|
1286
|
+
}) ?? responseText;
|
|
1281
1287
|
send({
|
|
1282
1288
|
type: "agent_call",
|
|
1283
1289
|
agent: ref.name,
|