@agent-native/core 0.7.18 → 0.7.19

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.
Files changed (47) hide show
  1. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  2. package/dist/agent/engine/builder-engine.js +15 -3
  3. package/dist/agent/engine/builder-engine.js.map +1 -1
  4. package/dist/agent/production-agent.js +1 -1
  5. package/dist/agent/production-agent.js.map +1 -1
  6. package/dist/cli/create.d.ts.map +1 -1
  7. package/dist/cli/create.js +13 -2
  8. package/dist/cli/create.js.map +1 -1
  9. package/dist/client/AssistantChat.d.ts.map +1 -1
  10. package/dist/client/AssistantChat.js +34 -4
  11. package/dist/client/AssistantChat.js.map +1 -1
  12. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  13. package/dist/client/MultiTabAssistantChat.js +5 -21
  14. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  15. package/dist/client/agent-chat-adapter.d.ts +10 -0
  16. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  17. package/dist/client/agent-chat-adapter.js +23 -3
  18. package/dist/client/agent-chat-adapter.js.map +1 -1
  19. package/dist/client/org/TeamPage.d.ts.map +1 -1
  20. package/dist/client/org/TeamPage.js +14 -2
  21. package/dist/client/org/TeamPage.js.map +1 -1
  22. package/dist/client/sse-event-processor.d.ts +6 -1
  23. package/dist/client/sse-event-processor.d.ts.map +1 -1
  24. package/dist/client/sse-event-processor.js +9 -3
  25. package/dist/client/sse-event-processor.js.map +1 -1
  26. package/dist/integrations/pending-tasks-retry-job.d.ts.map +1 -1
  27. package/dist/integrations/pending-tasks-retry-job.js +1 -1
  28. package/dist/integrations/pending-tasks-retry-job.js.map +1 -1
  29. package/dist/server/auth.d.ts +29 -0
  30. package/dist/server/auth.d.ts.map +1 -1
  31. package/dist/server/auth.js +32 -6
  32. package/dist/server/auth.js.map +1 -1
  33. package/dist/server/better-auth-instance.d.ts +15 -0
  34. package/dist/server/better-auth-instance.d.ts.map +1 -1
  35. package/dist/server/better-auth-instance.js +115 -0
  36. package/dist/server/better-auth-instance.js.map +1 -1
  37. package/dist/server/google-oauth.d.ts.map +1 -1
  38. package/dist/server/google-oauth.js +8 -15
  39. package/dist/server/google-oauth.js.map +1 -1
  40. package/dist/server/voice-providers-status.d.ts +7 -0
  41. package/dist/server/voice-providers-status.d.ts.map +1 -1
  42. package/dist/server/voice-providers-status.js +1 -0
  43. package/dist/server/voice-providers-status.js.map +1 -1
  44. package/dist/tools/store.d.ts.map +1 -1
  45. package/dist/tools/store.js +6 -1
  46. package/dist/tools/store.js.map +1 -1
  47. 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;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EACV,WAAW,EACX,kBAAkB,EAInB,MAAM,YAAY,CAAC;AAWpB,eAAO,MAAM,oBAAoB,EAAE,kBAUlC,CAAC;AAEF,eAAO,MAAM,wBAAwB,6PAe3B,CAAC;AAKX,eAAO,MAAM,qBAAqB,sBAAgB,CAAC;AAkZnD,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACpC,WAAW,CAEb"}
1
+ {"version":3,"file":"builder-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EACV,WAAW,EACX,kBAAkB,EAInB,MAAM,YAAY,CAAC;AAWpB,eAAO,MAAM,oBAAoB,EAAE,kBAUlC,CAAC;AAEF,eAAO,MAAM,wBAAwB,6PAe3B,CAAC;AAKX,eAAO,MAAM,qBAAqB,sBAAgB,CAAC;AAkanD,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACpC,WAAW,CAEb"}
@@ -148,7 +148,7 @@ class BuilderEngine {
148
148
  };
149
149
  return;
150
150
  }
151
- yield* parseJsonlStream(reader);
151
+ yield* parseJsonlStream(reader, opts.model);
152
152
  }
153
153
  }
