@agent-native/core 0.15.10 → 0.15.12

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 (69) hide show
  1. package/dist/a2a/server.d.ts +1 -0
  2. package/dist/a2a/server.d.ts.map +1 -1
  3. package/dist/a2a/server.js +25 -13
  4. package/dist/a2a/server.js.map +1 -1
  5. package/dist/a2a/types.d.ts +8 -0
  6. package/dist/a2a/types.d.ts.map +1 -1
  7. package/dist/a2a/types.js +0 -1
  8. package/dist/a2a/types.js.map +1 -1
  9. package/dist/action.d.ts +15 -0
  10. package/dist/action.d.ts.map +1 -1
  11. package/dist/action.js +6 -0
  12. package/dist/action.js.map +1 -1
  13. package/dist/agent/production-agent.d.ts +3 -0
  14. package/dist/agent/production-agent.d.ts.map +1 -1
  15. package/dist/agent/production-agent.js.map +1 -1
  16. package/dist/agent-web/config.d.ts +41 -0
  17. package/dist/agent-web/config.d.ts.map +1 -0
  18. package/dist/agent-web/config.js +162 -0
  19. package/dist/agent-web/config.js.map +1 -0
  20. package/dist/agent-web/generator.d.ts +95 -0
  21. package/dist/agent-web/generator.d.ts.map +1 -0
  22. package/dist/agent-web/generator.js +270 -0
  23. package/dist/agent-web/generator.js.map +1 -0
  24. package/dist/agent-web/index.d.ts +3 -0
  25. package/dist/agent-web/index.d.ts.map +1 -0
  26. package/dist/agent-web/index.js +3 -0
  27. package/dist/agent-web/index.js.map +1 -0
  28. package/dist/cli/audit-agent-web.d.ts +2 -0
  29. package/dist/cli/audit-agent-web.d.ts.map +1 -0
  30. package/dist/cli/audit-agent-web.js +201 -0
  31. package/dist/cli/audit-agent-web.js.map +1 -0
  32. package/dist/cli/index.js +17 -0
  33. package/dist/cli/index.js.map +1 -1
  34. package/dist/cli/migrate.d.ts +10 -0
  35. package/dist/cli/migrate.d.ts.map +1 -0
  36. package/dist/cli/migrate.js +78 -0
  37. package/dist/cli/migrate.js.map +1 -0
  38. package/dist/cli/templates-meta.d.ts.map +1 -1
  39. package/dist/cli/templates-meta.js +12 -0
  40. package/dist/cli/templates-meta.js.map +1 -1
  41. package/dist/client/settings/SettingsPanel.d.ts.map +1 -1
  42. package/dist/client/settings/SettingsPanel.js +6 -5
  43. package/dist/client/settings/SettingsPanel.js.map +1 -1
  44. package/dist/client/settings/useBuilderStatus.d.ts.map +1 -1
  45. package/dist/client/settings/useBuilderStatus.js +79 -37
  46. package/dist/client/settings/useBuilderStatus.js.map +1 -1
  47. package/dist/client/settings/useBuilderStatus.spec.js +84 -6
  48. package/dist/client/settings/useBuilderStatus.spec.js.map +1 -1
  49. package/dist/index.d.ts +2 -1
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +2 -0
  52. package/dist/index.js.map +1 -1
  53. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  54. package/dist/server/agent-chat-plugin.js +2 -0
  55. package/dist/server/agent-chat-plugin.js.map +1 -1
  56. package/dist/server/credential-provider.d.ts.map +1 -1
  57. package/dist/server/credential-provider.js +4 -2
  58. package/dist/server/credential-provider.js.map +1 -1
  59. package/dist/vite/agent-web-plugin.d.ts +17 -0
  60. package/dist/vite/agent-web-plugin.d.ts.map +1 -0
  61. package/dist/vite/agent-web-plugin.js +48 -0
  62. package/dist/vite/agent-web-plugin.js.map +1 -0
  63. package/dist/vite/index.d.ts +1 -0
  64. package/dist/vite/index.d.ts.map +1 -1
  65. package/dist/vite/index.js +1 -0
  66. package/dist/vite/index.js.map +1 -1
  67. package/docs/content/agent-web-surfaces.md +143 -0
  68. package/docs/content/migration-workbench.md +110 -0
  69. package/package.json +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"credential-provider.d.ts","sourceRoot":"","sources":["../../src/server/credential-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAMH;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAChC,I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;CAAE,CAAC,CAiBrD;AAeD;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CA8GvE;AAOD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,IAAI,OAAO,CAE9C;AAED,yEAAyE;AACzE,wBAAgB,qBAAqB,IAAI,MAAM,CAO9C;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,IAAI,MAAM,CAKjD;AAED;;;GAGG;AACH,wBAAgB,gCAAgC,IAAI,MAAM,CAKzD;AAED,uEAAuE;AACvE,wBAAgB,oBAAoB,IAAI,MAAM,GAAG,IAAI,CAGpD"}
