@agent-native/core 0.52.0 → 0.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -95
- package/blueprints/action/crud.md +98 -0
- package/blueprints/channel/discord.md +74 -0
- package/blueprints/provider/stripe.md +87 -0
- package/blueprints/sandbox/docker.md +78 -0
- package/dist/action.d.ts +24 -0
- package/dist/action.d.ts.map +1 -1
- package/dist/action.js +4 -0
- package/dist/action.js.map +1 -1
- package/dist/agent/observational-memory/compactor.d.ts +43 -0
- package/dist/agent/observational-memory/compactor.d.ts.map +1 -0
- package/dist/agent/observational-memory/compactor.js +50 -0
- package/dist/agent/observational-memory/compactor.js.map +1 -0
- package/dist/agent/observational-memory/config.d.ts +37 -0
- package/dist/agent/observational-memory/config.d.ts.map +1 -0
- package/dist/agent/observational-memory/config.js +48 -0
- package/dist/agent/observational-memory/config.js.map +1 -0
- package/dist/agent/observational-memory/index.d.ts +26 -0
- package/dist/agent/observational-memory/index.d.ts.map +1 -0
- package/dist/agent/observational-memory/index.js +25 -0
- package/dist/agent/observational-memory/index.js.map +1 -0
- package/dist/agent/observational-memory/internal-run.d.ts +37 -0
- package/dist/agent/observational-memory/internal-run.d.ts.map +1 -0
- package/dist/agent/observational-memory/internal-run.js +59 -0
- package/dist/agent/observational-memory/internal-run.js.map +1 -0
- package/dist/agent/observational-memory/message-text.d.ts +13 -0
- package/dist/agent/observational-memory/message-text.d.ts.map +1 -0
- package/dist/agent/observational-memory/message-text.js +46 -0
- package/dist/agent/observational-memory/message-text.js.map +1 -0
- package/dist/agent/observational-memory/migrations.d.ts +13 -0
- package/dist/agent/observational-memory/migrations.d.ts.map +1 -0
- package/dist/agent/observational-memory/migrations.js +43 -0
- package/dist/agent/observational-memory/migrations.js.map +1 -0
- package/dist/agent/observational-memory/observer.d.ts +37 -0
- package/dist/agent/observational-memory/observer.d.ts.map +1 -0
- package/dist/agent/observational-memory/observer.js +82 -0
- package/dist/agent/observational-memory/observer.js.map +1 -0
- package/dist/agent/observational-memory/plugin.d.ts +16 -0
- package/dist/agent/observational-memory/plugin.d.ts.map +1 -0
- package/dist/agent/observational-memory/plugin.js +26 -0
- package/dist/agent/observational-memory/plugin.js.map +1 -0
- package/dist/agent/observational-memory/prompts.d.ts +27 -0
- package/dist/agent/observational-memory/prompts.d.ts.map +1 -0
- package/dist/agent/observational-memory/prompts.js +42 -0
- package/dist/agent/observational-memory/prompts.js.map +1 -0
- package/dist/agent/observational-memory/read.d.ts +47 -0
- package/dist/agent/observational-memory/read.d.ts.map +1 -0
- package/dist/agent/observational-memory/read.js +99 -0
- package/dist/agent/observational-memory/read.js.map +1 -0
- package/dist/agent/observational-memory/reflector.d.ts +31 -0
- package/dist/agent/observational-memory/reflector.d.ts.map +1 -0
- package/dist/agent/observational-memory/reflector.js +76 -0
- package/dist/agent/observational-memory/reflector.js.map +1 -0
- package/dist/agent/observational-memory/schema.d.ts +267 -0
- package/dist/agent/observational-memory/schema.d.ts.map +1 -0
- package/dist/agent/observational-memory/schema.js +48 -0
- package/dist/agent/observational-memory/schema.js.map +1 -0
- package/dist/agent/observational-memory/store.d.ts +52 -0
- package/dist/agent/observational-memory/store.d.ts.map +1 -0
- package/dist/agent/observational-memory/store.js +197 -0
- package/dist/agent/observational-memory/store.js.map +1 -0
- package/dist/agent/observational-memory/types.d.ts +61 -0
- package/dist/agent/observational-memory/types.d.ts.map +1 -0
- package/dist/agent/observational-memory/types.js +9 -0
- package/dist/agent/observational-memory/types.js.map +1 -0
- package/dist/agent/production-agent.d.ts +15 -0
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +240 -1
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent/run-loop-with-resume.d.ts.map +1 -1
- package/dist/agent/run-loop-with-resume.js +49 -0
- package/dist/agent/run-loop-with-resume.js.map +1 -1
- package/dist/agent/run-store.d.ts +17 -0
- package/dist/agent/run-store.d.ts.map +1 -1
- package/dist/agent/run-store.js +55 -0
- package/dist/agent/run-store.js.map +1 -1
- package/dist/agent/runtime-context.d.ts +30 -0
- package/dist/agent/runtime-context.d.ts.map +1 -1
- package/dist/agent/runtime-context.js +54 -1
- package/dist/agent/runtime-context.js.map +1 -1
- package/dist/agent/tool-call-journal.d.ts +101 -0
- package/dist/agent/tool-call-journal.d.ts.map +1 -0
- package/dist/agent/tool-call-journal.js +214 -0
- package/dist/agent/tool-call-journal.js.map +1 -0
- package/dist/agent/types.d.ts +24 -0
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/agent/types.js.map +1 -1
- package/dist/cli/add.d.ts +109 -0
- package/dist/cli/add.d.ts.map +1 -0
- package/dist/cli/add.js +352 -0
- package/dist/cli/add.js.map +1 -0
- package/dist/cli/connect.d.ts +2 -2
- package/dist/cli/connect.d.ts.map +1 -1
- package/dist/cli/connect.js +92 -24
- package/dist/cli/connect.js.map +1 -1
- package/dist/cli/eval.d.ts +17 -0
- package/dist/cli/eval.d.ts.map +1 -0
- package/dist/cli/eval.js +121 -0
- package/dist/cli/eval.js.map +1 -0
- package/dist/cli/index.js +44 -3
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/mcp.d.ts.map +1 -1
- package/dist/cli/mcp.js +11 -5
- package/dist/cli/mcp.js.map +1 -1
- package/dist/cli/plan-local.d.ts +66 -5
- package/dist/cli/plan-local.d.ts.map +1 -1
- package/dist/cli/plan-local.js +495 -19
- package/dist/cli/plan-local.js.map +1 -1
- package/dist/cli/skills.d.ts +2 -2
- package/dist/cli/skills.d.ts.map +1 -1
- package/dist/cli/skills.js +70 -59
- package/dist/cli/skills.js.map +1 -1
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +118 -92
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/agent-chat-adapter.d.ts.map +1 -1
- package/dist/client/agent-chat-adapter.js +16 -0
- package/dist/client/agent-chat-adapter.js.map +1 -1
- package/dist/client/chat/tool-call-display.d.ts +20 -1
- package/dist/client/chat/tool-call-display.d.ts.map +1 -1
- package/dist/client/chat/tool-call-display.js +32 -7
- package/dist/client/chat/tool-call-display.js.map +1 -1
- package/dist/client/sse-event-processor.d.ts +13 -0
- package/dist/client/sse-event-processor.d.ts.map +1 -1
- package/dist/client/sse-event-processor.js +21 -0
- package/dist/client/sse-event-processor.js.map +1 -1
- package/dist/db/client.d.ts +4 -2
- package/dist/db/client.d.ts.map +1 -1
- package/dist/db/client.js +6 -4
- package/dist/db/client.js.map +1 -1
- package/dist/deploy/route-discovery.d.ts.map +1 -1
- package/dist/deploy/route-discovery.js +1 -0
- package/dist/deploy/route-discovery.js.map +1 -1
- package/dist/eval/agent-runner.d.ts +63 -0
- package/dist/eval/agent-runner.d.ts.map +1 -0
- package/dist/eval/agent-runner.js +142 -0
- package/dist/eval/agent-runner.js.map +1 -0
- package/dist/eval/define-eval.d.ts +29 -0
- package/dist/eval/define-eval.d.ts.map +1 -0
- package/dist/eval/define-eval.js +43 -0
- package/dist/eval/define-eval.js.map +1 -0
- package/dist/eval/index.d.ts +18 -0
- package/dist/eval/index.d.ts.map +1 -0
- package/dist/eval/index.js +17 -0
- package/dist/eval/index.js.map +1 -0
- package/dist/eval/report.d.ts +8 -0
- package/dist/eval/report.d.ts.map +1 -0
- package/dist/eval/report.js +44 -0
- package/dist/eval/report.js.map +1 -0
- package/dist/eval/runner.d.ts +67 -0
- package/dist/eval/runner.d.ts.map +1 -0
- package/dist/eval/runner.js +256 -0
- package/dist/eval/runner.js.map +1 -0
- package/dist/eval/scorer.d.ts +83 -0
- package/dist/eval/scorer.d.ts.map +1 -0
- package/dist/eval/scorer.js +195 -0
- package/dist/eval/scorer.js.map +1 -0
- package/dist/eval/types.d.ts +162 -0
- package/dist/eval/types.d.ts.map +1 -0
- package/dist/eval/types.js +20 -0
- package/dist/eval/types.js.map +1 -0
- package/dist/observability/traces.d.ts.map +1 -1
- package/dist/observability/traces.js +100 -1
- package/dist/observability/traces.js.map +1 -1
- package/dist/observability/tracing.d.ts +73 -0
- package/dist/observability/tracing.d.ts.map +1 -0
- package/dist/observability/tracing.js +126 -0
- package/dist/observability/tracing.js.map +1 -0
- package/dist/onboarding/default-steps.d.ts.map +1 -1
- package/dist/onboarding/default-steps.js +4 -1
- package/dist/onboarding/default-steps.js.map +1 -1
- package/dist/provider-api/actions/query-staged-dataset.d.ts +1 -1
- package/dist/scripts/agent-engines/list-agent-engines.d.ts.map +1 -1
- package/dist/scripts/agent-engines/list-agent-engines.js +10 -3
- package/dist/scripts/agent-engines/list-agent-engines.js.map +1 -1
- package/dist/server/action-discovery.d.ts.map +1 -1
- package/dist/server/action-discovery.js +4 -0
- package/dist/server/action-discovery.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts +9 -0
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +118 -110
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-teams.d.ts +62 -0
- package/dist/server/agent-teams.d.ts.map +1 -1
- package/dist/server/agent-teams.js +99 -2
- package/dist/server/agent-teams.js.map +1 -1
- package/dist/server/core-routes-plugin.d.ts.map +1 -1
- package/dist/server/core-routes-plugin.js +7 -4
- package/dist/server/core-routes-plugin.js.map +1 -1
- package/dist/server/credential-provider.d.ts.map +1 -1
- package/dist/server/credential-provider.js +2 -0
- package/dist/server/credential-provider.js.map +1 -1
- package/dist/server/framework-request-handler.d.ts.map +1 -1
- package/dist/server/framework-request-handler.js +33 -1
- package/dist/server/framework-request-handler.js.map +1 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +1 -0
- package/dist/server/index.js.map +1 -1
- package/dist/templates/workspace-core/.agents/skills/external-agents/SKILL.md +10 -0
- package/dist/templates/workspace-core/.agents/skills/harness-agents/SKILL.md +20 -0
- package/dist/templates/workspace-core/.agents/skills/observability/SKILL.md +20 -0
- package/docs/content/agent-teams.md +32 -0
- package/docs/content/blueprint-installer.md +73 -0
- package/docs/content/evals.md +141 -0
- package/docs/content/pr-visual-recap.md +7 -4
- package/docs/content/sandbox-adapters.md +134 -0
- package/docs/content/template-plan.md +20 -8
- package/package.json +5 -1
- package/src/templates/workspace-core/.agents/skills/external-agents/SKILL.md +10 -0
- package/src/templates/workspace-core/.agents/skills/harness-agents/SKILL.md +20 -0
- package/src/templates/workspace-core/.agents/skills/observability/SKILL.md +20 -0
|
@@ -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,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAC9B;IAAE,KAAK,EAAE,MAAM,GAAG,KAAK,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAK5C;AAED,qBAAa,yBAA0B,SAAQ,KAAK;IAClD,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;gBAElB,IAAI,EAAE;QAChB,kBAAkB,EAAE,MAAM,CAAC;QAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;KACtB;CAUF;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEvE;AAED;;;;;GAKG;AACH,wBAAgB,iCAAiC,IAAI,OAAO,CAG3D;AAED,wBAAgB,wCAAwC,IAAI,OAAO,
|
|
1
|
+
{"version":3,"file":"credential-provider.d.ts","sourceRoot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,EAAE;IAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,GACxD,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,GAAG,KAAK,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CA+FrD;AAED;;;;;;;;;GASG;AACH,wBAAsB,wBAAwB,CAC5C,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE;IAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,GACxD,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,GAAG,KAAK,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAiBrD;AAeD;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAyGvE;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;;;GAGG;AACH,wBAAgB,0BAA0B,IAAI,MAAM,CAKnD;AAED,uEAAuE;AACvE,wBAAgB,oBAAoB,IAAI,MAAM,GAAG,IAAI,CAGpD"}
|
|
@@ -68,6 +68,8 @@ export function isDeployCredentialFallbackAllowed() {
|
|
|
68
68
|
}
|
|
69
69
|
export function canUseDeployCredentialFallbackForRequest() {
|
|
70
70
|
const email = getRequestUserEmail();
|
|
71
|
+
if (email && isHostedWorkspaceRuntime())
|
|
72
|
+
return false;
|
|
71
73
|
if (!email)
|
|
72
74
|
return true;
|
|
73
75
|
return isDeployCredentialFallbackAllowed();
|
|
@@ -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,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,IAAI,CAAC,kBAAkB,yCAAyC,CACnG,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,2BAA2B,CAAC;QACxC,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAC,kBAAkB,CAAC;QAClD,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC,iBAAiB,CAAC;QAChD,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;IACtC,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CAAC,GAAW;IACjD,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,SAAS,CAAC;AACvC,CAAC;AAED;;;;;GA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E;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;;;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\";\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 \"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 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\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;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,IAAI,CAAC,kBAAkB,yCAAyC,CACnG,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,2BAA2B,CAAC;QACxC,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAC,kBAAkB,CAAC;QAClD,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC,iBAAiB,CAAC;QAChD,IAAI,CAAC,WAAW,G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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 && 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 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\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"framework-request-handler.d.ts","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,YAAY,EAAW,MAAM,IAAI,CAAC;AAQhD,QAAA,MAAM,gBAAgB,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"framework-request-handler.d.ts","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,YAAY,EAAW,MAAM,IAAI,CAAC;AAQhD,QAAA,MAAM,gBAAgB,mBAAmB,CAAC;AAkD1C;;;GAGG;AACH,MAAM,WAAW,SAAS;IACxB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;IAC/C,GAAG,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;CAClC;AAED;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAQ3E;AAED;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CAAC,QAAQ,EAAE,GAAG,GAAG,SAAS,CA0DjD;AA0CD;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,QAAQ,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAOjE;AAmBD;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,GAAG,EACb,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,EACtB,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;CAAO,GACjC,IAAI,CAuCN;AAmDD;;;GAGG;AACH,wBAAsB,iBAAiB,CACrC,QAAQ,EAAE,GAAG,EACb,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,IAAI,CAAC,CAqBf;AAkTD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,GAAG,CAAC,CAyBd;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
|
|
@@ -10,6 +10,7 @@ const APP_SHIM_KEY = "_agentNativeH3Shim";
|
|
|
10
10
|
const BOOTSTRAP_PROMISE_KEY = "_agentNativeBootstrapPromise";
|
|
11
11
|
const PLUGIN_READY_KEY = "_agentNativePluginReadyPromise";
|
|
12
12
|
const PLUGIN_READY_PLACEHOLDERS_KEY = "_agentNativePluginReadyPlaceholders";
|
|
13
|
+
const PLUGIN_FAILED_KEY = "_agentNativePluginInitFailures";
|
|
13
14
|
const PROVIDED_PLUGIN_STEMS_KEY = "_agentNativeProvidedPluginStems";
|
|
14
15
|
const MIDDLEWARE_DISPATCHER_PATCHED_KEY = "_agentNativeMiddlewareDispatcherPatched";
|
|
15
16
|
function getAppBasePath() {
|
|
@@ -204,6 +205,17 @@ export function trackPluginInit(nitroApp, promise, options = {}) {
|
|
|
204
205
|
// is still observable when awaitPluginsReady() re-awaits the promise.
|
|
205
206
|
const safe = promise.catch((err) => {
|
|
206
207
|
console.error("[agent-native] Plugin init failed:", err.message || err);
|
|
208
|
+
// Record the failure so the readiness gate can return a retryable 503 for
|
|
209
|
+
// this plugin's routes instead of letting them fall through to a bare
|
|
210
|
+
// "Cannot find any route matching" 404. That bare 404 is what kept biting
|
|
211
|
+
// external MCP clients (pi/codex/claude) and the connect flow on cold /
|
|
212
|
+
// propagating instances whose async init rejected (e.g. DB not yet
|
|
213
|
+
// reachable): the route never registered, so the placeholder released into
|
|
214
|
+
// a 404 the client couldn't recover from. A 503 is at least retryable.
|
|
215
|
+
const failures = (nitroApp[PLUGIN_FAILED_KEY] ??= new Map());
|
|
216
|
+
const msg = err?.message || String(err);
|
|
217
|
+
for (const p of options.paths?.filter(Boolean) ?? [])
|
|
218
|
+
failures.set(p, msg);
|
|
207
219
|
});
|
|
208
220
|
const entry = {
|
|
209
221
|
promise: safe,
|
|
@@ -230,7 +242,24 @@ function installPluginReadyPlaceholders(nitroApp, paths) {
|
|
|
230
242
|
installed.add(path);
|
|
231
243
|
registerMiddleware(nitroApp, path, (async (event) => {
|
|
232
244
|
const eventAny = event;
|
|
233
|
-
|
|
245
|
+
const reqPath = eventAny.context?._mountedPathname ?? event.url?.pathname ?? path;
|
|
246
|
+
await awaitFrameworkRoutesReadyForRequest(nitroApp, reqPath);
|
|
247
|
+
// If this plugin's async init failed, its real route was never
|
|
248
|
+
// registered. Return a retryable 503 instead of releasing into a bare
|
|
249
|
+
// 404 (external MCP clients can't recover from a 404; a 503 is at least
|
|
250
|
+
// a "try again" the client / next instance can act on).
|
|
251
|
+
const failures = nitroApp[PLUGIN_FAILED_KEY];
|
|
252
|
+
if (failures?.size) {
|
|
253
|
+
for (const [failedPath, msg] of failures) {
|
|
254
|
+
if (resolveMountMatch(reqPath, failedPath)) {
|
|
255
|
+
setResponseStatus(event, 503);
|
|
256
|
+
setResponseHeader(event, "retry-after", "5");
|
|
257
|
+
return {
|
|
258
|
+
error: `agent-native route is initializing or unavailable: ${msg}`,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
234
263
|
return undefined;
|
|
235
264
|
}), {
|
|
236
265
|
prepend: true,
|
|
@@ -452,6 +481,7 @@ async function bootstrapDefaultPlugins(nitroApp) {
|
|
|
452
481
|
const terminalModule = await import("../terminal/terminal-plugin.js");
|
|
453
482
|
const integrationsModule = await import("../integrations/plugin.js");
|
|
454
483
|
const contextXrayModule = await import("../agent/context-xray/plugin.js");
|
|
484
|
+
const observationalMemoryModule = await import("../agent/observational-memory/plugin.js");
|
|
455
485
|
const orgModule = await import("../org/plugin.js");
|
|
456
486
|
const onboardingModule = await import("../onboarding/plugin.js");
|
|
457
487
|
const frameworkImpls = {
|
|
@@ -460,6 +490,8 @@ async function bootstrapDefaultPlugins(nitroApp) {
|
|
|
460
490
|
"context-xray": contextXrayModule.defaultContextXrayPlugin,
|
|
461
491
|
"core-routes": serverModule.defaultCoreRoutesPlugin,
|
|
462
492
|
integrations: integrationsModule.defaultIntegrationsPlugin,
|
|
493
|
+
"observational-memory": observationalMemoryModule
|
|
494
|
+
.defaultObservationalMemoryPlugin,
|
|
463
495
|
onboarding: onboardingModule.defaultOnboardingPlugin,
|
|
464
496
|
org: orgModule.defaultOrgPlugin,
|
|
465
497
|
resources: serverModule.defaultResourcesPlugin,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"framework-request-handler.js","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AAC1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,MAAM,YAAY,GAAG,IAAI,OAAO,EAAU,CAAC;AA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AAM,IAAI,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,CAAC;QACvC,sEAAsE;QACtE,wEAAwE;QACxE,mCAAmC;QACnC,MAAM,MAAM,GAAG,aAAa,CAC1B,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,cAAc,CAAC,CACtC,CAAC,QAAQ,EAAE,CAAC;QACb,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1D,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,WAAW,SAAS,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,OAAO,EAAE,CAAC;QACjB,wEAAwE;QACxE,8DAA8D;QAC9D,MAAM,QAAQ,IAAI,OAAO,CAAC;IAC5B,CAAC;AACH,CAAC;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC","sourcesContent":["/**\n * Framework request handler — registers framework routes on Nitro's h3 instance.\n *\n * Nitro 3 exposes its h3 app as `nitroApp.h3`. We register framework routes\n * directly on it as middleware (`nitroApp.h3[\"~middleware\"]`), giving each\n * plugin a path-prefix-matched handler that runs before any file-based route.\n *\n * Plugins call `getH3App(nitroApp).use(path, handler)` exactly like h3 v1's\n * `app.use()` — the wrapper translates that into v2 middleware registration.\n *\n * Default plugins that the template doesn't provide are auto-mounted on the\n * first call to `getH3App()` per nitroApp instance.\n */\nimport type { EventHandler, H3Event } from \"h3\";\nimport { setResponseHeader, setResponseStatus } from \"h3\";\nimport { getMissingDefaultPlugins } from \"../deploy/route-discovery.js\";\nimport { captureError } from \"./capture-error.js\";\nimport { getConfiguredAppBasePath } from \"./app-base-path.js\";\n\nconst BOOTSTRAPPED = new WeakSet<object>();\nconst IN_BOOTSTRAP = new WeakSet<object>();\nconst FRAMEWORK_PREFIX = \"/_agent-native\";\nconst WELL_KNOWN_PREFIX = \"/.well-known\";\nconst APP_SHIM_KEY = \"_agentNativeH3Shim\";\nconst BOOTSTRAP_PROMISE_KEY = \"_agentNativeBootstrapPromise\";\nconst PLUGIN_READY_KEY = \"_agentNativePluginReadyPromise\";\nconst PLUGIN_READY_PLACEHOLDERS_KEY = \"_agentNativePluginReadyPlaceholders\";\nconst PROVIDED_PLUGIN_STEMS_KEY = \"_agentNativeProvidedPluginStems\";\nconst MIDDLEWARE_DISPATCHER_PATCHED_KEY =\n \"_agentNativeMiddlewareDispatcherPatched\";\n\ninterface PluginReadyEntry {\n promise: Promise<void>;\n paths?: string[];\n}\n\nfunction getAppBasePath(): string {\n return getConfiguredAppBasePath();\n}\n\nfunction pathMatchesPrefix(reqPath: string, prefix: string): boolean {\n return reqPath === prefix || reqPath.startsWith(prefix + \"/\");\n}\n\nfunction supportsAppBasePathMount(path: string): boolean {\n return (\n pathMatchesPrefix(path, FRAMEWORK_PREFIX) ||\n pathMatchesPrefix(path, WELL_KNOWN_PREFIX)\n );\n}\n\nfunction resolveMountMatch(\n reqPath: string,\n path: string,\n): { mountPath: string; strippedPath: string } | null {\n if (pathMatchesPrefix(reqPath, path)) {\n return { mountPath: path, strippedPath: reqPath.slice(path.length) || \"/\" };\n }\n\n const appBasePath = getAppBasePath();\n if (!appBasePath || !supportsAppBasePathMount(path)) return null;\n\n const prefixedPath = `${appBasePath}${path}`;\n if (!pathMatchesPrefix(reqPath, prefixedPath)) return null;\n return {\n mountPath: prefixedPath,\n strippedPath: reqPath.slice(prefixedPath.length) || \"/\",\n };\n}\n\n/**\n * Wrapper around Nitro's h3 instance that exposes a v1-style `.use()` API\n * for registering path-prefix middleware.\n */\nexport interface H3AppShim {\n use(path: string, handler: EventHandler): void;\n use(handler: EventHandler): void;\n}\n\n/**\n * Mark a default plugin slot as supplied by the app/template before the\n * framework default bootstrap runs.\n *\n * Bundled serverless functions often don't have the original\n * `server/plugins/*.ts` tree on disk at runtime, so filesystem route discovery\n * can falsely conclude a template plugin is missing. Explicit plugin factories\n * call this synchronously before awaiting bootstrap so the framework does not\n * auto-mount a generic default over the app's custom implementation.\n */\nexport function markDefaultPluginProvided(nitroApp: any, stem: string): void {\n if (!nitroApp || !stem) return;\n const existing = nitroApp[PROVIDED_PLUGIN_STEMS_KEY] as\n | Set<string>\n | undefined;\n const provided = existing ?? new Set<string>();\n provided.add(stem);\n nitroApp[PROVIDED_PLUGIN_STEMS_KEY] = provided;\n}\n\n/**\n * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this\n * to register routes via `.use(path, handler)`.\n *\n * On the first call per nitroApp, we kick off auto-mounting any missing\n * default plugins. User-facing plugin factories (createAgentChatPlugin,\n * createAuthPlugin, etc.) await this bootstrap via `awaitBootstrap()` so the\n * default plugins finish registering middleware before requests arrive.\n */\nexport function getH3App(nitroApp: any): H3AppShim {\n if (!nitroApp) throw new Error(\"getH3App: nitroApp is required\");\n ensureGlobalMiddlewareDispatch(nitroApp);\n\n // Reuse the cached shim if we've wrapped this nitroApp before\n const cached = nitroApp[APP_SHIM_KEY] as H3AppShim | undefined;\n if (cached) return cached;\n\n const shim: H3AppShim = {\n use(arg1: string | EventHandler, arg2?: EventHandler) {\n const path = typeof arg1 === \"string\" ? arg1 : \"\";\n const handler = (typeof arg1 === \"string\" ? arg2 : arg1) as EventHandler;\n if (typeof handler !== \"function\") {\n throw new Error(\"getH3App.use: handler must be a function\");\n }\n registerMiddleware(nitroApp, path, handler);\n },\n };\n\n nitroApp[APP_SHIM_KEY] = shim;\n\n if (!BOOTSTRAPPED.has(nitroApp)) {\n BOOTSTRAPPED.add(nitroApp);\n nitroApp[BOOTSTRAP_PROMISE_KEY] = bootstrapDefaultPlugins(nitroApp).catch(\n (err) => {\n console.warn(\n \"[agent-native] Failed to auto-mount default plugins:\",\n (err as Error).message,\n );\n captureError(err, {\n route: \"default-plugin-bootstrap\",\n tags: { phase: \"default-plugin-bootstrap\" },\n });\n },\n );\n\n // Readiness gate: Nitro v3 doesn't await async plugins, so routes\n // registered inside an async plugin may not exist when the first\n // request arrives. These middleware entries hold framework routes\n // until default-plugin bootstrap and tracked plugin inits complete.\n const readinessGate = (async (event: H3Event) => {\n const eventAny = event as any;\n await awaitFrameworkRoutesReadyForRequest(\n nitroApp,\n eventAny.context?._mountedPathname ?? event.url?.pathname ?? \"\",\n );\n // Fall through — the actual route handler runs next.\n return undefined;\n }) as EventHandler;\n registerMiddleware(nitroApp, FRAMEWORK_PREFIX, readinessGate, {\n prepend: true,\n });\n registerMiddleware(nitroApp, WELL_KNOWN_PREFIX, readinessGate, {\n prepend: true,\n });\n }\n\n return shim;\n}\n\n/**\n * Nitro 3 production builds generate a route dispatcher by overriding h3's\n * internal `~getMiddleware()` hook. Some generated dispatchers return only\n * route-rule middleware and skip the global `h3[\"~middleware\"]` array that\n * `getH3App().use()` appends to. Wrap the dispatcher once so framework routes\n * registered at runtime are still part of request dispatch.\n */\nfunction ensureGlobalMiddlewareDispatch(nitroApp: any): void {\n const h3 = nitroApp?.h3;\n if (!h3) return;\n const current = h3[\"~getMiddleware\"];\n if (h3[MIDDLEWARE_DISPATCHER_PATCHED_KEY] === current) return;\n\n const original = typeof current === \"function\" ? current.bind(h3) : undefined;\n\n const wrappedGetMiddleware = (event: H3Event, route: unknown) => {\n const originalResult = original ? original(event, route) : [];\n const originalList = Array.isArray(originalResult)\n ? originalResult\n : originalResult\n ? [originalResult]\n : [];\n const globalMiddleware = Array.isArray(h3[\"~middleware\"])\n ? h3[\"~middleware\"]\n : [];\n if (globalMiddleware.length === 0) return originalList;\n\n const alreadyIncluded = new Set(originalList);\n const missingGlobal = globalMiddleware.filter(\n (middleware) => !alreadyIncluded.has(middleware),\n );\n return missingGlobal.length\n ? [...missingGlobal, ...originalList]\n : originalList;\n };\n\n h3[\"~getMiddleware\"] = wrappedGetMiddleware;\n h3[MIDDLEWARE_DISPATCHER_PATCHED_KEY] = wrappedGetMiddleware;\n}\n\n/**\n * Wait for the framework's default-plugin bootstrap to complete.\n *\n * Called by user-facing plugin factories (`createAgentChatPlugin`, etc.) at\n * the top of their plugin function, so that by the time the function returns\n * — and Nitro starts accepting requests — all default plugins have finished\n * registering their middleware.\n *\n * No-op when called from inside the bootstrap itself (avoids deadlock when a\n * default plugin happens to be running as part of bootstrap).\n */\nexport async function awaitBootstrap(nitroApp: any): Promise<void> {\n if (!nitroApp || IN_BOOTSTRAP.has(nitroApp)) return;\n // Trigger bootstrap if it hasn't been already (idempotent — getH3App\n // creates the shim and kicks off bootstrap on first call).\n getH3App(nitroApp);\n const promise = nitroApp[BOOTSTRAP_PROMISE_KEY];\n if (promise) await promise;\n}\n\n/**\n * Wait until framework routes are safe to dispatch.\n *\n * Request-time gates must wait for both phases:\n * 1. default-plugin bootstrap, which discovers and starts missing plugins\n * 2. async plugin init promises, which register routes such as A2A cards\n */\nasync function awaitFrameworkRoutesReadyForRequest(\n nitroApp: any,\n reqPath: string,\n): Promise<void> {\n if (!nitroApp) return;\n const bootstrapPromise = nitroApp[BOOTSTRAP_PROMISE_KEY];\n if (bootstrapPromise) await bootstrapPromise;\n await awaitPluginsReady(nitroApp, reqPath);\n}\n\n/**\n * Track an async plugin's initialization promise. Nitro v3 calls plugins\n * synchronously and doesn't await async return values, so routes registered\n * inside an async plugin may not be ready when the first request arrives.\n *\n * Call this from the TOP of any async plugin so that the readiness gate\n * (installed by getH3App) can hold /_agent-native requests until the plugin\n * finishes mounting its routes.\n */\nexport function trackPluginInit(\n nitroApp: any,\n promise: Promise<void>,\n options: { paths?: string[] } = {},\n): void {\n if (!nitroApp) return;\n // Ensure the readiness gate exists even when the tracked plugin is the first\n // framework code to run in a serverless isolate. Otherwise an immediate\n // first request can fall through before the plugin registers its routes.\n getH3App(nitroApp);\n // Attach a no-op catch so the promise doesn't surface as an unhandled\n // rejection when Nitro v3 drops the async return value. The actual error\n // is still observable when awaitPluginsReady() re-awaits the promise.\n const safe = promise.catch((err) => {\n console.error(\n \"[agent-native] Plugin init failed:\",\n (err as Error).message || err,\n );\n });\n const entry: PluginReadyEntry = {\n promise: safe,\n paths: options.paths?.filter(Boolean),\n };\n const existing = nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined;\n if (existing) {\n existing.push(entry);\n } else {\n nitroApp[PLUGIN_READY_KEY] = [entry];\n }\n installPluginReadyPlaceholders(nitroApp, entry.paths);\n}\n\nfunction installPluginReadyPlaceholders(\n nitroApp: any,\n paths: string[] | undefined,\n): void {\n if (!paths?.length) return;\n const existing = nitroApp[PLUGIN_READY_PLACEHOLDERS_KEY] as\n | Set<string>\n | undefined;\n const installed = existing ?? new Set<string>();\n nitroApp[PLUGIN_READY_PLACEHOLDERS_KEY] = installed;\n\n for (const path of paths) {\n if (!path || installed.has(path)) continue;\n installed.add(path);\n registerMiddleware(\n nitroApp,\n path,\n (async (event: H3Event) => {\n const eventAny = event as any;\n await awaitFrameworkRoutesReadyForRequest(\n nitroApp,\n eventAny.context?._mountedPathname ?? event.url?.pathname ?? path,\n );\n return undefined;\n }) as EventHandler,\n {\n prepend: true,\n },\n );\n }\n}\n\n/**\n * Await all tracked plugin initializations. Called by the readiness gate\n * middleware before dispatching framework routes.\n */\nexport async function awaitPluginsReady(\n nitroApp: any,\n reqPath?: string,\n): Promise<void> {\n const entries = nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined;\n if (!entries?.length) return;\n\n const relevant = reqPath\n ? entries.filter((entry) =>\n entry.paths?.length\n ? entry.paths.some((path) => resolveMountMatch(reqPath, path))\n : true,\n )\n : entries;\n\n if (relevant.length) {\n await Promise.all(relevant.map((entry) => entry.promise));\n const completed = new Set(relevant);\n const latest =\n (nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined) ?? [];\n nitroApp[PLUGIN_READY_KEY] = latest.filter(\n (entry) => !completed.has(entry),\n );\n }\n}\n\n/**\n * Register a path-prefix middleware on Nitro's h3 instance.\n *\n * The middleware:\n * - Returns `next()` (continues) if the request path doesn't match.\n * - Otherwise dispatches to the handler. If the handler returns a value,\n * it short-circuits the request. If it returns undefined, next() runs.\n *\n * Path matching emulates h3 v1's `app.use(path, ...)` behavior:\n * - Exact-match prefix: `/foo` matches `/foo`, `/foo/bar`, but not `/foobar`\n * - Empty path: middleware runs on every request\n */\nfunction registerMiddleware(\n nitroApp: any,\n path: string,\n handler: EventHandler,\n options: { prepend?: boolean } = {},\n) {\n const h3 = nitroApp.h3;\n if (!h3 || !Array.isArray(h3[\"~middleware\"])) {\n throw new Error(\n \"[agent-native] Cannot register route: nitroApp.h3 is not available. \" +\n \"Make sure you're calling getH3App() from inside a Nitro plugin.\",\n );\n }\n\n const middleware = async (event: H3Event, next: () => any) => {\n let originalPathname: string | undefined;\n let originalEventPath: string | undefined;\n let hadEventPath = false;\n const restoreOriginalPath = () => {\n if (originalPathname !== undefined) {\n try {\n event.url.pathname = originalPathname;\n } catch {\n // ignore\n }\n originalPathname = undefined;\n }\n if (hadEventPath) {\n try {\n (event as any).path = originalEventPath;\n } catch {\n // ignore\n }\n } else {\n try {\n delete (event as any).path;\n } catch {\n // ignore\n }\n }\n };\n if (path) {\n const reqPath = event.url?.pathname ?? \"\";\n const match = resolveMountMatch(reqPath, path);\n if (!match) {\n return next();\n }\n // Strip the mount prefix from event.url.pathname so handlers that\n // dispatch sub-routes can read `event.path` (or `event.url.pathname`)\n // and see the path RELATIVE to their mount point — matching h3 v1's\n // `app.use(path, handler)` semantics.\n const eventAny = event as any;\n hadEventPath = \"path\" in eventAny;\n originalEventPath = eventAny.path;\n try {\n originalPathname = event.url.pathname;\n // Save the full path in context so handlers that need the original URL\n // (e.g. Better Auth, which extracts its own basePath prefix) can\n // reconstruct a Request with the un-stripped URL.\n eventAny.context = eventAny.context ?? {};\n eventAny.context._mountedPathname = originalPathname;\n eventAny.context._mountPrefix = match.mountPath;\n event.url.pathname = match.strippedPath;\n eventAny.path = `${match.strippedPath}${event.url.search || \"\"}`;\n } catch {\n // event.url is read-only on some runtimes — fall through. Handlers\n // that don't depend on prefix stripping (most of them) still work.\n }\n }\n try {\n const result = await handler(event);\n if (result === undefined) {\n // Restore the original pathname BEFORE calling next() so downstream\n // middleware sees the full URL — not the stripped mount-relative path.\n // Matches h3 v2's own sub-app middleware pattern where the restore\n // happens inside the next() callback, not after it returns.\n restoreOriginalPath();\n return next();\n }\n return result;\n } catch (err) {\n // Log 500s to the server console so they're debuggable, and respond\n // with JSON instead of the default HTML error page so clients can\n // surface error messages. This only applies to routes mounted under\n // the framework prefix (or middleware mounted at `/`, for which we\n // still want visibility).\n const reqPath = originalPathname ?? event.url?.pathname ?? \"\";\n const e = err as any;\n const status =\n typeof e?.statusCode === \"number\"\n ? e.statusCode\n : typeof e?.status === \"number\"\n ? e.status\n : 500;\n console.error(\n `[agent-native] ${event.method ?? \"\"} ${reqPath} failed (${status}):`,\n e?.stack || e?.message || e,\n );\n // Forward 5xx to server-side Sentry — Nitro's own `error` hook may not\n // fire here because we convert the throw into a normal JSON response,\n // and a console.error alone is invisible in deployed environments.\n // 4xx are user-input errors (validation, auth) and aren't worth\n // alerting on. Lazy-loaded so the framework-request-handler module\n // doesn't pull @sentry/node into bundles that don't need it.\n if (status >= 500) {\n // Static `import` would create a cycle (sentry.ts imports auth.ts\n // which imports… eventually, framework-request-handler.ts).\n import(\"./sentry.js\")\n .then(({ captureRouteError, isServerSentryEnabled }) => {\n if (!isServerSentryEnabled()) return;\n captureRouteError(err, {\n route: reqPath,\n method: event.method,\n userAgent: (() => {\n try {\n return event.headers?.get(\"user-agent\") ?? undefined;\n } catch {\n return undefined;\n }\n })(),\n });\n })\n .catch(() => {\n // Sentry is observability — never let it break a response path.\n });\n }\n try {\n setResponseStatus(event, status);\n setResponseHeader(event, \"content-type\", \"application/json\");\n } catch {\n // Response already sent — best effort.\n }\n return {\n error: e?.message || \"Internal server error\",\n // Only surface the stack to clients when explicitly enabled.\n // `NODE_ENV !== \"production\"` was unsafe — preview deploys and\n // any host that forgets to set NODE_ENV=production leaked stack\n // traces (file paths, dependency versions, internal route\n // topology) to anonymous callers. Operators who want stacks in\n // dev set `AGENT_NATIVE_DEBUG_ERRORS=1` explicitly.\n ...(status >= 500 &&\n process.env.AGENT_NATIVE_DEBUG_ERRORS === \"1\" &&\n e?.stack\n ? { stack: e.stack }\n : {}),\n };\n } finally {\n // Restore the original pathname so downstream middleware sees the\n // full URL.\n restoreOriginalPath();\n }\n };\n\n if (options.prepend) {\n h3[\"~middleware\"].unshift(middleware);\n } else {\n h3[\"~middleware\"].push(middleware);\n }\n}\n\n/**\n * Auto-mount any default framework plugins that the template doesn't provide.\n *\n * Runs once per nitroApp on the first `getH3App()` call. Uses route-discovery\n * to find which default plugin stems are missing from `server/plugins/`, then\n * dynamically imports and mounts them. If a workspace core is present in the\n * ancestor chain, plugin slots the workspace core exports are mounted from\n * there instead of from @agent-native/core — this is the middle layer of the\n * three-layer inheritance model (app local > workspace core > framework).\n */\nasync function bootstrapDefaultPlugins(nitroApp: any): Promise<void> {\n IN_BOOTSTRAP.add(nitroApp);\n try {\n const cwd = process.cwd();\n const discoveredMissing = await getMissingDefaultPlugins(cwd);\n const provided = nitroApp[PROVIDED_PLUGIN_STEMS_KEY] as\n | Set<string>\n | undefined;\n const missing = provided\n ? discoveredMissing.filter((stem) => !provided.has(stem))\n : discoveredMissing;\n if (missing.length === 0) return;\n\n // Lazy import to avoid circular dependency at module load time\n const serverModule = await import(\"./index.js\");\n const terminalModule = await import(\"../terminal/terminal-plugin.js\");\n const integrationsModule = await import(\"../integrations/plugin.js\");\n const contextXrayModule = await import(\"../agent/context-xray/plugin.js\");\n const orgModule = await import(\"../org/plugin.js\");\n const onboardingModule = await import(\"../onboarding/plugin.js\");\n\n const frameworkImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {\n \"agent-chat\": (serverModule as any).defaultAgentChatPlugin,\n auth: (serverModule as any).defaultAuthPlugin,\n \"context-xray\": (contextXrayModule as any).defaultContextXrayPlugin,\n \"core-routes\": (serverModule as any).defaultCoreRoutesPlugin,\n integrations: (integrationsModule as any).defaultIntegrationsPlugin,\n onboarding: (onboardingModule as any).defaultOnboardingPlugin,\n org: (orgModule as any).defaultOrgPlugin,\n resources: (serverModule as any).defaultResourcesPlugin,\n sentry: (serverModule as any).defaultSentryPlugin,\n terminal: (terminalModule as any).defaultTerminalPlugin,\n };\n\n // Workspace core layer: if the app is inside an enterprise monorepo with\n // `agent-native.workspaceCore` configured, pull in any plugin slots the\n // workspace core exports from its server entry. We dynamically import the\n // workspace core package at runtime.\n let workspaceImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {};\n try {\n const { getWorkspaceCoreExports } =\n await import(\"../deploy/workspace-core.js\");\n const ws = await getWorkspaceCoreExports(cwd);\n if (ws && Object.keys(ws.plugins).length > 0) {\n try {\n const wsServerModule = await loadWorkspaceCoreServer(\n ws.packageName,\n ws.packageDir,\n );\n for (const [slot, exportName] of Object.entries(ws.plugins)) {\n if (!exportName) continue;\n const impl = (wsServerModule as any)[exportName];\n if (typeof impl === \"function\") {\n workspaceImpls[slot] = impl;\n }\n }\n if (process.env.DEBUG) {\n console.log(\n `[agent-native] Workspace core ${ws.packageName} provides plugin slots: ${Object.keys(workspaceImpls).join(\", \")}`,\n );\n }\n } catch (e) {\n const msg = (e as Error).message ?? \"\";\n // Common cause: workspace-core's package.json points \"./server\"\n // at a TS source file (the scaffold default), but Node can't\n // resolve relative `.js` imports inside it without a TS loader.\n // Tell the user to compile to dist/ rather than just dumping the\n // raw resolution error.\n const tsLoadHint = /\\.js' imported from .*\\.ts/.test(msg)\n ? \" — workspace-core src is TypeScript but isn't being compiled. \" +\n \"Run `pnpm --filter \" +\n ws.packageName +\n \" build` and point its `./server` export at dist/server/index.js.\"\n : \"\";\n console.warn(\n `[agent-native] Failed to load workspace core ${ws.packageName}/server: ${msg}${tsLoadHint}`,\n );\n }\n }\n } catch {\n // Workspace shared package isn't available (e.g. running on an edge\n // runtime without fs). Silently fall through to framework defaults.\n }\n\n if (process.env.DEBUG)\n console.log(\n `[agent-native] Auto-mounting ${missing.length} default plugin(s): ${missing.join(\", \")}`,\n );\n\n for (const stem of missing) {\n // Prefer workspace-core impl over framework default when both exist.\n const impl = workspaceImpls[stem] ?? frameworkImpls[stem];\n if (typeof impl === \"function\") {\n try {\n await impl(nitroApp);\n } catch (e) {\n console.warn(\n `[agent-native] Failed to auto-mount default plugin ${stem}:`,\n (e as Error).message,\n );\n captureError(e, {\n route: \"default-plugin-bootstrap\",\n tags: { phase: \"default-plugin-bootstrap\", plugin: stem },\n });\n }\n }\n }\n } finally {\n IN_BOOTSTRAP.delete(nitroApp);\n }\n}\n\n/**\n * Load a workspace-core's `/server` entry, transparently handling TS source.\n *\n * The scaffolded workspace-core template ships TS sources without a build\n * step (exports point at `./src/server/index.ts`), so plain `await import()`\n * blows up the moment Node hits a relative `.js` import inside (the standard\n * TS ESM convention) — and even before that, Node may resolve the package\n * relative to the framework's own location rather than the user's monorepo.\n *\n * We try Node's plain `import()` first (fastest path when the user has\n * compiled to dist/) and fall through to jiti on any error. jiti is anchored\n * to a real file inside the workspace-core's directory, so its module\n * resolution starts in the right node_modules tree (handles pnpm hoisting\n * and linked workspaces) AND handles TS source files + `.js` → `.ts` ESM\n * extension remapping.\n *\n * Edge runtimes without `fs` won't be able to load jiti at all; the outer\n * try/catch silently falls through to framework defaults in that case.\n */\nexport async function loadWorkspaceCoreServer(\n packageName: string,\n packageDir: string,\n): Promise<any> {\n let firstErr: unknown;\n try {\n return await import(/* @vite-ignore */ `${packageName}/server`);\n } catch (e) {\n firstErr = e;\n }\n\n try {\n const { createJiti } = await import(\"jiti\");\n const { pathToFileURL } = await import(\"node:url\");\n const path = await import(\"node:path\");\n // Anchor jiti to a real file inside the workspace-core package so its\n // module resolution starts in the right node_modules tree (handles pnpm\n // hoisting and linked workspaces).\n const anchor = pathToFileURL(\n path.join(packageDir, \"package.json\"),\n ).toString();\n const jiti = createJiti(anchor, { interopDefault: true });\n return await jiti.import(`${packageName}/server`);\n } catch (jitiErr) {\n // jiti also failed — rethrow the original Node error since it's usually\n // more informative about *why* the package wasn't resolvable.\n throw firstErr ?? jitiErr;\n }\n}\n\nexport { FRAMEWORK_PREFIX };\n"]}
|
|
1
|
+
{"version":3,"file":"framework-request-handler.js","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AAC1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,MAAM,YAAY,GAAG,IAAI,OAAO,EAAU,CAAC;AAC3C,MAAM,YAAY,GAAG,IAAI,OAAO,EAAU,CAAC;AAC3C,MAAM,gBAAgB,GAAG,gBAAgB,CAAC;AAC1C,MAAM,iBAAiB,GAAG,cAAc,CAAC;AACzC,MAAM,YAAY,GAAG,oBAAoB,CAAC;AAC1C,MAAM,qBAAqB,GAAG,8BAA8B,CAAC;AAC7D,MAAM,gBAAgB,GAAG,gCAAgC,CAAC;AAC1D,MAAM,6BAA6B,GAAG,qCAAqC,CAAC;AAC5E,MAAM,iBAAiB,GAAG,gCAAgC,CAAC;AAC3D,MAAM,yBAAyB,GAAG,iCAAiC,CAAC;AACpE,MAAM,iCAAiC,GACrC,yCAAyC,CAAC;AAO5C,SAAS,cAAc;IACrB,OAAO,wBAAwB,EAAE,CAAC;AACpC,CAAC;AAED,SAAS,iBAAiB,CAAC,OAAe,EAAE,MAAc;IACxD,OAAO,OAAO,KAAK,MAAM,IAAI,OAAO,CAAC,UAAU,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,wBAAwB,CAAC,IAAY;IAC5C,OAAO,CACL,iBAAiB,CAAC,IAAI,EAAE,gBAAgB,CAAC;QACzC,iBAAiB,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAC3C,CAAC;AACJ,CAAC;AAED,SAAS,iBAAiB,CACxB,OAAe,EACf,IAAY;IAEZ,IAAI,i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AAkB,CAAC,GAAG,WAAW,SAAS,CAAC,CAAC;IAClE,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,QAAQ,GAAG,CAAC,CAAC;IACf,CAAC;IAED,IAAI,CAAC;QACH,MAAM,EAAE,UAAU,EAAE,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC;QAC5C,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,CAAC;QACnD,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,CAAC;QACvC,sEAAsE;QACtE,wEAAwE;QACxE,mCAAmC;QACnC,MAAM,MAAM,GAAG,aAAa,CAC1B,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,cAAc,CAAC,CACtC,CAAC,QAAQ,EAAE,CAAC;QACb,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1D,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,WAAW,SAAS,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,OAAO,EAAE,CAAC;QACjB,wEAAwE;QACxE,8DAA8D;QAC9D,MAAM,QAAQ,IAAI,OAAO,CAAC;IAC5B,CAAC;AACH,CAAC;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC","sourcesContent":["/**\n * Framework request handler — registers framework routes on Nitro's h3 instance.\n *\n * Nitro 3 exposes its h3 app as `nitroApp.h3`. We register framework routes\n * directly on it as middleware (`nitroApp.h3[\"~middleware\"]`), giving each\n * plugin a path-prefix-matched handler that runs before any file-based route.\n *\n * Plugins call `getH3App(nitroApp).use(path, handler)` exactly like h3 v1's\n * `app.use()` — the wrapper translates that into v2 middleware registration.\n *\n * Default plugins that the template doesn't provide are auto-mounted on the\n * first call to `getH3App()` per nitroApp instance.\n */\nimport type { EventHandler, H3Event } from \"h3\";\nimport { setResponseHeader, setResponseStatus } from \"h3\";\nimport { getMissingDefaultPlugins } from \"../deploy/route-discovery.js\";\nimport { captureError } from \"./capture-error.js\";\nimport { getConfiguredAppBasePath } from \"./app-base-path.js\";\n\nconst BOOTSTRAPPED = new WeakSet<object>();\nconst IN_BOOTSTRAP = new WeakSet<object>();\nconst FRAMEWORK_PREFIX = \"/_agent-native\";\nconst WELL_KNOWN_PREFIX = \"/.well-known\";\nconst APP_SHIM_KEY = \"_agentNativeH3Shim\";\nconst BOOTSTRAP_PROMISE_KEY = \"_agentNativeBootstrapPromise\";\nconst PLUGIN_READY_KEY = \"_agentNativePluginReadyPromise\";\nconst PLUGIN_READY_PLACEHOLDERS_KEY = \"_agentNativePluginReadyPlaceholders\";\nconst PLUGIN_FAILED_KEY = \"_agentNativePluginInitFailures\";\nconst PROVIDED_PLUGIN_STEMS_KEY = \"_agentNativeProvidedPluginStems\";\nconst MIDDLEWARE_DISPATCHER_PATCHED_KEY =\n \"_agentNativeMiddlewareDispatcherPatched\";\n\ninterface PluginReadyEntry {\n promise: Promise<void>;\n paths?: string[];\n}\n\nfunction getAppBasePath(): string {\n return getConfiguredAppBasePath();\n}\n\nfunction pathMatchesPrefix(reqPath: string, prefix: string): boolean {\n return reqPath === prefix || reqPath.startsWith(prefix + \"/\");\n}\n\nfunction supportsAppBasePathMount(path: string): boolean {\n return (\n pathMatchesPrefix(path, FRAMEWORK_PREFIX) ||\n pathMatchesPrefix(path, WELL_KNOWN_PREFIX)\n );\n}\n\nfunction resolveMountMatch(\n reqPath: string,\n path: string,\n): { mountPath: string; strippedPath: string } | null {\n if (pathMatchesPrefix(reqPath, path)) {\n return { mountPath: path, strippedPath: reqPath.slice(path.length) || \"/\" };\n }\n\n const appBasePath = getAppBasePath();\n if (!appBasePath || !supportsAppBasePathMount(path)) return null;\n\n const prefixedPath = `${appBasePath}${path}`;\n if (!pathMatchesPrefix(reqPath, prefixedPath)) return null;\n return {\n mountPath: prefixedPath,\n strippedPath: reqPath.slice(prefixedPath.length) || \"/\",\n };\n}\n\n/**\n * Wrapper around Nitro's h3 instance that exposes a v1-style `.use()` API\n * for registering path-prefix middleware.\n */\nexport interface H3AppShim {\n use(path: string, handler: EventHandler): void;\n use(handler: EventHandler): void;\n}\n\n/**\n * Mark a default plugin slot as supplied by the app/template before the\n * framework default bootstrap runs.\n *\n * Bundled serverless functions often don't have the original\n * `server/plugins/*.ts` tree on disk at runtime, so filesystem route discovery\n * can falsely conclude a template plugin is missing. Explicit plugin factories\n * call this synchronously before awaiting bootstrap so the framework does not\n * auto-mount a generic default over the app's custom implementation.\n */\nexport function markDefaultPluginProvided(nitroApp: any, stem: string): void {\n if (!nitroApp || !stem) return;\n const existing = nitroApp[PROVIDED_PLUGIN_STEMS_KEY] as\n | Set<string>\n | undefined;\n const provided = existing ?? new Set<string>();\n provided.add(stem);\n nitroApp[PROVIDED_PLUGIN_STEMS_KEY] = provided;\n}\n\n/**\n * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this\n * to register routes via `.use(path, handler)`.\n *\n * On the first call per nitroApp, we kick off auto-mounting any missing\n * default plugins. User-facing plugin factories (createAgentChatPlugin,\n * createAuthPlugin, etc.) await this bootstrap via `awaitBootstrap()` so the\n * default plugins finish registering middleware before requests arrive.\n */\nexport function getH3App(nitroApp: any): H3AppShim {\n if (!nitroApp) throw new Error(\"getH3App: nitroApp is required\");\n ensureGlobalMiddlewareDispatch(nitroApp);\n\n // Reuse the cached shim if we've wrapped this nitroApp before\n const cached = nitroApp[APP_SHIM_KEY] as H3AppShim | undefined;\n if (cached) return cached;\n\n const shim: H3AppShim = {\n use(arg1: string | EventHandler, arg2?: EventHandler) {\n const path = typeof arg1 === \"string\" ? arg1 : \"\";\n const handler = (typeof arg1 === \"string\" ? arg2 : arg1) as EventHandler;\n if (typeof handler !== \"function\") {\n throw new Error(\"getH3App.use: handler must be a function\");\n }\n registerMiddleware(nitroApp, path, handler);\n },\n };\n\n nitroApp[APP_SHIM_KEY] = shim;\n\n if (!BOOTSTRAPPED.has(nitroApp)) {\n BOOTSTRAPPED.add(nitroApp);\n nitroApp[BOOTSTRAP_PROMISE_KEY] = bootstrapDefaultPlugins(nitroApp).catch(\n (err) => {\n console.warn(\n \"[agent-native] Failed to auto-mount default plugins:\",\n (err as Error).message,\n );\n captureError(err, {\n route: \"default-plugin-bootstrap\",\n tags: { phase: \"default-plugin-bootstrap\" },\n });\n },\n );\n\n // Readiness gate: Nitro v3 doesn't await async plugins, so routes\n // registered inside an async plugin may not exist when the first\n // request arrives. These middleware entries hold framework routes\n // until default-plugin bootstrap and tracked plugin inits complete.\n const readinessGate = (async (event: H3Event) => {\n const eventAny = event as any;\n await awaitFrameworkRoutesReadyForRequest(\n nitroApp,\n eventAny.context?._mountedPathname ?? event.url?.pathname ?? \"\",\n );\n // Fall through — the actual route handler runs next.\n return undefined;\n }) as EventHandler;\n registerMiddleware(nitroApp, FRAMEWORK_PREFIX, readinessGate, {\n prepend: true,\n });\n registerMiddleware(nitroApp, WELL_KNOWN_PREFIX, readinessGate, {\n prepend: true,\n });\n }\n\n return shim;\n}\n\n/**\n * Nitro 3 production builds generate a route dispatcher by overriding h3's\n * internal `~getMiddleware()` hook. Some generated dispatchers return only\n * route-rule middleware and skip the global `h3[\"~middleware\"]` array that\n * `getH3App().use()` appends to. Wrap the dispatcher once so framework routes\n * registered at runtime are still part of request dispatch.\n */\nfunction ensureGlobalMiddlewareDispatch(nitroApp: any): void {\n const h3 = nitroApp?.h3;\n if (!h3) return;\n const current = h3[\"~getMiddleware\"];\n if (h3[MIDDLEWARE_DISPATCHER_PATCHED_KEY] === current) return;\n\n const original = typeof current === \"function\" ? current.bind(h3) : undefined;\n\n const wrappedGetMiddleware = (event: H3Event, route: unknown) => {\n const originalResult = original ? original(event, route) : [];\n const originalList = Array.isArray(originalResult)\n ? originalResult\n : originalResult\n ? [originalResult]\n : [];\n const globalMiddleware = Array.isArray(h3[\"~middleware\"])\n ? h3[\"~middleware\"]\n : [];\n if (globalMiddleware.length === 0) return originalList;\n\n const alreadyIncluded = new Set(originalList);\n const missingGlobal = globalMiddleware.filter(\n (middleware) => !alreadyIncluded.has(middleware),\n );\n return missingGlobal.length\n ? [...missingGlobal, ...originalList]\n : originalList;\n };\n\n h3[\"~getMiddleware\"] = wrappedGetMiddleware;\n h3[MIDDLEWARE_DISPATCHER_PATCHED_KEY] = wrappedGetMiddleware;\n}\n\n/**\n * Wait for the framework's default-plugin bootstrap to complete.\n *\n * Called by user-facing plugin factories (`createAgentChatPlugin`, etc.) at\n * the top of their plugin function, so that by the time the function returns\n * — and Nitro starts accepting requests — all default plugins have finished\n * registering their middleware.\n *\n * No-op when called from inside the bootstrap itself (avoids deadlock when a\n * default plugin happens to be running as part of bootstrap).\n */\nexport async function awaitBootstrap(nitroApp: any): Promise<void> {\n if (!nitroApp || IN_BOOTSTRAP.has(nitroApp)) return;\n // Trigger bootstrap if it hasn't been already (idempotent — getH3App\n // creates the shim and kicks off bootstrap on first call).\n getH3App(nitroApp);\n const promise = nitroApp[BOOTSTRAP_PROMISE_KEY];\n if (promise) await promise;\n}\n\n/**\n * Wait until framework routes are safe to dispatch.\n *\n * Request-time gates must wait for both phases:\n * 1. default-plugin bootstrap, which discovers and starts missing plugins\n * 2. async plugin init promises, which register routes such as A2A cards\n */\nasync function awaitFrameworkRoutesReadyForRequest(\n nitroApp: any,\n reqPath: string,\n): Promise<void> {\n if (!nitroApp) return;\n const bootstrapPromise = nitroApp[BOOTSTRAP_PROMISE_KEY];\n if (bootstrapPromise) await bootstrapPromise;\n await awaitPluginsReady(nitroApp, reqPath);\n}\n\n/**\n * Track an async plugin's initialization promise. Nitro v3 calls plugins\n * synchronously and doesn't await async return values, so routes registered\n * inside an async plugin may not be ready when the first request arrives.\n *\n * Call this from the TOP of any async plugin so that the readiness gate\n * (installed by getH3App) can hold /_agent-native requests until the plugin\n * finishes mounting its routes.\n */\nexport function trackPluginInit(\n nitroApp: any,\n promise: Promise<void>,\n options: { paths?: string[] } = {},\n): void {\n if (!nitroApp) return;\n // Ensure the readiness gate exists even when the tracked plugin is the first\n // framework code to run in a serverless isolate. Otherwise an immediate\n // first request can fall through before the plugin registers its routes.\n getH3App(nitroApp);\n // Attach a no-op catch so the promise doesn't surface as an unhandled\n // rejection when Nitro v3 drops the async return value. The actual error\n // is still observable when awaitPluginsReady() re-awaits the promise.\n const safe = promise.catch((err) => {\n console.error(\n \"[agent-native] Plugin init failed:\",\n (err as Error).message || err,\n );\n // Record the failure so the readiness gate can return a retryable 503 for\n // this plugin's routes instead of letting them fall through to a bare\n // \"Cannot find any route matching\" 404. That bare 404 is what kept biting\n // external MCP clients (pi/codex/claude) and the connect flow on cold /\n // propagating instances whose async init rejected (e.g. DB not yet\n // reachable): the route never registered, so the placeholder released into\n // a 404 the client couldn't recover from. A 503 is at least retryable.\n const failures = (nitroApp[PLUGIN_FAILED_KEY] ??= new Map<\n string,\n string\n >());\n const msg = (err as Error)?.message || String(err);\n for (const p of options.paths?.filter(Boolean) ?? []) failures.set(p, msg);\n });\n const entry: PluginReadyEntry = {\n promise: safe,\n paths: options.paths?.filter(Boolean),\n };\n const existing = nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined;\n if (existing) {\n existing.push(entry);\n } else {\n nitroApp[PLUGIN_READY_KEY] = [entry];\n }\n installPluginReadyPlaceholders(nitroApp, entry.paths);\n}\n\nfunction installPluginReadyPlaceholders(\n nitroApp: any,\n paths: string[] | undefined,\n): void {\n if (!paths?.length) return;\n const existing = nitroApp[PLUGIN_READY_PLACEHOLDERS_KEY] as\n | Set<string>\n | undefined;\n const installed = existing ?? new Set<string>();\n nitroApp[PLUGIN_READY_PLACEHOLDERS_KEY] = installed;\n\n for (const path of paths) {\n if (!path || installed.has(path)) continue;\n installed.add(path);\n registerMiddleware(\n nitroApp,\n path,\n (async (event: H3Event) => {\n const eventAny = event as any;\n const reqPath =\n eventAny.context?._mountedPathname ?? event.url?.pathname ?? path;\n await awaitFrameworkRoutesReadyForRequest(nitroApp, reqPath);\n // If this plugin's async init failed, its real route was never\n // registered. Return a retryable 503 instead of releasing into a bare\n // 404 (external MCP clients can't recover from a 404; a 503 is at least\n // a \"try again\" the client / next instance can act on).\n const failures = nitroApp[PLUGIN_FAILED_KEY] as\n | Map<string, string>\n | undefined;\n if (failures?.size) {\n for (const [failedPath, msg] of failures) {\n if (resolveMountMatch(reqPath, failedPath)) {\n setResponseStatus(event, 503);\n setResponseHeader(event, \"retry-after\", \"5\");\n return {\n error: `agent-native route is initializing or unavailable: ${msg}`,\n };\n }\n }\n }\n return undefined;\n }) as EventHandler,\n {\n prepend: true,\n },\n );\n }\n}\n\n/**\n * Await all tracked plugin initializations. Called by the readiness gate\n * middleware before dispatching framework routes.\n */\nexport async function awaitPluginsReady(\n nitroApp: any,\n reqPath?: string,\n): Promise<void> {\n const entries = nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined;\n if (!entries?.length) return;\n\n const relevant = reqPath\n ? entries.filter((entry) =>\n entry.paths?.length\n ? entry.paths.some((path) => resolveMountMatch(reqPath, path))\n : true,\n )\n : entries;\n\n if (relevant.length) {\n await Promise.all(relevant.map((entry) => entry.promise));\n const completed = new Set(relevant);\n const latest =\n (nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined) ?? [];\n nitroApp[PLUGIN_READY_KEY] = latest.filter(\n (entry) => !completed.has(entry),\n );\n }\n}\n\n/**\n * Register a path-prefix middleware on Nitro's h3 instance.\n *\n * The middleware:\n * - Returns `next()` (continues) if the request path doesn't match.\n * - Otherwise dispatches to the handler. If the handler returns a value,\n * it short-circuits the request. If it returns undefined, next() runs.\n *\n * Path matching emulates h3 v1's `app.use(path, ...)` behavior:\n * - Exact-match prefix: `/foo` matches `/foo`, `/foo/bar`, but not `/foobar`\n * - Empty path: middleware runs on every request\n */\nfunction registerMiddleware(\n nitroApp: any,\n path: string,\n handler: EventHandler,\n options: { prepend?: boolean } = {},\n) {\n const h3 = nitroApp.h3;\n if (!h3 || !Array.isArray(h3[\"~middleware\"])) {\n throw new Error(\n \"[agent-native] Cannot register route: nitroApp.h3 is not available. \" +\n \"Make sure you're calling getH3App() from inside a Nitro plugin.\",\n );\n }\n\n const middleware = async (event: H3Event, next: () => any) => {\n let originalPathname: string | undefined;\n let originalEventPath: string | undefined;\n let hadEventPath = false;\n const restoreOriginalPath = () => {\n if (originalPathname !== undefined) {\n try {\n event.url.pathname = originalPathname;\n } catch {\n // ignore\n }\n originalPathname = undefined;\n }\n if (hadEventPath) {\n try {\n (event as any).path = originalEventPath;\n } catch {\n // ignore\n }\n } else {\n try {\n delete (event as any).path;\n } catch {\n // ignore\n }\n }\n };\n if (path) {\n const reqPath = event.url?.pathname ?? \"\";\n const match = resolveMountMatch(reqPath, path);\n if (!match) {\n return next();\n }\n // Strip the mount prefix from event.url.pathname so handlers that\n // dispatch sub-routes can read `event.path` (or `event.url.pathname`)\n // and see the path RELATIVE to their mount point — matching h3 v1's\n // `app.use(path, handler)` semantics.\n const eventAny = event as any;\n hadEventPath = \"path\" in eventAny;\n originalEventPath = eventAny.path;\n try {\n originalPathname = event.url.pathname;\n // Save the full path in context so handlers that need the original URL\n // (e.g. Better Auth, which extracts its own basePath prefix) can\n // reconstruct a Request with the un-stripped URL.\n eventAny.context = eventAny.context ?? {};\n eventAny.context._mountedPathname = originalPathname;\n eventAny.context._mountPrefix = match.mountPath;\n event.url.pathname = match.strippedPath;\n eventAny.path = `${match.strippedPath}${event.url.search || \"\"}`;\n } catch {\n // event.url is read-only on some runtimes — fall through. Handlers\n // that don't depend on prefix stripping (most of them) still work.\n }\n }\n try {\n const result = await handler(event);\n if (result === undefined) {\n // Restore the original pathname BEFORE calling next() so downstream\n // middleware sees the full URL — not the stripped mount-relative path.\n // Matches h3 v2's own sub-app middleware pattern where the restore\n // happens inside the next() callback, not after it returns.\n restoreOriginalPath();\n return next();\n }\n return result;\n } catch (err) {\n // Log 500s to the server console so they're debuggable, and respond\n // with JSON instead of the default HTML error page so clients can\n // surface error messages. This only applies to routes mounted under\n // the framework prefix (or middleware mounted at `/`, for which we\n // still want visibility).\n const reqPath = originalPathname ?? event.url?.pathname ?? \"\";\n const e = err as any;\n const status =\n typeof e?.statusCode === \"number\"\n ? e.statusCode\n : typeof e?.status === \"number\"\n ? e.status\n : 500;\n console.error(\n `[agent-native] ${event.method ?? \"\"} ${reqPath} failed (${status}):`,\n e?.stack || e?.message || e,\n );\n // Forward 5xx to server-side Sentry — Nitro's own `error` hook may not\n // fire here because we convert the throw into a normal JSON response,\n // and a console.error alone is invisible in deployed environments.\n // 4xx are user-input errors (validation, auth) and aren't worth\n // alerting on. Lazy-loaded so the framework-request-handler module\n // doesn't pull @sentry/node into bundles that don't need it.\n if (status >= 500) {\n // Static `import` would create a cycle (sentry.ts imports auth.ts\n // which imports… eventually, framework-request-handler.ts).\n import(\"./sentry.js\")\n .then(({ captureRouteError, isServerSentryEnabled }) => {\n if (!isServerSentryEnabled()) return;\n captureRouteError(err, {\n route: reqPath,\n method: event.method,\n userAgent: (() => {\n try {\n return event.headers?.get(\"user-agent\") ?? undefined;\n } catch {\n return undefined;\n }\n })(),\n });\n })\n .catch(() => {\n // Sentry is observability — never let it break a response path.\n });\n }\n try {\n setResponseStatus(event, status);\n setResponseHeader(event, \"content-type\", \"application/json\");\n } catch {\n // Response already sent — best effort.\n }\n return {\n error: e?.message || \"Internal server error\",\n // Only surface the stack to clients when explicitly enabled.\n // `NODE_ENV !== \"production\"` was unsafe — preview deploys and\n // any host that forgets to set NODE_ENV=production leaked stack\n // traces (file paths, dependency versions, internal route\n // topology) to anonymous callers. Operators who want stacks in\n // dev set `AGENT_NATIVE_DEBUG_ERRORS=1` explicitly.\n ...(status >= 500 &&\n process.env.AGENT_NATIVE_DEBUG_ERRORS === \"1\" &&\n e?.stack\n ? { stack: e.stack }\n : {}),\n };\n } finally {\n // Restore the original pathname so downstream middleware sees the\n // full URL.\n restoreOriginalPath();\n }\n };\n\n if (options.prepend) {\n h3[\"~middleware\"].unshift(middleware);\n } else {\n h3[\"~middleware\"].push(middleware);\n }\n}\n\n/**\n * Auto-mount any default framework plugins that the template doesn't provide.\n *\n * Runs once per nitroApp on the first `getH3App()` call. Uses route-discovery\n * to find which default plugin stems are missing from `server/plugins/`, then\n * dynamically imports and mounts them. If a workspace core is present in the\n * ancestor chain, plugin slots the workspace core exports are mounted from\n * there instead of from @agent-native/core — this is the middle layer of the\n * three-layer inheritance model (app local > workspace core > framework).\n */\nasync function bootstrapDefaultPlugins(nitroApp: any): Promise<void> {\n IN_BOOTSTRAP.add(nitroApp);\n try {\n const cwd = process.cwd();\n const discoveredMissing = await getMissingDefaultPlugins(cwd);\n const provided = nitroApp[PROVIDED_PLUGIN_STEMS_KEY] as\n | Set<string>\n | undefined;\n const missing = provided\n ? discoveredMissing.filter((stem) => !provided.has(stem))\n : discoveredMissing;\n if (missing.length === 0) return;\n\n // Lazy import to avoid circular dependency at module load time\n const serverModule = await import(\"./index.js\");\n const terminalModule = await import(\"../terminal/terminal-plugin.js\");\n const integrationsModule = await import(\"../integrations/plugin.js\");\n const contextXrayModule = await import(\"../agent/context-xray/plugin.js\");\n const observationalMemoryModule =\n await import(\"../agent/observational-memory/plugin.js\");\n const orgModule = await import(\"../org/plugin.js\");\n const onboardingModule = await import(\"../onboarding/plugin.js\");\n\n const frameworkImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {\n \"agent-chat\": (serverModule as any).defaultAgentChatPlugin,\n auth: (serverModule as any).defaultAuthPlugin,\n \"context-xray\": (contextXrayModule as any).defaultContextXrayPlugin,\n \"core-routes\": (serverModule as any).defaultCoreRoutesPlugin,\n integrations: (integrationsModule as any).defaultIntegrationsPlugin,\n \"observational-memory\": (observationalMemoryModule as any)\n .defaultObservationalMemoryPlugin,\n onboarding: (onboardingModule as any).defaultOnboardingPlugin,\n org: (orgModule as any).defaultOrgPlugin,\n resources: (serverModule as any).defaultResourcesPlugin,\n sentry: (serverModule as any).defaultSentryPlugin,\n terminal: (terminalModule as any).defaultTerminalPlugin,\n };\n\n // Workspace core layer: if the app is inside an enterprise monorepo with\n // `agent-native.workspaceCore` configured, pull in any plugin slots the\n // workspace core exports from its server entry. We dynamically import the\n // workspace core package at runtime.\n let workspaceImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {};\n try {\n const { getWorkspaceCoreExports } =\n await import(\"../deploy/workspace-core.js\");\n const ws = await getWorkspaceCoreExports(cwd);\n if (ws && Object.keys(ws.plugins).length > 0) {\n try {\n const wsServerModule = await loadWorkspaceCoreServer(\n ws.packageName,\n ws.packageDir,\n );\n for (const [slot, exportName] of Object.entries(ws.plugins)) {\n if (!exportName) continue;\n const impl = (wsServerModule as any)[exportName];\n if (typeof impl === \"function\") {\n workspaceImpls[slot] = impl;\n }\n }\n if (process.env.DEBUG) {\n console.log(\n `[agent-native] Workspace core ${ws.packageName} provides plugin slots: ${Object.keys(workspaceImpls).join(\", \")}`,\n );\n }\n } catch (e) {\n const msg = (e as Error).message ?? \"\";\n // Common cause: workspace-core's package.json points \"./server\"\n // at a TS source file (the scaffold default), but Node can't\n // resolve relative `.js` imports inside it without a TS loader.\n // Tell the user to compile to dist/ rather than just dumping the\n // raw resolution error.\n const tsLoadHint = /\\.js' imported from .*\\.ts/.test(msg)\n ? \" — workspace-core src is TypeScript but isn't being compiled. \" +\n \"Run `pnpm --filter \" +\n ws.packageName +\n \" build` and point its `./server` export at dist/server/index.js.\"\n : \"\";\n console.warn(\n `[agent-native] Failed to load workspace core ${ws.packageName}/server: ${msg}${tsLoadHint}`,\n );\n }\n }\n } catch {\n // Workspace shared package isn't available (e.g. running on an edge\n // runtime without fs). Silently fall through to framework defaults.\n }\n\n if (process.env.DEBUG)\n console.log(\n `[agent-native] Auto-mounting ${missing.length} default plugin(s): ${missing.join(\", \")}`,\n );\n\n for (const stem of missing) {\n // Prefer workspace-core impl over framework default when both exist.\n const impl = workspaceImpls[stem] ?? frameworkImpls[stem];\n if (typeof impl === \"function\") {\n try {\n await impl(nitroApp);\n } catch (e) {\n console.warn(\n `[agent-native] Failed to auto-mount default plugin ${stem}:`,\n (e as Error).message,\n );\n captureError(e, {\n route: \"default-plugin-bootstrap\",\n tags: { phase: \"default-plugin-bootstrap\", plugin: stem },\n });\n }\n }\n }\n } finally {\n IN_BOOTSTRAP.delete(nitroApp);\n }\n}\n\n/**\n * Load a workspace-core's `/server` entry, transparently handling TS source.\n *\n * The scaffolded workspace-core template ships TS sources without a build\n * step (exports point at `./src/server/index.ts`), so plain `await import()`\n * blows up the moment Node hits a relative `.js` import inside (the standard\n * TS ESM convention) — and even before that, Node may resolve the package\n * relative to the framework's own location rather than the user's monorepo.\n *\n * We try Node's plain `import()` first (fastest path when the user has\n * compiled to dist/) and fall through to jiti on any error. jiti is anchored\n * to a real file inside the workspace-core's directory, so its module\n * resolution starts in the right node_modules tree (handles pnpm hoisting\n * and linked workspaces) AND handles TS source files + `.js` → `.ts` ESM\n * extension remapping.\n *\n * Edge runtimes without `fs` won't be able to load jiti at all; the outer\n * try/catch silently falls through to framework defaults in that case.\n */\nexport async function loadWorkspaceCoreServer(\n packageName: string,\n packageDir: string,\n): Promise<any> {\n let firstErr: unknown;\n try {\n return await import(/* @vite-ignore */ `${packageName}/server`);\n } catch (e) {\n firstErr = e;\n }\n\n try {\n const { createJiti } = await import(\"jiti\");\n const { pathToFileURL } = await import(\"node:url\");\n const path = await import(\"node:path\");\n // Anchor jiti to a real file inside the workspace-core package so its\n // module resolution starts in the right node_modules tree (handles pnpm\n // hoisting and linked workspaces).\n const anchor = pathToFileURL(\n path.join(packageDir, \"package.json\"),\n ).toString();\n const jiti = createJiti(anchor, { interopDefault: true });\n return await jiti.import(`${packageName}/server`);\n } catch (jitiErr) {\n // jiti also failed — rethrow the original Node error since it's usually\n // more informative about *why* the package wasn't resolvable.\n throw firstErr ?? jitiErr;\n }\n}\n\nexport { FRAMEWORK_PREFIX };\n"]}
|