@agent-native/core 0.114.13 → 0.114.16

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 (163) hide show
  1. package/bin/agent-native.js +35 -14
  2. package/bin/launcher.js +34 -0
  3. package/corpus/README.md +2 -2
  4. package/corpus/core/CHANGELOG.md +21 -0
  5. package/corpus/core/bin/agent-native.js +35 -14
  6. package/corpus/core/bin/launcher.js +34 -0
  7. package/corpus/core/docs/content/deployment.mdx +1 -1
  8. package/corpus/core/docs/content/frames.mdx +1 -1
  9. package/corpus/core/docs/content/integrations.mdx +27 -27
  10. package/corpus/core/docs/content/pr-visual-recap.mdx +17 -13
  11. package/corpus/core/docs/content/workspace-management.mdx +1 -1
  12. package/corpus/core/package.json +2 -1
  13. package/corpus/core/src/agent/engine/builder-engine.ts +4 -0
  14. package/corpus/core/src/client/AgentPanel.tsx +10 -4
  15. package/corpus/core/src/client/ConnectBuilderCard.tsx +5 -1
  16. package/corpus/core/src/client/chat/markdown-renderer.tsx +3 -5
  17. package/corpus/core/src/client/error-format.ts +2 -1
  18. package/corpus/core/src/client/index.ts +1 -0
  19. package/corpus/core/src/client/integrations/IntegrationsPanel.tsx +2 -18
  20. package/corpus/core/src/client/resources/McpIntegrationDialog.tsx +43 -32
  21. package/corpus/core/src/client/resources/mcp-integration-catalog.ts +4 -2
  22. package/corpus/core/src/client/settings/BackgroundAgentSection.tsx +5 -1
  23. package/corpus/core/src/client/settings/SettingsPanel.tsx +4 -4
  24. package/corpus/core/src/client/settings/useBuilderStatus.ts +3 -0
  25. package/corpus/core/src/localization/default-messages.ts +1 -7
  26. package/corpus/core/src/server/builder-browser.ts +4 -0
  27. package/corpus/core/src/server/builder-design-systems.ts +6 -1
  28. package/corpus/core/src/server/fusion-app.ts +5 -1
  29. package/corpus/core/src/shared/builder-link-tracking.ts +41 -0
  30. package/corpus/core/src/shared/index.ts +1 -0
  31. package/corpus/templates/analytics/AGENTS.md +10 -1
  32. package/corpus/templates/analytics/actions/save-dashboard-report-subscription.ts +10 -2
  33. package/corpus/templates/analytics/app/components/dashboard/SqlChart.tsx +5 -4
  34. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/index.tsx +20 -32
  35. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/report-panel-window.ts +62 -0
  36. package/corpus/templates/analytics/changelog/2026-07-21-chart-series-controls-stay-open-while-moving-from-the-legend.md +6 -0
  37. package/corpus/templates/analytics/changelog/2026-07-21-dashboard-email-captures-complete-large-dashboards-in-chunks.md +6 -0
  38. package/corpus/templates/analytics/seeds/dashboards/agent-native-templates-first-party.json +4 -4
  39. package/corpus/templates/analytics/server/jobs/dashboard-report.ts +1 -8
  40. package/corpus/templates/analytics/server/lib/dashboard-report-subscriptions.ts +39 -7
  41. package/corpus/templates/analytics/server/lib/dashboard-report.ts +341 -251
  42. package/corpus/templates/analytics/server/lib/first-party-dashboard-repair.ts +114 -0
  43. package/corpus/templates/analytics/server/lib/first-party-metric-catalog.ts +84 -6
  44. package/corpus/templates/analytics/server/plugins/db.ts +13 -0
  45. package/corpus/templates/clips/app/components/library/bulk-action-toolbar.tsx +25 -8
  46. package/corpus/templates/clips/app/components/library/library-grid.tsx +118 -9
  47. package/corpus/templates/clips/app/components/library/library-layout.tsx +1 -1
  48. package/corpus/templates/clips/app/components/library/recording-card.tsx +10 -8
  49. package/corpus/templates/clips/app/components/player/video-player.tsx +10 -4
  50. package/corpus/templates/clips/app/i18n/en-US.ts +6 -0
  51. package/corpus/templates/clips/app/routes/_app.trash.tsx +16 -1
  52. package/corpus/templates/clips/changelog/2026-07-21-choose-which-whisper-model-to-use-in-settings.md +6 -0
  53. package/corpus/templates/clips/changelog/2026-07-21-fixed-organization-recording-visibility-default.md +6 -0
  54. package/corpus/templates/clips/changelog/2026-07-21-meeting-notes-stop-when-calls-end.md +6 -0
  55. package/corpus/templates/clips/desktop/src/app.tsx +90 -78
  56. package/corpus/templates/clips/desktop/src/hooks/useMeetingTranscription.ts +2 -0
  57. package/corpus/templates/clips/desktop/src/hooks/useWhisperSettings.ts +172 -0
  58. package/corpus/templates/clips/desktop/src/lib/meeting-call-app.ts +41 -0
  59. package/corpus/templates/clips/desktop/src/lib/silence-events.ts +1 -0
  60. package/corpus/templates/clips/desktop/src/shared/config.ts +1 -0
  61. package/corpus/templates/clips/desktop/src/styles.css +80 -7
  62. package/corpus/templates/clips/desktop/src-tauri/src/config.rs +32 -0
  63. package/corpus/templates/clips/desktop/src-tauri/src/lib.rs +3 -0
  64. package/corpus/templates/clips/desktop/src-tauri/src/silence_detector.rs +268 -20
  65. package/corpus/templates/clips/desktop/src-tauri/src/whisper_model.rs +285 -164
  66. package/corpus/templates/clips/desktop/src-tauri/src/whisper_speech.rs +18 -7
  67. package/corpus/templates/clips/learnings.defaults.md +1 -1
  68. package/corpus/templates/clips/server/plugins/db.ts +11 -0
  69. package/corpus/templates/clips/shared/builder-credits.ts +1 -1
  70. package/corpus/templates/content/app/components/editor/database/DatabaseView.tsx +20 -38
  71. package/corpus/templates/content/app/components/editor/previewDocumentSaveController.ts +40 -1
  72. package/corpus/templates/design/app/components/design/FusionAppBanner.tsx +9 -1
  73. package/corpus/templates/design/app/components/design/edit-panel/component-section.tsx +5 -1
  74. package/corpus/templates/design/app/pages/DesignSystemSetup.tsx +9 -1
  75. package/corpus/templates/slides/app/components/design-system/DesignSystemSetup.tsx +9 -1
  76. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  77. package/dist/agent/engine/builder-engine.js +4 -0
  78. package/dist/agent/engine/builder-engine.js.map +1 -1
  79. package/dist/client/AgentPanel.d.ts.map +1 -1
  80. package/dist/client/AgentPanel.js +10 -3
  81. package/dist/client/AgentPanel.js.map +1 -1
  82. package/dist/client/ConnectBuilderCard.d.ts.map +1 -1
  83. package/dist/client/ConnectBuilderCard.js +5 -1
  84. package/dist/client/ConnectBuilderCard.js.map +1 -1
  85. package/dist/client/chat/markdown-renderer.d.ts.map +1 -1
  86. package/dist/client/chat/markdown-renderer.js +3 -2
  87. package/dist/client/chat/markdown-renderer.js.map +1 -1
  88. package/dist/client/error-format.d.ts +1 -1
  89. package/dist/client/error-format.d.ts.map +1 -1
  90. package/dist/client/error-format.js +1 -1
  91. package/dist/client/error-format.js.map +1 -1
  92. package/dist/client/index.d.ts +1 -0
  93. package/dist/client/index.d.ts.map +1 -1
  94. package/dist/client/index.js +1 -0
  95. package/dist/client/index.js.map +1 -1
  96. package/dist/client/integrations/IntegrationsPanel.d.ts.map +1 -1
  97. package/dist/client/integrations/IntegrationsPanel.js +3 -4
  98. package/dist/client/integrations/IntegrationsPanel.js.map +1 -1
  99. package/dist/client/resources/McpIntegrationDialog.d.ts.map +1 -1
  100. package/dist/client/resources/McpIntegrationDialog.js +21 -7
  101. package/dist/client/resources/McpIntegrationDialog.js.map +1 -1
  102. package/dist/client/resources/mcp-integration-catalog.d.ts.map +1 -1
  103. package/dist/client/resources/mcp-integration-catalog.js +2 -2
  104. package/dist/client/resources/mcp-integration-catalog.js.map +1 -1
  105. package/dist/client/settings/BackgroundAgentSection.d.ts.map +1 -1
  106. package/dist/client/settings/BackgroundAgentSection.js +5 -1
  107. package/dist/client/settings/BackgroundAgentSection.js.map +1 -1
  108. package/dist/client/settings/SettingsPanel.js +1 -1
  109. package/dist/client/settings/SettingsPanel.js.map +1 -1
  110. package/dist/client/settings/useBuilderStatus.d.ts.map +1 -1
  111. package/dist/client/settings/useBuilderStatus.js +2 -0
  112. package/dist/client/settings/useBuilderStatus.js.map +1 -1
  113. package/dist/collab/struct-routes.d.ts +1 -1
  114. package/dist/file-upload/actions/upload-image.d.ts +1 -1
  115. package/dist/localization/default-messages.d.ts +0 -6
  116. package/dist/localization/default-messages.d.ts.map +1 -1
  117. package/dist/localization/default-messages.js +1 -7
  118. package/dist/localization/default-messages.js.map +1 -1
  119. package/dist/observability/routes.d.ts +5 -5
  120. package/dist/resources/handlers.d.ts +1 -1
  121. package/dist/secrets/routes.d.ts +9 -9
  122. package/dist/server/builder-browser.d.ts.map +1 -1
  123. package/dist/server/builder-browser.js +4 -0
  124. package/dist/server/builder-browser.js.map +1 -1
  125. package/dist/server/builder-design-systems.d.ts.map +1 -1
  126. package/dist/server/builder-design-systems.js +6 -1
  127. package/dist/server/builder-design-systems.js.map +1 -1
  128. package/dist/server/fusion-app.d.ts.map +1 -1
  129. package/dist/server/fusion-app.js +2 -1
  130. package/dist/server/fusion-app.js.map +1 -1
  131. package/dist/server/transcribe-voice.d.ts +1 -1
  132. package/dist/shared/builder-link-tracking.d.ts +14 -0
  133. package/dist/shared/builder-link-tracking.d.ts.map +1 -0
  134. package/dist/shared/builder-link-tracking.js +26 -0
  135. package/dist/shared/builder-link-tracking.js.map +1 -0
  136. package/dist/shared/index.d.ts +1 -0
  137. package/dist/shared/index.d.ts.map +1 -1
  138. package/dist/shared/index.js +1 -0
  139. package/dist/shared/index.js.map +1 -1
  140. package/docs/content/deployment.mdx +1 -1
  141. package/docs/content/frames.mdx +1 -1
  142. package/docs/content/integrations.mdx +27 -27
  143. package/docs/content/pr-visual-recap.mdx +17 -13
  144. package/docs/content/workspace-management.mdx +1 -1
  145. package/package.json +3 -2
  146. package/src/agent/engine/builder-engine.ts +4 -0
  147. package/src/client/AgentPanel.tsx +10 -4
  148. package/src/client/ConnectBuilderCard.tsx +5 -1
  149. package/src/client/chat/markdown-renderer.tsx +3 -5
  150. package/src/client/error-format.ts +2 -1
  151. package/src/client/index.ts +1 -0
  152. package/src/client/integrations/IntegrationsPanel.tsx +2 -18
  153. package/src/client/resources/McpIntegrationDialog.tsx +43 -32
  154. package/src/client/resources/mcp-integration-catalog.ts +4 -2
  155. package/src/client/settings/BackgroundAgentSection.tsx +5 -1
  156. package/src/client/settings/SettingsPanel.tsx +4 -4
  157. package/src/client/settings/useBuilderStatus.ts +3 -0
  158. package/src/localization/default-messages.ts +1 -7
  159. package/src/server/builder-browser.ts +4 -0
  160. package/src/server/builder-design-systems.ts +6 -1
  161. package/src/server/fusion-app.ts +5 -1
  162. package/src/shared/builder-link-tracking.ts +41 -0
  163. package/src/shared/index.ts +1 -0