@@ -83,8 +83,6 @@ function isBuilderCredentialKey(key) {
83
83
  return BUILDER_CREDENTIAL_KEYS.includes(key);
84
84
  }
85
85
  function isHostedWorkspaceRuntime() {
86
- if (isLocalDatabase())
87
- return false;
88
86
  const hasFusionPreview = Boolean(process.env.FUSION_ENVIRONMENT ||
89
87
  process.env.FUSION_ENV_ORIGIN ||
90
88
  process.env.VITE_FUSION_ENV_ORIGIN);
@@ -94,6 +92,10 @@ function isHostedWorkspaceRuntime() {
94
92
  }
95
93
  function canUseBuilderDeployCredentialFallbackForRequest() {
96
94
  const email = getRequestUserEmail();
95
+ // Builder workspace previews can run with NODE_ENV=development and their DB
96
+ // detection can look local during early startup. Once a real signed-in user
97
+ // is present, hosted workspace flags are enough to make deployment-level
98
+ // Builder keys unsafe as an identity fallback.
97
99
  if (email && isHostedWorkspaceRuntime())
98
100
  return false;
99
101
  return canUseDeployCredentialFallbackForRequest();
@@ -1 +1 @@
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;AACzC,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5E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O,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;IACvC,IAAI,WAAW,EAAE,CAAC;QAChB,OAAO,CAAC,GAAG,CACT,wBAAwB,GAAG,yCAAyC,CAAC,CAAC,KAAK,EAAE,CAC9E,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,8EAA8E;AAC9E,uEAAuE;AACvE,iEAAiE;AACjE,8EAA8E;AAE9E;;;;;;GAMG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;AAC3C,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,qBAAqB;IACnC,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,oBAAoB;QAChC,OAAO,CAAC,GAAG,CAAC,QAAQ;QACpB,OAAO,CAAC,GAAG,CAAC,gBAAgB;QAC5B,wBAAwB,CACzB,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,wBAAwB;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,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\";\nimport { getRequestUserEmail, getRequestOrgId } from \"./request-context.js\";\nimport { isLocalDatabase } from \"../db/client.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 (process.env.NODE_ENV !== \"production\") return true;\n return isLocalDatabase();\n}\n\nexport function canUseDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\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] as const;\n\nfunction isBuilderCredentialKey(key: string): boolean {\n return (BUILDER_CREDENTIAL_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHostedWorkspaceRuntime(): boolean {\n if (isLocalDatabase()) return false;\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 canUseBuilderDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n if (email && isHostedWorkspaceRuntime()) return false;\n return canUseDeployCredentialFallbackForRequest();\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\";\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 // Always trace Builder lookups — these come up in \"I connected Builder but\n // chat still says Use Builder\" support requests, and without scope-by-scope\n // visibility into where the lookup actually went, the only diagnostic move\n // is to ask the user to redo the connect flow. Mirrors `resolveSecret`'s\n // default-on trace gate for BUILDER_* keys.\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 console.log(\n `[builder-credential] key=${key} email=${email} scope=user hit=true`,\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 console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=org hit=true`,\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 console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=workspace hit=true`,\n );\n return { value: workspaceSecret.value, source: \"workspace\" };\n }\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} miss tried=user,org,workspace`,\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 console.log(\n `[builder-credential] key=${key} email=${email} scope=workspace-solo hit=true`,\n );\n return { value: soloWorkspaceSecret.value, source: \"workspace\" };\n }\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=(none) miss tried=user,workspace-solo`,\n );\n }\n } catch (err) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=${scopeAttempted} error=${(err as Error)?.message ?? err}`,\n );\n // Secrets table not ready — treat as missing.\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 * Resolve where the effective Builder private key came from. Used by status\n * UIs so they can distinguish a deploy fallback from a user/org connection.\n */\nexport async function resolveBuilderCredentialSource(): Promise<BuilderCredentialSource | null> {\n const scoped = await resolveScopedBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n if (scoped) return scoped.source;\n return canUseBuilderDeployCredentialFallbackForRequest() &&\n process.env.BUILDER_PRIVATE_KEY\n ? \"env\"\n : null;\n}\n\n/**\n * Resolve all per-user Builder credentials. Used by the status endpoint\n * and agent-chat-plugin to get orgName, userId, etc.\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}> {\n const [privateKey, publicKey, userId, orgName, orgKind] = await Promise.all([\n resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\"),\n resolveBuilderCredential(\"BUILDER_PUBLIC_KEY\"),\n resolveBuilderCredential(\"BUILDER_USER_ID\"),\n resolveBuilderCredential(\"BUILDER_ORG_NAME\"),\n resolveBuilderCredential(\"BUILDER_ORG_KIND\"),\n ]);\n return { privateKey, publicKey, userId, orgName, orgKind };\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 },\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\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: creds.privateKey },\n { key: \"BUILDER_PUBLIC_KEY\", value: creds.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 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: creds.privateKey,\n publicKey: creds.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 // Log Builder-credential lookups by default so \"I connected Builder but\n // chat says no LLM\" reports can be diagnosed from server logs without\n // re-running anything. Keep noise low by gating other keys behind a flag.\n const traceLookup =\n key.startsWith(\"BUILDER_\") ||\n /^(1|true)$/i.test(process.env.DEBUG_CREDENTIAL_RESOLVE ?? \"\");\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/** 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;AACzC,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD;;;;;;;;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,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC1C,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC3C,CAAC;AAED,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IACzC,kBAAkB,CAAS;IAC3B,iBAAiB,CAAU;IAC3B,WAAW,CAAU;IAE9B,YAAY,IAKX;QACC,KAAK,CACH,IAAI,CAAC,OAAO;YACV,gCAAgC,I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CAAC,gBAAgB;QAC5B,wBAAwB,CACzB,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,wBAAwB;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,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\";\nimport { getRequestUserEmail, getRequestOrgId } from \"./request-context.js\";\nimport { isLocalDatabase } from \"../db/client.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 (process.env.NODE_ENV !== \"production\") return true;\n return isLocalDatabase();\n}\n\nexport function canUseDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\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] 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 canUseBuilderDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n // Builder workspace previews can run with NODE_ENV=development and their DB\n // detection can look local during early startup. Once a real signed-in user\n // is present, hosted workspace flags are enough to make deployment-level\n // Builder keys unsafe as an identity fallback.\n if (email && isHostedWorkspaceRuntime()) return false;\n return canUseDeployCredentialFallbackForRequest();\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\";\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 // Always trace Builder lookups — these come up in \"I connected Builder but\n // chat still says Use Builder\" support requests, and without scope-by-scope\n // visibility into where the lookup actually went, the only diagnostic move\n // is to ask the user to redo the connect flow. Mirrors `resolveSecret`'s\n // default-on trace gate for BUILDER_* keys.\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 console.log(\n `[builder-credential] key=${key} email=${email} scope=user hit=true`,\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 console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=org hit=true`,\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 console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=workspace hit=true`,\n );\n return { value: workspaceSecret.value, source: \"workspace\" };\n }\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} miss tried=user,org,workspace`,\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 console.log(\n `[builder-credential] key=${key} email=${email} scope=workspace-solo hit=true`,\n );\n return { value: soloWorkspaceSecret.value, source: \"workspace\" };\n }\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=(none) miss tried=user,workspace-solo`,\n );\n }\n } catch (err) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=${scopeAttempted} error=${(err as Error)?.message ?? err}`,\n );\n // Secrets table not ready — treat as missing.\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 * Resolve where the effective Builder private key came from. Used by status\n * UIs so they can distinguish a deploy fallback from a user/org connection.\n */\nexport async function resolveBuilderCredentialSource(): Promise<BuilderCredentialSource | null> {\n const scoped = await resolveScopedBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n if (scoped) return scoped.source;\n return canUseBuilderDeployCredentialFallbackForRequest() &&\n process.env.BUILDER_PRIVATE_KEY\n ? \"env\"\n : null;\n}\n\n/**\n * Resolve all per-user Builder credentials. Used by the status endpoint\n * and agent-chat-plugin to get orgName, userId, etc.\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}> {\n const [privateKey, publicKey, userId, orgName, orgKind] = await Promise.all([\n resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\"),\n resolveBuilderCredential(\"BUILDER_PUBLIC_KEY\"),\n resolveBuilderCredential(\"BUILDER_USER_ID\"),\n resolveBuilderCredential(\"BUILDER_ORG_NAME\"),\n resolveBuilderCredential(\"BUILDER_ORG_KIND\"),\n ]);\n return { privateKey, publicKey, userId, orgName, orgKind };\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 },\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\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: creds.privateKey },\n { key: \"BUILDER_PUBLIC_KEY\", value: creds.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 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: creds.privateKey,\n publicKey: creds.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 // Log Builder-credential lookups by default so \"I connected Builder but\n // chat says no LLM\" reports can be diagnosed from server logs without\n // re-running anything. Keep noise low by gating other keys behind a flag.\n const traceLookup =\n key.startsWith(\"BUILDER_\") ||\n /^(1|true)$/i.test(process.env.DEBUG_CREDENTIAL_RESOLVE ?? \"\");\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/** 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"]}
@@ -0,0 +1,17 @@
1
+ import type { Plugin } from "vite";
2
+ import { type AgentWebInputConfig, type AgentWebPage } from "../agent-web/index.js";
3
+ export interface AgentWebVitePluginOptions {
4
+ siteName: string;
5
+ siteUrl: string;
6
+ description?: string;
7
+ pages: AgentWebPage[] | (() => AgentWebPage[]);
8
+ agentWeb?: AgentWebInputConfig | boolean;
9
+ outputDirs?: string[];
10
+ organization?: {
11
+ name: string;
12
+ url?: string;
13
+ sameAs?: string[];
14
+ };
15
+ }
16
+ export declare function createAgentWebVitePlugin(options: AgentWebVitePluginOptions): Plugin;
17
+ //# sourceMappingURL=agent-web-plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-web-plugin.d.ts","sourceRoot":"","sources":["../../src/vite/agent-web-plugin.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,EAGL,KAAK,mBAAmB,EACxB,KAAK,YAAY,EAClB,MAAM,uBAAuB,CAAC;AAE/B,MAAM,WAAW,yBAAyB;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,YAAY,EAAE,GAAG,CAAC,MAAM,YAAY,EAAE,CAAC,CAAC;IAC/C,QAAQ,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC;IACzC,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,YAAY,CAAC,EAAE;QACb,IAAI,EAAE,MAAM,CAAC;QACb,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;KACnB,CAAC;CACH;AAED,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,yBAAyB,GACjC,MAAM,CAiDR"}
@@ -0,0 +1,48 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { buildAgentWebStaticFiles, normalizeAgentWebConfig, } from "../agent-web/index.js";
4
+ export function createAgentWebVitePlugin(options) {
5
+ let rootDir = process.cwd();
6
+ return {
7
+ name: "agent-web-surfaces",
8
+ apply: "build",
9
+ configResolved(config) {
10
+ rootDir = config.root;
11
+ },
12
+ closeBundle() {
13
+ const pages = typeof options.pages === "function" ? options.pages() : options.pages;
14
+ const config = normalizeAgentWebConfig(options.agentWeb ?? {}, {
15
+ hasPublicRoutes: pages.length > 0,
16
+ });
17
+ if (!config.discoverable)
18
+ return;
19
+ const files = buildAgentWebStaticFiles({
20
+ siteName: options.siteName,
21
+ siteUrl: options.siteUrl,
22
+ description: options.description,
23
+ pages,
24
+ config,
25
+ organization: options.organization,
26
+ });
27
+ const outputDirs = options.outputDirs ?? [
28
+ "public",
29
+ "dist",
30
+ "dist/client",
31
+ "dist/server/public",
32
+ "build/client",
33
+ ];
34
+ for (const dir of outputDirs) {
35
+ const outDir = path.resolve(rootDir, dir);
36
+ if (!fs.existsSync(outDir))
37
+ continue;
38
+ for (const file of files) {
39
+ const outPath = path.resolve(outDir, file.path);
40
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
41
+ fs.writeFileSync(outPath, file.content);
42
+ }
43
+ }
44
+ this.info(`[agent-web] Generated ${files.length} files for ${pages.length} public routes`);
45
+ },
46
+ };
47
+ }
48
+ //# sourceMappingURL=agent-web-plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-web-plugin.js","sourceRoot":"","sources":["../../src/vite/agent-web-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EACL,wBAAwB,EACxB,uBAAuB,GAGxB,MAAM,uBAAuB,CAAC;AAgB/B,MAAM,UAAU,wBAAwB,CACtC,OAAkC;IAElC,IAAI,OAAO,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAE5B,OAAO;QACL,IAAI,EAAE,oBAAoB;QAC1B,KAAK,EAAE,OAAO;QACd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;oBACzD,EAAE,CAAC,aAAa,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;gBAC1C,CAAC;YACH,CAAC;YAED,IAAI,CAAC,IAAI,CACP,yBAAyB,KAAK,CAAC,MAAM,cAAc,KAAK,CAAC,MAAM,gBAAgB,CAChF,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport type { Plugin } from \"vite\";\nimport {\n buildAgentWebStaticFiles,\n normalizeAgentWebConfig,\n type AgentWebInputConfig,\n type AgentWebPage,\n} from \"../agent-web/index.js\";\n\nexport interface AgentWebVitePluginOptions {\n siteName: string;\n siteUrl: string;\n description?: string;\n pages: AgentWebPage[] | (() => AgentWebPage[]);\n agentWeb?: AgentWebInputConfig | boolean;\n outputDirs?: string[];\n organization?: {\n name: string;\n url?: string;\n sameAs?: string[];\n };\n}\n\nexport function createAgentWebVitePlugin(\n options: AgentWebVitePluginOptions,\n): Plugin {\n let rootDir = process.cwd();\n\n return {\n name: \"agent-web-surfaces\",\n apply: \"build\",\n configResolved(config) {\n rootDir = config.root;\n },\n closeBundle() {\n const pages =\n typeof options.pages === \"function\" ? options.pages() : options.pages;\n const config = normalizeAgentWebConfig(options.agentWeb ?? {}, {\n hasPublicRoutes: pages.length > 0,\n });\n if (!config.discoverable) return;\n\n const files = buildAgentWebStaticFiles({\n siteName: options.siteName,\n siteUrl: options.siteUrl,\n description: options.description,\n pages,\n config,\n organization: options.organization,\n });\n\n const outputDirs = options.outputDirs ?? [\n \"public\",\n \"dist\",\n \"dist/client\",\n \"dist/server/public\",\n \"build/client\",\n ];\n\n for (const dir of outputDirs) {\n const outDir = path.resolve(rootDir, dir);\n if (!fs.existsSync(outDir)) continue;\n for (const file of files) {\n const outPath = path.resolve(outDir, file.path);\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n fs.writeFileSync(outPath, file.content);\n }\n }\n\n this.info(\n `[agent-web] Generated ${files.length} files for ${pages.length} public routes`,\n );\n },\n };\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  export { defineConfig, type ClientConfigOptions, type NitroOptions, } from "./client.js";
2
2
  export { actionTypesPlugin, generateActionRegistryForProject, } from "./action-types-plugin.js";
