@agent-native/core 0.84.56 → 0.84.58

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 (151) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/core/CHANGELOG.md +14 -0
  3. package/corpus/core/docs/content/locales/ar-SA/template-analytics.mdx +2 -0
  4. package/corpus/core/docs/content/locales/ar-SA/template-clips.mdx +2 -0
  5. package/corpus/core/docs/content/locales/de-DE/template-analytics.mdx +2 -0
  6. package/corpus/core/docs/content/locales/de-DE/template-clips.mdx +2 -0
  7. package/corpus/core/docs/content/locales/es-ES/template-analytics.mdx +2 -0
  8. package/corpus/core/docs/content/locales/es-ES/template-clips.mdx +2 -0
  9. package/corpus/core/docs/content/locales/fr-FR/template-analytics.mdx +2 -0
  10. package/corpus/core/docs/content/locales/fr-FR/template-clips.mdx +2 -0
  11. package/corpus/core/docs/content/locales/hi-IN/template-analytics.mdx +2 -0
  12. package/corpus/core/docs/content/locales/hi-IN/template-clips.mdx +2 -0
  13. package/corpus/core/docs/content/locales/ja-JP/template-analytics.mdx +2 -0
  14. package/corpus/core/docs/content/locales/ja-JP/template-clips.mdx +2 -0
  15. package/corpus/core/docs/content/locales/ko-KR/template-analytics.mdx +2 -0
  16. package/corpus/core/docs/content/locales/ko-KR/template-clips.mdx +2 -0
  17. package/corpus/core/docs/content/locales/pt-BR/template-analytics.mdx +2 -0
  18. package/corpus/core/docs/content/locales/pt-BR/template-clips.mdx +2 -0
  19. package/corpus/core/docs/content/locales/zh-CN/template-analytics.mdx +2 -0
  20. package/corpus/core/docs/content/locales/zh-CN/template-clips.mdx +2 -0
  21. package/corpus/core/docs/content/locales/zh-TW/template-analytics.mdx +2 -0
  22. package/corpus/core/docs/content/locales/zh-TW/template-clips.mdx +2 -0
  23. package/corpus/core/docs/content/template-analytics.mdx +2 -0
  24. package/corpus/core/docs/content/template-clips.mdx +22 -10
  25. package/corpus/core/docs/content/tracking.mdx +2 -0
  26. package/corpus/core/package.json +1 -1
  27. package/corpus/core/src/action.ts +11 -0
  28. package/corpus/core/src/agent/production-agent.ts +24 -46
  29. package/corpus/core/src/client/AssistantChat.tsx +69 -12
  30. package/corpus/core/src/client/MultiTabAssistantChat.tsx +1 -1
  31. package/corpus/core/src/client/conversation/use-near-bottom-autoscroll.ts +45 -2
  32. package/corpus/core/src/coding-tools/run-code.ts +1 -0
  33. package/corpus/core/src/integrations/webhook-handler.ts +10 -9
  34. package/corpus/core/src/server/action-discovery.ts +3 -0
  35. package/corpus/core/src/server/credential-provider.ts +11 -6
  36. package/corpus/templates/analytics/.agents/skills/session-replay/SKILL.md +8 -0
  37. package/corpus/templates/analytics/AGENTS.md +5 -0
  38. package/corpus/templates/analytics/actions/create-session-replay-agent-link.ts +31 -0
  39. package/corpus/templates/analytics/app/i18n/zh-TW.ts +2 -0
  40. package/corpus/templates/analytics/app/i18n-data.ts +20 -0
  41. package/corpus/templates/analytics/app/pages/sessions/SessionDetailPage.tsx +65 -3
  42. package/corpus/templates/analytics/changelog/2026-07-02-session-replays-can-be-copied-as-temporary-private-links-for-agents.md +6 -0
  43. package/corpus/templates/analytics/server/handlers/session-replay.ts +78 -0
  44. package/corpus/templates/analytics/server/lib/agent-chat-plan-mode.ts +29 -0
  45. package/corpus/templates/analytics/server/lib/session-replay-agent-context.ts +313 -0
  46. package/corpus/templates/analytics/server/lib/session-replay.ts +198 -3
  47. package/corpus/templates/analytics/server/plugins/agent-chat.ts +9 -1
  48. package/corpus/templates/analytics/server/routes/[...page].get.ts +104 -1
  49. package/corpus/templates/analytics/server/routes/api/session-replay/agent-context.json.get.ts +48 -0
  50. package/corpus/templates/analytics/server/routes/api/session-replay/agent-events.json.get.ts +63 -0
  51. package/corpus/templates/analytics/shared/session-replay-agent-access.ts +10 -0
  52. package/corpus/templates/clips/.agents/skills/video-sharing/SKILL.md +14 -8
  53. package/corpus/templates/clips/AGENTS.md +3 -2
  54. package/corpus/templates/clips/actions/create-recording-agent-link.ts +90 -0
  55. package/corpus/templates/clips/app/components/player/share-dialog.tsx +43 -46
  56. package/corpus/templates/clips/app/components/sharing/share-ui.tsx +5 -3
  57. package/corpus/templates/clips/app/i18n/ar-SA.ts +1 -1
  58. package/corpus/templates/clips/app/i18n/de-DE.ts +1 -1
  59. package/corpus/templates/clips/app/i18n/en-US.ts +1 -1
  60. package/corpus/templates/clips/app/i18n/es-ES.ts +1 -1
  61. package/corpus/templates/clips/app/i18n/fr-FR.ts +1 -1
  62. package/corpus/templates/clips/app/i18n/hi-IN.ts +1 -1
  63. package/corpus/templates/clips/app/i18n/ja-JP.ts +1 -1
  64. package/corpus/templates/clips/app/i18n/ko-KR.ts +1 -1
  65. package/corpus/templates/clips/app/i18n/pt-BR.ts +1 -1
  66. package/corpus/templates/clips/app/i18n/zh-CN.ts +1 -1
  67. package/corpus/templates/clips/app/i18n/zh-TW.ts +1 -1
  68. package/corpus/templates/clips/app/routes/share.$shareId.tsx +100 -46
  69. package/corpus/templates/clips/changelog/2026-07-02-private-recordings-can-be-shared-with-agents-through-temporary-links-without-making-them-public.md +6 -0
  70. package/corpus/templates/clips/server/lib/public-agent-context.ts +26 -13
  71. package/corpus/templates/clips/server/routes/api/agent-context.json.get.ts +2 -1
  72. package/corpus/templates/clips/server/routes/api/agent-frame.jpg.get.ts +2 -1
  73. package/corpus/templates/clips/server/routes/api/agent-transcript.json.get.ts +2 -1
  74. package/corpus/templates/clips/server/routes/api/public-recording.get.ts +7 -2
  75. package/corpus/templates/clips/shared/agent-context.ts +5 -0
  76. package/corpus/templates/design/actions/list-design-extensions.ts +2 -2
  77. package/corpus/templates/design/app/components/design/CodeWorkbenchHost.tsx +11 -89
  78. package/corpus/templates/design/app/components/design/DesignExtensionsPanel.tsx +314 -181
  79. package/corpus/templates/design/app/components/design/DesignImportPanel.tsx +92 -134
  80. package/corpus/templates/design/app/components/design/EditPanel.tsx +93 -19
  81. package/corpus/templates/design/app/components/design/MultiScreenCanvas.tsx +18 -26
  82. package/corpus/templates/design/app/components/design/TokensPanel.tsx +220 -192
  83. package/corpus/templates/design/app/components/design/code-workbench-theme.ts +150 -0
  84. package/corpus/templates/design/app/i18n/zh-TW.ts +5 -7
  85. package/corpus/templates/design/app/i18n-data.ts +61 -77
  86. package/corpus/templates/design/app/lib/design-import.ts +4 -1
  87. package/corpus/templates/design/app/pages/DesignEditor.tsx +97 -48
  88. package/corpus/templates/design/changelog/2026-07-02-design-inspector-and-canvas-controls-stay-consistent-when-se.md +6 -0
  89. package/corpus/templates/design/changelog/2026-07-02-fixed-a-crash-when-opening-the-code-editor.md +6 -0
  90. package/corpus/templates/design/changelog/2026-07-02-fixed-motion-drawer-open-transition.md +6 -0
  91. package/corpus/templates/design/changelog/2026-07-02-improved-design-assets-panel.md +6 -0
  92. package/dist/action.d.ts +8 -0
  93. package/dist/action.d.ts.map +1 -1
  94. package/dist/action.js +3 -0
  95. package/dist/action.js.map +1 -1
  96. package/dist/agent/production-agent.d.ts +10 -11
  97. package/dist/agent/production-agent.d.ts.map +1 -1
  98. package/dist/agent/production-agent.js +21 -44
  99. package/dist/agent/production-agent.js.map +1 -1
  100. package/dist/client/AssistantChat.d.ts +1 -0
  101. package/dist/client/AssistantChat.d.ts.map +1 -1
  102. package/dist/client/AssistantChat.js +61 -11
  103. package/dist/client/AssistantChat.js.map +1 -1
  104. package/dist/client/MultiTabAssistantChat.js +1 -1
  105. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  106. package/dist/client/conversation/use-near-bottom-autoscroll.d.ts.map +1 -1
  107. package/dist/client/conversation/use-near-bottom-autoscroll.js +43 -2
  108. package/dist/client/conversation/use-near-bottom-autoscroll.js.map +1 -1
  109. package/dist/coding-tools/run-code.d.ts.map +1 -1
  110. package/dist/coding-tools/run-code.js +1 -0
  111. package/dist/coding-tools/run-code.js.map +1 -1
  112. package/dist/collab/routes.d.ts +2 -2
  113. package/dist/integrations/webhook-handler.d.ts +1 -0
  114. package/dist/integrations/webhook-handler.d.ts.map +1 -1
  115. package/dist/integrations/webhook-handler.js +9 -9
  116. package/dist/integrations/webhook-handler.js.map +1 -1
  117. package/dist/notifications/routes.d.ts +3 -3
  118. package/dist/observability/routes.d.ts +3 -3
  119. package/dist/resources/handlers.d.ts +1 -1
  120. package/dist/server/action-discovery.d.ts.map +1 -1
  121. package/dist/server/action-discovery.js +3 -0
  122. package/dist/server/action-discovery.js.map +1 -1
  123. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  124. package/dist/server/credential-provider.d.ts +4 -0
  125. package/dist/server/credential-provider.d.ts.map +1 -1
  126. package/dist/server/credential-provider.js +13 -7
  127. package/dist/server/credential-provider.js.map +1 -1
  128. package/docs/content/locales/ar-SA/template-analytics.mdx +2 -0
  129. package/docs/content/locales/ar-SA/template-clips.mdx +2 -0
  130. package/docs/content/locales/de-DE/template-analytics.mdx +2 -0
  131. package/docs/content/locales/de-DE/template-clips.mdx +2 -0
  132. package/docs/content/locales/es-ES/template-analytics.mdx +2 -0
  133. package/docs/content/locales/es-ES/template-clips.mdx +2 -0
  134. package/docs/content/locales/fr-FR/template-analytics.mdx +2 -0
  135. package/docs/content/locales/fr-FR/template-clips.mdx +2 -0
  136. package/docs/content/locales/hi-IN/template-analytics.mdx +2 -0
  137. package/docs/content/locales/hi-IN/template-clips.mdx +2 -0
  138. package/docs/content/locales/ja-JP/template-analytics.mdx +2 -0
  139. package/docs/content/locales/ja-JP/template-clips.mdx +2 -0
  140. package/docs/content/locales/ko-KR/template-analytics.mdx +2 -0
  141. package/docs/content/locales/ko-KR/template-clips.mdx +2 -0
  142. package/docs/content/locales/pt-BR/template-analytics.mdx +2 -0
  143. package/docs/content/locales/pt-BR/template-clips.mdx +2 -0
  144. package/docs/content/locales/zh-CN/template-analytics.mdx +2 -0
  145. package/docs/content/locales/zh-CN/template-clips.mdx +2 -0
  146. package/docs/content/locales/zh-TW/template-analytics.mdx +2 -0
  147. package/docs/content/locales/zh-TW/template-clips.mdx +2 -0
  148. package/docs/content/template-analytics.mdx +2 -0
  149. package/docs/content/template-clips.mdx +22 -10
  150. package/docs/content/tracking.mdx +2 -0
  151. package/package.json +1 -1