@@ -4143,25 +4143,6 @@ function DatabaseItemPreview({
4143
4143
  draftVersionsRef.current.set(documentId, null);
4144
4144
  else if (result.draft) {
4145
4145
  draftVersionsRef.current.set(documentId, result.draft.version);
4146
- if (
4147
- previewDraftNeedsConflict({
4148
- returnedDraft: result.draft,
4149
- pending: controller.pending,
4150
- })
4151
- ) {
4152
- controller.notifyDraftConflict({
4153
- lastSaved: snapshot.lastSaved,
4154
- pending: {
4155
- title: result.draft.title,
4156
- content: result.draft.content,
4157
- loadedUpdatedAt:
4158
- result.draft.baseDocumentUpdatedAt ?? undefined,
4159
- loadedContentWasEmpty:
4160
- result.draft.loadedContentWasEmpty === 1,
4161
- },
4162
- deferredReason: "conflict",
4163
- });
4164
- }
4165
4146
  } else {
4166
4147
  // Another tab already removed the row. Treat the stale delete as
4167
4148
  // converged instead of retaining a version that can never match.
@@ -4186,24 +4167,6 @@ function DatabaseItemPreview({
4186
4167
  draftVersionsRef.current.set(documentId, result.draft.version);
4187
4168
  } else if (result.draft) {
4188
4169
  draftVersionsRef.current.set(documentId, result.draft.version);
4189
- if (
4190
- previewDraftNeedsConflict({
4191
- returnedDraft: result.draft,
4192
- pending: controller.pending,
4193
- })
4194
- ) {
4195
- controller.notifyDraftConflict({
4196
- lastSaved: snapshot.lastSaved,
4197
- pending: {
4198
- title: result.draft.title,
4199
- content: result.draft.content,
4200
- loadedUpdatedAt:
4201
- result.draft.baseDocumentUpdatedAt ?? undefined,
4202
- loadedContentWasEmpty: result.draft.loadedContentWasEmpty === 1,
4203
- },
4204
- deferredReason: "conflict",
4205
- });
4206
- }
4207
4170
  } else {
4208
4171
  // A competing tab deleted the version we tried to update. Reset to
4209
4172
  // create mode and enqueue the latest pending payload once; keeping
@@ -4298,7 +4261,13 @@ function DatabaseItemPreview({
4298
4261
  );
4299
4262
  return;
4300
4263
  }
4301
- resolve(undefined);
4264
+ resolve({
4265
+ outcome: "saved" as const,
4266
+ loadedUpdatedAt: result.updatedAt,
4267
+ loadedContentWasEmpty: isEffectivelyEmptyDocumentContent(
4268
+ result.content,
4269
+ ),
4270
+ });
4302
4271
  },
4303
4272
  onError: reject,
4304
4273
  },
@@ -4410,6 +4379,8 @@ function DatabaseItemPreview({
4410
4379
  }
4411
4380
  return;
4412
4381
  }
4382
+ const previouslyExpectedVersion =
4383
+ draftVersionsRef.current.get(documentId) ?? null;
4413
4384
  draftVersionsRef.current.set(documentId, draft.version);
4414
4385
  const controller = peekPreviewDocumentSaveController(documentId);
4415
4386
  if (!controller) return;
@@ -4431,8 +4402,19 @@ function DatabaseItemPreview({
4431
4402
  ? draft.deferredReason
4432
4403
  : null,
4433
4404
  } as const;
4405
+ // A poll tick simply confirming a version this client's own debounced
4406
+ // write already advanced the ref to is not an external change — it is
4407
+ // this client's typing racing ahead of its own last round trip. Comparing
4408
+ // that echo against the still-live `pending` would flag a conflict on
4409
+ // almost every keystroke. Only treat the draft as having moved out from
4410
+ // under the user when its version is newer than what this client itself
4411
+ // last recorded.
4412
+ const draftAdvancedExternally =
4413
+ previouslyExpectedVersion !== null &&
4414
+ draft.version > previouslyExpectedVersion;
4434
4415
  if (controllerDirty) {
4435
4416
  if (
4417
+ draftAdvancedExternally &&
4436
4418
  previewDraftNeedsConflict({
4437
4419
  returnedDraft: draft,
4438
4420
  pending: controller.pending,
@@ -67,6 +67,19 @@ export interface PreviewDocumentSaveDeferred {
67
67
  conflictSnapshot?: PreviewDocumentDraftSnapshot;
68
68
  }
69
69
 
70
+ /**
71
+ * A successful save can report the server's fresh `updatedAt`/emptiness back
72
+ * to the controller so its baseline stops looking stale. Without this, a
73
+ * baseline seeded as empty (a brand-new page) stays flagged empty forever, so
74
+ * a later poll of content the user just saved themselves gets mistaken for a
75
+ * non-empty body arriving externally over an empty one.
76
+ */
77
+ export interface PreviewDocumentSaveSuccess {
78
+ outcome: "saved";
79
+ loadedUpdatedAt?: string;
80
+ loadedContentWasEmpty?: boolean;
81
+ }
82
+
70
83
  export interface PreviewDocumentSaveAdapter {
71
84
  save: (
72
85
  documentId: string,
@@ -151,6 +164,18 @@ function payloadsEqual(a: PreviewDocumentPayload, b: PreviewDocumentPayload) {
151
164
  return a.title === b.title && a.content === b.content;
152
165
  }
153
166
 
167
+ function asSaveSuccess(result: unknown): PreviewDocumentSaveSuccess | null {
168
+ if (
169
+ result &&
170
+ typeof result === "object" &&
171
+ "outcome" in result &&
172
+ (result as { outcome?: unknown }).outcome === "saved"
173
+ ) {
174
+ return result as PreviewDocumentSaveSuccess;
175
+ }
176
+ return null;
177
+ }
178
+
154
179
  export function createPreviewDocumentSaveController(
155
180
  args: PreviewDocumentSaveAdapter & {
156
181
  /**
@@ -230,7 +255,21 @@ export function createPreviewDocumentSaveController(
230
255
  }
231
256
  return;
232
257
  }
233
- lastSaved = attempted;
258
+ // Adopt the server's fresh metadata (if the adapter reported it) into
259
+ // the confirmed baseline. Otherwise `loadedUpdatedAt`/
260
+ // `loadedContentWasEmpty` would keep carrying whatever was true when
261
+ // the controller was created/last marked — e.g. "empty" for a
262
+ // brand-new page — forever, even after real content has been saved.
263
+ const success = asSaveSuccess(result);
264
+ lastSaved = {
265
+ ...attempted,
266
+ ...(success?.loadedUpdatedAt !== undefined
267
+ ? { loadedUpdatedAt: success.loadedUpdatedAt }
268
+ : {}),
269
+ ...(success?.loadedContentWasEmpty !== undefined
270
+ ? { loadedContentWasEmpty: success.loadedContentWasEmpty }
271
+ : {}),
272
+ };
234
273
  hasSavedLocally = true;
235
274
  deferredReason = null;
236
275
  inFlight = null;
@@ -2,6 +2,7 @@ import {
2
2
  useActionMutation,
3
3
  useActionQuery,
4
4
  } from "@agent-native/core/client/hooks";
5
+ import { withBuilderUtmTrackingParams } from "@agent-native/core/shared";
5
6
  import {
6
7
  IconAlertTriangle,
7
8
  IconApps,
@@ -315,7 +316,14 @@ export function FusionAppBanner({
315
316
  </DropdownMenuTrigger>
316
317
  <DropdownMenuContent align="end">
317
318
  <DropdownMenuItem asChild className="cursor-pointer">
318
- <a href={editorUrl} target="_blank" rel="noreferrer">
319
+ <a
320
+ href={withBuilderUtmTrackingParams(editorUrl, {
321
+ campaign: "product",
322
+ content: "fusion_editor",
323
+ })}
324
+ target="_blank"
325
+ rel="noreferrer"
326
+ >
319
327
  <IconExternalLink className="me-2 size-3.5" />
320
328
  {
321
329
  "Open in Builder" /* i18n-ignore fusion app banner, flag-gated feature */
@@ -3,6 +3,7 @@ import {
3
3
  useActionQuery,
4
4
  } from "@agent-native/core/client/hooks";
5
5
  import { useT } from "@agent-native/core/client/i18n";
6
+ import { withBuilderUtmTrackingParams } from "@agent-native/core/shared";
6
7
  import { propNameToDataAttribute } from "@shared/component-model";
7
8
  import {
8
9
  IconArrowRight,
@@ -168,7 +169,10 @@ function MakeItRealCard({
168
169
  `Generating ${migrateResult.branchName ?? "React app"}.`}
169
170
  </p>
170
171
  <a
171
- href={migrateResult.url}
172
+ href={withBuilderUtmTrackingParams(migrateResult.url, {
173
+ campaign: "product",
174
+ content: "design_migration",
175
+ })}
172
176
  target="_blank"
173
177
  rel="noopener noreferrer"
174
178
  className="inline-flex h-6 shrink-0 items-center gap-1 rounded-md px-1.5 text-[10px] font-semibold text-[var(--design-editor-accent-color)] hover:bg-[var(--design-editor-panel-raised-bg)]"
@@ -2,6 +2,7 @@ import { appApiPath } from "@agent-native/core/client/api-path";
2
2
  import { useActionQuery } from "@agent-native/core/client/hooks";
3
3
  import { useT } from "@agent-native/core/client/i18n";
4
4
  import { openAgentSidebar } from "@agent-native/core/client/navigation";
5
+ import { withBuilderUtmTrackingParams } from "@agent-native/core/shared";
5
6
  import {
6
7
  useSetPageTitle,
7
8
  useSetHeaderActions,
@@ -1128,7 +1129,14 @@ function BuilderIndexPreview({
1128
1129
  <div className="flex items-center gap-2 border-t border-border pt-4">
1129
1130
  {result.builderUrl ? (
1130
1131
  <Button asChild className="cursor-pointer">
1131
- <a href={result.builderUrl} target="_blank" rel="noreferrer">
1132
+ <a
1133
+ href={withBuilderUtmTrackingParams(result.builderUrl, {
1134
+ campaign: "product",
1135
+ content: "design_system_intelligence",
1136
+ })}
1137
+ target="_blank"
1138
+ rel="noreferrer"
1139
+ >
1132
1140
  <IconExternalLink className="size-4" />
1133
1141
  {"Open in Builder" /* i18n-ignore Builder link action */}
1134
1142
  </a>
@@ -6,6 +6,7 @@ import {
6
6
  } from "@agent-native/core/client/hooks";
7
7
  import { useT } from "@agent-native/core/client/i18n";
8
8
  import { openAgentSidebar } from "@agent-native/core/client/navigation";
9
+ import { withBuilderUtmTrackingParams } from "@agent-native/core/shared";
9
10
  import {
10
11
  IconWorld,
11
12
  IconPalette,
@@ -921,7 +922,14 @@ function BuilderIndexPreview({
921
922
 
922
923
  <div className="flex flex-wrap items-center gap-2 border-t border-border pt-3">
923
924
  <Button size="sm" asChild className="cursor-pointer">
924
- <a href={result.builderUrl} target="_blank" rel="noreferrer">
925
+ <a
926
+ href={withBuilderUtmTrackingParams(result.builderUrl, {
927
+ campaign: "product",
928
+ content: "design_system_intelligence",
929
+ })}
930
+ target="_blank"
931
+ rel="noreferrer"
932
+ >
925
933
  <IconExternalLink className="w-3.5 h-3.5" />
926
934
  {t("designSystemSetup.openInBuilder")}
927
935
  </a>
@@ -1 +1 @@
1
- {"version":3,"file":"builder-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AA0BH,OAAO,KAAK,EACV,WAAW,EACX,kBAAkB,EAInB,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,oBAAoB,EAAE,kBAMlC,CAAC;AAEF,eAAO,MAAM,wBAAwB,kLAAuC,CAAC;AAkB7E,eAAO,MAAM,qBAAqB,yCAAoC,CAAC;AA0vBvE,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACpC,WAAW,CAEb"}
1
+ {"version":3,"file":"builder-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AA2BH,OAAO,KAAK,EACV,WAAW,EACX,kBAAkB,EAInB,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,oBAAoB,EAAE,kBAMlC,CAAC;AAEF,eAAO,MAAM,wBAAwB,kLAAuC,CAAC;AAkB7E,eAAO,MAAM,qBAAqB,yCAAoC,CAAC;AA6vBvE,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACpC,WAAW,CAEb"}
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { captureError } from "../../server/capture-error.js";
16
16
  import { clearBuilderCredentialAuthFailure, resolveBuilderCredentials, getBuilderGatewayBaseUrl, recordBuilderCredentialAuthFailure, } from "../../server/credential-provider.js";
17
+ import { applyBuilderUtmTrackingParams } from "../../shared/builder-link-tracking.js";
17
18
  import { normalizeReasoningEffortForModel, } from "../../shared/reasoning-effort.js";
18
19
  import { isInBackgroundFunctionRuntime } from "../durable-background.js";
19
20
  import { BUILDER_MODEL_CONFIG } from "../model-config.js";
@@ -85,6 +86,9 @@ async function buildUpgradeUrl() {
85
86
  url.searchParams.set("agentNativeConnectSource", "gateway_quota_upgrade");
86
87
  url.searchParams.set("agentNativeFlow", "connect_llm");
87
88
  url.searchParams.set("framework", "agent-native");
89
+ applyBuilderUtmTrackingParams(url.searchParams, {
90
+ content: "gateway_quota_upgrade",
91
+ });
88
92
  return url.toString();
89
93
  }
90
94
  class BuilderEngine {
@@ -1 +1 @@
1
- {"version":3,"file":"builder-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EACL,iCAAiC,EACjC,yBAAyB,EACzB,wBAAwB,EACxB,kCAAkC,GACnC,MAAM,qCAA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OAK3C;IACC,MAAM,GAAG,GAAG,IAAI,KAAK,CACnB,OAAO,CAAC,SAAS;QACf,CAAC,CAAC,+DAA+D,OAAO,CAAC,SAAS,GAAG;QACrF,CAAC,CAAC,kDAAkD,CACvD,CAAC;IACF,GAAG,CAAC,IAAI,GAAG,6BAA6B,CAAC;IACzC,YAAY,CAAC,GAAG,EAAE;QAChB,KAAK,EAAE,2BAA2B;QAClC,IAAI,EAAE;YACJ,MAAM,EAAE,gBAAgB;YACxB,KAAK,EAAE,QAAQ;YACf,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,SAAS,EAAE,uBAAuB;YAClC,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACtE;QACD,KAAK,EAAE;YACL,aAAa,EAAE,OAAO,CAAC,UAAU,EAAE,MAAM;YACzC,WAAW,EAAE,OAAO,CAAC,UAAU,EAAE,QAAQ;YACzC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B;QACD,QAAQ,EAAE;YACR,cAAc,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 { captureError } from \"../../server/capture-error.js\";\nimport {\n clearBuilderCredentialAuthFailure,\n resolveBuilderCredentials,\n getBuilderGatewayBaseUrl,\n recordBuilderCredentialAuthFailure,\n} from \"../../server/credential-provider.js\";\nimport {\n normalizeReasoningEffortForModel,\n type ReasoningEffort,\n} from \"../../shared/reasoning-effort.js\";\nimport { isInBackgroundFunctionRuntime } from \"../durable-background.js\";\nimport { BUILDER_MODEL_CONFIG } from \"../model-config.js\";\nimport { getBuilderGatewayRequestHeaders } from \"./builder-gateway-headers.js\";\nimport {\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n LLM_MISSING_CREDENTIALS_MESSAGE,\n} from \"./credential-errors.js\";\nimport { FIRST_STREAM_EVENT_TIMEOUT_MS } from \"./first-event-timeout.js\";\nimport { resolveMaxOutputTokensForEngine } from \"./output-tokens.js\";\nimport {\n engineMessagesToBuilderGatewayAnthropic,\n engineToolsToAnthropic,\n} from \"./translate-anthropic.js\";\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineContentPart,\n EngineEvent,\n EngineStreamOptions,\n} from \"./types.js\";\n\nexport const BUILDER_CAPABILITIES: EngineCapabilities = {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n};\n\nexport const BUILDER_SUPPORTED_MODELS = BUILDER_MODEL_CONFIG.supportedModels;\n\n// Keep the foreground hosted gateway timeout below the synchronous serverless\n// wall so the agent loop can append a continuation and persist terminal state\n// before the host hard-kills the invocation.\nconst DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;\nconst MAX_HOSTED_FOREGROUND_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;\n/**\n * Netlify background functions have a 15-minute wall. Keep the Builder gateway\n * ceiling below that, but above the run-manager's 13-minute soft-timeout so\n * durable background runs checkpoint before this timer wins.\n */\nconst MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS = 14 * 60_000;\n/** Local and non-hosted runtimes have no synchronous serverless wall. */\nconst MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS =\n MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\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 *\n * We can't deep-link to a per-org billing page from `BUILDER_ORG_NAME` because\n * that field is the org's display name (e.g. \"Nicholas kipchumba Space\"), not\n * a URL-safe slug or id. URL-encoding the display name produces segments like\n * `/app/organizations/Nicholas%20kipchumba%20Space/billing` which Builder's\n * router treats as unknown and silently bounces to `/app/projects`. The\n * Builder CLI-auth callback doesn't expose the org slug/id today, so we route\n * to the org-agnostic subscription page. Agent Native attribution lets Builder\n * skip generic onboarding for new users who land there from an upgrade CTA.\n */\nasync function buildUpgradeUrl(): Promise<string> {\n const url = new URL(\"https://builder.io/account/subscription\");\n url.searchParams.set(\"signupSource\", \"agent-native\");\n url.searchParams.set(\"agentNativeConnectSource\", \"gateway_quota_upgrade\");\n url.searchParams.set(\"agentNativeFlow\", \"connect_llm\");\n url.searchParams.set(\"framework\", \"agent-native\");\n return url.toString();\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 creds = await resolveBuilderCredentials();\n const authHeader = creds.privateKey ? `Bearer ${creds.privateKey}` : null;\n const spaceId = creds.publicKey;\n const builderUserId = creds.userId;\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 = engineMessagesToBuilderGatewayAnthropic(opts.messages);\n const tools = engineToolsToAnthropic(opts.tools);\n const thinkingBudget =\n opts.providerOptions?.anthropic?.thinking?.budgetTokens;\n const reasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort ??\n (typeof thinkingBudget === \"number\"\n ? mapReasoningEffort(thinkingBudget)\n : undefined),\n );\n\n // Apply prompt caching to system + tools (stable prefix) and to the last\n // user message (moving cache breakpoint so growing history gets cached\n // across tool-loop iterations at ~90% off input cost).\n // Templates can opt out by setting providerOptions.anthropic.cacheControl=false.\n const cacheEnabled =\n opts.providerOptions?.anthropic?.cacheControl !== false;\n\n // System: wrap in array with cache_control when caching is on.\n const systemValue: unknown = opts.systemPrompt\n ? cacheEnabled\n ? [\n {\n type: \"text\",\n text: opts.systemPrompt,\n cache_control: { type: \"ephemeral\" },\n },\n ]\n : opts.systemPrompt\n : undefined;\n\n // Tools: add cache_control to the last tool definition.\n let cachedTools = tools;\n if (cacheEnabled && tools.length > 0) {\n cachedTools = [...tools];\n const last = { ...cachedTools[cachedTools.length - 1] } as any;\n last.cache_control = { type: \"ephemeral\" };\n cachedTools[cachedTools.length - 1] = last;\n }\n\n // Messages: add a moving cache breakpoint on the last user message's last\n // content block so the entire conversation prefix is cached.\n let cachedMessages = messages;\n if (cacheEnabled && messages.length > 0) {\n let lastUserIdx = -1;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n if ((messages[i] as any).role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n if (lastUserIdx >= 0) {\n cachedMessages = [...messages];\n const lastMsg = { ...cachedMessages[lastUserIdx] } as any;\n if (Array.isArray(lastMsg.content) && lastMsg.content.length > 0) {\n const content = [...lastMsg.content];\n const lastBlock = { ...content[content.length - 1] } as any;\n lastBlock.cache_control = { type: \"ephemeral\" };\n content[content.length - 1] = lastBlock;\n lastMsg.content = content;\n cachedMessages[lastUserIdx] = lastMsg;\n }\n }\n }\n\n const body: Record<string, unknown> = {\n model: opts.model,\n messages: cachedMessages,\n ...(systemValue !== undefined ? { system: systemValue } : {}),\n ...(cachedTools.length > 0 ? { tools: cachedTools } : {}),\n max_tokens: resolveMaxOutputTokensForEngine(\n this.name,\n opts.maxOutputTokens,\n opts.model,\n ),\n ...(typeof opts.temperature === \"number\"\n ? { temperature: opts.temperature }\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 = creds.orgName || \"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 ...getBuilderGatewayRequestHeaders(),\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: gatewayAbort.effectiveTimeoutMs(),\n timedOut,\n elapsedMs: Date.now() - tStart,\n });\n }\n yield createBuilderGatewayTimeoutStop(\n err,\n timedOut,\n gatewayAbort.effectiveTimeoutMs(),\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 // A successful gateway call proves the connected credentials are valid\n // again. Clear any prior auth-failure marker so status / chat-card\n // surfaces stop flagging the connection as broken. This is the only\n // self-healing path for workspace/env-managed credentials, which never\n // flow through writeBuilderCredentials.\n try {\n const creds = await resolveBuilderCredentials();\n await clearBuilderCredentialAuthFailure({\n privateKey: creds.privateKey,\n publicKey: creds.publicKey,\n });\n } catch {\n // Marker clearing is best-effort; a stale marker just means the user\n // sees \"reconnect Builder\" until the next successful call clears it.\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 abortSignal: gatewayAbort.signal,\n didGatewayTimeout: gatewayAbort.didTimeout,\n getGatewayTimeoutMs: gatewayAbort.effectiveTimeoutMs,\n onFirstEvent: gatewayAbort.markFirstEvent,\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 await recordBuilderCredentialAuthFailure({ status, code, message });\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 && isBuilderCredentialAuthError(message)) {\n await recordBuilderCredentialAuthFailure({ status, code, message });\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 (code === \"rate_limit_exceeded\") {\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 up transient concurrency throttles and retries\n // the turn. Daily gateway caps use `rate_limit_exceeded` above and must\n // not loop.\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 abortSignal?: AbortSignal,\n): AsyncIterable<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n while (true) {\n const { done, value } = await readStreamChunk(reader, abortSignal);\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 // Flush any bytes the streaming decoder buffered for an incomplete multibyte\n // sequence at the end of the stream; otherwise a trailing multibyte char in\n // the final chunk is silently dropped from the last line.\n buffer += decoder.decode();\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 abortSignal?: AbortSignal;\n didGatewayTimeout?: () => boolean;\n getGatewayTimeoutMs?: () => number;\n onFirstEvent?: () => void;\n gatewayUrl?: URL;\n requestStartedAt?: number;\n } = {},\n): AsyncIterable<EngineEvent> {\n const parts: EngineContentPart[] = [];\n let pendingText = \"\";\n let pendingThinking: { text: string; signature?: string } | null = null;\n\n const flushPendingText = () => {\n if (pendingText) {\n parts.push({ type: \"text\", text: pendingText });\n pendingText = \"\";\n }\n };\n\n const flushPendingThinking = () => {\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 const flushPending = () => {\n flushPendingText();\n flushPendingThinking();\n };\n\n try {\n for await (const line of readJsonlLines(\n reader,\n captureContext.abortSignal,\n )) {\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 // Heartbeats are transport-level keepalives, not proof the model is\n // producing output — every other parsed event counts as first progress.\n if (event?.type !== \"heartbeat\") {\n captureContext.onFirstEvent?.();\n }\n\n switch (event.type) {\n case \"text-delta\": {\n const text = event.text ?? \"\";\n flushPendingThinking();\n pendingText += text;\n yield { type: \"text-delta\", text };\n break;\n }\n\n case \"thinking-delta\":\n case \"reasoning-delta\": {\n const text = event.text ?? \"\";\n flushPendingText();\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 \"heartbeat\":\n yield { type: \"gateway-heartbeat\" };\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 === \"invalid_request\") {\n // errorCode has no retry-trigger keywords, so isRetryableError\n // won't loop on broken history.\n const errMsg =\n event.error ||\n event.message ||\n \"Builder gateway rejected the request as malformed.\";\n const errCode =\n typeof event.errorCode === \"string\"\n ? event.errorCode\n : typeof event.code === \"string\"\n ? event.code\n : \"invalid_request\";\n console.warn(\n `[builder-engine] stop reason=invalid_request model=${model} code=${errCode} error=${errMsg}`,\n );\n yield {\n type: \"stop\",\n reason: \"error\",\n error: errMsg,\n errorCode: errCode,\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 gatewayErrCode = event.errorCode ?? event.code;\n const isCredentialAuthError =\n Boolean(explicitErrMsg) &&\n isBuilderCredentialAuthError(String(errMsg));\n // Anthropic's bare \"Connection error.\" often arrives here with no\n // gateway code. Tag it as a network error so in-run retries and\n // run-level resume treat it as transient instead of terminal.\n const isProviderConnectionError =\n typeof explicitErrMsg === \"string\" &&\n isProviderConnectionErrorMessage(String(explicitErrMsg));\n const errCode = isCredentialAuthError\n ? \"builder_auth_error\"\n : isProviderConnectionError\n ? BUILDER_GATEWAY_NETWORK_ERROR_CODE\n : (gatewayErrCode ??\n (!explicitErrMsg ? \"builder_gateway_error\" : undefined));\n console.error(\n `[builder-engine] stop reason=error model=${model} code=${errCode ?? \"(none)\"} error=${errMsg}`,\n );\n if (isCredentialAuthError) {\n await recordBuilderCredentialAuthFailure({\n code:\n typeof gatewayErrCode === \"string\" ? gatewayErrCode : errCode,\n message: String(errMsg),\n });\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 const gatewayTimeoutMs =\n captureContext.getGatewayTimeoutMs?.() ??\n DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;\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 readStreamChunk(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n abortSignal?: AbortSignal,\n): Promise<ReadableStreamReadResult<Uint8Array>> {\n if (!abortSignal) return reader.read();\n if (abortSignal.aborted) {\n return Promise.reject(abortSignal.reason ?? new Error(\"Stream aborted\"));\n }\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n reject(abortSignal.reason ?? new Error(\"Stream aborted\"));\n };\n abortSignal.addEventListener(\"abort\", onAbort, { once: true });\n reader.read().then(\n (value) => {\n abortSignal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (err) => {\n abortSignal.removeEventListener(\"abort\", onAbort);\n reject(err);\n },\n );\n });\n}\n\nfunction normalizeGatewayErrorText(raw: string, status: number): string {\n const text = raw.trim();\n const looksHtml = /<html[\\s>]|<body[\\s>]|<head[\\s>]/i.test(text);\n const readable = looksHtml ? htmlToText(text) : text;\n if (/inactivity timeout/i.test(readable)) {\n return `Builder gateway returned ${status}: Inactivity Timeout. The upstream connection was idle too long before sending data.`;\n }\n if (looksHtml) {\n return `Builder gateway returned ${status}: ${readable.slice(0, 240)}`;\n }\n return readable;\n}\n\nfunction htmlToText(html: string): string {\n return html\n .replace(/<script[\\s\\S]*?<\\/script>/gi, \" \")\n .replace(/<style[\\s\\S]*?<\\/style>/gi, \" \")\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/(p|div|h1|h2|h3|li|tr)>/gi, \"\\n\")\n .replace(/<[^>]+>/g, \" \")\n .replace(/&nbsp;/gi, \" \")\n .replace(/&lt;/gi, \"<\")\n .replace(/&gt;/gi, \">\")\n .replace(/&amp;/gi, \"&\")\n .replace(/&quot;/gi, '\"')\n .replace(/&#39;/gi, \"'\")\n .replace(/[ \\t]+/g, \" \")\n .replace(/\\n\\s+/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\nexport function createBuilderEngine(\n _config: Record<string, unknown> = {},\n): AgentEngine {\n return new BuilderEngine();\n}\n\nfunction resolveMaxBuilderGatewayTimeoutMs(): number {\n if (isInBackgroundFunctionRuntime()) {\n return MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n\n if (!isHostedBuilderRuntime()) {\n return MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n\n try {\n const base = getBuilderGatewayBaseUrl();\n if (/^https?:\\/\\/(localhost|127\\.0\\.0\\.1)([:/]|$)/i.test(base)) {\n return MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n } catch {\n // ignore malformed override\n }\n return MAX_HOSTED_FOREGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\n}\n\nfunction isHostedBuilderRuntime(): boolean {\n if (\n process.env.NETLIFY &&\n process.env.NETLIFY !== \"false\" &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n if (\n process.env.AWS_LAMBDA_FUNCTION_NAME &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n return Boolean(\n process.env.CF_PAGES ||\n process.env.VERCEL ||\n process.env.VERCEL_ENV ||\n process.env.RENDER ||\n process.env.FLY_APP_NAME ||\n process.env.K_SERVICE,\n );\n}\n\nfunction getBuilderGatewayTimeoutMs(): number {\n const raw = process.env.AGENT_NATIVE_BUILDER_GATEWAY_TIMEOUT_MS;\n const maxMs = resolveMaxBuilderGatewayTimeoutMs();\n if (!raw) return maxMs;\n const parsed = Number(raw);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return maxMs;\n }\n return Math.min(parsed, maxMs);\n}\n\n/**\n * Two-stage abort deadline: until the first real stream event arrives, the\n * effective deadline is min(totalTimeoutMs, FIRST_STREAM_EVENT_TIMEOUT_MS) —\n * a wedged gateway that never streams anything gets cut off in ~2 minutes\n * instead of riding the full flat timeout. Once `markFirstEvent()` fires, the\n * timer reschedules for whatever remains of the original total deadline, so\n * a request that starts streaming still gets the full budget it always did.\n */\nfunction createGatewayAbortSignal(\n parentSignal: AbortSignal,\n totalTimeoutMs: number,\n): {\n signal: AbortSignal;\n didTimeout: () => boolean;\n effectiveTimeoutMs: () => number;\n markFirstEvent: () => void;\n cleanup: () => void;\n} {\n const controller = new AbortController();\n let timedOut = false;\n let firstEventSeen = false;\n const startedAt = Date.now();\n\n const abortFromParent = () => {\n if (!controller.signal.aborted) {\n controller.abort(parentSignal.reason);\n }\n };\n\n const fireTimeout = () => {\n timedOut = true;\n if (!controller.signal.aborted) {\n controller.abort(new Error(\"Builder gateway request timed out\"));\n }\n };\n\n const firstEventDeadlineMs = Math.min(\n totalTimeoutMs,\n FIRST_STREAM_EVENT_TIMEOUT_MS,\n );\n let timeout = setTimeout(fireTimeout, firstEventDeadlineMs);\n\n if (parentSignal.aborted) abortFromParent();\n parentSignal.addEventListener(\"abort\", abortFromParent, { once: true });\n\n return {\n signal: controller.signal,\n didTimeout: () => timedOut,\n effectiveTimeoutMs: () =>\n firstEventSeen ? totalTimeoutMs : firstEventDeadlineMs,\n markFirstEvent: () => {\n if (firstEventSeen || timedOut) return;\n firstEventSeen = true;\n // The first-event window was already the binding constraint (total\n // timeout <= it) — nothing to reschedule.\n if (firstEventDeadlineMs >= totalTimeoutMs) return;\n clearTimeout(timeout);\n const remainingMs = Math.max(\n 0,\n totalTimeoutMs - (Date.now() - startedAt),\n );\n timeout = setTimeout(fireTimeout, remainingMs);\n },\n cleanup: () => {\n clearTimeout(timeout);\n parentSignal.removeEventListener(\"abort\", abortFromParent);\n },\n };\n}\n\nfunction isBuilderCredentialAuthError(message: string): boolean {\n const lowerMessage = message.toLowerCase();\n const referencesAccessToken =\n lowerMessage.includes(\"personal access token\") ||\n lowerMessage.includes(\"access token\");\n const rejectedToken =\n lowerMessage.includes(\"invalid\") ||\n lowerMessage.includes(\"inactive\") ||\n lowerMessage.includes(\"expired\") ||\n lowerMessage.includes(\"revoked\");\n return (\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 (referencesAccessToken && rejectedToken)\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 // Anthropic SDK's APIConnectionError default (\"Connection error.\") is\n // often forwarded by the Builder gateway as a stop event with no code.\n text.includes(\"connection error\") ||\n text.includes(\"connection reset\") ||\n text.includes(\"connection closed\") ||\n text.includes(\"stream closed\") ||\n text.includes(\"terminated\")\n );\n}\n\nfunction isProviderConnectionErrorMessage(message: string): boolean {\n return message.trim().toLowerCase() === \"connection error.\";\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"]}
1
+ {"version":3,"file":"builder-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EACL,iCAAiC,E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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 { captureError } from \"../../server/capture-error.js\";\nimport {\n clearBuilderCredentialAuthFailure,\n resolveBuilderCredentials,\n getBuilderGatewayBaseUrl,\n recordBuilderCredentialAuthFailure,\n} from \"../../server/credential-provider.js\";\nimport { applyBuilderUtmTrackingParams } from \"../../shared/builder-link-tracking.js\";\nimport {\n normalizeReasoningEffortForModel,\n type ReasoningEffort,\n} from \"../../shared/reasoning-effort.js\";\nimport { isInBackgroundFunctionRuntime } from \"../durable-background.js\";\nimport { BUILDER_MODEL_CONFIG } from \"../model-config.js\";\nimport { getBuilderGatewayRequestHeaders } from \"./builder-gateway-headers.js\";\nimport {\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n LLM_MISSING_CREDENTIALS_MESSAGE,\n} from \"./credential-errors.js\";\nimport { FIRST_STREAM_EVENT_TIMEOUT_MS } from \"./first-event-timeout.js\";\nimport { resolveMaxOutputTokensForEngine } from \"./output-tokens.js\";\nimport {\n engineMessagesToBuilderGatewayAnthropic,\n engineToolsToAnthropic,\n} from \"./translate-anthropic.js\";\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineContentPart,\n EngineEvent,\n EngineStreamOptions,\n} from \"./types.js\";\n\nexport const BUILDER_CAPABILITIES: EngineCapabilities = {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n};\n\nexport const BUILDER_SUPPORTED_MODELS = BUILDER_MODEL_CONFIG.supportedModels;\n\n// Keep the foreground hosted gateway timeout below the synchronous serverless\n// wall so the agent loop can append a continuation and persist terminal state\n// before the host hard-kills the invocation.\nconst DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;\nconst MAX_HOSTED_FOREGROUND_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;\n/**\n * Netlify background functions have a 15-minute wall. Keep the Builder gateway\n * ceiling below that, but above the run-manager's 13-minute soft-timeout so\n * durable background runs checkpoint before this timer wins.\n */\nconst MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS = 14 * 60_000;\n/** Local and non-hosted runtimes have no synchronous serverless wall. */\nconst MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS =\n MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\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 *\n * We can't deep-link to a per-org billing page from `BUILDER_ORG_NAME` because\n * that field is the org's display name (e.g. \"Nicholas kipchumba Space\"), not\n * a URL-safe slug or id. URL-encoding the display name produces segments like\n * `/app/organizations/Nicholas%20kipchumba%20Space/billing` which Builder's\n * router treats as unknown and silently bounces to `/app/projects`. The\n * Builder CLI-auth callback doesn't expose the org slug/id today, so we route\n * to the org-agnostic subscription page. Agent Native attribution lets Builder\n * skip generic onboarding for new users who land there from an upgrade CTA.\n */\nasync function buildUpgradeUrl(): Promise<string> {\n const url = new URL(\"https://builder.io/account/subscription\");\n url.searchParams.set(\"signupSource\", \"agent-native\");\n url.searchParams.set(\"agentNativeConnectSource\", \"gateway_quota_upgrade\");\n url.searchParams.set(\"agentNativeFlow\", \"connect_llm\");\n url.searchParams.set(\"framework\", \"agent-native\");\n applyBuilderUtmTrackingParams(url.searchParams, {\n content: \"gateway_quota_upgrade\",\n });\n return url.toString();\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 creds = await resolveBuilderCredentials();\n const authHeader = creds.privateKey ? `Bearer ${creds.privateKey}` : null;\n const spaceId = creds.publicKey;\n const builderUserId = creds.userId;\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 = engineMessagesToBuilderGatewayAnthropic(opts.messages);\n const tools = engineToolsToAnthropic(opts.tools);\n const thinkingBudget =\n opts.providerOptions?.anthropic?.thinking?.budgetTokens;\n const reasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort ??\n (typeof thinkingBudget === \"number\"\n ? mapReasoningEffort(thinkingBudget)\n : undefined),\n );\n\n // Apply prompt caching to system + tools (stable prefix) and to the last\n // user message (moving cache breakpoint so growing history gets cached\n // across tool-loop iterations at ~90% off input cost).\n // Templates can opt out by setting providerOptions.anthropic.cacheControl=false.\n const cacheEnabled =\n opts.providerOptions?.anthropic?.cacheControl !== false;\n\n // System: wrap in array with cache_control when caching is on.\n const systemValue: unknown = opts.systemPrompt\n ? cacheEnabled\n ? [\n {\n type: \"text\",\n text: opts.systemPrompt,\n cache_control: { type: \"ephemeral\" },\n },\n ]\n : opts.systemPrompt\n : undefined;\n\n // Tools: add cache_control to the last tool definition.\n let cachedTools = tools;\n if (cacheEnabled && tools.length > 0) {\n cachedTools = [...tools];\n const last = { ...cachedTools[cachedTools.length - 1] } as any;\n last.cache_control = { type: \"ephemeral\" };\n cachedTools[cachedTools.length - 1] = last;\n }\n\n // Messages: add a moving cache breakpoint on the last user message's last\n // content block so the entire conversation prefix is cached.\n let cachedMessages = messages;\n if (cacheEnabled && messages.length > 0) {\n let lastUserIdx = -1;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n if ((messages[i] as any).role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n if (lastUserIdx >= 0) {\n cachedMessages = [...messages];\n const lastMsg = { ...cachedMessages[lastUserIdx] } as any;\n if (Array.isArray(lastMsg.content) && lastMsg.content.length > 0) {\n const content = [...lastMsg.content];\n const lastBlock = { ...content[content.length - 1] } as any;\n lastBlock.cache_control = { type: \"ephemeral\" };\n content[content.length - 1] = lastBlock;\n lastMsg.content = content;\n cachedMessages[lastUserIdx] = lastMsg;\n }\n }\n }\n\n const body: Record<string, unknown> = {\n model: opts.model,\n messages: cachedMessages,\n ...(systemValue !== undefined ? { system: systemValue } : {}),\n ...(cachedTools.length > 0 ? { tools: cachedTools } : {}),\n max_tokens: resolveMaxOutputTokensForEngine(\n this.name,\n opts.maxOutputTokens,\n opts.model,\n ),\n ...(typeof opts.temperature === \"number\"\n ? { temperature: opts.temperature }\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 = creds.orgName || \"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 ...getBuilderGatewayRequestHeaders(),\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: gatewayAbort.effectiveTimeoutMs(),\n timedOut,\n elapsedMs: Date.now() - tStart,\n });\n }\n yield createBuilderGatewayTimeoutStop(\n err,\n timedOut,\n gatewayAbort.effectiveTimeoutMs(),\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 // A successful gateway call proves the connected credentials are valid\n // again. Clear any prior auth-failure marker so status / chat-card\n // surfaces stop flagging the connection as broken. This is the only\n // self-healing path for workspace/env-managed credentials, which never\n // flow through writeBuilderCredentials.\n try {\n const creds = await resolveBuilderCredentials();\n await clearBuilderCredentialAuthFailure({\n privateKey: creds.privateKey,\n publicKey: creds.publicKey,\n });\n } catch {\n // Marker clearing is best-effort; a stale marker just means the user\n // sees \"reconnect Builder\" until the next successful call clears it.\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 abortSignal: gatewayAbort.signal,\n didGatewayTimeout: gatewayAbort.didTimeout,\n getGatewayTimeoutMs: gatewayAbort.effectiveTimeoutMs,\n onFirstEvent: gatewayAbort.markFirstEvent,\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 await recordBuilderCredentialAuthFailure({ status, code, message });\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 && isBuilderCredentialAuthError(message)) {\n await recordBuilderCredentialAuthFailure({ status, code, message });\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 (code === \"rate_limit_exceeded\") {\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 up transient concurrency throttles and retries\n // the turn. Daily gateway caps use `rate_limit_exceeded` above and must\n // not loop.\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 abortSignal?: AbortSignal,\n): AsyncIterable<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n while (true) {\n const { done, value } = await readStreamChunk(reader, abortSignal);\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 // Flush any bytes the streaming decoder buffered for an incomplete multibyte\n // sequence at the end of the stream; otherwise a trailing multibyte char in\n // the final chunk is silently dropped from the last line.\n buffer += decoder.decode();\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 abortSignal?: AbortSignal;\n didGatewayTimeout?: () => boolean;\n getGatewayTimeoutMs?: () => number;\n onFirstEvent?: () => void;\n gatewayUrl?: URL;\n requestStartedAt?: number;\n } = {},\n): AsyncIterable<EngineEvent> {\n const parts: EngineContentPart[] = [];\n let pendingText = \"\";\n let pendingThinking: { text: string; signature?: string } | null = null;\n\n const flushPendingText = () => {\n if (pendingText) {\n parts.push({ type: \"text\", text: pendingText });\n pendingText = \"\";\n }\n };\n\n const flushPendingThinking = () => {\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 const flushPending = () => {\n flushPendingText();\n flushPendingThinking();\n };\n\n try {\n for await (const line of readJsonlLines(\n reader,\n captureContext.abortSignal,\n )) {\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 // Heartbeats are transport-level keepalives, not proof the model is\n // producing output — every other parsed event counts as first progress.\n if (event?.type !== \"heartbeat\") {\n captureContext.onFirstEvent?.();\n }\n\n switch (event.type) {\n case \"text-delta\": {\n const text = event.text ?? \"\";\n flushPendingThinking();\n pendingText += text;\n yield { type: \"text-delta\", text };\n break;\n }\n\n case \"thinking-delta\":\n case \"reasoning-delta\": {\n const text = event.text ?? \"\";\n flushPendingText();\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 \"heartbeat\":\n yield { type: \"gateway-heartbeat\" };\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 === \"invalid_request\") {\n // errorCode has no retry-trigger keywords, so isRetryableError\n // won't loop on broken history.\n const errMsg =\n event.error ||\n event.message ||\n \"Builder gateway rejected the request as malformed.\";\n const errCode =\n typeof event.errorCode === \"string\"\n ? event.errorCode\n : typeof event.code === \"string\"\n ? event.code\n : \"invalid_request\";\n console.warn(\n `[builder-engine] stop reason=invalid_request model=${model} code=${errCode} error=${errMsg}`,\n );\n yield {\n type: \"stop\",\n reason: \"error\",\n error: errMsg,\n errorCode: errCode,\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 gatewayErrCode = event.errorCode ?? event.code;\n const isCredentialAuthError =\n Boolean(explicitErrMsg) &&\n isBuilderCredentialAuthError(String(errMsg));\n // Anthropic's bare \"Connection error.\" often arrives here with no\n // gateway code. Tag it as a network error so in-run retries and\n // run-level resume treat it as transient instead of terminal.\n const isProviderConnectionError =\n typeof explicitErrMsg === \"string\" &&\n isProviderConnectionErrorMessage(String(explicitErrMsg));\n const errCode = isCredentialAuthError\n ? \"builder_auth_error\"\n : isProviderConnectionError\n ? BUILDER_GATEWAY_NETWORK_ERROR_CODE\n : (gatewayErrCode ??\n (!explicitErrMsg ? \"builder_gateway_error\" : undefined));\n console.error(\n `[builder-engine] stop reason=error model=${model} code=${errCode ?? \"(none)\"} error=${errMsg}`,\n );\n if (isCredentialAuthError) {\n await recordBuilderCredentialAuthFailure({\n code:\n typeof gatewayErrCode === \"string\" ? gatewayErrCode : errCode,\n message: String(errMsg),\n });\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 const gatewayTimeoutMs =\n captureContext.getGatewayTimeoutMs?.() ??\n DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;\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 readStreamChunk(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n abortSignal?: AbortSignal,\n): Promise<ReadableStreamReadResult<Uint8Array>> {\n if (!abortSignal) return reader.read();\n if (abortSignal.aborted) {\n return Promise.reject(abortSignal.reason ?? new Error(\"Stream aborted\"));\n }\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n reject(abortSignal.reason ?? new Error(\"Stream aborted\"));\n };\n abortSignal.addEventListener(\"abort\", onAbort, { once: true });\n reader.read().then(\n (value) => {\n abortSignal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (err) => {\n abortSignal.removeEventListener(\"abort\", onAbort);\n reject(err);\n },\n );\n });\n}\n\nfunction normalizeGatewayErrorText(raw: string, status: number): string {\n const text = raw.trim();\n const looksHtml = /<html[\\s>]|<body[\\s>]|<head[\\s>]/i.test(text);\n const readable = looksHtml ? htmlToText(text) : text;\n if (/inactivity timeout/i.test(readable)) {\n return `Builder gateway returned ${status}: Inactivity Timeout. The upstream connection was idle too long before sending data.`;\n }\n if (looksHtml) {\n return `Builder gateway returned ${status}: ${readable.slice(0, 240)}`;\n }\n return readable;\n}\n\nfunction htmlToText(html: string): string {\n return html\n .replace(/<script[\\s\\S]*?<\\/script>/gi, \" \")\n .replace(/<style[\\s\\S]*?<\\/style>/gi, \" \")\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/(p|div|h1|h2|h3|li|tr)>/gi, \"\\n\")\n .replace(/<[^>]+>/g, \" \")\n .replace(/&nbsp;/gi, \" \")\n .replace(/&lt;/gi, \"<\")\n .replace(/&gt;/gi, \">\")\n .replace(/&amp;/gi, \"&\")\n .replace(/&quot;/gi, '\"')\n .replace(/&#39;/gi, \"'\")\n .replace(/[ \\t]+/g, \" \")\n .replace(/\\n\\s+/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\nexport function createBuilderEngine(\n _config: Record<string, unknown> = {},\n): AgentEngine {\n return new BuilderEngine();\n}\n\nfunction resolveMaxBuilderGatewayTimeoutMs(): number {\n if (isInBackgroundFunctionRuntime()) {\n return MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n\n if (!isHostedBuilderRuntime()) {\n return MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n\n try {\n const base = getBuilderGatewayBaseUrl();\n if (/^https?:\\/\\/(localhost|127\\.0\\.0\\.1)([:/]|$)/i.test(base)) {\n return MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n } catch {\n // ignore malformed override\n }\n return MAX_HOSTED_FOREGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\n}\n\nfunction isHostedBuilderRuntime(): boolean {\n if (\n process.env.NETLIFY &&\n process.env.NETLIFY !== \"false\" &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n if (\n process.env.AWS_LAMBDA_FUNCTION_NAME &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n return Boolean(\n process.env.CF_PAGES ||\n process.env.VERCEL ||\n process.env.VERCEL_ENV ||\n process.env.RENDER ||\n process.env.FLY_APP_NAME ||\n process.env.K_SERVICE,\n );\n}\n\nfunction getBuilderGatewayTimeoutMs(): number {\n const raw = process.env.AGENT_NATIVE_BUILDER_GATEWAY_TIMEOUT_MS;\n const maxMs = resolveMaxBuilderGatewayTimeoutMs();\n if (!raw) return maxMs;\n const parsed = Number(raw);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return maxMs;\n }\n return Math.min(parsed, maxMs);\n}\n\n/**\n * Two-stage abort deadline: until the first real stream event arrives, the\n * effective deadline is min(totalTimeoutMs, FIRST_STREAM_EVENT_TIMEOUT_MS) —\n * a wedged gateway that never streams anything gets cut off in ~2 minutes\n * instead of riding the full flat timeout. Once `markFirstEvent()` fires, the\n * timer reschedules for whatever remains of the original total deadline, so\n * a request that starts streaming still gets the full budget it always did.\n */\nfunction createGatewayAbortSignal(\n parentSignal: AbortSignal,\n totalTimeoutMs: number,\n): {\n signal: AbortSignal;\n didTimeout: () => boolean;\n effectiveTimeoutMs: () => number;\n markFirstEvent: () => void;\n cleanup: () => void;\n} {\n const controller = new AbortController();\n let timedOut = false;\n let firstEventSeen = false;\n const startedAt = Date.now();\n\n const abortFromParent = () => {\n if (!controller.signal.aborted) {\n controller.abort(parentSignal.reason);\n }\n };\n\n const fireTimeout = () => {\n timedOut = true;\n if (!controller.signal.aborted) {\n controller.abort(new Error(\"Builder gateway request timed out\"));\n }\n };\n\n const firstEventDeadlineMs = Math.min(\n totalTimeoutMs,\n FIRST_STREAM_EVENT_TIMEOUT_MS,\n );\n let timeout = setTimeout(fireTimeout, firstEventDeadlineMs);\n\n if (parentSignal.aborted) abortFromParent();\n parentSignal.addEventListener(\"abort\", abortFromParent, { once: true });\n\n return {\n signal: controller.signal,\n didTimeout: () => timedOut,\n effectiveTimeoutMs: () =>\n firstEventSeen ? totalTimeoutMs : firstEventDeadlineMs,\n markFirstEvent: () => {\n if (firstEventSeen || timedOut) return;\n firstEventSeen = true;\n // The first-event window was already the binding constraint (total\n // timeout <= it) — nothing to reschedule.\n if (firstEventDeadlineMs >= totalTimeoutMs) return;\n clearTimeout(timeout);\n const remainingMs = Math.max(\n 0,\n totalTimeoutMs - (Date.now() - startedAt),\n );\n timeout = setTimeout(fireTimeout, remainingMs);\n },\n cleanup: () => {\n clearTimeout(timeout);\n parentSignal.removeEventListener(\"abort\", abortFromParent);\n },\n };\n}\n\nfunction isBuilderCredentialAuthError(message: string): boolean {\n const lowerMessage = message.toLowerCase();\n const referencesAccessToken =\n lowerMessage.includes(\"personal access token\") ||\n lowerMessage.includes(\"access token\");\n const rejectedToken =\n lowerMessage.includes(\"invalid\") ||\n lowerMessage.includes(\"inactive\") ||\n lowerMessage.includes(\"expired\") ||\n lowerMessage.includes(\"revoked\");\n return (\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 (referencesAccessToken && rejectedToken)\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 // Anthropic SDK's APIConnectionError default (\"Connection error.\") is\n // often forwarded by the Builder gateway as a stop event with no code.\n text.includes(\"connection error\") ||\n text.includes(\"connection reset\") ||\n text.includes(\"connection closed\") ||\n text.includes(\"stream closed\") ||\n text.includes(\"terminated\")\n );\n}\n\nfunction isProviderConnectionErrorMessage(message: string): boolean {\n return message.trim().toLowerCase() === \"connection error.\";\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"]}