3
3
  export { agentsBundlePlugin } from "./agents-bundle-plugin.js";
4
+ export { createAgentWebVitePlugin, type AgentWebVitePluginOptions, } from "./agent-web-plugin.js";
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vite/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,KAAK,mBAAmB,EACxB,KAAK,YAAY,GAClB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,gCAAgC,GACjC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vite/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,KAAK,mBAAmB,EACxB,KAAK,YAAY,GAClB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,gCAAgC,GACjC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EACL,wBAAwB,EACxB,KAAK,yBAAyB,GAC/B,MAAM,uBAAuB,CAAC"}
@@ -1,4 +1,5 @@
1
1
  export { defineConfig, } from "./client.js";
2
2
  export { actionTypesPlugin, generateActionRegistryForProject, } from "./action-types-plugin.js";
3
3
  export { agentsBundlePlugin } from "./agents-bundle-plugin.js";
4
+ export { createAgentWebVitePlugin, } from "./agent-web-plugin.js";
4
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/vite/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,GAGb,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,gCAAgC,GACjC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC","sourcesContent":["export {\n defineConfig,\n type ClientConfigOptions,\n type NitroOptions,\n} from \"./client.js\";\nexport {\n actionTypesPlugin,\n generateActionRegistryForProject,\n} from \"./action-types-plugin.js\";\nexport { agentsBundlePlugin } from \"./agents-bundle-plugin.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/vite/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,GAGb,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,gCAAgC,GACjC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EACL,wBAAwB,GAEzB,MAAM,uBAAuB,CAAC","sourcesContent":["export {\n defineConfig,\n type ClientConfigOptions,\n type NitroOptions,\n} from \"./client.js\";\nexport {\n actionTypesPlugin,\n generateActionRegistryForProject,\n} from \"./action-types-plugin.js\";\nexport { agentsBundlePlugin } from \"./agents-bundle-plugin.js\";\nexport {\n createAgentWebVitePlugin,\n type AgentWebVitePluginOptions,\n} from \"./agent-web-plugin.js\";\n"]}
@@ -0,0 +1,143 @@
1
+ ---
2
+ title: "Agent Web Surfaces"
3
+ description: "Make public routes crawlable, readable, citable, and optionally callable by agents."
4
+ ---
5
+
6
+ # Agent Web Surfaces
7
+
8
+ Agent Web surfaces make public Agent-Native routes easy for agents to crawl, read, cite, and eventually call. The goal is not to make every app endpoint public. The goal is to publish a clean public surface for pages that are already public, while keeping private data and tool access behind explicit controls.
9
+
10
+ The docs site is the reference implementation. It publishes:
11
+
12
+ - `/robots.txt` with a crawler policy that allows retrieval but disallows training by default.
13
+ - `/sitemap.xml` with absolute canonical URLs and `lastmod` when the source file exposes it.
14
+ - `/llms.txt` and `/llms-full.txt` for agent-friendly content discovery.
15
+ - Markdown mirrors such as `/docs/getting-started.md`.
16
+ - `Accept: text/markdown` responses for public docs pages after a production build.
17
+ - JSON-LD for base organization, website, and page metadata.
18
+
19
+ ## Configuration
20
+
21
+ Add `agentWeb` under the existing workspace app config. The public route list is still derived from the app's route access settings; `agentWeb` controls how that public surface is represented to agents.
22
+
23
+ ```json
24
+ {
25
+ "agent-native": {
26
+ "workspaceApp": {
27
+ "audience": "public",
28
+ "protectedPaths": ["/admin/*"],
29
+ "agentWeb": {
30
+ "discoverable": true,
31
+ "markdownTwins": true,
32
+ "llmsTxt": true,
33
+ "jsonLd": true,
34
+ "publicAgentCard": true,
35
+ "publicMcp": false,
36
+ "crawlerPolicy": "discoverable-no-training",
37
+ "crawlers": {
38
+ "training": "disallow",
39
+ "search": "allow",
40
+ "userTriggered": "allow",
41
+ "codingAgents": "allow",
42
+ "autonomousAgents": "allow"
43
+ }
44
+ }
45
+ }
46
+ }
47
+ }
48
+ ```
49
+
50
+ For most apps, leave the defaults alone. If an app has any public route, `discoverable` defaults on. The default crawler policy is "discoverable, not trainable": search, user-triggered retrieval, coding agents, and autonomous browsing agents are allowed; training crawlers are disallowed.
51
+
52
+ ## Route Source Of Truth
53
+
54
+ Agent Web discovery follows the route access model:
55
+
56
+ - Public apps expose every route except `protectedPaths`.
57
+ - Internal apps expose only `publicPaths`.
58
+ - Public share and form pages can be readable by agents.
59
+ - Submitted private data, authenticated dashboards, and user/org state are never included just because a nearby page is public.
60
+
61
+ This keeps mixed apps natural. A forms app can expose a public form page and keep submissions private. A content app can expose published posts and keep the editor private. A docs site can expose everything except admin tools.
62
+
63
+ ## Public Pages Are Not Public Tools
64
+
65
+ Public page access and public tool access are separate. A route being public only means agents can read that route as HTML, Markdown, sitemap entries, llms entries, and structured data.
66
+
67
+ To expose an action through a public agent protocol later, the action must opt in:
68
+
69
+ ```ts
70
+ export default defineAction({
71
+ description: "Search published docs",
72
+ readOnly: true,
73
+ publicAgent: {
74
+ expose: true,
75
+ readOnly: true,
76
+ requiresAuth: false,
77
+ isConsequential: false,
78
+ title: "Search published docs",
79
+ },
80
+ run: async (args) => {
81
+ // ...
82
+ },
83
+ });
84
+ ```
85
+
86
+ `agentWeb.publicMcp` stays `false` by default. When public MCP is enabled, the server should expose only actions with `publicAgent.expose === true`, and should still exclude consequential or write actions unless the action and auth policy explicitly allow them.
87
+
88
+ ## Build-Time Files
89
+
90
+ Framework utilities in `@agent-native/core/agent-web` generate the common files from one page list:
91
+
92
+ ```ts
93
+ import {
94
+ buildAgentWebStaticFiles,
95
+ normalizeAgentWebConfig,
96
+ } from "@agent-native/core/agent-web";
97
+
98
+ const config = normalizeAgentWebConfig(
99
+ { crawlerPolicy: "discoverable-no-training" },
100
+ { hasPublicRoutes: true },
101
+ );
102
+
103
+ const files = buildAgentWebStaticFiles({
104
+ siteName: "My Agent-Native App",
105
+ siteUrl: "https://example.com",
106
+ description: "Public docs for my app.",
107
+ config,
108
+ pages: [
109
+ {
110
+ path: "/docs",
111
+ title: "Docs",
112
+ description: "Start here.",
113
+ markdown: "# Docs\n\nStart here.\n",
114
+ markdownPath: "/docs/getting-started.md",
115
+ lastmod: new Date(),
116
+ },
117
+ ],
118
+ });
119
+ ```
120
+
121
+ Vite apps can use `createAgentWebVitePlugin` from `@agent-native/core/vite` to write those files into `public`, `dist`, `dist/client`, `dist/server/public`, or `build/client` during production builds.
122
+
123
+ ## Audit A Site
124
+
125
+ Use the CLI audit against a deployed site or a local production server:
126
+
127
+ ```bash
128
+ agent-native audit-agent-web --url https://www.agent-native.com
129
+ ```
130
+
131
+ The audit checks for:
132
+
133
+ - SSR-visible HTML.
134
+ - Canonical URLs.
135
+ - JSON-LD.
136
+ - `robots.txt` policy and absolute sitemap URL.
137
+ - Absolute sitemap entries.
138
+ - `/llms.txt` and `/llms-full.txt`.
139
+ - Markdown mirrors.
140
+ - `Accept: text/markdown`.
141
+ - No accidental 401/403 blocks for common agent retrieval user agents.
142
+
143
+ The audit exits non-zero if a required public surface is missing.
@@ -0,0 +1,110 @@
1
+ ---
2
+ title: "Migration Workbench"
3
+ description: "Use a local agent-native Workbench to migrate existing apps into agent-native with assessment, approval, generated output, and verification."
4
+ ---
5
+
6
+ # Migration Workbench
7
+
8
+ Migration Workbench is a local agent-native app for moving existing applications into the agent-native framework. It is designed for migrations where an agent can do useful work, but every important step should be auditable and verified.
9
+
10
+ The product promise is: **let the agent run, but prove it**.
11
+
12
+ V1 focuses on **Next.js to standalone agent-native**. Builder.io Publish and AEM exits are designed into the adapter interfaces, but are intended as follow-on enterprise adapters rather than the first shipped path.
13
+
14
+ ## How It Works
15
+
16
+ Run:
17
+
18
+ ```bash
19
+ agent-native migrate ./my-next-app --out ../migrated-app
20
+ ```
21
+
22
+ The command scaffolds the hidden `migration` template and writes a seed file with the source and output paths. The Workbench UI then guides the run:
23
+
24
+ 1. **Discover** reads the source project and creates `01-assessment.md`.
25
+ 2. **Plan** creates recipe tasks and writes `02-plan.md` plus `03-tasks.md`.
26
+ 3. **Approve** unlocks generated output writes.
27
+ 4. **Sweep** runs migration tasks against the generated output project.
28
+ 5. **Verify** runs deterministic checks and writes `04-report.md`.
29
+
30
+ The source project is read-only. Generated output is written to a separate `outputRoot`.
31
+
32
+ ## Agent-Native Mapping
33
+
34
+ The V1 recipes are named after the framework contracts they enforce:
35
+
36
+ | Source pattern | Agent-native target |
37
+ | --------------------------- | ----------------------------------------------------------------- |
38
+ | API routes / server actions | `actions/`, except uploads, webhooks, OAuth, and streaming routes |
39
+ | app-owned data | Drizzle SQL tables plus actions |
40
+ | direct LLM calls | agent chat delegation |
41
+ | important client state | `application_state` navigation and selection |
42
+ | UI mutations | optimistic action mutations |
43
+ | shared resources | ownership, sharing, and access helpers |
44
+ | public pages | server rendering |
45
+ | logged-in workflows | persistent client app shell |
46
+
47
+ This is the difference between porting React code and actually migrating to agent-native.
48
+
49
+ ## Adapter Model
50
+
51
+ `@agent-native/migrate` exposes a reusable engine:
52
+
53
+ - `SourceAdapter` detects and inventories existing projects.
54
+ - `TargetAdapter` scaffolds and verifies output.
55
+ - `MigrationRecipe` turns IR graph inventory into tasks.
56
+ - `Verifier` returns structured migration evidence.
57
+
58
+ The intermediate representation is split into four graphs:
59
+
60
+ - `SiteGraph`: routes, redirects, public/private classification, metadata.
61
+ - `ComponentGraph`: reusable UI components and design tokens.
62
+ - `ContentGraph`: CMS models, static content, and assets.
63
+ - `BehaviorGraph`: API endpoints, data stores, auth, jobs, client state, and LLM calls.
64
+
65
+ ## Builder.io And AEM
66
+
67
+ Builder.io is a target decision, not a source assumption. Builder Publish should be used for marketing, docs, landing, and content surfaces. Transactional SaaS state, dashboards, app-owned data, and workflows stay in agent-native SQL/actions.
68
+
69
+ AEM support should be implemented as a source adapter family:
70
+
71
+ - `crawl`: URLs, sitemap, screenshots, SEO, redirects.
72
+ - `api`: AEM GraphQL Content Fragments and DAM metadata.
73
+ - `package`: Vault/JCR package parsing.
74
+ - `code`: HTL components, dialogs, templates, and policies.
75
+ - `enterprise`: combines available modes and emits confidence/gap reports.
76
+
77
+ AEM output is two-pipeline: content extraction into Builder or SQL, plus frontend regeneration and component mapping into agent-native UI.
78
+
79
+ ## Verification
80
+
81
+ The default verifier path is deterministic:
82
+
83
+ - output file smoke checks
84
+ - route inventory parity artifacts
85
+ - agent-native conformance checks
86
+ - future Playwright smoke tests
87
+ - future visual, a11y, Lighthouse, SEO, and redirect checks
88
+
89
+ AI browser tools can help generate or repair flows, but deterministic Playwright-style checks should remain the truth oracle.
90
+
91
+ ## Package Exports
92
+
93
+ Use the engine directly when building adapters or custom migration workflows:
94
+
95
+ ```ts
96
+ import {
97
+ createMigrationRun,
98
+ discoverMigration,
99
+ planMigration,
100
+ nextjsSourceAdapter,
101
+ agentNativeTargetAdapter,
102
+ } from "@agent-native/migrate";
103
+ ```
104
+
105
+ Subpath exports are available for first-party V1 adapters:
106
+
107
+ ```ts
108
+ import { nextjsSourceAdapter } from "@agent-native/migrate/source-nextjs";
109
+ import { agentNativeTargetAdapter } from "@agent-native/migrate/target-agent-native";
110
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.15.10",
3
+ "version": "0.15.12",
4
4
  "type": "module",
5
5
  "description": "Framework for agent-native application development — where AI agents and UI share state via files",
6
6
  "license": "MIT",
@@ -31,6 +31,7 @@
31
31
  "./server/agent-discovery": "./dist/server/agent-discovery.js",
32
32
  "./server/request-context": "./dist/server/request-context.js",
33
33
  "./server/design-token-utils": "./dist/server/design-token-utils.js",
34
+ "./agent-web": "./dist/agent-web/index.js",
34
35
  "./db": "./dist/db/index.js",
35
36
  "./db/schema": "./dist/db/schema.js",
36
37
  "./db/drizzle-config": "./dist/db/drizzle-config.js",