@@ -60,6 +60,10 @@ export function readDeployCredentialEnv(key) {
60
60
  * single-tenant contexts. In hosted production with a shared database, every
61
61
  * signed-in user needs their own user/org/workspace credential so one deploy
62
62
  * key does not silently power another tenant's chat.
63
+ *
64
+ * @deprecated Use `canUseDeployCredentialFallbackForRequest()` for generic
65
+ * provider secrets. This stricter helper remains for legacy call sites with
66
+ * identity-bearing deploy credentials.
63
67
  */
64
68
  export function isDeployCredentialFallbackAllowed() {
65
69
  if (!isProductionLikeRuntime())
@@ -68,11 +72,13 @@ export function isDeployCredentialFallbackAllowed() {
68
72
  }
69
73
  export function canUseDeployCredentialFallbackForRequest() {
70
74
  const email = getRequestUserEmail();
71
- if (email && isHostedWorkspaceRuntime())
72
- return false;
73
75
  if (!email)
74
76
  return true;
75
- return isDeployCredentialFallbackAllowed();
77
+ if (isHostedWorkspaceRuntime())
78
+ return false;
79
+ if (!isProductionLikeRuntime())
80
+ return true;
81
+ return isLocalDatabase();
76
82
  }
77
83
  const BUILDER_CREDENTIAL_KEYS = [
78
84
  "BUILDER_PRIVATE_KEY",
@@ -722,10 +728,10 @@ export async function resolveSecret(key) {
722
728
  }
723
729
  // Secrets table not ready — treat as missing.
724
730
  }
725
- // Authenticated multi-tenant context: never fall back to process.env.
726
- // The deploy-level value would silently impersonate the actual key
727
- // owner across every tenant. Local/single-tenant deployments keep the
728
- // original env fallback for BYO-server workflows.
731
+ // Read deployment-provided env values as fallbacks; framework code must not
732
+ // write to `process.env`, but keys supplied by the host remain valid config.
733
+ // Builder credentials keep a narrower path below because those keys carry a
734
+ // Builder identity rather than just enabling a provider call.
729
735
  const envFallback = (isBuilderCredentialKey(key)
730
736
  ? canUseBuilderDeployCredentialFallbackForRequest()
731
737
  : canUseDeployCredentialFallbackForRequest())
@@ -1 +1 @@
1
- {"version":3,"file":"credential-provider.js","sourceRoot":"","sources":["../../src/server/credential-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;QACpC,gDAAgD,CACjD,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gCAAgC;IAC9C,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,iCAAiC;QAC7C,+CAA+C,CAChD,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,0BAA0B;IACxC,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,2BAA2B;QACvC,mDAAmD,CACpD,CAAC;AACJ,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,oBAAoB;IAClC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;IAC5C,OAAO,GAAG,CAAC,CAAC,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC","sourcesContent":["/**\n * Credential provider abstraction.\n *\n * Every feature that needs an external credential (Anthropic API key,\n * Google OAuth tokens, OpenAI key, Slack bot token, etc.) should go through\n * one of the resolve*() helpers here instead of reading `process.env`\n * directly. That way the same feature can work in three modes:\n *\n * 1. User set their own key in .env → use it directly\n * 2. User connected Builder via `/cli-auth` → route through Builder proxy\n * 3. Neither → throw FeatureNotConfigured\n *\n * Templates catch FeatureNotConfigured and show a \"Connect Builder (1 click) /\n * set up your own key (guide)\" card.\n *\n * Today these helpers are used by the Builder-hosted LLM gateway, and the\n * shape is meant to grow to cover future managed credential integrations\n * (e.g. additional Builder-hosted services) without rewrites.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { isLocalDatabase } from \"../db/client.js\";\nimport { getRequestUserEmail, getRequestOrgId } from \"./request-context.js\";\n\n/**\n * Decide which `app_secrets` scope a Builder/credential write should use.\n *\n * Org scope (\"everyone in this org sees these credentials\") wins when the\n * connecting user is an owner or admin of an active org — the write\n * privileges shared infra. A plain member or a user without an active\n * org falls through to per-user scope so a teammate can't silently\n * overwrite the org-shared connection.\n */\nexport function resolveCredentialWriteScope(\n email: string,\n orgId: string | null | undefined,\n role: string | null | undefined,\n): { scope: \"user\" | \"org\"; scopeId: string } {\n if (orgId && (role === \"owner\" || role === \"admin\")) {\n return { scope: \"org\", scopeId: orgId };\n }\n return { scope: \"user\", scopeId: email };\n}\n\nexport class FeatureNotConfiguredError extends Error {\n readonly requiredCredential: string;\n readonly builderConnectUrl?: string;\n readonly byokDocsUrl?: string;\n\n constructor(opts: {\n requiredCredential: string;\n message?: string;\n builderConnectUrl?: string;\n byokDocsUrl?: string;\n }) {\n super(\n opts.message ??\n `Feature requires credential \"${opts.requiredCredential}\". Connect Builder or set your own key.`,\n );\n this.name = \"FeatureNotConfiguredError\";\n this.requiredCredential = opts.requiredCredential;\n this.builderConnectUrl = opts.builderConnectUrl;\n this.byokDocsUrl = opts.byokDocsUrl;\n }\n}\n\n/**\n * Deployment-level credential fallback for single-tenant/local operation.\n * Multi-tenant call sites must gate this explicitly before calling.\n */\nexport function readDeployCredentialEnv(key: string): string | undefined {\n return process.env[key] || undefined;\n}\n\n/**\n * Deployment-level credentials are safe as a runtime fallback only in local /\n * single-tenant contexts. In hosted production with a shared database, every\n * signed-in user needs their own user/org/workspace credential so one deploy\n * key does not silently power another tenant's chat.\n */\nexport function isDeployCredentialFallbackAllowed(): boolean {\n if (!isProductionLikeRuntime()) return true;\n return isLocalDatabase();\n}\n\nexport function canUseDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n if (email && isHostedWorkspaceRuntime()) return false;\n if (!email) return true;\n return isDeployCredentialFallbackAllowed();\n}\n\nconst BUILDER_CREDENTIAL_KEYS = [\n \"BUILDER_PRIVATE_KEY\",\n \"BUILDER_PUBLIC_KEY\",\n \"BUILDER_USER_ID\",\n \"BUILDER_ORG_NAME\",\n \"BUILDER_ORG_KIND\",\n \"BUILDER_SUBSCRIPTION\",\n \"BUILDER_SUBSCRIPTION_LEVEL\",\n \"BUILDER_SUBSCRIPTION_NAME\",\n \"BUILDER_IS_ENTERPRISE\",\n \"BUILDER_IS_FREE_ACCOUNT\",\n] as const;\n\nfunction isBuilderCredentialKey(key: string): boolean {\n return (BUILDER_CREDENTIAL_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHostedWorkspaceRuntime(): boolean {\n const hasFusionPreview = Boolean(\n process.env.FUSION_ENVIRONMENT ||\n process.env.FUSION_ENV_ORIGIN ||\n process.env.VITE_FUSION_ENV_ORIGIN,\n );\n return (\n /^(1|true)$/i.test(process.env.AGENT_NATIVE_WORKSPACE ?? \"\") ||\n /^(1|true)$/i.test(process.env.VITE_AGENT_NATIVE_WORKSPACE ?? \"\") ||\n hasFusionPreview\n );\n}\n\nfunction isProductionLikeRuntime(): boolean {\n return (\n process.env.NODE_ENV === \"production\" ||\n /^(1|true)$/i.test(process.env.NETLIFY ?? \"\") ||\n /^(1|true)$/i.test(process.env.VERCEL ?? \"\") ||\n /^(1|true)$/i.test(process.env.CF_PAGES ?? \"\") ||\n Boolean(\n process.env.AWS_LAMBDA_FUNCTION_NAME ||\n process.env.AWS_EXECUTION_ENV ||\n process.env.FUNCTIONS_WORKER_RUNTIME ||\n process.env.K_SERVICE ||\n process.env.RENDER,\n )\n );\n}\n\n/**\n * Whether deployment-level Builder env keys may back the current request.\n *\n * This is intentionally self-contained rather than delegating to\n * `canUseDeployCredentialFallbackForRequest`. That generic helper blocks the\n * deploy fallback for any signed-in user in a hosted workspace runtime, so the\n * Builder dogfooding escape hatch must apply its own hosted-workspace exception\n * here instead of inheriting the generic helper's stricter (and hatch-unaware)\n * decision. Reading the env once into locals keeps the rules legible.\n *\n * Rules (all evaluated against the live request/runtime, not a build-time value):\n * - No signed-in user → safe to use the deploy env (nobody to mis-identify).\n * - Hosted workspace + signed-in user → deploy-level Builder keys would\n * impersonate that user, so block them — UNLESS a developer has explicitly\n * opted into the local dogfooding escape hatch (non-prod only). Default OFF;\n * hosted/shared production deployments are never affected.\n * - Otherwise → allowed in non-prod, or on a local/single-tenant database.\n */\nfunction canUseBuilderDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n if (!email) return true;\n\n const isProductionRuntime = isProductionLikeRuntime();\n // Local dogfooding escape hatch: lets the env / root-`.env` Builder key back\n // a signed-in user so running the app locally doesn't require completing the\n // Builder connect flow first. Non-prod only.\n const localDevOptIn =\n !isProductionRuntime &&\n /^(1|true)$/i.test(process.env.AGENT_NATIVE_LOCAL_BUILDER_ENV ?? \"\");\n\n if (isHostedWorkspaceRuntime() && !localDevOptIn) return false;\n\n // Deploy fallback is safe in non-prod or on a local/single-tenant database.\n return !isProductionRuntime || isLocalDatabase();\n}\n\nfunction shouldTraceCredentialResolve(): boolean {\n return /^(1|true)$/i.test(\n process.env.AGENT_NATIVE_DEBUG_CREDENTIAL_RESOLVE ??\n process.env.DEBUG_CREDENTIAL_RESOLVE ??\n \"\",\n );\n}\n\n// ---------------------------------------------------------------------------\n// Builder credential resolution:\n//\n// 1. **Request-scoped credentials.** A signed-in user can connect Builder\n// through the CLI-auth flow. Owner/admin connections land at org scope;\n// member/no-org connections land at user scope.\n//\n// 2. **Deployment fallback.** BUILDER_PRIVATE_KEY in env still makes local\n// and single-tenant deploys work out of the box, but it no longer blocks\n// per-user connect. Request-scoped credentials win whenever present.\n//\n// To run multi-tenant SaaS: prefer leaving BUILDER_PRIVATE_KEY unset unless a\n// shared fallback identity is intentional.\n// ---------------------------------------------------------------------------\n\ntype BuilderCredentialSource = \"user\" | \"org\" | \"workspace\" | \"env\";\ninterface BuilderResolvedCredentials {\n privateKey: string | null;\n publicKey: string | null;\n userId: string | null;\n orgName: string | null;\n orgKind: string | null;\n subscription: string | null;\n subscriptionLevel: string | null;\n subscriptionName: string | null;\n isEnterprise: boolean | null;\n isFreeAccount: boolean | null;\n source: Exclude<BuilderCredentialSource, \"env\">;\n}\n\nfunction isCompleteBuilderConnection(creds: BuilderResolvedCredentials) {\n return Boolean(creds.privateKey && creds.publicKey);\n}\n\nfunction readOptionalBuilderBoolean(\n value: string | null | undefined,\n): boolean | null {\n if (value == null || value === \"\") return null;\n return /^(1|true)$/i.test(value);\n}\n\nexport function isBuilderPrivateKey(value: string | null | undefined): boolean {\n return typeof value === \"string\" && value.trim().startsWith(\"bpk-\");\n}\n\nasync function readBuilderCredentialScope(\n readAppSecret: typeof import(\"../secrets/storage.js\").readAppSecret,\n scope: \"user\" | \"org\" | \"workspace\",\n scopeId: string,\n): Promise<BuilderResolvedCredentials> {\n const values = await Promise.all(\n BUILDER_CREDENTIAL_KEYS.map(async (key) => {\n const secret = await readAppSecret({ key, scope, scopeId });\n return [key, secret?.value ?? null] as const;\n }),\n );\n const map = new Map<string, string | null>(values);\n return {\n privateKey: map.get(\"BUILDER_PRIVATE_KEY\") ?? null,\n publicKey: map.get(\"BUILDER_PUBLIC_KEY\") ?? null,\n userId: map.get(\"BUILDER_USER_ID\") ?? null,\n orgName: map.get(\"BUILDER_ORG_NAME\") ?? null,\n orgKind: map.get(\"BUILDER_ORG_KIND\") ?? null,\n subscription: map.get(\"BUILDER_SUBSCRIPTION\") ?? null,\n subscriptionLevel: map.get(\"BUILDER_SUBSCRIPTION_LEVEL\") ?? null,\n subscriptionName: map.get(\"BUILDER_SUBSCRIPTION_NAME\") ?? null,\n isEnterprise: readOptionalBuilderBoolean(map.get(\"BUILDER_IS_ENTERPRISE\")),\n isFreeAccount: readOptionalBuilderBoolean(\n map.get(\"BUILDER_IS_FREE_ACCOUNT\"),\n ),\n source: scope === \"workspace\" ? \"workspace\" : scope,\n };\n}\n\nasync function resolveScopedBuilderCredential(\n key: string,\n): Promise<{ value: string; source: \"user\" | \"org\" | \"workspace\" } | null> {\n const email = getRequestUserEmail();\n if (!email) return null;\n\n // Trace only when explicitly requested. These diagnostics are useful for\n // support, but they include account identifiers and run on hot paths.\n const traceLookup = shouldTraceCredentialResolve();\n let scopeAttempted = \"user\";\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n\n // 1. Per-user override: a user can paste their own key in settings to\n // overrule the org-shared one (handy for a personal sandbox).\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret) {\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=user hit=true`,\n );\n }\n return { value: userSecret.value, source: \"user\" };\n }\n\n // 2. Per-org shared credential: when one teammate connects Builder\n // as an owner/admin we write the OAuth result at org scope so\n // every member of that org gets the AI chat working without\n // re-running the connect flow. Resolution falls back here\n // silently — the caller never has to know which scope answered.\n const orgId = getRequestOrgId();\n if (orgId) {\n scopeAttempted = \"org\";\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret) {\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=org hit=true`,\n );\n }\n return { value: orgSecret.value, source: \"org\" };\n }\n\n // Older setup flows wrote shared credentials at workspace scope.\n // Keep reading those rows so status UIs and runtime resolution agree\n // for users who connected before org-scoped Builder credentials existed.\n scopeAttempted = \"workspace\";\n const workspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: orgId,\n });\n if (workspaceSecret) {\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=workspace hit=true`,\n );\n }\n return { value: workspaceSecret.value, source: \"workspace\" };\n }\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} miss tried=user,org,workspace`,\n );\n }\n } else {\n scopeAttempted = \"workspace-solo\";\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret) {\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=workspace-solo hit=true`,\n );\n }\n return { value: soloWorkspaceSecret.value, source: \"workspace\" };\n }\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=(none) miss tried=user,workspace-solo`,\n );\n }\n }\n } catch (err) {\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=${scopeAttempted} error=${(err as Error)?.message ?? err}`,\n );\n }\n // Secrets table not ready — treat as missing.\n }\n return null;\n}\n\nasync function resolveScopedBuilderCredentials(): Promise<BuilderResolvedCredentials | null> {\n const email = getRequestUserEmail();\n if (!email) return null;\n\n const traceLookup = shouldTraceCredentialResolve();\n let scopeAttempted = \"user\";\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n const traceScope = (creds: BuilderResolvedCredentials, scopeId: string) => {\n if (!traceLookup) return;\n console.log(\n `[builder-credential] scope=${creds.source} scopeId=${scopeId} email=${email} complete=${isCompleteBuilderConnection(creds)} private=${Boolean(creds.privateKey)} public=${Boolean(creds.publicKey)}`,\n );\n };\n\n const userCreds = await readBuilderCredentialScope(\n readAppSecret,\n \"user\",\n email,\n );\n traceScope(userCreds, email);\n if (isCompleteBuilderConnection(userCreds)) return userCreds;\n\n const orgId = getRequestOrgId();\n if (orgId) {\n scopeAttempted = \"org\";\n const orgCreds = await readBuilderCredentialScope(\n readAppSecret,\n \"org\",\n orgId,\n );\n traceScope(orgCreds, orgId);\n if (isCompleteBuilderConnection(orgCreds)) return orgCreds;\n\n scopeAttempted = \"workspace\";\n const workspaceCreds = await readBuilderCredentialScope(\n readAppSecret,\n \"workspace\",\n orgId,\n );\n traceScope(workspaceCreds, orgId);\n if (isCompleteBuilderConnection(workspaceCreds)) return workspaceCreds;\n } else {\n scopeAttempted = \"workspace-solo\";\n const scopeId = `solo:${email}`;\n const workspaceCreds = await readBuilderCredentialScope(\n readAppSecret,\n \"workspace\",\n scopeId,\n );\n traceScope(workspaceCreds, scopeId);\n if (isCompleteBuilderConnection(workspaceCreds)) return workspaceCreds;\n }\n } catch (err) {\n if (traceLookup) {\n console.log(\n `[builder-credential] email=${email} scope=${scopeAttempted} credentials error=${(err as Error)?.message ?? err}`,\n );\n }\n }\n return null;\n}\n\n/**\n * Resolve a Builder credential for the current request. User/org credentials\n * win; deployment env is only a fallback. This lets local/root .env keys keep\n * a template working while still allowing users to connect their own Builder\n * account from Settings or onboarding.\n */\nexport async function resolveBuilderCredential(\n key: string,\n): Promise<string | null> {\n const scoped = await resolveScopedBuilderCredential(key);\n if (scoped) return scoped.value;\n if (!canUseBuilderDeployCredentialFallbackForRequest()) return null;\n return readDeployCredentialEnv(key) ?? null;\n}\n\n/**\n * True when `BUILDER_PRIVATE_KEY` is set at the deployment level. This means\n * a deploy-level fallback exists; it does not prevent per-user connect.\n */\nexport function isBuilderEnvManaged(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/**\n * Resolve the Builder private key for the current request. User/org OAuth\n * credentials win; deploy-level `BUILDER_PRIVATE_KEY` is the fallback.\n */\nexport async function resolveBuilderPrivateKey(): Promise<string | null> {\n return resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n}\n\n/**\n * Resolve the current user's Builder auth header.\n * Returns `\"Bearer <key>\"` or null.\n */\nexport async function resolveBuilderAuthHeader(): Promise<string | null> {\n const key = await resolveBuilderPrivateKey();\n return key ? `Bearer ${key}` : null;\n}\n\n/**\n * Check whether the current user has a Builder private key configured\n * (per-user or deployment-level).\n */\nexport async function resolveHasBuilderPrivateKey(): Promise<boolean> {\n return !!(await resolveBuilderPrivateKey());\n}\n\n/**\n * Check whether the current request has the complete Builder credential bundle\n * needed for Builder-backed assistant/image-generation calls.\n */\nexport async function resolveHasCompleteBuilderConnection(): Promise<boolean> {\n const creds = await resolveBuilderCredentials();\n return !!(creds.privateKey && creds.publicKey);\n}\n\n/**\n * Resolve where the effective Builder assistant connection came from. This\n * intentionally requires a complete private+public key pair from one scope so\n * status UIs don't report a mixed user/org credential set as connected.\n */\nexport async function resolveBuilderCredentialSource(): Promise<BuilderCredentialSource | null> {\n const scoped = await resolveScopedBuilderCredentials();\n if (scoped) return scoped.source;\n return canUseBuilderDeployCredentialFallbackForRequest() &&\n process.env.BUILDER_PRIVATE_KEY\n ? \"env\"\n : null;\n}\n\n/**\n * Resolve the Builder assistant credential bundle from one complete scope.\n * A partial user row is treated as a miss so the org-shared connection can\n * still power the assistant for teammates.\n */\nexport async function resolveBuilderCredentials(): Promise<{\n privateKey: string | null;\n publicKey: string | null;\n userId: string | null;\n orgName: string | null;\n orgKind: string | null;\n subscription: string | null;\n subscriptionLevel: string | null;\n subscriptionName: string | null;\n isEnterprise: boolean | null;\n isFreeAccount: boolean | null;\n}> {\n const scoped = await resolveScopedBuilderCredentials();\n if (scoped) {\n const {\n privateKey,\n publicKey,\n userId,\n orgName,\n orgKind,\n subscription,\n subscriptionLevel,\n subscriptionName,\n isEnterprise,\n isFreeAccount,\n } = scoped;\n return {\n privateKey,\n publicKey,\n userId,\n orgName,\n orgKind,\n subscription,\n subscriptionLevel,\n subscriptionName,\n isEnterprise,\n isFreeAccount,\n };\n }\n const privateKey = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_PRIVATE_KEY\") ?? null)\n : null;\n const publicKey = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_PUBLIC_KEY\") ?? null)\n : null;\n const userId = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_USER_ID\") ?? null)\n : null;\n const orgName = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_ORG_NAME\") ?? null)\n : null;\n const orgKind = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_ORG_KIND\") ?? null)\n : null;\n const subscription = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_SUBSCRIPTION\") ?? null)\n : null;\n const subscriptionLevel = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_SUBSCRIPTION_LEVEL\") ?? null)\n : null;\n const subscriptionName = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_SUBSCRIPTION_NAME\") ?? null)\n : null;\n const isEnterprise = canUseBuilderDeployCredentialFallbackForRequest()\n ? readOptionalBuilderBoolean(\n readDeployCredentialEnv(\"BUILDER_IS_ENTERPRISE\"),\n )\n : null;\n const isFreeAccount = canUseBuilderDeployCredentialFallbackForRequest()\n ? readOptionalBuilderBoolean(\n readDeployCredentialEnv(\"BUILDER_IS_FREE_ACCOUNT\"),\n )\n : null;\n return {\n privateKey,\n publicKey,\n userId,\n orgName,\n orgKind,\n subscription,\n subscriptionLevel,\n subscriptionName,\n isEnterprise,\n isFreeAccount,\n };\n}\n\nconst BUILDER_AUTH_FAILURE_SETTING_PREFIX = \"builder-auth-failure:\";\n\nexport interface BuilderCredentialAuthFailure {\n fingerprint: string;\n message: string;\n status?: number;\n code?: string;\n at: number;\n ownerEmail?: string | null;\n orgId?: string | null;\n}\n\nexport function builderCredentialFingerprint(\n privateKey?: string | null,\n publicKey?: string | null,\n): string | null {\n if (!privateKey || !publicKey) return null;\n return createHash(\"sha256\")\n .update(privateKey)\n .update(\"\\0\")\n .update(publicKey)\n .digest(\"hex\")\n .slice(0, 24);\n}\n\nfunction builderAuthFailureSettingKey(fingerprint: string): string {\n return `${BUILDER_AUTH_FAILURE_SETTING_PREFIX}${fingerprint}`;\n}\n\nexport async function getBuilderCredentialAuthFailure(\n creds: {\n privateKey?: string | null;\n publicKey?: string | null;\n } = {},\n): Promise<BuilderCredentialAuthFailure | null> {\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return null;\n try {\n const { getSetting } = await import(\"../settings/store.js\");\n const row = await getSetting(builderAuthFailureSettingKey(fingerprint));\n if (!row) return null;\n return {\n fingerprint,\n message:\n typeof row.message === \"string\" && row.message\n ? row.message\n : \"Builder rejected the connected credentials. Reconnect Builder.io.\",\n status: typeof row.status === \"number\" ? row.status : undefined,\n code: typeof row.code === \"string\" ? row.code : undefined,\n at: typeof row.at === \"number\" ? row.at : Date.now(),\n ownerEmail:\n typeof row.ownerEmail === \"string\" ? row.ownerEmail : undefined,\n orgId: typeof row.orgId === \"string\" ? row.orgId : undefined,\n };\n } catch {\n return null;\n }\n}\n\nexport async function recordBuilderCredentialAuthFailure(details?: {\n status?: number;\n code?: string;\n message?: string;\n}): Promise<void> {\n try {\n const creds = await resolveBuilderCredentials();\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return;\n const { putSetting } = await import(\"../settings/store.js\");\n await putSetting(builderAuthFailureSettingKey(fingerprint), {\n fingerprint,\n message:\n details?.message ||\n \"Builder rejected the connected credentials. Reconnect Builder.io.\",\n ...(typeof details?.status === \"number\" && { status: details.status }),\n ...(details?.code && { code: details.code }),\n at: Date.now(),\n ownerEmail: getRequestUserEmail() ?? null,\n orgId: getRequestOrgId() ?? null,\n });\n } catch {\n // Best-effort marker only; the chat error is still returned to the user.\n }\n}\n\nexport async function clearBuilderCredentialAuthFailure(creds: {\n privateKey?: string | null;\n publicKey?: string | null;\n}): Promise<void> {\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return;\n try {\n const { deleteSetting } = await import(\"../settings/store.js\");\n await deleteSetting(builderAuthFailureSettingKey(fingerprint));\n } catch {\n // A stale failure marker should not block writing fresh credentials.\n }\n}\n\n/**\n * Write Builder credentials to `app_secrets`.\n *\n * Scope decision (see `resolveCredentialWriteScope`): when the connecting\n * user is owner/admin of an active org we write at `scope: \"org\"` so every\n * member of that org auto-resolves the credentials via\n * `resolveBuilderCredential`'s org fallback — no per-user re-connect\n * needed. A plain member or a user with no active org writes at\n * `scope: \"user\"` (the safe default that doesn't trample the org's shared\n * connection).\n *\n * Stale-credential cleanup: before writing the new values we (1) clear ALL\n * five BUILDER_* keys at the target scope, so optional fields the new\n * connection doesn't carry (e.g. user picked a Builder space that returns\n * no orgName) don't leave the previous connection's metadata behind, and\n * (2) when writing at org scope, also clear the writer's own user-scope\n * BUILDER_* rows so a stale personal override from an earlier connect\n * doesn't shadow the new org write on resolution (user scope wins org\n * scope by design — see `resolveScopedBuilderCredential`). The org-scope\n * row is intentionally left alone when writing at user scope: that row is\n * shared with the rest of the org and a single user's personal override\n * shouldn't blow it away. (Victoria's \"I signed in again with my Builder\n * space and it still says no credits\" report on 2026-05-11 was exactly\n * this stale-shadow case.)\n *\n * Returns the actual scope/scopeId used so the caller can show \"Connected\n * for Builder.io\" vs \"Connected (personal)\" in the UI.\n */\nexport async function writeBuilderCredentials(\n email: string,\n creds: {\n privateKey: string;\n publicKey: string;\n userId?: string | null;\n orgName?: string | null;\n orgKind?: string | null;\n subscription?: string | null;\n subscriptionLevel?: string | null;\n subscriptionName?: string | null;\n isEnterprise?: boolean | null;\n isFreeAccount?: boolean | null;\n },\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const privateKey = creds.privateKey.trim();\n const publicKey = creds.publicKey.trim();\n if (!isBuilderPrivateKey(privateKey)) {\n throw new Error(\n \"Builder returned a credential that is not a Builder private key (expected bpk-...). Restart the Builder connect flow and choose a space that can issue a private key.\",\n );\n }\n if (!publicKey) {\n throw new Error(\n \"Builder did not return a public API key. Restart the Builder connect flow.\",\n );\n }\n\n const { writeAppSecret, deleteAppSecret } =\n await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n\n // Clear stale rows before writing the new connection. See the function's\n // doc comment for the two cases this handles.\n const cleanups: Array<Promise<unknown>> = BUILDER_CREDENTIAL_KEYS.map((key) =>\n deleteAppSecret({\n key,\n scope: target.scope,\n scopeId: target.scopeId,\n }).catch(() => {}),\n );\n if (target.scope === \"org\") {\n for (const key of BUILDER_CREDENTIAL_KEYS) {\n cleanups.push(\n deleteAppSecret({ key, scope: \"user\", scopeId: email }).catch(() => {}),\n );\n }\n }\n await Promise.all(cleanups);\n\n const entries: Array<{ key: string; value: string }> = [\n { key: \"BUILDER_PRIVATE_KEY\", value: privateKey },\n { key: \"BUILDER_PUBLIC_KEY\", value: publicKey },\n ];\n if (creds.userId) {\n entries.push({ key: \"BUILDER_USER_ID\", value: creds.userId });\n }\n if (creds.orgName) {\n entries.push({ key: \"BUILDER_ORG_NAME\", value: creds.orgName });\n }\n if (creds.orgKind) {\n entries.push({ key: \"BUILDER_ORG_KIND\", value: creds.orgKind });\n }\n if (creds.subscription) {\n entries.push({ key: \"BUILDER_SUBSCRIPTION\", value: creds.subscription });\n }\n if (creds.subscriptionLevel) {\n entries.push({\n key: \"BUILDER_SUBSCRIPTION_LEVEL\",\n value: creds.subscriptionLevel,\n });\n }\n if (creds.subscriptionName) {\n entries.push({\n key: \"BUILDER_SUBSCRIPTION_NAME\",\n value: creds.subscriptionName,\n });\n }\n if (typeof creds.isEnterprise === \"boolean\") {\n entries.push({\n key: \"BUILDER_IS_ENTERPRISE\",\n value: String(creds.isEnterprise),\n });\n }\n if (typeof creds.isFreeAccount === \"boolean\") {\n entries.push({\n key: \"BUILDER_IS_FREE_ACCOUNT\",\n value: String(creds.isFreeAccount),\n });\n }\n await Promise.all(\n entries.map(({ key, value }) =>\n writeAppSecret({\n key,\n value,\n scope: target.scope,\n scopeId: target.scopeId,\n }),\n ),\n );\n await clearBuilderCredentialAuthFailure({\n privateKey,\n publicKey,\n });\n return target;\n}\n\n/**\n * Delete Builder credentials.\n *\n * Default behaviour: clears only this user's per-user override (so a\n * member can disconnect their personal Builder identity without\n * collapsing the org-wide connection for every teammate). To revoke the\n * org's shared connection, pass `{ orgId, role }` for an owner/admin —\n * matching the same authority gate `writeBuilderCredentials` uses on\n * write. Plain members can never reach the org-scoped row.\n */\nexport async function deleteBuilderCredentials(\n email: string,\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { deleteAppSecret } = await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n await Promise.all(\n BUILDER_CREDENTIAL_KEYS.map((key) =>\n deleteAppSecret({\n key,\n scope: target.scope,\n scopeId: target.scopeId,\n }).catch(() => {}),\n ),\n );\n return target;\n}\n\n// ---------------------------------------------------------------------------\n// Generic request-scoped secret resolution\n//\n// New consumers should prefer this over reading `process.env.X` directly.\n// User-pasted and shared secrets live in `app_secrets` (encrypted). The\n// settings UI / onboarding panels can write user, org, or workspace rows.\n// Deploy-level env vars are the fallback for unauthenticated/CLI/background\n// contexts where there's no user to scope by — never the silent fallback\n// for an authenticated request, since on a multi-tenant deploy that would\n// silently identify every user as whoever set the deploy-level key\n// (KVesta Space, 2026-04).\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a request-scoped secret. Reads from `app_secrets` first (current\n * user override, active org, then workspace row); falls back to `process.env`\n * only when the deploy fallback policy allows it.\n */\nexport async function resolveSecret(key: string): Promise<string | null> {\n const traceLookup = shouldTraceCredentialResolve();\n const email = getRequestUserEmail();\n if (email) {\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n // Per-user override first.\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=user hit=true`,\n );\n }\n return userSecret.value;\n }\n\n const orgId = getRequestOrgId();\n if (orgId) {\n // Fall back to the active org's shared row, when present. Builder\n // Connect uses this first-class org scope.\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${orgId} scope=org hit=true`,\n );\n }\n return orgSecret.value;\n }\n\n // Registered secrets historically used \"workspace\" scope for\n // org-shared configuration. Keep reading it so Settings status and\n // runtime resolution agree.\n const workspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: orgId,\n });\n if (workspaceSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${orgId} scope=workspace hit=true`,\n );\n }\n return workspaceSecret.value;\n }\n } else {\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=workspace-solo hit=true`,\n );\n }\n return soloWorkspaceSecret.value;\n }\n }\n } catch (err) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=error err=${(err as Error)?.message ?? err}`,\n );\n }\n // Secrets table not ready — treat as missing.\n }\n // Authenticated multi-tenant context: never fall back to process.env.\n // The deploy-level value would silently impersonate the actual key\n // owner across every tenant. Local/single-tenant deployments keep the\n // original env fallback for BYO-server workflows.\n const envFallback = (\n isBuilderCredentialKey(key)\n ? canUseBuilderDeployCredentialFallbackForRequest()\n : canUseDeployCredentialFallbackForRequest()\n )\n ? process.env[key] || null\n : null;\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${getRequestOrgId() ?? \"(none)\"} scope=${envFallback ? \"env-fallback\" : \"none\"} hit=${!!envFallback}`,\n );\n }\n return envFallback;\n }\n // Unauthenticated / local-dev / CLI / background context: env fallback\n // is safe because there's no user to mis-identify.\n const value = process.env[key] || null;\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=(none) scope=env-anonymous hit=${!!value}`,\n );\n }\n return value;\n}\n\n// ---------------------------------------------------------------------------\n// Synchronous helpers — env-only fallbacks for contexts where per-user\n// lookup isn't possible (sync isConfigured checks, CLI scripts).\n// ---------------------------------------------------------------------------\n\n/**\n * True when a Builder private key is configured at the deployment level.\n *\n * This is the same env-only check as `isBuilderEnvManaged()`. For \"does this\n * request have access to Builder via user/org/env credentials?\" use the async\n * `resolveHasBuilderPrivateKey()`.\n */\nexport function hasBuilderPrivateKey(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/** The origin for Builder-proxied API calls. Overridable for testing. */\nexport function getBuilderProxyOrigin(): string {\n return (\n process.env.BUILDER_PROXY_ORIGIN ||\n process.env.AIR_HOST ||\n process.env.BUILDER_API_HOST ||\n \"https://api.builder.io\"\n );\n}\n\n/**\n * Base URL for the public Builder LLM gateway, which lives at\n * api.builder.io/agent-native/gateway.\n * Override via BUILDER_GATEWAY_BASE_URL for staging / testing.\n */\nexport function getBuilderGatewayBaseUrl(): string {\n return (\n process.env.BUILDER_GATEWAY_BASE_URL ||\n \"https://api.builder.io/agent-native/gateway/v1\"\n );\n}\n\n/**\n * Base URL for Builder-managed image generation.\n * Override via BUILDER_IMAGE_GENERATION_BASE_URL for staging / testing.\n */\nexport function getBuilderImageGenerationBaseUrl(): string {\n return (\n process.env.BUILDER_IMAGE_GENERATION_BASE_URL ||\n \"https://api.builder.io/agent-native/images/v1\"\n );\n}\n\n/**\n * Base URL for Builder-managed web search.\n * Override via BUILDER_WEB_SEARCH_BASE_URL for staging / testing.\n */\nexport function getBuilderWebSearchBaseUrl(): string {\n return (\n process.env.BUILDER_WEB_SEARCH_BASE_URL ||\n \"https://api.builder.io/agent-native/web-search/v1\"\n );\n}\n\n/** Authorization header value for Builder-proxied calls (env-only). */\nexport function getBuilderAuthHeader(): string | null {\n const key = process.env.BUILDER_PRIVATE_KEY;\n return key ? `Bearer ${key}` : null;\n}\n"]}
1
+ {"version":3,"file":"credential-provider.js","sourceRoot":"","sources":["../../src/server/credential-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5E;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2B,CACzC,KAAa,EACb,KAAgC,EAChC,IAA+B;IAE/B,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,CAAC,EAAE,CAAC;QACpD,OAAO,EAAE,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AO,CAAC,GAAG,CAAC,mBAAmB,CAAC;IAC5C,OAAO,GAAG,CAAC,CAAC,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC","sourcesContent":["/**\n * Credential provider abstraction.\n *\n * Every feature that needs an external credential (Anthropic API key,\n * Google OAuth tokens, OpenAI key, Slack bot token, etc.) should go through\n * one of the resolve*() helpers here instead of reading `process.env`\n * directly. That way the same feature can work in three modes:\n *\n * 1. User set their own key in .env → use it directly\n * 2. User connected Builder via `/cli-auth` → route through Builder proxy\n * 3. Neither → throw FeatureNotConfigured\n *\n * Templates catch FeatureNotConfigured and show a \"Connect Builder (1 click) /\n * set up your own key (guide)\" card.\n *\n * Today these helpers are used by the Builder-hosted LLM gateway, and the\n * shape is meant to grow to cover future managed credential integrations\n * (e.g. additional Builder-hosted services) without rewrites.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { isLocalDatabase } from \"../db/client.js\";\nimport { getRequestUserEmail, getRequestOrgId } from \"./request-context.js\";\n\n/**\n * Decide which `app_secrets` scope a Builder/credential write should use.\n *\n * Org scope (\"everyone in this org sees these credentials\") wins when the\n * connecting user is an owner or admin of an active org — the write\n * privileges shared infra. A plain member or a user without an active\n * org falls through to per-user scope so a teammate can't silently\n * overwrite the org-shared connection.\n */\nexport function resolveCredentialWriteScope(\n email: string,\n orgId: string | null | undefined,\n role: string | null | undefined,\n): { scope: \"user\" | \"org\"; scopeId: string } {\n if (orgId && (role === \"owner\" || role === \"admin\")) {\n return { scope: \"org\", scopeId: orgId };\n }\n return { scope: \"user\", scopeId: email };\n}\n\nexport class FeatureNotConfiguredError extends Error {\n readonly requiredCredential: string;\n readonly builderConnectUrl?: string;\n readonly byokDocsUrl?: string;\n\n constructor(opts: {\n requiredCredential: string;\n message?: string;\n builderConnectUrl?: string;\n byokDocsUrl?: string;\n }) {\n super(\n opts.message ??\n `Feature requires credential \"${opts.requiredCredential}\". Connect Builder or set your own key.`,\n );\n this.name = \"FeatureNotConfiguredError\";\n this.requiredCredential = opts.requiredCredential;\n this.builderConnectUrl = opts.builderConnectUrl;\n this.byokDocsUrl = opts.byokDocsUrl;\n }\n}\n\n/**\n * Deployment-level credential fallback for single-tenant/local operation.\n * Multi-tenant call sites must gate this explicitly before calling.\n */\nexport function readDeployCredentialEnv(key: string): string | undefined {\n return process.env[key] || undefined;\n}\n\n/**\n * Deployment-level credentials are safe as a runtime fallback only in local /\n * single-tenant contexts. In hosted production with a shared database, every\n * signed-in user needs their own user/org/workspace credential so one deploy\n * key does not silently power another tenant's chat.\n *\n * @deprecated Use `canUseDeployCredentialFallbackForRequest()` for generic\n * provider secrets. This stricter helper remains for legacy call sites with\n * identity-bearing deploy credentials.\n */\nexport function isDeployCredentialFallbackAllowed(): boolean {\n if (!isProductionLikeRuntime()) return true;\n return isLocalDatabase();\n}\n\nexport function canUseDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n if (!email) return true;\n if (isHostedWorkspaceRuntime()) return false;\n if (!isProductionLikeRuntime()) return true;\n return isLocalDatabase();\n}\n\nconst BUILDER_CREDENTIAL_KEYS = [\n \"BUILDER_PRIVATE_KEY\",\n \"BUILDER_PUBLIC_KEY\",\n \"BUILDER_USER_ID\",\n \"BUILDER_ORG_NAME\",\n \"BUILDER_ORG_KIND\",\n \"BUILDER_SUBSCRIPTION\",\n \"BUILDER_SUBSCRIPTION_LEVEL\",\n \"BUILDER_SUBSCRIPTION_NAME\",\n \"BUILDER_IS_ENTERPRISE\",\n \"BUILDER_IS_FREE_ACCOUNT\",\n] as const;\n\nfunction isBuilderCredentialKey(key: string): boolean {\n return (BUILDER_CREDENTIAL_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHostedWorkspaceRuntime(): boolean {\n const hasFusionPreview = Boolean(\n process.env.FUSION_ENVIRONMENT ||\n process.env.FUSION_ENV_ORIGIN ||\n process.env.VITE_FUSION_ENV_ORIGIN,\n );\n return (\n /^(1|true)$/i.test(process.env.AGENT_NATIVE_WORKSPACE ?? \"\") ||\n /^(1|true)$/i.test(process.env.VITE_AGENT_NATIVE_WORKSPACE ?? \"\") ||\n hasFusionPreview\n );\n}\n\nfunction isProductionLikeRuntime(): boolean {\n return (\n process.env.NODE_ENV === \"production\" ||\n /^(1|true)$/i.test(process.env.NETLIFY ?? \"\") ||\n /^(1|true)$/i.test(process.env.VERCEL ?? \"\") ||\n /^(1|true)$/i.test(process.env.CF_PAGES ?? \"\") ||\n Boolean(\n process.env.AWS_LAMBDA_FUNCTION_NAME ||\n process.env.AWS_EXECUTION_ENV ||\n process.env.FUNCTIONS_WORKER_RUNTIME ||\n process.env.K_SERVICE ||\n process.env.RENDER,\n )\n );\n}\n\n/**\n * Whether deployment-level Builder env keys may back the current request.\n *\n * This is intentionally self-contained rather than delegating to\n * `canUseDeployCredentialFallbackForRequest`. That generic helper blocks the\n * deploy fallback for any signed-in user in a hosted workspace runtime, so the\n * Builder dogfooding escape hatch must apply its own hosted-workspace exception\n * here instead of inheriting the generic helper's stricter (and hatch-unaware)\n * decision. Reading the env once into locals keeps the rules legible.\n *\n * Rules (all evaluated against the live request/runtime, not a build-time value):\n * - No signed-in user → safe to use the deploy env (nobody to mis-identify).\n * - Hosted workspace + signed-in user → deploy-level Builder keys would\n * impersonate that user, so block them — UNLESS a developer has explicitly\n * opted into the local dogfooding escape hatch (non-prod only). Default OFF;\n * hosted/shared production deployments are never affected.\n * - Otherwise → allowed in non-prod, or on a local/single-tenant database.\n */\nfunction canUseBuilderDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n if (!email) return true;\n\n const isProductionRuntime = isProductionLikeRuntime();\n // Local dogfooding escape hatch: lets the env / root-`.env` Builder key back\n // a signed-in user so running the app locally doesn't require completing the\n // Builder connect flow first. Non-prod only.\n const localDevOptIn =\n !isProductionRuntime &&\n /^(1|true)$/i.test(process.env.AGENT_NATIVE_LOCAL_BUILDER_ENV ?? \"\");\n\n if (isHostedWorkspaceRuntime() && !localDevOptIn) return false;\n\n // Deploy fallback is safe in non-prod or on a local/single-tenant database.\n return !isProductionRuntime || isLocalDatabase();\n}\n\nfunction shouldTraceCredentialResolve(): boolean {\n return /^(1|true)$/i.test(\n process.env.AGENT_NATIVE_DEBUG_CREDENTIAL_RESOLVE ??\n process.env.DEBUG_CREDENTIAL_RESOLVE ??\n \"\",\n );\n}\n\n// ---------------------------------------------------------------------------\n// Builder credential resolution:\n//\n// 1. **Request-scoped credentials.** A signed-in user can connect Builder\n// through the CLI-auth flow. Owner/admin connections land at org scope;\n// member/no-org connections land at user scope.\n//\n// 2. **Deployment fallback.** BUILDER_PRIVATE_KEY in env still makes local\n// and single-tenant deploys work out of the box, but it no longer blocks\n// per-user connect. Request-scoped credentials win whenever present.\n//\n// To run multi-tenant SaaS: prefer leaving BUILDER_PRIVATE_KEY unset unless a\n// shared fallback identity is intentional.\n// ---------------------------------------------------------------------------\n\ntype BuilderCredentialSource = \"user\" | \"org\" | \"workspace\" | \"env\";\ninterface BuilderResolvedCredentials {\n privateKey: string | null;\n publicKey: string | null;\n userId: string | null;\n orgName: string | null;\n orgKind: string | null;\n subscription: string | null;\n subscriptionLevel: string | null;\n subscriptionName: string | null;\n isEnterprise: boolean | null;\n isFreeAccount: boolean | null;\n source: Exclude<BuilderCredentialSource, \"env\">;\n}\n\nfunction isCompleteBuilderConnection(creds: BuilderResolvedCredentials) {\n return Boolean(creds.privateKey && creds.publicKey);\n}\n\nfunction readOptionalBuilderBoolean(\n value: string | null | undefined,\n): boolean | null {\n if (value == null || value === \"\") return null;\n return /^(1|true)$/i.test(value);\n}\n\nexport function isBuilderPrivateKey(value: string | null | undefined): boolean {\n return typeof value === \"string\" && value.trim().startsWith(\"bpk-\");\n}\n\nasync function readBuilderCredentialScope(\n readAppSecret: typeof import(\"../secrets/storage.js\").readAppSecret,\n scope: \"user\" | \"org\" | \"workspace\",\n scopeId: string,\n): Promise<BuilderResolvedCredentials> {\n const values = await Promise.all(\n BUILDER_CREDENTIAL_KEYS.map(async (key) => {\n const secret = await readAppSecret({ key, scope, scopeId });\n return [key, secret?.value ?? null] as const;\n }),\n );\n const map = new Map<string, string | null>(values);\n return {\n privateKey: map.get(\"BUILDER_PRIVATE_KEY\") ?? null,\n publicKey: map.get(\"BUILDER_PUBLIC_KEY\") ?? null,\n userId: map.get(\"BUILDER_USER_ID\") ?? null,\n orgName: map.get(\"BUILDER_ORG_NAME\") ?? null,\n orgKind: map.get(\"BUILDER_ORG_KIND\") ?? null,\n subscription: map.get(\"BUILDER_SUBSCRIPTION\") ?? null,\n subscriptionLevel: map.get(\"BUILDER_SUBSCRIPTION_LEVEL\") ?? null,\n subscriptionName: map.get(\"BUILDER_SUBSCRIPTION_NAME\") ?? null,\n isEnterprise: readOptionalBuilderBoolean(map.get(\"BUILDER_IS_ENTERPRISE\")),\n isFreeAccount: readOptionalBuilderBoolean(\n map.get(\"BUILDER_IS_FREE_ACCOUNT\"),\n ),\n source: scope === \"workspace\" ? \"workspace\" : scope,\n };\n}\n\nasync function resolveScopedBuilderCredential(\n key: string,\n): Promise<{ value: string; source: \"user\" | \"org\" | \"workspace\" } | null> {\n const email = getRequestUserEmail();\n if (!email) return null;\n\n // Trace only when explicitly requested. These diagnostics are useful for\n // support, but they include account identifiers and run on hot paths.\n const traceLookup = shouldTraceCredentialResolve();\n let scopeAttempted = \"user\";\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n\n // 1. Per-user override: a user can paste their own key in settings to\n // overrule the org-shared one (handy for a personal sandbox).\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret) {\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=user hit=true`,\n );\n }\n return { value: userSecret.value, source: \"user\" };\n }\n\n // 2. Per-org shared credential: when one teammate connects Builder\n // as an owner/admin we write the OAuth result at org scope so\n // every member of that org gets the AI chat working without\n // re-running the connect flow. Resolution falls back here\n // silently — the caller never has to know which scope answered.\n const orgId = getRequestOrgId();\n if (orgId) {\n scopeAttempted = \"org\";\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret) {\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=org hit=true`,\n );\n }\n return { value: orgSecret.value, source: \"org\" };\n }\n\n // Older setup flows wrote shared credentials at workspace scope.\n // Keep reading those rows so status UIs and runtime resolution agree\n // for users who connected before org-scoped Builder credentials existed.\n scopeAttempted = \"workspace\";\n const workspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: orgId,\n });\n if (workspaceSecret) {\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=workspace hit=true`,\n );\n }\n return { value: workspaceSecret.value, source: \"workspace\" };\n }\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} miss tried=user,org,workspace`,\n );\n }\n } else {\n scopeAttempted = \"workspace-solo\";\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret) {\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=workspace-solo hit=true`,\n );\n }\n return { value: soloWorkspaceSecret.value, source: \"workspace\" };\n }\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=(none) miss tried=user,workspace-solo`,\n );\n }\n }\n } catch (err) {\n if (traceLookup) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=${scopeAttempted} error=${(err as Error)?.message ?? err}`,\n );\n }\n // Secrets table not ready — treat as missing.\n }\n return null;\n}\n\nasync function resolveScopedBuilderCredentials(): Promise<BuilderResolvedCredentials | null> {\n const email = getRequestUserEmail();\n if (!email) return null;\n\n const traceLookup = shouldTraceCredentialResolve();\n let scopeAttempted = \"user\";\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n const traceScope = (creds: BuilderResolvedCredentials, scopeId: string) => {\n if (!traceLookup) return;\n console.log(\n `[builder-credential] scope=${creds.source} scopeId=${scopeId} email=${email} complete=${isCompleteBuilderConnection(creds)} private=${Boolean(creds.privateKey)} public=${Boolean(creds.publicKey)}`,\n );\n };\n\n const userCreds = await readBuilderCredentialScope(\n readAppSecret,\n \"user\",\n email,\n );\n traceScope(userCreds, email);\n if (isCompleteBuilderConnection(userCreds)) return userCreds;\n\n const orgId = getRequestOrgId();\n if (orgId) {\n scopeAttempted = \"org\";\n const orgCreds = await readBuilderCredentialScope(\n readAppSecret,\n \"org\",\n orgId,\n );\n traceScope(orgCreds, orgId);\n if (isCompleteBuilderConnection(orgCreds)) return orgCreds;\n\n scopeAttempted = \"workspace\";\n const workspaceCreds = await readBuilderCredentialScope(\n readAppSecret,\n \"workspace\",\n orgId,\n );\n traceScope(workspaceCreds, orgId);\n if (isCompleteBuilderConnection(workspaceCreds)) return workspaceCreds;\n } else {\n scopeAttempted = \"workspace-solo\";\n const scopeId = `solo:${email}`;\n const workspaceCreds = await readBuilderCredentialScope(\n readAppSecret,\n \"workspace\",\n scopeId,\n );\n traceScope(workspaceCreds, scopeId);\n if (isCompleteBuilderConnection(workspaceCreds)) return workspaceCreds;\n }\n } catch (err) {\n if (traceLookup) {\n console.log(\n `[builder-credential] email=${email} scope=${scopeAttempted} credentials error=${(err as Error)?.message ?? err}`,\n );\n }\n }\n return null;\n}\n\n/**\n * Resolve a Builder credential for the current request. User/org credentials\n * win; deployment env is only a fallback. This lets local/root .env keys keep\n * a template working while still allowing users to connect their own Builder\n * account from Settings or onboarding.\n */\nexport async function resolveBuilderCredential(\n key: string,\n): Promise<string | null> {\n const scoped = await resolveScopedBuilderCredential(key);\n if (scoped) return scoped.value;\n if (!canUseBuilderDeployCredentialFallbackForRequest()) return null;\n return readDeployCredentialEnv(key) ?? null;\n}\n\n/**\n * True when `BUILDER_PRIVATE_KEY` is set at the deployment level. This means\n * a deploy-level fallback exists; it does not prevent per-user connect.\n */\nexport function isBuilderEnvManaged(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/**\n * Resolve the Builder private key for the current request. User/org OAuth\n * credentials win; deploy-level `BUILDER_PRIVATE_KEY` is the fallback.\n */\nexport async function resolveBuilderPrivateKey(): Promise<string | null> {\n return resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n}\n\n/**\n * Resolve the current user's Builder auth header.\n * Returns `\"Bearer <key>\"` or null.\n */\nexport async function resolveBuilderAuthHeader(): Promise<string | null> {\n const key = await resolveBuilderPrivateKey();\n return key ? `Bearer ${key}` : null;\n}\n\n/**\n * Check whether the current user has a Builder private key configured\n * (per-user or deployment-level).\n */\nexport async function resolveHasBuilderPrivateKey(): Promise<boolean> {\n return !!(await resolveBuilderPrivateKey());\n}\n\n/**\n * Check whether the current request has the complete Builder credential bundle\n * needed for Builder-backed assistant/image-generation calls.\n */\nexport async function resolveHasCompleteBuilderConnection(): Promise<boolean> {\n const creds = await resolveBuilderCredentials();\n return !!(creds.privateKey && creds.publicKey);\n}\n\n/**\n * Resolve where the effective Builder assistant connection came from. This\n * intentionally requires a complete private+public key pair from one scope so\n * status UIs don't report a mixed user/org credential set as connected.\n */\nexport async function resolveBuilderCredentialSource(): Promise<BuilderCredentialSource | null> {\n const scoped = await resolveScopedBuilderCredentials();\n if (scoped) return scoped.source;\n return canUseBuilderDeployCredentialFallbackForRequest() &&\n process.env.BUILDER_PRIVATE_KEY\n ? \"env\"\n : null;\n}\n\n/**\n * Resolve the Builder assistant credential bundle from one complete scope.\n * A partial user row is treated as a miss so the org-shared connection can\n * still power the assistant for teammates.\n */\nexport async function resolveBuilderCredentials(): Promise<{\n privateKey: string | null;\n publicKey: string | null;\n userId: string | null;\n orgName: string | null;\n orgKind: string | null;\n subscription: string | null;\n subscriptionLevel: string | null;\n subscriptionName: string | null;\n isEnterprise: boolean | null;\n isFreeAccount: boolean | null;\n}> {\n const scoped = await resolveScopedBuilderCredentials();\n if (scoped) {\n const {\n privateKey,\n publicKey,\n userId,\n orgName,\n orgKind,\n subscription,\n subscriptionLevel,\n subscriptionName,\n isEnterprise,\n isFreeAccount,\n } = scoped;\n return {\n privateKey,\n publicKey,\n userId,\n orgName,\n orgKind,\n subscription,\n subscriptionLevel,\n subscriptionName,\n isEnterprise,\n isFreeAccount,\n };\n }\n const privateKey = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_PRIVATE_KEY\") ?? null)\n : null;\n const publicKey = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_PUBLIC_KEY\") ?? null)\n : null;\n const userId = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_USER_ID\") ?? null)\n : null;\n const orgName = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_ORG_NAME\") ?? null)\n : null;\n const orgKind = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_ORG_KIND\") ?? null)\n : null;\n const subscription = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_SUBSCRIPTION\") ?? null)\n : null;\n const subscriptionLevel = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_SUBSCRIPTION_LEVEL\") ?? null)\n : null;\n const subscriptionName = canUseBuilderDeployCredentialFallbackForRequest()\n ? (readDeployCredentialEnv(\"BUILDER_SUBSCRIPTION_NAME\") ?? null)\n : null;\n const isEnterprise = canUseBuilderDeployCredentialFallbackForRequest()\n ? readOptionalBuilderBoolean(\n readDeployCredentialEnv(\"BUILDER_IS_ENTERPRISE\"),\n )\n : null;\n const isFreeAccount = canUseBuilderDeployCredentialFallbackForRequest()\n ? readOptionalBuilderBoolean(\n readDeployCredentialEnv(\"BUILDER_IS_FREE_ACCOUNT\"),\n )\n : null;\n return {\n privateKey,\n publicKey,\n userId,\n orgName,\n orgKind,\n subscription,\n subscriptionLevel,\n subscriptionName,\n isEnterprise,\n isFreeAccount,\n };\n}\n\nconst BUILDER_AUTH_FAILURE_SETTING_PREFIX = \"builder-auth-failure:\";\n\nexport interface BuilderCredentialAuthFailure {\n fingerprint: string;\n message: string;\n status?: number;\n code?: string;\n at: number;\n ownerEmail?: string | null;\n orgId?: string | null;\n}\n\nexport function builderCredentialFingerprint(\n privateKey?: string | null,\n publicKey?: string | null,\n): string | null {\n if (!privateKey || !publicKey) return null;\n return createHash(\"sha256\")\n .update(privateKey)\n .update(\"\\0\")\n .update(publicKey)\n .digest(\"hex\")\n .slice(0, 24);\n}\n\nfunction builderAuthFailureSettingKey(fingerprint: string): string {\n return `${BUILDER_AUTH_FAILURE_SETTING_PREFIX}${fingerprint}`;\n}\n\nexport async function getBuilderCredentialAuthFailure(\n creds: {\n privateKey?: string | null;\n publicKey?: string | null;\n } = {},\n): Promise<BuilderCredentialAuthFailure | null> {\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return null;\n try {\n const { getSetting } = await import(\"../settings/store.js\");\n const row = await getSetting(builderAuthFailureSettingKey(fingerprint));\n if (!row) return null;\n return {\n fingerprint,\n message:\n typeof row.message === \"string\" && row.message\n ? row.message\n : \"Builder rejected the connected credentials. Reconnect Builder.io.\",\n status: typeof row.status === \"number\" ? row.status : undefined,\n code: typeof row.code === \"string\" ? row.code : undefined,\n at: typeof row.at === \"number\" ? row.at : Date.now(),\n ownerEmail:\n typeof row.ownerEmail === \"string\" ? row.ownerEmail : undefined,\n orgId: typeof row.orgId === \"string\" ? row.orgId : undefined,\n };\n } catch {\n return null;\n }\n}\n\nexport async function recordBuilderCredentialAuthFailure(details?: {\n status?: number;\n code?: string;\n message?: string;\n}): Promise<void> {\n try {\n const creds = await resolveBuilderCredentials();\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return;\n const { putSetting } = await import(\"../settings/store.js\");\n await putSetting(builderAuthFailureSettingKey(fingerprint), {\n fingerprint,\n message:\n details?.message ||\n \"Builder rejected the connected credentials. Reconnect Builder.io.\",\n ...(typeof details?.status === \"number\" && { status: details.status }),\n ...(details?.code && { code: details.code }),\n at: Date.now(),\n ownerEmail: getRequestUserEmail() ?? null,\n orgId: getRequestOrgId() ?? null,\n });\n } catch {\n // Best-effort marker only; the chat error is still returned to the user.\n }\n}\n\nexport async function clearBuilderCredentialAuthFailure(creds: {\n privateKey?: string | null;\n publicKey?: string | null;\n}): Promise<void> {\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return;\n try {\n const { deleteSetting } = await import(\"../settings/store.js\");\n await deleteSetting(builderAuthFailureSettingKey(fingerprint));\n } catch {\n // A stale failure marker should not block writing fresh credentials.\n }\n}\n\n/**\n * Write Builder credentials to `app_secrets`.\n *\n * Scope decision (see `resolveCredentialWriteScope`): when the connecting\n * user is owner/admin of an active org we write at `scope: \"org\"` so every\n * member of that org auto-resolves the credentials via\n * `resolveBuilderCredential`'s org fallback — no per-user re-connect\n * needed. A plain member or a user with no active org writes at\n * `scope: \"user\"` (the safe default that doesn't trample the org's shared\n * connection).\n *\n * Stale-credential cleanup: before writing the new values we (1) clear ALL\n * five BUILDER_* keys at the target scope, so optional fields the new\n * connection doesn't carry (e.g. user picked a Builder space that returns\n * no orgName) don't leave the previous connection's metadata behind, and\n * (2) when writing at org scope, also clear the writer's own user-scope\n * BUILDER_* rows so a stale personal override from an earlier connect\n * doesn't shadow the new org write on resolution (user scope wins org\n * scope by design — see `resolveScopedBuilderCredential`). The org-scope\n * row is intentionally left alone when writing at user scope: that row is\n * shared with the rest of the org and a single user's personal override\n * shouldn't blow it away. (Victoria's \"I signed in again with my Builder\n * space and it still says no credits\" report on 2026-05-11 was exactly\n * this stale-shadow case.)\n *\n * Returns the actual scope/scopeId used so the caller can show \"Connected\n * for Builder.io\" vs \"Connected (personal)\" in the UI.\n */\nexport async function writeBuilderCredentials(\n email: string,\n creds: {\n privateKey: string;\n publicKey: string;\n userId?: string | null;\n orgName?: string | null;\n orgKind?: string | null;\n subscription?: string | null;\n subscriptionLevel?: string | null;\n subscriptionName?: string | null;\n isEnterprise?: boolean | null;\n isFreeAccount?: boolean | null;\n },\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const privateKey = creds.privateKey.trim();\n const publicKey = creds.publicKey.trim();\n if (!isBuilderPrivateKey(privateKey)) {\n throw new Error(\n \"Builder returned a credential that is not a Builder private key (expected bpk-...). Restart the Builder connect flow and choose a space that can issue a private key.\",\n );\n }\n if (!publicKey) {\n throw new Error(\n \"Builder did not return a public API key. Restart the Builder connect flow.\",\n );\n }\n\n const { writeAppSecret, deleteAppSecret } =\n await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n\n // Clear stale rows before writing the new connection. See the function's\n // doc comment for the two cases this handles.\n const cleanups: Array<Promise<unknown>> = BUILDER_CREDENTIAL_KEYS.map((key) =>\n deleteAppSecret({\n key,\n scope: target.scope,\n scopeId: target.scopeId,\n }).catch(() => {}),\n );\n if (target.scope === \"org\") {\n for (const key of BUILDER_CREDENTIAL_KEYS) {\n cleanups.push(\n deleteAppSecret({ key, scope: \"user\", scopeId: email }).catch(() => {}),\n );\n }\n }\n await Promise.all(cleanups);\n\n const entries: Array<{ key: string; value: string }> = [\n { key: \"BUILDER_PRIVATE_KEY\", value: privateKey },\n { key: \"BUILDER_PUBLIC_KEY\", value: publicKey },\n ];\n if (creds.userId) {\n entries.push({ key: \"BUILDER_USER_ID\", value: creds.userId });\n }\n if (creds.orgName) {\n entries.push({ key: \"BUILDER_ORG_NAME\", value: creds.orgName });\n }\n if (creds.orgKind) {\n entries.push({ key: \"BUILDER_ORG_KIND\", value: creds.orgKind });\n }\n if (creds.subscription) {\n entries.push({ key: \"BUILDER_SUBSCRIPTION\", value: creds.subscription });\n }\n if (creds.subscriptionLevel) {\n entries.push({\n key: \"BUILDER_SUBSCRIPTION_LEVEL\",\n value: creds.subscriptionLevel,\n });\n }\n if (creds.subscriptionName) {\n entries.push({\n key: \"BUILDER_SUBSCRIPTION_NAME\",\n value: creds.subscriptionName,\n });\n }\n if (typeof creds.isEnterprise === \"boolean\") {\n entries.push({\n key: \"BUILDER_IS_ENTERPRISE\",\n value: String(creds.isEnterprise),\n });\n }\n if (typeof creds.isFreeAccount === \"boolean\") {\n entries.push({\n key: \"BUILDER_IS_FREE_ACCOUNT\",\n value: String(creds.isFreeAccount),\n });\n }\n await Promise.all(\n entries.map(({ key, value }) =>\n writeAppSecret({\n key,\n value,\n scope: target.scope,\n scopeId: target.scopeId,\n }),\n ),\n );\n await clearBuilderCredentialAuthFailure({\n privateKey,\n publicKey,\n });\n return target;\n}\n\n/**\n * Delete Builder credentials.\n *\n * Default behaviour: clears only this user's per-user override (so a\n * member can disconnect their personal Builder identity without\n * collapsing the org-wide connection for every teammate). To revoke the\n * org's shared connection, pass `{ orgId, role }` for an owner/admin —\n * matching the same authority gate `writeBuilderCredentials` uses on\n * write. Plain members can never reach the org-scoped row.\n */\nexport async function deleteBuilderCredentials(\n email: string,\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { deleteAppSecret } = await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n await Promise.all(\n BUILDER_CREDENTIAL_KEYS.map((key) =>\n deleteAppSecret({\n key,\n scope: target.scope,\n scopeId: target.scopeId,\n }).catch(() => {}),\n ),\n );\n return target;\n}\n\n// ---------------------------------------------------------------------------\n// Generic request-scoped secret resolution\n//\n// New consumers should prefer this over reading `process.env.X` directly.\n// User-pasted and shared secrets live in `app_secrets` (encrypted). The\n// settings UI / onboarding panels can write user, org, or workspace rows.\n// Deploy-level env vars are the fallback for unauthenticated/CLI/background\n// contexts where there's no user to scope by — never the silent fallback\n// for an authenticated request, since on a multi-tenant deploy that would\n// silently identify every user as whoever set the deploy-level key\n// (KVesta Space, 2026-04).\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a request-scoped secret. Reads from `app_secrets` first (current\n * user override, active org, then workspace row); falls back to `process.env`\n * only when the deploy fallback policy allows it.\n */\nexport async function resolveSecret(key: string): Promise<string | null> {\n const traceLookup = shouldTraceCredentialResolve();\n const email = getRequestUserEmail();\n if (email) {\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n // Per-user override first.\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=user hit=true`,\n );\n }\n return userSecret.value;\n }\n\n const orgId = getRequestOrgId();\n if (orgId) {\n // Fall back to the active org's shared row, when present. Builder\n // Connect uses this first-class org scope.\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${orgId} scope=org hit=true`,\n );\n }\n return orgSecret.value;\n }\n\n // Registered secrets historically used \"workspace\" scope for\n // org-shared configuration. Keep reading it so Settings status and\n // runtime resolution agree.\n const workspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: orgId,\n });\n if (workspaceSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${orgId} scope=workspace hit=true`,\n );\n }\n return workspaceSecret.value;\n }\n } else {\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=workspace-solo hit=true`,\n );\n }\n return soloWorkspaceSecret.value;\n }\n }\n } catch (err) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=error err=${(err as Error)?.message ?? err}`,\n );\n }\n // Secrets table not ready — treat as missing.\n }\n // Read deployment-provided env values as fallbacks; framework code must not\n // write to `process.env`, but keys supplied by the host remain valid config.\n // Builder credentials keep a narrower path below because those keys carry a\n // Builder identity rather than just enabling a provider call.\n const envFallback = (\n isBuilderCredentialKey(key)\n ? canUseBuilderDeployCredentialFallbackForRequest()\n : canUseDeployCredentialFallbackForRequest()\n )\n ? process.env[key] || null\n : null;\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${getRequestOrgId() ?? \"(none)\"} scope=${envFallback ? \"env-fallback\" : \"none\"} hit=${!!envFallback}`,\n );\n }\n return envFallback;\n }\n // Unauthenticated / local-dev / CLI / background context: env fallback\n // is safe because there's no user to mis-identify.\n const value = process.env[key] || null;\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=(none) scope=env-anonymous hit=${!!value}`,\n );\n }\n return value;\n}\n\n// ---------------------------------------------------------------------------\n// Synchronous helpers — env-only fallbacks for contexts where per-user\n// lookup isn't possible (sync isConfigured checks, CLI scripts).\n// ---------------------------------------------------------------------------\n\n/**\n * True when a Builder private key is configured at the deployment level.\n *\n * This is the same env-only check as `isBuilderEnvManaged()`. For \"does this\n * request have access to Builder via user/org/env credentials?\" use the async\n * `resolveHasBuilderPrivateKey()`.\n */\nexport function hasBuilderPrivateKey(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/** The origin for Builder-proxied API calls. Overridable for testing. */\nexport function getBuilderProxyOrigin(): string {\n return (\n process.env.BUILDER_PROXY_ORIGIN ||\n process.env.AIR_HOST ||\n process.env.BUILDER_API_HOST ||\n \"https://api.builder.io\"\n );\n}\n\n/**\n * Base URL for the public Builder LLM gateway, which lives at\n * api.builder.io/agent-native/gateway.\n * Override via BUILDER_GATEWAY_BASE_URL for staging / testing.\n */\nexport function getBuilderGatewayBaseUrl(): string {\n return (\n process.env.BUILDER_GATEWAY_BASE_URL ||\n \"https://api.builder.io/agent-native/gateway/v1\"\n );\n}\n\n/**\n * Base URL for Builder-managed image generation.\n * Override via BUILDER_IMAGE_GENERATION_BASE_URL for staging / testing.\n */\nexport function getBuilderImageGenerationBaseUrl(): string {\n return (\n process.env.BUILDER_IMAGE_GENERATION_BASE_URL ||\n \"https://api.builder.io/agent-native/images/v1\"\n );\n}\n\n/**\n * Base URL for Builder-managed web search.\n * Override via BUILDER_WEB_SEARCH_BASE_URL for staging / testing.\n */\nexport function getBuilderWebSearchBaseUrl(): string {\n return (\n process.env.BUILDER_WEB_SEARCH_BASE_URL ||\n \"https://api.builder.io/agent-native/web-search/v1\"\n );\n}\n\n/** Authorization header value for Builder-proxied calls (env-only). */\nexport function getBuilderAuthHeader(): string | null {\n const key = process.env.BUILDER_PRIVATE_KEY;\n return key ? `Bearer ${key}` : null;\n}\n"]}
@@ -147,6 +147,8 @@ pnpm dev
147
147
 
148
148
  **سطح موصل واسع.** تأتي أحداث BigQuery وGA4 وتحليلات المنتج وCRM والدعم والمجتمع وGitHub/Jira وSEO وأحداث `/track` للطرف الأول من خلال actions التي يمكن للوكيل الاتصال بها.
149
149
 
150
+ **Session replay agent handoff.** Session recordings stay private, but the session detail page can mint a temporary **Copy for agent** link. The two-hour `agent_access` URL lets an external agent read replay summaries, timelines, and bounded event details without exposing blob/provider URLs or making the recording public.
151
+
150
152
  ### العمل مع الوكيل
151
153
 
152
154
  يعرف الوكيل دائمًا ما تنظر إليه. يتم إدخال حالة الشاشة الحالية في كل رسالة ككتلة `<current-screen>` - فهي تحتوي على العرض النشط، ولوحة المعلومات المفتوحة أو التحليل، وأي عوامل تصفية محددة.
@@ -131,6 +131,8 @@ API، لذا فإن النماذج التي تقبل النص أو الصور ا
131
131
  | `/api/agent-transcript.json?id=<recordingId>` | أجزاء النص ذات الطابع الزمني مع `startMs`، `endMs`، والطوابع الزمنية القابلة للقراءة، والنص، وتسميات المصدر الاختيارية |
132
132
  | `/api/agent-frame.jpg?id=<recordingId>&atMs=<ms>` | إطار JPEG مستخرج من الفيديو بطابع زمني للفيديو الأصلي |
133
133
 
134
+ Temporary private agent links are also supported: the Share dialog can mint a two-hour `agent_access` URL for any recording the viewer can access. Agents use that token with the share page and JSON APIs, and the clip does not become public.
135
+
134
136
  تتبع نقاط النهاية نفس القواعد العامة/كلمة المرور/انتهاء الصلاحية مثل صفحة المشاركة.
135
137
  تتطلب المقاطع المحمية بكلمة مرور كلمة المرور مرة واحدة؛ تعود الاستجابات الناجحة
136
138
  روابط رمزية قصيرة العمر بحيث لا يحتاج وكلاء المراحل النهائية إلى النص العادي
@@ -147,6 +147,8 @@ CLI gibt den lokalen Entwickler URL aus. Melden Sie sich bei Google an und öffn
147
147
 
148
148
  **Breite Konnektoroberfläche.** BigQuery, GA4, Produktanalyse, CRM, Support, Community, GitHub/Jira, SEO und Erstanbieter-`/track`-Ereignisse kommen alle über actions, das der Agent anrufen kann.
149
149
 
150
+ **Session replay agent handoff.** Session recordings stay private, but the session detail page can mint a temporary **Copy for agent** link. The two-hour `agent_access` URL lets an external agent read replay summaries, timelines, and bounded event details without exposing blob/provider URLs or making the recording public.
151
+
150
152
  ### Zusammenarbeit mit dem Agenten
151
153
 
152
154
  Der Agent weiß immer, was Sie sehen. Der aktuelle Bildschirmstatus wird als `<current-screen>`-Block in jede Nachricht eingefügt – er enthält die aktive Ansicht, das geöffnete Dashboard oder die geöffnete Analyse und alle ausgewählten Filter.
@@ -131,6 +131,8 @@ Agent.
131
131
  | `/api/agent-transcript.json?id=<recordingId>` | Transkriptsegmente mit Zeitstempel mit `startMs`, `endMs`, lesbaren Zeitstempeln, Text und optionalen Quellenbezeichnungen |
132
132
  | `/api/agent-frame.jpg?id=<recordingId>&atMs=<ms>` | Ein JPEG-Frame, der mit einem Originalvideo-Zeitstempel aus dem Video extrahiert wurde |
133
133
 
134
+ Temporary private agent links are also supported: the Share dialog can mint a two-hour `agent_access` URL for any recording the viewer can access. Agents use that token with the share page and JSON APIs, and the clip does not become public.
135
+
134
136
  Die Endpunkte folgen denselben öffentlichen/Passwort-/Ablaufregeln wie die Freigabeseite.
135
137
  Passwortgeschützte Clips erfordern das einmalige Passwort; Erfolgreiche Antworten werden zurückgegeben
136
138
  kurzlebige tokenisierte Links, sodass nachgeschaltete Agenten den Klartext nicht benötigen
@@ -147,6 +147,8 @@ El CLI imprime el desarrollador local URL. Inicia sesión con Google y luego abr
147
147
 
148
148
  **Amplia superficie de conector.** BigQuery, GA4, análisis de productos, CRM, soporte, comunidad, GitHub/Jira, SEO y eventos propios `/track` llegan a través de actions al que el agente puede llamar.
149
149
 
150
+ **Session replay agent handoff.** Session recordings stay private, but the session detail page can mint a temporary **Copy for agent** link. The two-hour `agent_access` URL lets an external agent read replay summaries, timelines, and bounded event details without exposing blob/provider URLs or making the recording public.
151
+
150
152
  ### Trabajar con el agente
151
153
 
152
154
  El agente siempre sabe lo que estás mirando. El estado actual de la pantalla se inyecta en cada mensaje como un bloque `<current-screen>`: contiene la vista activa, el panel o análisis abierto y los filtros seleccionados.
@@ -131,6 +131,8 @@ agente.
131
131
  | `/api/agent-transcript.json?id=<recordingId>` | Segmentos de transcripción con marca de tiempo con `startMs`, `endMs`, marcas de tiempo legibles, texto y etiquetas de origen opcionales |
132
132
  | `/api/agent-frame.jpg?id=<recordingId>&atMs=<ms>` | Un fotograma JPEG extraído del vídeo en una marca de tiempo del vídeo original |
133
133
 
134
+ Temporary private agent links are also supported: the Share dialog can mint a two-hour `agent_access` URL for any recording the viewer can access. Agents use that token with the share page and JSON APIs, and the clip does not become public.
135
+
134
136
  Los puntos finales siguen las mismas reglas de público/contraseña/caducidad que la página para compartir.
135
137
  Los clips protegidos con contraseña requieren la contraseña una vez; regresan respuestas exitosas
136
138
  Enlaces tokenizados de corta duración para que los agentes posteriores no necesiten el texto sin formato
@@ -147,6 +147,8 @@ Le CLI imprime le développement local URL. Connectez-vous avec Google, puis ouv
147
147
 
148
148
  **Large surface de connecteur.** Les événements BigQuery, GA4, analyses de produits, CRM, support, communauté, GitHub/Jira, SEO et `/track` propriétaires passent tous par actions que l'agent peut appeler.
149
149
 
150
+ **Session replay agent handoff.** Session recordings stay private, but the session detail page can mint a temporary **Copy for agent** link. The two-hour `agent_access` URL lets an external agent read replay summaries, timelines, and bounded event details without exposing blob/provider URLs or making the recording public.
151
+
150
152
  ### Travailler avec l'agent
151
153
 
152
154
  L'agent sait toujours ce que vous regardez. L'état actuel de l'écran est injecté dans chaque message sous forme de bloc `<current-screen>` : il contient la vue active, le tableau de bord ou l'analyse ouvert et tous les filtres sélectionnés.
@@ -131,6 +131,8 @@ agent.
131
131
  | `/api/agent-transcript.json?id=<recordingId>` | Segments de transcription horodatés avec `startMs`, `endMs`, horodatages lisibles, texte et étiquettes de source facultatives |
132
132
  | `/api/agent-frame.jpg?id=<recordingId>&atMs=<ms>` | Une image JPEG extraite de la vidéo avec un horodatage de la vidéo d'origine |
133
133
 
134
+ Temporary private agent links are also supported: the Share dialog can mint a two-hour `agent_access` URL for any recording the viewer can access. Agents use that token with the share page and JSON APIs, and the clip does not become public.
135
+
134
136
  Les points de terminaison suivent les mêmes règles de public/mot de passe/expiration que la page de partage.
135
137
  Les clips protégés par mot de passe nécessitent le mot de passe une seule fois ; les réponses positives reviennent
136
138
  Liens tokenisés de courte durée afin que les agents en aval n'aient pas besoin du texte brut
@@ -147,6 +147,8 @@ CLI स्थानीय डेव URL प्रिंट करता है
147
147
 
148
148
  **व्यापक कनेक्टर सतह।** BigQuery, GA4, उत्पाद विश्लेषण, CRM, समर्थन, समुदाय, GitHub/Jira, SEO, और प्रथम-पक्ष `/track` इवेंट सभी actions के माध्यम से आते हैं जिन्हें एजेंट कॉल कर सकता है।
149
149
 
150
+ **Session replay agent handoff.** Session recordings stay private, but the session detail page can mint a temporary **Copy for agent** link. The two-hour `agent_access` URL lets an external agent read replay summaries, timelines, and bounded event details without exposing blob/provider URLs or making the recording public.
151
+
150
152
  ### एजेंट के साथ काम करना
151
153
 
152
154
  एजेंट को हमेशा पता होता है कि आप क्या देख रहे हैं। वर्तमान स्क्रीन स्थिति को प्रत्येक संदेश में `<current-screen>` ब्लॉक के रूप में इंजेक्ट किया जाता है - इसमें सक्रिय दृश्य, खुला डैशबोर्ड या विश्लेषण और कोई भी चयनित फ़िल्टर शामिल होता है।
@@ -131,6 +131,8 @@ APIs, इसलिए मॉडल जो केवल पाठ या स्
131
131
  | `/api/agent-transcript.json?id=<recordingId>` | `startMs`, `endMs`, पठनीय टाइमस्टैम्प, टेक्स्ट और वैकल्पिक स्रोत लेबल के साथ टाइमस्टैम्प्ड ट्रांसक्रिप्ट सेगमेंट |
132
132
  | `/api/agent-frame.jpg?id=<recordingId>&atMs=<ms>` | मूल-वीडियो टाइमस्टैम्प पर वीडियो से निकाला गया एक JPEG फ्रेम |
133
133
 
134
+ Temporary private agent links are also supported: the Share dialog can mint a two-hour `agent_access` URL for any recording the viewer can access. Agents use that token with the share page and JSON APIs, and the clip does not become public.
135
+
134
136
  एंडपॉइंट शेयर पेज के समान सार्वजनिक/पासवर्ड/समाप्ति नियमों का पालन करते हैं।
135
137
  पासवर्ड-सुरक्षित क्लिप को एक बार पासवर्ड की आवश्यकता होती है; सफल प्रत्युत्तर वापस आते हैं
136
138
  अल्पकालिक टोकनयुक्त लिंक ताकि डाउनस्ट्रीम एजेंटों को प्लेनटेक्स्ट की आवश्यकता न हो
@@ -147,6 +147,8 @@ CLI はローカル開発 URL を出力します。 Google でログインし、
147
147
 
148
148
  **幅広いコネクタ サーフェス。** BigQuery、GA4、製品分析、CRM、サポート、コミュニティ、GitHub/Jira、SEO、ファーストパーティ `/track` イベントはすべて、エージェントが呼び出すことができる actions 経由で行われます。
149
149
 
150
+ **Session replay agent handoff.** Session recordings stay private, but the session detail page can mint a temporary **Copy for agent** link. The two-hour `agent_access` URL lets an external agent read replay summaries, timelines, and bounded event details without exposing blob/provider URLs or making the recording public.
151
+
150
152
  ### エージェントとの連携
151
153
 
152
154
  エージェントは、あなたが何を見ているのかを常に知っています。現在の画面状態は、`<current-screen>` ブロックとしてすべてのメッセージに挿入されます。これには、アクティブなビュー、開いているダッシュボードまたは分析、選択したフィルターが含まれます。
@@ -131,6 +131,8 @@ API なので、テキストまたは静止画像のみを受け入れるモデ
131
131
  | `/api/agent-transcript.json?id=<recordingId>` | `startMs`、`endMs`、読み取り可能なタイムスタンプ、テキスト、およびオプションのソース ラベルを含むタイムスタンプ付きトランスクリプト セグメント |
132
132
  | `/api/agent-frame.jpg?id=<recordingId>&atMs=<ms>` | 元のビデオのタイムスタンプでビデオから抽出された JPEG フレーム |
133
133
 
134
+ Temporary private agent links are also supported: the Share dialog can mint a two-hour `agent_access` URL for any recording the viewer can access. Agents use that token with the share page and JSON APIs, and the clip does not become public.
135
+
134
136
  エンドポイントは、共有ページと同じパブリック/パスワード/有効期限ルールに従います。
135
137
  パスワードで保護されたクリップでは、パスワードが 1 回必要になります。成功した応答が返されます
136
138
  トークン化されたリンクは有効期間が短いため、ダウンストリーム エージェントはプレーンテキストを必要としません
@@ -147,6 +147,8 @@ CLI는 로컬 개발자 URL를 인쇄합니다. Google에 로그인한 다음 **
147
147
 
148
148
  **광범위한 커넥터 표면.** BigQuery, GA4, 제품 분석, CRM, 지원, 커뮤니티, GitHub/Jira, SEO 및 자사 `/track` 이벤트는 모두 에이전트가 호출할 수 있는 actions를 통해 제공됩니다.
149
149
 
150
+ **Session replay agent handoff.** Session recordings stay private, but the session detail page can mint a temporary **Copy for agent** link. The two-hour `agent_access` URL lets an external agent read replay summaries, timelines, and bounded event details without exposing blob/provider URLs or making the recording public.
151
+
150
152
  ### 에이전트와 협력하기
151
153
 
152
154
  에이전트는 항상 귀하가 무엇을 보고 있는지 알고 있습니다. 현재 화면 상태는 모든 메시지에 `<current-screen>` 블록으로 삽입됩니다. 여기에는 활성 보기, 열려 있는 대시보드 또는 분석, 선택한 필터가 포함됩니다.
@@ -131,6 +131,8 @@ API, 텍스트나 정지 이미지만 허용하는 모델도 여전히 무엇을
131
131
  | `/api/agent-transcript.json?id=<recordingId>` | `startMs`, `endMs`, 읽을 수 있는 타임스탬프, 텍스트 및 선택적 소스 라벨이 포함된 타임스탬프 기록 세그먼트 |
132
132
  | `/api/agent-frame.jpg?id=<recordingId>&atMs=<ms>` | 원본 비디오 타임스탬프의 비디오에서 추출된 JPEG 프레임 |
133
133
 
134
+ Temporary private agent links are also supported: the Share dialog can mint a two-hour `agent_access` URL for any recording the viewer can access. Agents use that token with the share page and JSON APIs, and the clip does not become public.
135
+
134
136
  엔드포인트는 공유 페이지와 동일한 공개/비밀번호/만료 규칙을 따릅니다.
135
137
  비밀번호로 보호된 클립에는 비밀번호가 한 번만 필요합니다. 성공적인 응답 반환
136
138
  다운스트림 에이전트에 일반 텍스트가 필요하지 않도록 단기 토큰화된 링크
@@ -147,6 +147,8 @@ O CLI imprime o dev local URL. Faça login com o Google e abra a página **Fonte
147
147
 
148
148
  **Superfície de conector ampla.** BigQuery, GA4, análise de produto, CRM, suporte, comunidade, GitHub/Jira, SEO e eventos `/track` primários, todos vêm por meio do actions que o agente pode ligar.
149
149
 
150
+ **Session replay agent handoff.** Session recordings stay private, but the session detail page can mint a temporary **Copy for agent** link. The two-hour `agent_access` URL lets an external agent read replay summaries, timelines, and bounded event details without exposing blob/provider URLs or making the recording public.
151
+
150
152
  ### Trabalhando com o agente
151
153
 
152
154
  O agente sempre sabe o que você está vendo. O estado atual da tela é injetado em cada mensagem como um bloco `<current-screen>` — ele contém a visualização ativa, o painel ou análise aberta e quaisquer filtros selecionados.
@@ -131,6 +131,8 @@ agente.
131
131
  | `/api/agent-transcript.json?id=<recordingId>` | Segmentos de transcrição com carimbo de data e hora com `startMs`, `endMs`, carimbos de data e hora legíveis, texto e rótulos de origem opcionais |
132
132
  | `/api/agent-frame.jpg?id=<recordingId>&atMs=<ms>` | Um quadro JPEG extraído do vídeo em um carimbo de data/hora do vídeo original |
133
133
 
134
+ Temporary private agent links are also supported: the Share dialog can mint a two-hour `agent_access` URL for any recording the viewer can access. Agents use that token with the share page and JSON APIs, and the clip does not become public.
135
+
134
136
  Os endpoints seguem as mesmas regras de público/senha/expiração da página de compartilhamento.
135
137
  Clipes protegidos por senha exigem a senha uma vez; retorno de respostas bem-sucedidas
136
138
  links tokenizados de curta duração para que os agentes downstream não precisem do texto simples
@@ -147,6 +147,8 @@ CLI 打印本地开发 URL。使用 Google 登录,然后打开 **数据源**
147
147
 
148
148
  **广泛的连接器表面。** BigQuery、GA4、产品分析、CRM、支持、社区、GitHub/Jira、SEO 和第一方 `/track` 事件均来自代理可以调用的 actions。
149
149
 
150
+ **Session replay agent handoff.** Session recordings stay private, but the session detail page can mint a temporary **Copy for agent** link. The two-hour `agent_access` URL lets an external agent read replay summaries, timelines, and bounded event details without exposing blob/provider URLs or making the recording public.
151
+
150
152
  ### 与代理合作
151
153
 
152
154
  代理始终知道您在看什么。当前屏幕状态作为 `<current-screen>` 块注入到每条消息中 - 它包含活动视图、打开的仪表板或分析以及任何选定的过滤器。
@@ -131,6 +131,8 @@ APIs,因此仅接受文本或静态图像的模型仍然可以理解内容
131
131
  | `/api/agent-transcript.json?id=<recordingId>` | 带有 `startMs`、`endMs`、可读时间戳、文本和可选源标签的时间戳转录片段 |
132
132
  | `/api/agent-frame.jpg?id=<recordingId>&atMs=<ms>` | 以原始视频时间戳从视频中提取的 JPEG 帧 |
133
133
 
134
+ Temporary private agent links are also supported: the Share dialog can mint a two-hour `agent_access` URL for any recording the viewer can access. Agents use that token with the share page and JSON APIs, and the clip does not become public.
135
+
134
136
  端点遵循与共享页面相同的公共/密码/过期规则。
135
137
  受密码保护的剪辑需要密码一次;成功响应返回
136
138
  短暂的标记化链接,因此下游代理不需要明文
@@ -147,6 +147,8 @@ CLI 列印本機開發 URL。使用 Google 登入,然後開啟 **資料來源*
147
147
 
148
148
  **廣泛的連線器表面。** BigQuery、GA4、產品分析、CRM、支援、社群、GitHub/Jira、SEO 和第一方 `/track` 事件均來自代理可以呼叫的 actions。
149
149
 
150
+ **Session replay agent handoff.** Session recordings stay private, but the session detail page can mint a temporary **Copy for agent** link. The two-hour `agent_access` URL lets an external agent read replay summaries, timelines, and bounded event details without exposing blob/provider URLs or making the recording public.
151
+
150
152
  ### 與代理合作
151
153
 
152
154
  代理始終知道您在看什麼。目前螢幕狀態作為 `<current-screen>` 塊注入到每條訊息中 - 它包含活動檢視、開啟的儀表板或分析以及任何選定的過濾器。
@@ -131,6 +131,8 @@ APIs,因此僅接受文字或靜態圖片的模型仍然可以理解內容
131
131
  | `/api/agent-transcript.json?id=<recordingId>` | 帶有 `startMs`、`endMs`、可讀時間戳、文字和可選來源標籤的時間戳轉錄片段 |
132
132
  | `/api/agent-frame.jpg?id=<recordingId>&atMs=<ms>` | 以原始影片時間戳從影片中擷取的 JPEG 幀 |
133
133
 
134
+ Temporary private agent links are also supported: the Share dialog can mint a two-hour `agent_access` URL for any recording the viewer can access. Agents use that token with the share page and JSON APIs, and the clip does not become public.
135
+
134
136
  端點遵循與共用頁面相同的公開/密碼/過期規則。
135
137
  受密碼保護的剪輯需要密碼一次;成功回應返回
136
138
  短暫的標記化連結,因此下游代理不需要明文
@@ -152,6 +152,8 @@ The CLI prints the local dev URL. Sign in with Google, then open the **Data Sour
152
152
 
153
153
  **Broad connector surface.** BigQuery, GA4, product analytics, CRM, support, community, GitHub/Jira, SEO, and first-party `/track` events all come through actions the agent can call.
154
154
 
155
+ **Session replay agent handoff.** Session recordings stay private, but the session detail page can mint a temporary **Copy for agent** link. The two-hour `agent_access` URL lets an external agent read replay summaries, timelines, and bounded event details without exposing blob/provider URLs or making the recording public.
156
+
155
157
  ### Working with the agent
156
158
 
157
159
  The agent always knows what you're looking at. The current screen state is injected into every message as a `<current-screen>` block — it contains the active view, the open dashboard or analysis, and any selected filters.