154
154
  async function* emitHttpError(response) {
@@ -252,7 +252,7 @@ async function* readJsonlLines(reader) {
252
252
  if (tail)
253
253
  yield tail;
254
254
  }
255
- async function* parseJsonlStream(reader) {
255
+ async function* parseJsonlStream(reader, model) {
256
256
  const parts = [];
257
257
  let pendingText = "";
258
258
  let pendingThinking = null;
@@ -355,10 +355,22 @@ async function* parseJsonlStream(reader) {
355
355
  };
356
356
  }
357
357
  else if (reason === "error") {
358
+ // Surface every diagnostic the gateway gave us so the user (and
359
+ // our logs) get more than a bare "Gateway error". The gateway
360
+ // sometimes emits an error stop event with no message — most
361
+ // commonly when the upstream provider rejects the model for
362
+ // this account (Opus quotas have hit this in practice).
363
+ const errMsg = event.error ??
364
+ event.message ??
365
+ event.detail ??
366
+ `Gateway error (no detail; raw event: ${JSON.stringify(event)})`;
367
+ const errCode = event.errorCode ?? event.code;
368
+ console.error(`[builder-engine] stop reason=error model=${model} code=${errCode ?? "(none)"} error=${errMsg}`);
358
369
  yield {
359
370
  type: "stop",
360
371
  reason: "error",
361
- error: event.error ?? "Gateway error",
372
+ error: errMsg,
373
+ ...(errCode ? { errorCode: errCode } : {}),
362
374
  };
363
375
  }
364
376
  else if (reason === "end_turn" ||
@@ -1 +1 @@
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;AAE7C,MAAM,CAAC,MAAM,oBAAoB,GAAuB;IACtD,QAAQ,EAAE,IAAI;IACd,uEAAuE;IACvE,yEAAyE;IACzE,sE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AAM,CAAC,MAAM,EAAE,CAAC;QACxB,CAAC;QAAC,MAAM,CAAC;YACP,8BAA8B;QAChC,CAAC;IACH,CAAC;AACH,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\";\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 \"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 * three-level `reasoning_effort` enum (low / medium / high).\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): \"low\" | \"medium\" | \"high\" {\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: \"BUILDER_PRIVATE_KEY is not set\",\n errorCode: \"missing_credentials\",\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\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 ...(typeof thinkingBudget === \"number\"\n ? { reasoning_effort: mapReasoningEffort(thinkingBudget) }\n : {}),\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 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);\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 = rawText;\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): 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 yield {\n type: \"stop\",\n reason: \"error\",\n error: `Builder gateway emitted invalid JSONL: ${line}`,\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 yield {\n type: \"stop\",\n reason: \"error\",\n error: event.error ?? \"Gateway error\",\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\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":[],"mapp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AAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;oBACjC,CAAC;yBAAM,CAAC;wBACN,MAAM;4BACJ,IAAI,EAAE,MAAM;4BACZ,MAAM,EAAE,OAAO;4BACf,KAAK,EAAE,wBAAwB,MAAM,EAAE;yBACxC,CAAC;oBACJ,CAAC;oBACD,OAAO;gBACT,CAAC;gBAED;oBACE,kDAAkD;oBAClD,MAAM;YACV,CAAC;QACH,CAAC;QAED,4EAA4E;QAC5E,YAAY,EAAE,CAAC;QACf,MAAM,EAAE,IAAI,EAAE,mBAAmB,EAAE,KAAK,EAAE,CAAC;QAC3C,MAAM;YACJ,IAAI,EAAE,MAAM;YACZ,MAAM,EAAE,OAAO;YACf,KAAK,EAAE,mDAAmD;SAC3D,CAAC;IACJ,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM;YACJ,IAAI,EAAE,MAAM;YACZ,MAAM,EAAE,OAAO;YACf,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;SACxD,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,wEAAwE;QACxE,kEAAkE;QAClE,mEAAmE;QACnE,IAAI,CAAC;YACH,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC;QACxB,CAAC;QAAC,MAAM,CAAC;YACP,8BAA8B;QAChC,CAAC;IACH,CAAC;AACH,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\";\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 \"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 * three-level `reasoning_effort` enum (low / medium / high).\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): \"low\" | \"medium\" | \"high\" {\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: \"BUILDER_PRIVATE_KEY is not set\",\n errorCode: \"missing_credentials\",\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\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 ...(typeof thinkingBudget === \"number\"\n ? { reasoning_effort: mapReasoningEffort(thinkingBudget) }\n : {}),\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 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 = rawText;\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 yield {\n type: \"stop\",\n reason: \"error\",\n error: `Builder gateway emitted invalid JSONL: ${line}`,\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\nexport function createBuilderEngine(\n _config: Record<string, unknown> = {},\n): AgentEngine {\n return new BuilderEngine();\n}\n"]}
@@ -129,7 +129,7 @@ export async function getOwnerActiveApiKey(ownerEmail) {
129
129
  export async function getOwnerAnthropicApiKey(ownerEmail) {
130
130
  return getOwnerApiKey("anthropic", ownerEmail);
131
131
  }
132
- const MAX_ITERATIONS = 40;
132
+ const MAX_ITERATIONS = 100;
133
133
  const MAX_RETRIES = 3;
134
134
  const RETRY_BASE_DELAY_MS = 2000;
135
135
  function generateRunId() {