@agent-native/core 0.12.22 → 0.12.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/agent/engine/ai-sdk-engine.d.ts +2 -0
  2. package/dist/agent/engine/ai-sdk-engine.d.ts.map +1 -1
  3. package/dist/agent/engine/ai-sdk-engine.js +4 -2
  4. package/dist/agent/engine/ai-sdk-engine.js.map +1 -1
  5. package/dist/agent/engine/anthropic-engine.d.ts.map +1 -1
  6. package/dist/agent/engine/anthropic-engine.js +2 -1
  7. package/dist/agent/engine/anthropic-engine.js.map +1 -1
  8. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  9. package/dist/agent/engine/builder-engine.js +117 -8
  10. package/dist/agent/engine/builder-engine.js.map +1 -1
  11. package/dist/agent/engine/registry.d.ts.map +1 -1
  12. package/dist/agent/engine/registry.js +24 -13
  13. package/dist/agent/engine/registry.js.map +1 -1
  14. package/dist/agent/production-agent.d.ts +1 -0
  15. package/dist/agent/production-agent.d.ts.map +1 -1
  16. package/dist/agent/production-agent.js +20 -10
  17. package/dist/agent/production-agent.js.map +1 -1
  18. package/dist/agent/thread-data-builder.d.ts +10 -0
  19. package/dist/agent/thread-data-builder.d.ts.map +1 -1
  20. package/dist/agent/thread-data-builder.js +80 -0
  21. package/dist/agent/thread-data-builder.js.map +1 -1
  22. package/dist/agent/types.d.ts +7 -0
  23. package/dist/agent/types.d.ts.map +1 -1
  24. package/dist/agent/types.js.map +1 -1
  25. package/dist/cli/create.d.ts.map +1 -1
  26. package/dist/cli/create.js +3 -3
  27. package/dist/cli/create.js.map +1 -1
  28. package/dist/client/AgentPanel.d.ts.map +1 -1
  29. package/dist/client/AgentPanel.js +10 -2
  30. package/dist/client/AgentPanel.js.map +1 -1
  31. package/dist/client/AssistantChat.d.ts.map +1 -1
  32. package/dist/client/AssistantChat.js +169 -15
  33. package/dist/client/AssistantChat.js.map +1 -1
  34. package/dist/client/ErrorBoundary.d.ts.map +1 -1
  35. package/dist/client/ErrorBoundary.js +3 -2
  36. package/dist/client/ErrorBoundary.js.map +1 -1
  37. package/dist/client/FeedbackButton.js +1 -1
  38. package/dist/client/FeedbackButton.js.map +1 -1
  39. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  40. package/dist/client/agent-chat-adapter.js +93 -45
  41. package/dist/client/agent-chat-adapter.js.map +1 -1
  42. package/dist/client/analytics.d.ts.map +1 -1
  43. package/dist/client/analytics.js +26 -0
  44. package/dist/client/analytics.js.map +1 -1
  45. package/dist/client/components/ui/tooltip.js +1 -1
  46. package/dist/client/components/ui/tooltip.js.map +1 -1
  47. package/dist/client/composer/PromptComposer.js +1 -1
  48. package/dist/client/composer/PromptComposer.js.map +1 -1
  49. package/dist/client/composer/TiptapComposer.d.ts +5 -0
  50. package/dist/client/composer/TiptapComposer.d.ts.map +1 -1
  51. package/dist/client/composer/TiptapComposer.js +12 -7
  52. package/dist/client/composer/TiptapComposer.js.map +1 -1
  53. package/dist/client/onboarding/OnboardingPanel.js +2 -1
  54. package/dist/client/onboarding/OnboardingPanel.js.map +1 -1
  55. package/dist/client/progress/RunsTray.d.ts.map +1 -1
  56. package/dist/client/progress/RunsTray.js +18 -3
  57. package/dist/client/progress/RunsTray.js.map +1 -1
  58. package/dist/client/resources/ResourceTree.d.ts.map +1 -1
  59. package/dist/client/resources/ResourceTree.js +5 -4
  60. package/dist/client/resources/ResourceTree.js.map +1 -1
  61. package/dist/client/resources/ResourcesPanel.js +1 -1
  62. package/dist/client/resources/ResourcesPanel.js.map +1 -1
  63. package/dist/client/settings/useBuilderStatus.d.ts.map +1 -1
  64. package/dist/client/settings/useBuilderStatus.js +5 -3
  65. package/dist/client/settings/useBuilderStatus.js.map +1 -1
  66. package/dist/client/sse-event-processor.d.ts.map +1 -1
  67. package/dist/client/sse-event-processor.js +3 -0
  68. package/dist/client/sse-event-processor.js.map +1 -1
  69. package/dist/collab/client.d.ts +9 -0
  70. package/dist/collab/client.d.ts.map +1 -1
  71. package/dist/collab/client.js +36 -10
  72. package/dist/collab/client.js.map +1 -1
  73. package/dist/extensions/html-shell.d.ts.map +1 -1
  74. package/dist/extensions/html-shell.js +12 -0
  75. package/dist/extensions/html-shell.js.map +1 -1
  76. package/dist/mcp-client/errors.d.ts +2 -0
  77. package/dist/mcp-client/errors.d.ts.map +1 -0
  78. package/dist/mcp-client/errors.js +47 -0
  79. package/dist/mcp-client/errors.js.map +1 -0
  80. package/dist/mcp-client/manager.d.ts.map +1 -1
  81. package/dist/mcp-client/manager.js +44 -15
  82. package/dist/mcp-client/manager.js.map +1 -1
  83. package/dist/mcp-client/routes.d.ts +1 -2
  84. package/dist/mcp-client/routes.d.ts.map +1 -1
  85. package/dist/mcp-client/routes.js +2 -27
  86. package/dist/mcp-client/routes.js.map +1 -1
  87. package/dist/onboarding/default-steps.js +1 -1
  88. package/dist/onboarding/default-steps.js.map +1 -1
  89. package/dist/progress/store.d.ts +2 -0
  90. package/dist/progress/store.d.ts.map +1 -1
  91. package/dist/progress/store.js +44 -0
  92. package/dist/progress/store.js.map +1 -1
  93. package/dist/server/action-routes.d.ts +2 -0
  94. package/dist/server/action-routes.d.ts.map +1 -1
  95. package/dist/server/action-routes.js +4 -1
  96. package/dist/server/action-routes.js.map +1 -1
  97. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  98. package/dist/server/agent-chat-plugin.js +27 -15
  99. package/dist/server/agent-chat-plugin.js.map +1 -1
  100. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  101. package/dist/server/core-routes-plugin.js +31 -9
  102. package/dist/server/core-routes-plugin.js.map +1 -1
  103. package/dist/server/credential-provider.d.ts +8 -0
  104. package/dist/server/credential-provider.d.ts.map +1 -1
  105. package/dist/server/credential-provider.js +29 -3
  106. package/dist/server/credential-provider.js.map +1 -1
  107. package/dist/server/index.d.ts +1 -1
  108. package/dist/server/index.d.ts.map +1 -1
  109. package/dist/server/index.js +1 -1
  110. package/dist/server/index.js.map +1 -1
  111. package/dist/server/request-context.d.ts +9 -0
  112. package/dist/server/request-context.d.ts.map +1 -1
  113. package/dist/server/request-context.js +13 -0
  114. package/dist/server/request-context.js.map +1 -1
  115. package/dist/terminal/terminal-plugin.d.ts.map +1 -1
  116. package/dist/terminal/terminal-plugin.js +4 -3
  117. package/dist/terminal/terminal-plugin.js.map +1 -1
  118. package/package.json +1 -1
@@ -46,6 +46,14 @@ export declare class FeatureNotConfiguredError extends Error {
46
46
  * Multi-tenant call sites must gate this explicitly before calling.
47
47
  */
48
48
  export declare function readDeployCredentialEnv(key: string): string | undefined;
49
+ /**
50
+ * Deployment-level credentials are safe as a runtime fallback only in local /
51
+ * single-tenant contexts. In hosted production with a shared database, every
52
+ * signed-in user needs their own user/org/workspace credential so one deploy
53
+ * key does not silently power another tenant's chat.
54
+ */
55
+ export declare function isDeployCredentialFallbackAllowed(): boolean;
56
+ export declare function canUseDeployCredentialFallbackForRequest(): boolean;
49
57
  type BuilderCredentialSource = "user" | "org" | "env";
50
58
  /**
51
59
  * Resolve a Builder credential for the current request. User/org credentials
@@ -1 +1 @@
1
- {"version":3,"file":"credential-provider.d.ts","sourceRoot":"","sources":["../../src/server/credential-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAIH;;;;;;;;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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AAeD;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAuDvE;AAOD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,IAAI,OAAO,CAE9C;AAED,yEAAyE;AACzE,wBAAgB,qBAAqB,IAAI,MAAM,CAO9C;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,IAAI,MAAM,CAKjD;AAED;;;GAGG;AACH,wBAAgB,gCAAgC,IAAI,MAAM,CAKzD;AAED,uEAAuE;AACvE,wBAAgB,oBAAoB,IAAI,MAAM,GAAG,IAAI,CAGpD"}
@@ -18,6 +18,7 @@
18
18
  * (e.g. additional Builder-hosted services) without rewrites.
19
19
  */
20
20
  import { getRequestUserEmail, getRequestOrgId } from "./request-context.js";
21
+ import { isLocalDatabase } from "../db/client.js";
21
22
  /**
22
23
  * Decide which `app_secrets` scope a Builder/credential write should use.
23
24
  *
@@ -53,6 +54,23 @@ export class FeatureNotConfiguredError extends Error {
53
54
  export function readDeployCredentialEnv(key) {
54
55
  return process.env[key] || undefined;
55
56
  }
57
+ /**
58
+ * Deployment-level credentials are safe as a runtime fallback only in local /
59
+ * single-tenant contexts. In hosted production with a shared database, every
60
+ * signed-in user needs their own user/org/workspace credential so one deploy
61
+ * key does not silently power another tenant's chat.
62
+ */
63
+ export function isDeployCredentialFallbackAllowed() {
64
+ if (process.env.NODE_ENV !== "production")
65
+ return true;
66
+ return isLocalDatabase();
67
+ }
68
+ export function canUseDeployCredentialFallbackForRequest() {
69
+ const email = getRequestUserEmail();
70
+ if (!email)
71
+ return true;
72
+ return isDeployCredentialFallbackAllowed();
73
+ }
56
74
  async function resolveScopedBuilderCredential(key) {
57
75
  const email = getRequestUserEmail();
58
76
  if (!email)
@@ -99,6 +117,8 @@ export async function resolveBuilderCredential(key) {
99
117
  const scoped = await resolveScopedBuilderCredential(key);
100
118
  if (scoped)
101
119
  return scoped.value;
120
+ if (!canUseDeployCredentialFallbackForRequest())
121
+ return null;
102
122
  return readDeployCredentialEnv(key) ?? null;
103
123
  }
104
124
  /**
@@ -138,7 +158,10 @@ export async function resolveBuilderCredentialSource() {
138
158
  const scoped = await resolveScopedBuilderCredential("BUILDER_PRIVATE_KEY");
139
159
  if (scoped)
140
160
  return scoped.source;
141
- return process.env.BUILDER_PRIVATE_KEY ? "env" : null;
161
+ return canUseDeployCredentialFallbackForRequest() &&
162
+ process.env.BUILDER_PRIVATE_KEY
163
+ ? "env"
164
+ : null;
142
165
  }
143
166
  /**
144
167
  * Resolve all per-user Builder credentials. Used by the status endpoint
@@ -286,8 +309,11 @@ export async function resolveSecret(key) {
286
309
  }
287
310
  // Authenticated multi-tenant context: never fall back to process.env.
288
311
  // The deploy-level value would silently impersonate the actual key
289
- // owner across every tenant.
290
- return null;
312
+ // owner across every tenant. Local/single-tenant deployments keep the
313
+ // original env fallback for BYO-server workflows.
314
+ return canUseDeployCredentialFallbackForRequest()
315
+ ? process.env[key] || null
316
+ : null;
291
317
  }
292
318
  // Unauthenticated / local-dev / CLI / background context: env fallback
293
319
  // is safe because there's no user to mis-identify.
@@ -1 +1 @@
1
- {"version":3,"file":"credential-provider.js","sourceRoot":"","sources":["../../src/server/credential-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5E;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2B,CACzC,KAAa,EACb,KAAgC,EAChC,IAA+B;IAE/B,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,CAAC,EAAE,CAAC;QACpD,OAAO,EAAE,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;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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 { getRequestUserEmail, getRequestOrgId } from \"./request-context.js\";\n\n/**\n * Decide which `app_secrets` scope a Builder/credential write should use.\n *\n * Org scope (\"everyone in this org sees these credentials\") wins when the\n * connecting user is an owner or admin of an active org — the write\n * privileges shared infra. A plain member or a user without an active\n * org falls through to per-user scope so a teammate can't silently\n * overwrite the org-shared connection.\n */\nexport function resolveCredentialWriteScope(\n email: string,\n orgId: string | null | undefined,\n role: string | null | undefined,\n): { scope: \"user\" | \"org\"; scopeId: string } {\n if (orgId && (role === \"owner\" || role === \"admin\")) {\n return { scope: \"org\", scopeId: orgId };\n }\n return { scope: \"user\", scopeId: email };\n}\n\nexport class FeatureNotConfiguredError extends Error {\n readonly requiredCredential: string;\n readonly builderConnectUrl?: string;\n readonly byokDocsUrl?: string;\n\n constructor(opts: {\n requiredCredential: string;\n message?: string;\n builderConnectUrl?: string;\n byokDocsUrl?: string;\n }) {\n super(\n opts.message ??\n `Feature requires credential \"${opts.requiredCredential}\". Connect Builder or set your own key.`,\n );\n this.name = \"FeatureNotConfiguredError\";\n this.requiredCredential = opts.requiredCredential;\n this.builderConnectUrl = opts.builderConnectUrl;\n this.byokDocsUrl = opts.byokDocsUrl;\n }\n}\n\n/**\n * Deployment-level credential fallback for single-tenant/local operation.\n * Multi-tenant call sites must gate this explicitly before calling.\n */\nexport function readDeployCredentialEnv(key: string): string | undefined {\n return process.env[key] || undefined;\n}\n\n// ---------------------------------------------------------------------------\n// 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\" | \"env\";\n\nasync function resolveScopedBuilderCredential(\n key: string,\n): Promise<{ value: string; source: \"user\" | \"org\" } | null> {\n const email = getRequestUserEmail();\n if (!email) return null;\n\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) return { value: userSecret.value, source: \"user\" };\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 const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret) return { value: orgSecret.value, source: \"org\" };\n }\n } catch {\n // Secrets table not ready — treat as missing.\n }\n return null;\n}\n\n/**\n * Resolve a Builder credential for the current request. User/org credentials\n * win; deployment env is only a fallback. This lets local/root .env keys keep\n * a template working while still allowing users to connect their own Builder\n * account from Settings or onboarding.\n */\nexport async function resolveBuilderCredential(\n key: string,\n): Promise<string | null> {\n const scoped = await resolveScopedBuilderCredential(key);\n if (scoped) return scoped.value;\n return readDeployCredentialEnv(key) ?? null;\n}\n\n/**\n * True when `BUILDER_PRIVATE_KEY` is set at the deployment level. This means\n * a deploy-level fallback exists; it does not prevent per-user connect.\n */\nexport function isBuilderEnvManaged(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/**\n * Resolve the Builder private key for the current request. User/org OAuth\n * credentials win; deploy-level `BUILDER_PRIVATE_KEY` is the fallback.\n */\nexport async function resolveBuilderPrivateKey(): Promise<string | null> {\n return resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n}\n\n/**\n * Resolve the current user's Builder auth header.\n * Returns `\"Bearer <key>\"` or null.\n */\nexport async function resolveBuilderAuthHeader(): Promise<string | null> {\n const key = await resolveBuilderPrivateKey();\n return key ? `Bearer ${key}` : null;\n}\n\n/**\n * Check whether the current user has a Builder private key configured\n * (per-user or deployment-level).\n */\nexport async function resolveHasBuilderPrivateKey(): Promise<boolean> {\n return !!(await resolveBuilderPrivateKey());\n}\n\n/**\n * Resolve where the effective Builder private key came from. Used by status\n * UIs so they can distinguish a deploy fallback from a user/org connection.\n */\nexport async function resolveBuilderCredentialSource(): Promise<BuilderCredentialSource | null> {\n const scoped = await resolveScopedBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n if (scoped) return scoped.source;\n return process.env.BUILDER_PRIVATE_KEY ? \"env\" : null;\n}\n\n/**\n * Resolve all per-user Builder credentials. Used by the status endpoint\n * and agent-chat-plugin to get orgName, userId, etc.\n */\nexport async function resolveBuilderCredentials(): Promise<{\n privateKey: string | null;\n publicKey: string | null;\n userId: string | null;\n orgName: string | null;\n orgKind: string | null;\n}> {\n const [privateKey, publicKey, userId, orgName, orgKind] = await Promise.all([\n resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\"),\n resolveBuilderCredential(\"BUILDER_PUBLIC_KEY\"),\n resolveBuilderCredential(\"BUILDER_USER_ID\"),\n resolveBuilderCredential(\"BUILDER_ORG_NAME\"),\n resolveBuilderCredential(\"BUILDER_ORG_KIND\"),\n ]);\n return { privateKey, publicKey, userId, orgName, orgKind };\n}\n\nconst BUILDER_CREDENTIAL_KEYS = [\n \"BUILDER_PRIVATE_KEY\",\n \"BUILDER_PUBLIC_KEY\",\n \"BUILDER_USER_ID\",\n \"BUILDER_ORG_NAME\",\n \"BUILDER_ORG_KIND\",\n] as const;\n\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 * Returns the actual scope/scopeId used so the caller can show \"Connected\n * for Builder.io\" vs \"Connected (personal)\" in the UI.\n */\nexport async function writeBuilderCredentials(\n email: string,\n creds: {\n privateKey: string;\n publicKey: string;\n userId?: string | null;\n orgName?: string | null;\n orgKind?: string | null;\n },\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { writeAppSecret } = await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n\n const entries: Array<{ key: string; value: string }> = [\n { key: \"BUILDER_PRIVATE_KEY\", value: creds.privateKey },\n { key: \"BUILDER_PUBLIC_KEY\", value: creds.publicKey },\n ];\n if (creds.userId) {\n entries.push({ key: \"BUILDER_USER_ID\", value: creds.userId });\n }\n if (creds.orgName) {\n entries.push({ key: \"BUILDER_ORG_NAME\", value: creds.orgName });\n }\n if (creds.orgKind) {\n entries.push({ key: \"BUILDER_ORG_KIND\", value: creds.orgKind });\n }\n await Promise.all(\n entries.map(({ key, value }) =>\n writeAppSecret({\n key,\n value,\n scope: target.scope,\n scopeId: target.scopeId,\n }),\n ),\n );\n 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 for unauthenticated/CLI/background contexts.\n */\nexport async function resolveSecret(key: string): Promise<string | null> {\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) return userSecret.value;\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) return orgSecret.value;\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) return workspaceSecret.value;\n } else {\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret?.value) return soloWorkspaceSecret.value;\n }\n } catch {\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.\n return null;\n }\n // Unauthenticated / local-dev / CLI / background context: env fallback\n // is safe because there's no user to mis-identify.\n return process.env[key] || null;\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://ai-services.builder.io\"\n );\n}\n\n/**\n * Base URL for the public Builder LLM gateway (distinct from the internal\n * proxy origin above — the public gateway lives at\n * api.builder.io/agent-native/gateway, while the internal origin is\n * ai-services.builder.io).\n * Override via BUILDER_GATEWAY_BASE_URL for staging / testing.\n */\nexport function getBuilderGatewayBaseUrl(): string {\n return (\n process.env.BUILDER_GATEWAY_BASE_URL ||\n \"https://api.builder.io/agent-native/gateway/v1\"\n );\n}\n\n/**\n * Base URL for Builder-managed image generation.\n * Override via BUILDER_IMAGE_GENERATION_BASE_URL for staging / testing.\n */\nexport function getBuilderImageGenerationBaseUrl(): string {\n return (\n process.env.BUILDER_IMAGE_GENERATION_BASE_URL ||\n \"https://api.builder.io/agent-native/images/v1\"\n );\n}\n\n/** Authorization header value for Builder-proxied calls (env-only). */\nexport function getBuilderAuthHeader(): string | null {\n const key = process.env.BUILDER_PRIVATE_KEY;\n return key ? `Bearer ${key}` : null;\n}\n"]}
1
+ {"version":3,"file":"credential-provider.js","sourceRoot":"","sources":["../../src/server/credential-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,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,IAA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,OAAO,CAAC,GAAG,CAAC,iCAAiC;QAC7C,+CAA+C,CAChD,CAAC;AACJ,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,oBAAoB;IAClC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;IAC5C,OAAO,GAAG,CAAC,CAAC,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC","sourcesContent":["/**\n * Credential provider abstraction.\n *\n * Every feature that needs an external credential (Anthropic API key,\n * Google OAuth tokens, OpenAI key, Slack bot token, etc.) should go through\n * one of the resolve*() helpers here instead of reading `process.env`\n * directly. That way the same feature can work in three modes:\n *\n * 1. User set their own key in .env → use it directly\n * 2. User connected Builder via `/cli-auth` → route through Builder proxy\n * 3. Neither → throw FeatureNotConfigured\n *\n * Templates catch FeatureNotConfigured and show a \"Connect Builder (1 click) /\n * set up your own key (guide)\" card.\n *\n * Today these helpers are used by the Builder-hosted LLM gateway, and the\n * shape is meant to grow to cover future managed credential integrations\n * (e.g. additional Builder-hosted services) without rewrites.\n */\n\nimport { 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\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\" | \"env\";\n\nasync function resolveScopedBuilderCredential(\n key: string,\n): Promise<{ value: string; source: \"user\" | \"org\" } | null> {\n const email = getRequestUserEmail();\n if (!email) return null;\n\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) return { value: userSecret.value, source: \"user\" };\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 const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret) return { value: orgSecret.value, source: \"org\" };\n }\n } catch {\n // Secrets table not ready — treat as missing.\n }\n return null;\n}\n\n/**\n * Resolve a Builder credential for the current request. User/org credentials\n * win; deployment env is only a fallback. This lets local/root .env keys keep\n * a template working while still allowing users to connect their own Builder\n * account from Settings or onboarding.\n */\nexport async function resolveBuilderCredential(\n key: string,\n): Promise<string | null> {\n const scoped = await resolveScopedBuilderCredential(key);\n if (scoped) return scoped.value;\n if (!canUseDeployCredentialFallbackForRequest()) return null;\n return readDeployCredentialEnv(key) ?? null;\n}\n\n/**\n * True when `BUILDER_PRIVATE_KEY` is set at the deployment level. This means\n * a deploy-level fallback exists; it does not prevent per-user connect.\n */\nexport function isBuilderEnvManaged(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/**\n * Resolve the Builder private key for the current request. User/org OAuth\n * credentials win; deploy-level `BUILDER_PRIVATE_KEY` is the fallback.\n */\nexport async function resolveBuilderPrivateKey(): Promise<string | null> {\n return resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n}\n\n/**\n * Resolve the current user's Builder auth header.\n * Returns `\"Bearer <key>\"` or null.\n */\nexport async function resolveBuilderAuthHeader(): Promise<string | null> {\n const key = await resolveBuilderPrivateKey();\n return key ? `Bearer ${key}` : null;\n}\n\n/**\n * Check whether the current user has a Builder private key configured\n * (per-user or deployment-level).\n */\nexport async function resolveHasBuilderPrivateKey(): Promise<boolean> {\n return !!(await resolveBuilderPrivateKey());\n}\n\n/**\n * Resolve where the effective Builder private key came from. Used by status\n * UIs so they can distinguish a deploy fallback from a user/org connection.\n */\nexport async function resolveBuilderCredentialSource(): Promise<BuilderCredentialSource | null> {\n const scoped = await resolveScopedBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n if (scoped) return scoped.source;\n return canUseDeployCredentialFallbackForRequest() &&\n process.env.BUILDER_PRIVATE_KEY\n ? \"env\"\n : null;\n}\n\n/**\n * Resolve all per-user Builder credentials. Used by the status endpoint\n * and agent-chat-plugin to get orgName, userId, etc.\n */\nexport async function resolveBuilderCredentials(): Promise<{\n privateKey: string | null;\n publicKey: string | null;\n userId: string | null;\n orgName: string | null;\n orgKind: string | null;\n}> {\n const [privateKey, publicKey, userId, orgName, orgKind] = await Promise.all([\n resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\"),\n resolveBuilderCredential(\"BUILDER_PUBLIC_KEY\"),\n resolveBuilderCredential(\"BUILDER_USER_ID\"),\n resolveBuilderCredential(\"BUILDER_ORG_NAME\"),\n resolveBuilderCredential(\"BUILDER_ORG_KIND\"),\n ]);\n return { privateKey, publicKey, userId, orgName, orgKind };\n}\n\nconst BUILDER_CREDENTIAL_KEYS = [\n \"BUILDER_PRIVATE_KEY\",\n \"BUILDER_PUBLIC_KEY\",\n \"BUILDER_USER_ID\",\n \"BUILDER_ORG_NAME\",\n \"BUILDER_ORG_KIND\",\n] as const;\n\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 * Returns the actual scope/scopeId used so the caller can show \"Connected\n * for Builder.io\" vs \"Connected (personal)\" in the UI.\n */\nexport async function writeBuilderCredentials(\n email: string,\n creds: {\n privateKey: string;\n publicKey: string;\n userId?: string | null;\n orgName?: string | null;\n orgKind?: string | null;\n },\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { writeAppSecret } = await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n\n const entries: Array<{ key: string; value: string }> = [\n { key: \"BUILDER_PRIVATE_KEY\", value: creds.privateKey },\n { key: \"BUILDER_PUBLIC_KEY\", value: creds.publicKey },\n ];\n if (creds.userId) {\n entries.push({ key: \"BUILDER_USER_ID\", value: creds.userId });\n }\n if (creds.orgName) {\n entries.push({ key: \"BUILDER_ORG_NAME\", value: creds.orgName });\n }\n if (creds.orgKind) {\n entries.push({ key: \"BUILDER_ORG_KIND\", value: creds.orgKind });\n }\n await Promise.all(\n entries.map(({ key, value }) =>\n writeAppSecret({\n key,\n value,\n scope: target.scope,\n scopeId: target.scopeId,\n }),\n ),\n );\n 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 for unauthenticated/CLI/background contexts.\n */\nexport async function resolveSecret(key: string): Promise<string | null> {\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) return userSecret.value;\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) return orgSecret.value;\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) return workspaceSecret.value;\n } else {\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret?.value) return soloWorkspaceSecret.value;\n }\n } catch {\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 return canUseDeployCredentialFallbackForRequest()\n ? process.env[key] || null\n : null;\n }\n // Unauthenticated / local-dev / CLI / background context: env fallback\n // is safe because there's no user to mis-identify.\n return process.env[key] || null;\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://ai-services.builder.io\"\n );\n}\n\n/**\n * Base URL for the public Builder LLM gateway (distinct from the internal\n * proxy origin above — the public gateway lives at\n * api.builder.io/agent-native/gateway, while the internal origin is\n * ai-services.builder.io).\n * Override via BUILDER_GATEWAY_BASE_URL for staging / testing.\n */\nexport function getBuilderGatewayBaseUrl(): string {\n return (\n process.env.BUILDER_GATEWAY_BASE_URL ||\n \"https://api.builder.io/agent-native/gateway/v1\"\n );\n}\n\n/**\n * Base URL for Builder-managed image generation.\n * Override via BUILDER_IMAGE_GENERATION_BASE_URL for staging / testing.\n */\nexport function getBuilderImageGenerationBaseUrl(): string {\n return (\n process.env.BUILDER_IMAGE_GENERATION_BASE_URL ||\n \"https://api.builder.io/agent-native/images/v1\"\n );\n}\n\n/** Authorization header value for Builder-proxied calls (env-only). */\nexport function getBuilderAuthHeader(): string | null {\n const key = process.env.BUILDER_PRIVATE_KEY;\n return key ? `Bearer ${key}` : null;\n}\n"]}
@@ -25,7 +25,7 @@ export { wrapWithAnalytics } from "./analytics.js";
25
25
  export { getH3App, awaitBootstrap, type H3AppShim, } from "./framework-request-handler.js";
26
26
  export { autoDiscoverActions, autoDiscoverScripts, loadActionsFromStaticRegistry, mergeCoreSharingActions, registerPackageActions, } from "./action-discovery.js";
27
27
  export { mountActionRoutes, type MountActionRoutesOptions, } from "./action-routes.js";
28
- export { runWithRequestContext, hasRequestContext, getRequestContext, getRequestUserEmail, getRequestOrgId, getRequestTimezone, getRequestRunContext, getCredentialContext, isIntegrationCallerRequest, type RequestContext, type RequestRunContext, } from "./request-context.js";
28
+ export { runWithRequestContext, hasRequestContext, getRequestContext, getRequestUserEmail, getRequestUserName, getRequestOrgId, getRequestTimezone, getRequestRunContext, getCredentialContext, isIntegrationCallerRequest, type RequestContext, type RequestRunContext, } from "./request-context.js";
29
29
  export { formatDateInTimezone, todayInTimezone } from "./date-utils.js";
30
30
  export { createOnboardingPlugin, defaultOnboardingPlugin, } from "../onboarding/plugin.js";
31
31
  export { registerFileUploadProvider, unregisterFileUploadProvider, listFileUploadProviders, getActiveFileUploadProvider, uploadFile, builderFileUploadProvider, type FileUploadInput, type FileUploadProvider, type FileUploadResult, } from "../file-upload/index.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,aAAa,EACb,KAAK,mBAAmB,EACxB,KAAK,YAAY,GAClB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,MAAM,UAAU,CAAC;AACpE,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,UAAU,EACV,UAAU,EACV,aAAa,EACb,eAAe,EACf,YAAY,EACZ,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,EACd,KAAK,2BAA2B,EAChC,KAAK,WAAW,EAChB,KAAK,WAAW,GACjB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,aAAa,EAAE,KAAK,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,KAAK,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EACL,4BAA4B,EAC5B,KAAK,WAAW,EAChB,KAAK,WAAW,EA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,EACnB,qBAAqB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,YAAY,IAAI,2BAA2B,GACjD,MAAM,wBAAwB,CAAC;AAUhC,MAAM,MAAM,cAAc,GAAG,CAAC,QAAQ,EAAE,GAAG,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AACrE,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,cAAc,GAAG,cAAc,CAErE"}
@@ -28,7 +28,7 @@ export { wrapWithAnalytics } from "./analytics.js";
28
28
  export { getH3App, awaitBootstrap, } from "./framework-request-handler.js";
29
29
  export { autoDiscoverActions, autoDiscoverScripts, loadActionsFromStaticRegistry, mergeCoreSharingActions, registerPackageActions, } from "./action-discovery.js";
30
30
  export { mountActionRoutes, } from "./action-routes.js";
31
- export { runWithRequestContext, hasRequestContext, getRequestContext, getRequestUserEmail, getRequestOrgId, getRequestTimezone, getRequestRunContext, getCredentialContext, isIntegrationCallerRequest, } from "./request-context.js";
31
+ export { runWithRequestContext, hasRequestContext, getRequestContext, getRequestUserEmail, getRequestUserName, getRequestOrgId, getRequestTimezone, getRequestRunContext, getCredentialContext, isIntegrationCallerRequest, } from "./request-context.js";
32
32
  export { formatDateInTimezone, todayInTimezone } from "./date-utils.js";
33
33
  export { createOnboardingPlugin, defaultOnboardingPlugin, } from "../onboarding/plugin.js";
34
34
  export { registerFileUploadProvider, unregisterFileUploadProvider, listFileUploadProviders, getActiveFileUploadProvider, uploadFile, builderFileUploadProvider, } from "../file-upload/index.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,aAAa,GAGd,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAA0B,MAAM,UAAU,CAAC;AACpE,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,U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,qBAAqB,EACrB,cAAc,EACd,wBAAwB,GAIzB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,mBAAmB,EACnB,qBAAqB,EACrB,gCAAgC,EAChC,oBAAoB,EACpB,wBAAwB,EACxB,wBAAwB,EACxB,2BAA2B,EAC3B,yBAAyB,EACzB,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,EACxB,aAAa,GACd,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,yBAAyB,EACzB,yBAAyB,EACzB,6BAA6B,EAC7B,gCAAgC,EAChC,eAAe,GAEhB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,gBAAgB,GAGjB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,WAAW,EACX,WAAW,EACX,SAAS,GAIV,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACpB,yBAAyB,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GAGtB,MAAM,wBAAwB,CAAC;AAWhC,MAAM,UAAU,iBAAiB,CAAC,GAAmB;IACnD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["export {\n createServer,\n upsertEnvFile,\n type CreateServerOptions,\n type EnvKeyConfig,\n} from \"./create-server.js\";\n\nexport { readBody, streamFile } from \"./h3-helpers.js\";\nexport { createSSEHandler, type SSEHandlerOptions } from \"./sse.js\";\nexport {\n mountAuthMiddleware,\n autoMountAuth,\n getSession,\n addSession,\n removeSession,\n getSessionEmail,\n runAuthGuard,\n setDesktopExchange,\n setDesktopExchangeError,\n safeReturnPath,\n type DesktopExchangeErrorPayload,\n type AuthSession,\n type AuthOptions,\n} from \"./auth.js\";\nexport { requireEnvKey, type MissingKeyResponse } from \"./missing-key.js\";\nexport { verifyCaptcha, type CaptchaVerifyResult } from \"./captcha.js\";\nexport {\n createProductionAgentHandler,\n type ActionEntry,\n type ScriptEntry,\n type ProductionAgentOptions,\n type ActionTool,\n type ScriptTool,\n type AgentMessage,\n type AgentChatRequest,\n type AgentChatEvent,\n type AgentChatReference,\n type MentionProvider,\n type MentionProviderItem,\n type AgentLoopFinalResponseGuard,\n type AgentLoopFinalResponseGuardContext,\n type AgentLoopFinalResponseGuardResult,\n type AgentLoopToolCallSummary,\n type AgentLoopToolResultSummary,\n} from \"../agent/index.js\";\nexport { createDevScriptRegistry } from \"../scripts/dev/index.js\";\n\nexport {\n createPollHandler,\n recordChange,\n getVersion,\n getChangesSince,\n} from \"./poll.js\";\nexport { createAuthPlugin, defaultAuthPlugin } from \"./auth-plugin.js\";\nexport {\n initServerSentry,\n isServerSentryEnabled,\n setSentryUserForRequest,\n captureRouteError,\n type RouteErrorContext,\n} from \"./sentry.js\";\nexport {\n captureError,\n captureServerError,\n registerErrorCaptureProvider,\n type CaptureErrorContext,\n type CaptureErrorProvider,\n} from \"./capture-error.js\";\nexport { createSentryPlugin, defaultSentryPlugin } from \"./sentry-plugin.js\";\n// Re-export the org plugin so the auto-discovery's DEFAULT_PLUGIN_REGISTRY\n// (which references \"defaultOrgPlugin\" from @agent-native/core/server) can\n// resolve it during the deploy build worker-entry generation.\nexport { createOrgPlugin, defaultOrgPlugin } from \"../org/plugin.js\";\nexport {\n createGoogleAuthPlugin,\n type GoogleAuthPluginOptions,\n} from \"./google-auth-plugin.js\";\nexport {\n createAgentChatPlugin,\n defaultAgentChatPlugin,\n type AgentChatPluginOptions,\n} from \"./agent-chat-plugin.js\";\nexport {\n createThread,\n getThread,\n listThreads,\n updateThreadData,\n deleteThread,\n type ChatThread,\n type ChatThreadSummary,\n} from \"../chat-threads/store.js\";\nexport {\n createResourcesPlugin,\n defaultResourcesPlugin,\n} from \"./resources-plugin.js\";\nexport {\n createCoreRoutesPlugin,\n defaultCoreRoutesPlugin,\n FRAMEWORK_ROUTE_PREFIX,\n type CoreRoutesPluginOptions,\n} from \"./core-routes-plugin.js\";\nexport {\n createTerminalPlugin,\n defaultTerminalPlugin,\n type TerminalPluginOptions,\n} from \"../terminal/terminal-plugin.js\";\nexport {\n createCollabPlugin,\n type CollabPluginOptions,\n} from \"./collab-plugin.js\";\n\nexport {\n spawnTask,\n getTask,\n getTaskByThread,\n listTasks,\n sendToTask,\n markTaskErrored,\n type AgentTask,\n type SpawnTaskOptions,\n} from \"./agent-teams.js\";\nexport { isOAuthConnected, getOAuthAccounts } from \"./oauth-helpers.js\";\nexport { wrapWithAnalytics } from \"./analytics.js\";\nexport {\n getH3App,\n awaitBootstrap,\n type H3AppShim,\n} from \"./framework-request-handler.js\";\nexport {\n autoDiscoverActions,\n autoDiscoverScripts,\n loadActionsFromStaticRegistry,\n mergeCoreSharingActions,\n registerPackageActions,\n} from \"./action-discovery.js\";\nexport {\n mountActionRoutes,\n type MountActionRoutesOptions,\n} from \"./action-routes.js\";\nexport {\n runWithRequestContext,\n hasRequestContext,\n getRequestContext,\n getRequestUserEmail,\n getRequestOrgId,\n getRequestTimezone,\n getRequestRunContext,\n getCredentialContext,\n isIntegrationCallerRequest,\n type RequestContext,\n type RequestRunContext,\n} from \"./request-context.js\";\nexport { formatDateInTimezone, todayInTimezone } from \"./date-utils.js\";\n\nexport {\n createOnboardingPlugin,\n defaultOnboardingPlugin,\n} from \"../onboarding/plugin.js\";\n\nexport {\n registerFileUploadProvider,\n unregisterFileUploadProvider,\n listFileUploadProviders,\n getActiveFileUploadProvider,\n uploadFile,\n builderFileUploadProvider,\n type FileUploadInput,\n type FileUploadProvider,\n type FileUploadResult,\n} from \"../file-upload/index.js\";\n\nexport {\n createIntegrationsPlugin,\n defaultIntegrationsPlugin,\n slackAdapter,\n telegramAdapter,\n whatsappAdapter,\n emailAdapter,\n type PlatformAdapter,\n type IncomingMessage,\n type OutgoingMessage,\n type IntegrationStatus,\n type IntegrationsPluginOptions,\n} from \"../integrations/index.js\";\n\nexport {\n isElectron,\n isMobile,\n getOrigin,\n getAppBasePath,\n getAppUrl,\n resolveOAuthRedirectUri,\n isAllowedOAuthRedirectUri,\n encodeOAuthState,\n decodeOAuthState,\n resolveOAuthOwner,\n createOAuthSession,\n oauthCallbackResponse,\n oauthErrorPage,\n oauthDesktopExchangePage,\n type OAuthStatePayload,\n type OAuthOwnerResult,\n type OAuthSessionResult,\n} from \"./google-oauth.js\";\n\nexport {\n FeatureNotConfiguredError,\n hasBuilderPrivateKey,\n isBuilderEnvManaged,\n getBuilderProxyOrigin,\n getBuilderImageGenerationBaseUrl,\n getBuilderAuthHeader,\n resolveBuilderPrivateKey,\n resolveBuilderAuthHeader,\n resolveHasBuilderPrivateKey,\n resolveBuilderCredentials,\n resolveBuilderCredential,\n writeBuilderCredentials,\n deleteBuilderCredentials,\n resolveSecret,\n} from \"./credential-provider.js\";\nexport {\n getBuilderBranchProjectId,\n isBuilderBranchingEnabled,\n resolveBuilderBranchProjectId,\n resolveIsBuilderBranchingEnabled,\n runBuilderAgent,\n type RunBuilderAgentResult,\n} from \"./builder-browser.js\";\n\nexport {\n sendEmail,\n isEmailConfigured,\n getEmailProvider,\n type EmailProvider,\n type SendEmailArgs,\n} from \"./email.js\";\nexport {\n renderEmail,\n emailStrong,\n emailLink,\n type RenderEmailArgs,\n type RenderedEmail,\n type EmailCta,\n} from \"./email-template.js\";\nexport { getAppProductionUrl, getFirstPartyProdUrl } from \"./app-url.js\";\nexport {\n getConfiguredAppBasePath,\n normalizeAppBasePath,\n withConfiguredAppBasePath,\n} from \"./app-base-path.js\";\nexport {\n signShortLivedToken,\n verifyShortLivedToken,\n type ShortLivedTokenClaims,\n type VerifyResult as ShortLivedTokenVerifyResult,\n} from \"./short-lived-token.js\";\n\n// SSR handler is NOT re-exported here — it uses a virtual module\n// (virtual:react-router/server-build) that only exists at Vite dev/build time.\n// Including it in this barrel would break the esbuild CF Pages bundler.\n// Templates import directly: import { ssrHandler } from \"@agent-native/core/server/ssr-handler\"\n\n// Nitro plugin helper — re-exported so templates don't need nitro as a direct dependency.\n// defineNitroPlugin is an identity function; this typed wrapper lets templates use it\n// without resolving `nitro/runtime` (which requires Nitro's virtual modules at runtime).\nexport type NitroPluginDef = (nitroApp: any) => void | Promise<void>;\nexport function defineNitroPlugin(def: NitroPluginDef): NitroPluginDef {\n return def;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,aAAa,GAGd,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAA0B,MAAM,UAAU,CAAC;AACpE,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,UAAU,EACV,UAAU,EACV,aAAa,EACb,eAAe,EACf,YAAY,EACZ,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,GAIf,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,aAAa,EAA2B,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAA4B,MAAM,cAAc,CAAC;AACvE,OAAO,EACL,4BAA4B,GAiB7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAElE,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,eAAe,GAChB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACvE,OAAO,EACL,gBAAgB,EAChB,qBAAqB,EACrB,uBAAuB,EACvB,iBAAiB,GAElB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,4BAA4B,GAG7B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,oBAAoB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AAoB,CAAC;AAC5B,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GAGtB,MAAM,wBAAwB,CAAC;AAWhC,MAAM,UAAU,iBAAiB,CAAC,GAAmB;IACnD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["export {\n createServer,\n upsertEnvFile,\n type CreateServerOptions,\n type EnvKeyConfig,\n} from \"./create-server.js\";\n\nexport { readBody, streamFile } from \"./h3-helpers.js\";\nexport { createSSEHandler, type SSEHandlerOptions } from \"./sse.js\";\nexport {\n mountAuthMiddleware,\n autoMountAuth,\n getSession,\n addSession,\n removeSession,\n getSessionEmail,\n runAuthGuard,\n setDesktopExchange,\n setDesktopExchangeError,\n safeReturnPath,\n type DesktopExchangeErrorPayload,\n type AuthSession,\n type AuthOptions,\n} from \"./auth.js\";\nexport { requireEnvKey, type MissingKeyResponse } from \"./missing-key.js\";\nexport { verifyCaptcha, type CaptchaVerifyResult } from \"./captcha.js\";\nexport {\n createProductionAgentHandler,\n type ActionEntry,\n type ScriptEntry,\n type ProductionAgentOptions,\n type ActionTool,\n type ScriptTool,\n type AgentMessage,\n type AgentChatRequest,\n type AgentChatEvent,\n type AgentChatReference,\n type MentionProvider,\n type MentionProviderItem,\n type AgentLoopFinalResponseGuard,\n type AgentLoopFinalResponseGuardContext,\n type AgentLoopFinalResponseGuardResult,\n type AgentLoopToolCallSummary,\n type AgentLoopToolResultSummary,\n} from \"../agent/index.js\";\nexport { createDevScriptRegistry } from \"../scripts/dev/index.js\";\n\nexport {\n createPollHandler,\n recordChange,\n getVersion,\n getChangesSince,\n} from \"./poll.js\";\nexport { createAuthPlugin, defaultAuthPlugin } from \"./auth-plugin.js\";\nexport {\n initServerSentry,\n isServerSentryEnabled,\n setSentryUserForRequest,\n captureRouteError,\n type RouteErrorContext,\n} from \"./sentry.js\";\nexport {\n captureError,\n captureServerError,\n registerErrorCaptureProvider,\n type CaptureErrorContext,\n type CaptureErrorProvider,\n} from \"./capture-error.js\";\nexport { createSentryPlugin, defaultSentryPlugin } from \"./sentry-plugin.js\";\n// Re-export the org plugin so the auto-discovery's DEFAULT_PLUGIN_REGISTRY\n// (which references \"defaultOrgPlugin\" from @agent-native/core/server) can\n// resolve it during the deploy build worker-entry generation.\nexport { createOrgPlugin, defaultOrgPlugin } from \"../org/plugin.js\";\nexport {\n createGoogleAuthPlugin,\n type GoogleAuthPluginOptions,\n} from \"./google-auth-plugin.js\";\nexport {\n createAgentChatPlugin,\n defaultAgentChatPlugin,\n type AgentChatPluginOptions,\n} from \"./agent-chat-plugin.js\";\nexport {\n createThread,\n getThread,\n listThreads,\n updateThreadData,\n deleteThread,\n type ChatThread,\n type ChatThreadSummary,\n} from \"../chat-threads/store.js\";\nexport {\n createResourcesPlugin,\n defaultResourcesPlugin,\n} from \"./resources-plugin.js\";\nexport {\n createCoreRoutesPlugin,\n defaultCoreRoutesPlugin,\n FRAMEWORK_ROUTE_PREFIX,\n type CoreRoutesPluginOptions,\n} from \"./core-routes-plugin.js\";\nexport {\n createTerminalPlugin,\n defaultTerminalPlugin,\n type TerminalPluginOptions,\n} from \"../terminal/terminal-plugin.js\";\nexport {\n createCollabPlugin,\n type CollabPluginOptions,\n} from \"./collab-plugin.js\";\n\nexport {\n spawnTask,\n getTask,\n getTaskByThread,\n listTasks,\n sendToTask,\n markTaskErrored,\n type AgentTask,\n type SpawnTaskOptions,\n} from \"./agent-teams.js\";\nexport { isOAuthConnected, getOAuthAccounts } from \"./oauth-helpers.js\";\nexport { wrapWithAnalytics } from \"./analytics.js\";\nexport {\n getH3App,\n awaitBootstrap,\n type H3AppShim,\n} from \"./framework-request-handler.js\";\nexport {\n autoDiscoverActions,\n autoDiscoverScripts,\n loadActionsFromStaticRegistry,\n mergeCoreSharingActions,\n registerPackageActions,\n} from \"./action-discovery.js\";\nexport {\n mountActionRoutes,\n type MountActionRoutesOptions,\n} from \"./action-routes.js\";\nexport {\n runWithRequestContext,\n hasRequestContext,\n getRequestContext,\n getRequestUserEmail,\n getRequestUserName,\n getRequestOrgId,\n getRequestTimezone,\n getRequestRunContext,\n getCredentialContext,\n isIntegrationCallerRequest,\n type RequestContext,\n type RequestRunContext,\n} from \"./request-context.js\";\nexport { formatDateInTimezone, todayInTimezone } from \"./date-utils.js\";\n\nexport {\n createOnboardingPlugin,\n defaultOnboardingPlugin,\n} from \"../onboarding/plugin.js\";\n\nexport {\n registerFileUploadProvider,\n unregisterFileUploadProvider,\n listFileUploadProviders,\n getActiveFileUploadProvider,\n uploadFile,\n builderFileUploadProvider,\n type FileUploadInput,\n type FileUploadProvider,\n type FileUploadResult,\n} from \"../file-upload/index.js\";\n\nexport {\n createIntegrationsPlugin,\n defaultIntegrationsPlugin,\n slackAdapter,\n telegramAdapter,\n whatsappAdapter,\n emailAdapter,\n type PlatformAdapter,\n type IncomingMessage,\n type OutgoingMessage,\n type IntegrationStatus,\n type IntegrationsPluginOptions,\n} from \"../integrations/index.js\";\n\nexport {\n isElectron,\n isMobile,\n getOrigin,\n getAppBasePath,\n getAppUrl,\n resolveOAuthRedirectUri,\n isAllowedOAuthRedirectUri,\n encodeOAuthState,\n decodeOAuthState,\n resolveOAuthOwner,\n createOAuthSession,\n oauthCallbackResponse,\n oauthErrorPage,\n oauthDesktopExchangePage,\n type OAuthStatePayload,\n type OAuthOwnerResult,\n type OAuthSessionResult,\n} from \"./google-oauth.js\";\n\nexport {\n FeatureNotConfiguredError,\n hasBuilderPrivateKey,\n isBuilderEnvManaged,\n getBuilderProxyOrigin,\n getBuilderImageGenerationBaseUrl,\n getBuilderAuthHeader,\n resolveBuilderPrivateKey,\n resolveBuilderAuthHeader,\n resolveHasBuilderPrivateKey,\n resolveBuilderCredentials,\n resolveBuilderCredential,\n writeBuilderCredentials,\n deleteBuilderCredentials,\n resolveSecret,\n} from \"./credential-provider.js\";\nexport {\n getBuilderBranchProjectId,\n isBuilderBranchingEnabled,\n resolveBuilderBranchProjectId,\n resolveIsBuilderBranchingEnabled,\n runBuilderAgent,\n type RunBuilderAgentResult,\n} from \"./builder-browser.js\";\n\nexport {\n sendEmail,\n isEmailConfigured,\n getEmailProvider,\n type EmailProvider,\n type SendEmailArgs,\n} from \"./email.js\";\nexport {\n renderEmail,\n emailStrong,\n emailLink,\n type RenderEmailArgs,\n type RenderedEmail,\n type EmailCta,\n} from \"./email-template.js\";\nexport { getAppProductionUrl, getFirstPartyProdUrl } from \"./app-url.js\";\nexport {\n getConfiguredAppBasePath,\n normalizeAppBasePath,\n withConfiguredAppBasePath,\n} from \"./app-base-path.js\";\nexport {\n signShortLivedToken,\n verifyShortLivedToken,\n type ShortLivedTokenClaims,\n type VerifyResult as ShortLivedTokenVerifyResult,\n} from \"./short-lived-token.js\";\n\n// SSR handler is NOT re-exported here — it uses a virtual module\n// (virtual:react-router/server-build) that only exists at Vite dev/build time.\n// Including it in this barrel would break the esbuild CF Pages bundler.\n// Templates import directly: import { ssrHandler } from \"@agent-native/core/server/ssr-handler\"\n\n// Nitro plugin helper — re-exported so templates don't need nitro as a direct dependency.\n// defineNitroPlugin is an identity function; this typed wrapper lets templates use it\n// without resolving `nitro/runtime` (which requires Nitro's virtual modules at runtime).\nexport type NitroPluginDef = (nitroApp: any) => void | Promise<void>;\nexport function defineNitroPlugin(def: NitroPluginDef): NitroPluginDef {\n return def;\n}\n"]}
@@ -38,6 +38,7 @@ export interface RequestRunContext {
38
38
  }
39
39
  export interface RequestContext {
40
40
  userEmail?: string;
41
+ userName?: string;
41
42
  orgId?: string;
42
43
  timezone?: string;
43
44
  /**
@@ -111,6 +112,14 @@ export declare function hasRequestContext(): boolean;
111
112
  * `process.env.AGENT_USER_EMAIL`.
112
113
  */
113
114
  export declare function getRequestUserEmail(): string | undefined;
115
+ /**
116
+ * Get the current request's display name, when the auth provider supplied one.
117
+ *
118
+ * The same request-context fallback rules as `getRequestUserEmail()` apply:
119
+ * HTTP/A2A calls only read AsyncLocalStorage, while CLI scripts may opt in via
120
+ * `AGENT_USER_NAME`.
121
+ */
122
+ export declare function getRequestUserName(): string | undefined;
114
123
  /**
115
124
  * Get the current request's org ID.
116
125
  *
@@ -1 +1 @@
1
- {"version":3,"file":"request-context.d.ts","sourceRoot":"","sources":["../../src/server/request-context.ts"],"names":[],"mappings":"AAmBA;;;;;;;;;;GAUG;AACH,MAAM,WAAW,iBAAiB;IAChC,wEAAwE;IACxE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gDAAgD;IAChD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4DAA4D;IAC5D,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,yDAAyD;IACzD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6DAA6D;IAC7D,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,8DAA8D;IAC9D,MAAM,CAAC,EAAE,OAAO,0BAA0B,EAAE,WAAW,CAAC;IACxD,yDAAyD;IACzD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,SAAS,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IACpD,8DAA8D;IAC9D,WAAW,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAC1E;AAED,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;OAMG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B;;;;OAIG;IACH,WAAW,CAAC,EAAE;QACZ,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,QAAQ,EAAE,OAAO,0BAA0B,EAAE,eAAe,CAAC;QAC7D,cAAc,CAAC,EAAE,MAAM,CAAC;KACzB,C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  return store.userEmail;
103
103
  return process.env.AGENT_USER_EMAIL;
104
104
  }
105
+ /**
106
+ * Get the current request's display name, when the auth provider supplied one.
107
+ *
108
+ * The same request-context fallback rules as `getRequestUserEmail()` apply:
109
+ * HTTP/A2A calls only read AsyncLocalStorage, while CLI scripts may opt in via
110
+ * `AGENT_USER_NAME`.
111
+ */
112
+ export function getRequestUserName() {
113
+ const store = als.getStore();
114
+ if (store !== undefined)
115
+ return store.userName;
116
+ return process.env.AGENT_USER_NAME;
117
+ }
105
118
  /**
106
119
  * Get the current request's org ID.
107
120
  *
@@ -1 +1 @@
1
- {"version":3,"file":"request-context.js","sourceRoot":"","sources":["../../src/server/request-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAgErD,MAAM,UAAU,GAAG,gCAAyC,CAAC;AAC7D,MAAM,aAAa,GAAG,sCAA+C,CAAC;AAMtE,MAAM,SAAS,GAAG,UAAsC,CAAC;AACzD,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC;IAC3B,SAAS,CAAC,UAAU,CAAC,GAAG,IAAI,iBAAiB,EAAkB,CAAC;AAClE,CAAC;AACD,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,EAAE,CAAC;IAC9B,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,CAAC;AAChC,CAAC;AACD,MAAM,GAAG,GAAG,SAAS,CAAC,UAAU,CAAE,CAAC;AACnC,MAAM,SAAS,GAAG,SAAS,CAAC,aAAa,CAAE,CAAC;AAE5C;;;;;;;;;GASG;AACH,MAAM,UAAU,yBAAyB,CACvC,QAAgC;IAEhC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACzB,OAAO,GAAG,EAAE;QACV,MAAM,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACtC,IAAI,CAAC,KAAK,CAAC,CAAC;YAA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AM,KAAK,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAC;IAC7B,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC,QAAQ,CAAC;IAC/C,OAAO,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;AACzC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,0BAA0B;IACxC,OAAO,GAAG,CAAC,QAAQ,EAAE,EAAE,mBAAmB,KAAK,IAAI,CAAC;AACtD,CAAC;AAED,MAAM,UAAU,4BAA4B;IAG1C,OAAO,GAAG,CAAC,QAAQ,EAAE,EAAE,WAAW,CAAC;AACrC,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,oBAAoB;IAIlC,MAAM,SAAS,GAAG,mBAAmB,EAAE,CAAC;IACxC,IAAI,CAAC,SAAS;QAAE,OAAO,IAAI,CAAC;IAC5B,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,eAAe,EAAE,IAAI,IAAI,EAAE,CAAC;AACzD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB;IAClC,MAAM,KAAK,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAC;IAC7B,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,KAAK,CAAC,GAAG,CAAC;AACnB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB;IACrC,MAAM,KAAK,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAC;IAC7B,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,IAAI,CAAC,KAAK,CAAC,GAAG;QAAE,KAAK,CAAC,GAAG,GAAG,EAAE,CAAC;IAC/B,OAAO,KAAK,CAAC,GAAG,CAAC;AACnB,CAAC","sourcesContent":["/**\n * Per-request context using AsyncLocalStorage.\n *\n * Replaces the unsafe pattern of mutating `process.env.AGENT_USER_EMAIL` /\n * `process.env.AGENT_ORG_ID` on every request. On Node.js (Netlify, self-hosted)\n * concurrent requests would overwrite each other's env vars. AsyncLocalStorage\n * gives each async call-chain its own isolated context.\n *\n * Supported on all deployment targets:\n * - Node.js (native)\n * - Cloudflare Workers (via nodejs_compat flag)\n * - Deno Deploy (via node:async_hooks compat)\n *\n * For CLI scripts that run outside a request context, the getters fall back to\n * process.env so existing `AGENT_USER_EMAIL=x pnpm action foo` invocations\n * continue to work.\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\n/**\n * Per-request agent-run state. Lives on `RequestContext.run` so the\n * agent-chat plugin can populate fields as the run progresses (owner,\n * resolved API key, system prompt, engine, model, threadId) without\n * mutating module-scope `let` bindings — those leak across concurrent\n * requests on a single Node.js process.\n *\n * Mutated in-place by `prepareRun`, `onEngineResolved`, `onRunStart` so\n * tool factory closures (automation, fetch, team, builder-browser) read\n * the live per-request value via `getRequestRunContext()`.\n */\nexport interface RequestRunContext {\n /** Origin of the current request (used by the builder-browser tool). */\n requestOrigin?: string;\n /** Resolved owner email (set by prepareRun). */\n owner?: string;\n /** Owner's active Anthropic API key (set by prepareRun). */\n userApiKey?: string;\n /** Thread ID for the current run (set by onRunStart). */\n threadId?: string;\n /** System prompt actually sent to the model for this run. */\n systemPrompt?: string;\n /** Engine instance for this run (set by onEngineResolved). */\n engine?: import(\"../agent/engine/types.js\").AgentEngine;\n /** Model name for this run (set by onEngineResolved). */\n model?: string;\n /** Tool calls made so far in the current agent loop. */\n toolCalls?: Array<{ name: string; input: unknown }>;\n /** Tool results returned so far in the current agent loop. */\n toolResults?: Array<{ name: string; content: string; isError: boolean }>;\n}\n\nexport interface RequestContext {\n userEmail?: string;\n orgId?: string;\n timezone?: string;\n /**\n * True when this request is being processed by an integration-platform\n * webhook (Slack, Telegram, etc.) where the function timeout is the\n * binding constraint. Code that calls slow remote APIs can use this to apply\n * tighter budgets on this path while leaving normal agent-chat callers\n * (5+ min budget) unaffected.\n */\n isIntegrationCaller?: boolean;\n /**\n * Metadata for the currently-processing integration task. This lets tools\n * that start long-running remote work persist a continuation that can update\n * the originating platform thread after the current function budget ends.\n */\n integration?: {\n taskId: string;\n attempts?: number;\n incoming: import(\"../integrations/types.js\").IncomingMessage;\n placeholderRef?: string;\n };\n /**\n * Mutable per-request agent-run state. Populated by the agent-chat plugin\n * during a run; tool closures dereference it on each invocation.\n */\n run?: RequestRunContext;\n}\n\nconst GLOBAL_KEY = \"__agentNativeRequestContextAls\" as const;\nconst OBSERVERS_KEY = \"__agentNativeRequestContextObservers\" as const;\ntype RequestContextObserver = (ctx: RequestContext) => void;\ntype GlobalWithRequestContext = typeof globalThis & {\n [GLOBAL_KEY]?: AsyncLocalStorage<RequestContext>;\n [OBSERVERS_KEY]?: RequestContextObserver[];\n};\nconst globalRef = globalThis as GlobalWithRequestContext;\nif (!globalRef[GLOBAL_KEY]) {\n globalRef[GLOBAL_KEY] = new AsyncLocalStorage<RequestContext>();\n}\nif (!globalRef[OBSERVERS_KEY]) {\n globalRef[OBSERVERS_KEY] = [];\n}\nconst als = globalRef[GLOBAL_KEY]!;\nconst observers = globalRef[OBSERVERS_KEY]!;\n\n/**\n * Register a callback fired every time `runWithRequestContext` enters a new\n * scope. The hook runs INSIDE the AsyncLocalStorage scope, so observability\n * helpers that read the current isolation scope (e.g. Sentry) attach to the\n * right per-request context.\n *\n * Returned function unregisters the observer. Observers must never throw —\n * any error is swallowed so a misbehaving observer can't break the request\n * path.\n */\nexport function addRequestContextObserver(\n observer: RequestContextObserver,\n): () => void {\n observers.push(observer);\n return () => {\n const i = observers.indexOf(observer);\n if (i !== -1) observers.splice(i, 1);\n };\n}\n\n/**\n * Run a callback within a per-request context. The context is available to all\n * async operations spawned from `fn` via `getRequestUserEmail()` / `getRequestOrgId()`.\n *\n * Any registered `addRequestContextObserver` callbacks fire inside the new\n * scope before `fn` runs, so observability code can pin user/org info onto\n * isolation-scoped backends (Sentry, OpenTelemetry, etc.).\n */\nexport function runWithRequestContext<T>(\n ctx: RequestContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return als.run(ctx, () => {\n if (observers.length > 0) {\n for (const obs of observers) {\n try {\n obs(ctx);\n } catch {\n // Observers must never break the request path.\n }\n }\n }\n return fn();\n });\n}\n\n/**\n * Return the active request context, if this call chain is running under one.\n *\n * This is intentionally distinct from `getRequestUserEmail()`: callers that\n * have an active context with no authenticated user must not fall through to\n * process-wide CLI fallbacks such as `AGENT_USER_EMAIL` or \"latest session\".\n */\nexport function getRequestContext(): RequestContext | undefined {\n return als.getStore();\n}\n\n/**\n * True when AsyncLocalStorage has an active context for this call chain.\n * Useful for helpers that support both HTTP requests and standalone CLI runs.\n */\nexport function hasRequestContext(): boolean {\n return als.getStore() !== undefined;\n}\n\n/**\n * Get the current request's user email.\n *\n * - If a request context exists (HTTP/A2A path), returns its `userEmail` —\n * even when that value is `undefined`. The env fallback MUST NOT fire here:\n * a stale process-wide `AGENT_USER_EMAIL` from a CLI run or previous bug\n * would leak into an unauthenticated A2A/API call (e.g. unsigned or API-key\n * modes where `runWithRequestContext({ userEmail: undefined })` is used).\n * - Only when there is NO request context (CLI scripts) do we fall back to\n * `process.env.AGENT_USER_EMAIL`.\n */\nexport function getRequestUserEmail(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) return store.userEmail;\n return process.env.AGENT_USER_EMAIL;\n}\n\n/**\n * Get the current request's org ID.\n *\n * Same store-aware semantics as `getRequestUserEmail()` — env fallback is\n * CLI-only, so a request that explicitly has no org doesn't inherit a stale\n * `process.env.AGENT_ORG_ID` from a prior request on the same Lambda instance.\n */\nexport function getRequestOrgId(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) return store.orgId;\n return process.env.AGENT_ORG_ID;\n}\n\n/**\n * Get the current request's IANA timezone (e.g. \"America/Los_Angeles\").\n * The UI sends this via the `x-user-timezone` header on every action call, and\n * the agent chat plugin propagates it into the request context so that\n * agent-initiated tool calls also see the user's timezone. Falls back to\n * `process.env.AGENT_USER_TIMEZONE` only for CLI scripts (no request context).\n */\nexport function getRequestTimezone(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) return store.timezone;\n return process.env.AGENT_USER_TIMEZONE;\n}\n\n/**\n * Returns true when this request is on an integration-platform path (Slack,\n * Telegram, etc.) — i.e. we're inside the integration plugin's processor\n * function and the platform's deliver-by deadline plus the host's function\n * timeout are the binding budget. Non-integration callers (CLI, normal\n * agent chat) should treat this as `false`.\n */\nexport function isIntegrationCallerRequest(): boolean {\n return als.getStore()?.isIntegrationCaller === true;\n}\n\nexport function getIntegrationRequestContext():\n | NonNullable<RequestContext[\"integration\"]>\n | undefined {\n return als.getStore()?.integration;\n}\n\n/**\n * Convenience: returns `{ userEmail, orgId }` from the active request context,\n * suitable for passing to `resolveCredential(key, ctx)`. Returns `null` when\n * no user is associated with the call (e.g. an unauthenticated public route).\n *\n * For framework actions auto-mounted at `/_agent-native/actions/...` this is\n * always populated because action-routes wraps every invocation in\n * `runWithRequestContext`. For hand-written `/api/*` routes the calling code\n * is responsible for setting up the context (see `runWithRequestContext`).\n */\nexport function getCredentialContext(): {\n userEmail: string;\n orgId: string | null;\n} | null {\n const userEmail = getRequestUserEmail();\n if (!userEmail) return null;\n return { userEmail, orgId: getRequestOrgId() ?? null };\n}\n\n/**\n * Get the active request's mutable agent-run state. Returns `undefined` when\n * called outside an agent run (e.g. before `prepareRun` or in a non-agent\n * code path). Callers must tolerate the field absence; use the helper\n * `requireRequestRunContext()` if missing context is a programming error.\n */\nexport function getRequestRunContext(): RequestRunContext | undefined {\n const store = als.getStore();\n if (!store) return undefined;\n return store.run;\n}\n\n/**\n * Ensure a `RequestRunContext` exists on the active request store and\n * return it. Used by the agent-chat handler to attach run state once it\n * starts processing a chat request. Returns `undefined` if there is no\n * active request store (caller should not be invoking this outside ALS).\n */\nexport function ensureRequestRunContext(): RequestRunContext | undefined {\n const store = als.getStore();\n if (!store) return undefined;\n if (!store.run) store.run = {};\n return store.run;\n}\n"]}
1
+ {"version":3,"file":"request-context.js","sourceRoot":"","sources":["../../src/server/request-context.ts"],"names":[],"mappings":"AA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0BAA0B;IACxC,OAAO,GAAG,CAAC,QAAQ,EAAE,EAAE,mBAAmB,KAAK,IAAI,CAAC;AACtD,CAAC;AAED,MAAM,UAAU,4BAA4B;IAG1C,OAAO,GAAG,CAAC,QAAQ,EAAE,EAAE,WAAW,CAAC;AACrC,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,oBAAoB;IAIlC,MAAM,SAAS,GAAG,mBAAmB,EAAE,CAAC;IACxC,IAAI,CAAC,SAAS;QAAE,OAAO,IAAI,CAAC;IAC5B,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,eAAe,EAAE,IAAI,IAAI,EAAE,CAAC;AACzD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB;IAClC,MAAM,KAAK,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAC;IAC7B,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,KAAK,CAAC,GAAG,CAAC;AACnB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB;IACrC,MAAM,KAAK,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAC;IAC7B,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,IAAI,CAAC,KAAK,CAAC,GAAG;QAAE,KAAK,CAAC,GAAG,GAAG,EAAE,CAAC;IAC/B,OAAO,KAAK,CAAC,GAAG,CAAC;AACnB,CAAC","sourcesContent":["/**\n * Per-request context using AsyncLocalStorage.\n *\n * Replaces the unsafe pattern of mutating `process.env.AGENT_USER_EMAIL` /\n * `process.env.AGENT_ORG_ID` on every request. On Node.js (Netlify, self-hosted)\n * concurrent requests would overwrite each other's env vars. AsyncLocalStorage\n * gives each async call-chain its own isolated context.\n *\n * Supported on all deployment targets:\n * - Node.js (native)\n * - Cloudflare Workers (via nodejs_compat flag)\n * - Deno Deploy (via node:async_hooks compat)\n *\n * For CLI scripts that run outside a request context, the getters fall back to\n * process.env so existing `AGENT_USER_EMAIL=x pnpm action foo` invocations\n * continue to work.\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\n/**\n * Per-request agent-run state. Lives on `RequestContext.run` so the\n * agent-chat plugin can populate fields as the run progresses (owner,\n * resolved API key, system prompt, engine, model, threadId) without\n * mutating module-scope `let` bindings — those leak across concurrent\n * requests on a single Node.js process.\n *\n * Mutated in-place by `prepareRun`, `onEngineResolved`, `onRunStart` so\n * tool factory closures (automation, fetch, team, builder-browser) read\n * the live per-request value via `getRequestRunContext()`.\n */\nexport interface RequestRunContext {\n /** Origin of the current request (used by the builder-browser tool). */\n requestOrigin?: string;\n /** Resolved owner email (set by prepareRun). */\n owner?: string;\n /** Owner's active Anthropic API key (set by prepareRun). */\n userApiKey?: string;\n /** Thread ID for the current run (set by onRunStart). */\n threadId?: string;\n /** System prompt actually sent to the model for this run. */\n systemPrompt?: string;\n /** Engine instance for this run (set by onEngineResolved). */\n engine?: import(\"../agent/engine/types.js\").AgentEngine;\n /** Model name for this run (set by onEngineResolved). */\n model?: string;\n /** Tool calls made so far in the current agent loop. */\n toolCalls?: Array<{ name: string; input: unknown }>;\n /** Tool results returned so far in the current agent loop. */\n toolResults?: Array<{ name: string; content: string; isError: boolean }>;\n}\n\nexport interface RequestContext {\n userEmail?: string;\n userName?: string;\n orgId?: string;\n timezone?: string;\n /**\n * True when this request is being processed by an integration-platform\n * webhook (Slack, Telegram, etc.) where the function timeout is the\n * binding constraint. Code that calls slow remote APIs can use this to apply\n * tighter budgets on this path while leaving normal agent-chat callers\n * (5+ min budget) unaffected.\n */\n isIntegrationCaller?: boolean;\n /**\n * Metadata for the currently-processing integration task. This lets tools\n * that start long-running remote work persist a continuation that can update\n * the originating platform thread after the current function budget ends.\n */\n integration?: {\n taskId: string;\n attempts?: number;\n incoming: import(\"../integrations/types.js\").IncomingMessage;\n placeholderRef?: string;\n };\n /**\n * Mutable per-request agent-run state. Populated by the agent-chat plugin\n * during a run; tool closures dereference it on each invocation.\n */\n run?: RequestRunContext;\n}\n\nconst GLOBAL_KEY = \"__agentNativeRequestContextAls\" as const;\nconst OBSERVERS_KEY = \"__agentNativeRequestContextObservers\" as const;\ntype RequestContextObserver = (ctx: RequestContext) => void;\ntype GlobalWithRequestContext = typeof globalThis & {\n [GLOBAL_KEY]?: AsyncLocalStorage<RequestContext>;\n [OBSERVERS_KEY]?: RequestContextObserver[];\n};\nconst globalRef = globalThis as GlobalWithRequestContext;\nif (!globalRef[GLOBAL_KEY]) {\n globalRef[GLOBAL_KEY] = new AsyncLocalStorage<RequestContext>();\n}\nif (!globalRef[OBSERVERS_KEY]) {\n globalRef[OBSERVERS_KEY] = [];\n}\nconst als = globalRef[GLOBAL_KEY]!;\nconst observers = globalRef[OBSERVERS_KEY]!;\n\n/**\n * Register a callback fired every time `runWithRequestContext` enters a new\n * scope. The hook runs INSIDE the AsyncLocalStorage scope, so observability\n * helpers that read the current isolation scope (e.g. Sentry) attach to the\n * right per-request context.\n *\n * Returned function unregisters the observer. Observers must never throw —\n * any error is swallowed so a misbehaving observer can't break the request\n * path.\n */\nexport function addRequestContextObserver(\n observer: RequestContextObserver,\n): () => void {\n observers.push(observer);\n return () => {\n const i = observers.indexOf(observer);\n if (i !== -1) observers.splice(i, 1);\n };\n}\n\n/**\n * Run a callback within a per-request context. The context is available to all\n * async operations spawned from `fn` via `getRequestUserEmail()` / `getRequestOrgId()`.\n *\n * Any registered `addRequestContextObserver` callbacks fire inside the new\n * scope before `fn` runs, so observability code can pin user/org info onto\n * isolation-scoped backends (Sentry, OpenTelemetry, etc.).\n */\nexport function runWithRequestContext<T>(\n ctx: RequestContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return als.run(ctx, () => {\n if (observers.length > 0) {\n for (const obs of observers) {\n try {\n obs(ctx);\n } catch {\n // Observers must never break the request path.\n }\n }\n }\n return fn();\n });\n}\n\n/**\n * Return the active request context, if this call chain is running under one.\n *\n * This is intentionally distinct from `getRequestUserEmail()`: callers that\n * have an active context with no authenticated user must not fall through to\n * process-wide CLI fallbacks such as `AGENT_USER_EMAIL` or \"latest session\".\n */\nexport function getRequestContext(): RequestContext | undefined {\n return als.getStore();\n}\n\n/**\n * True when AsyncLocalStorage has an active context for this call chain.\n * Useful for helpers that support both HTTP requests and standalone CLI runs.\n */\nexport function hasRequestContext(): boolean {\n return als.getStore() !== undefined;\n}\n\n/**\n * Get the current request's user email.\n *\n * - If a request context exists (HTTP/A2A path), returns its `userEmail` —\n * even when that value is `undefined`. The env fallback MUST NOT fire here:\n * a stale process-wide `AGENT_USER_EMAIL` from a CLI run or previous bug\n * would leak into an unauthenticated A2A/API call (e.g. unsigned or API-key\n * modes where `runWithRequestContext({ userEmail: undefined })` is used).\n * - Only when there is NO request context (CLI scripts) do we fall back to\n * `process.env.AGENT_USER_EMAIL`.\n */\nexport function getRequestUserEmail(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) return store.userEmail;\n return process.env.AGENT_USER_EMAIL;\n}\n\n/**\n * Get the current request's display name, when the auth provider supplied one.\n *\n * The same request-context fallback rules as `getRequestUserEmail()` apply:\n * HTTP/A2A calls only read AsyncLocalStorage, while CLI scripts may opt in via\n * `AGENT_USER_NAME`.\n */\nexport function getRequestUserName(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) return store.userName;\n return process.env.AGENT_USER_NAME;\n}\n\n/**\n * Get the current request's org ID.\n *\n * Same store-aware semantics as `getRequestUserEmail()` — env fallback is\n * CLI-only, so a request that explicitly has no org doesn't inherit a stale\n * `process.env.AGENT_ORG_ID` from a prior request on the same Lambda instance.\n */\nexport function getRequestOrgId(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) return store.orgId;\n return process.env.AGENT_ORG_ID;\n}\n\n/**\n * Get the current request's IANA timezone (e.g. \"America/Los_Angeles\").\n * The UI sends this via the `x-user-timezone` header on every action call, and\n * the agent chat plugin propagates it into the request context so that\n * agent-initiated tool calls also see the user's timezone. Falls back to\n * `process.env.AGENT_USER_TIMEZONE` only for CLI scripts (no request context).\n */\nexport function getRequestTimezone(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) return store.timezone;\n return process.env.AGENT_USER_TIMEZONE;\n}\n\n/**\n * Returns true when this request is on an integration-platform path (Slack,\n * Telegram, etc.) — i.e. we're inside the integration plugin's processor\n * function and the platform's deliver-by deadline plus the host's function\n * timeout are the binding budget. Non-integration callers (CLI, normal\n * agent chat) should treat this as `false`.\n */\nexport function isIntegrationCallerRequest(): boolean {\n return als.getStore()?.isIntegrationCaller === true;\n}\n\nexport function getIntegrationRequestContext():\n | NonNullable<RequestContext[\"integration\"]>\n | undefined {\n return als.getStore()?.integration;\n}\n\n/**\n * Convenience: returns `{ userEmail, orgId }` from the active request context,\n * suitable for passing to `resolveCredential(key, ctx)`. Returns `null` when\n * no user is associated with the call (e.g. an unauthenticated public route).\n *\n * For framework actions auto-mounted at `/_agent-native/actions/...` this is\n * always populated because action-routes wraps every invocation in\n * `runWithRequestContext`. For hand-written `/api/*` routes the calling code\n * is responsible for setting up the context (see `runWithRequestContext`).\n */\nexport function getCredentialContext(): {\n userEmail: string;\n orgId: string | null;\n} | null {\n const userEmail = getRequestUserEmail();\n if (!userEmail) return null;\n return { userEmail, orgId: getRequestOrgId() ?? null };\n}\n\n/**\n * Get the active request's mutable agent-run state. Returns `undefined` when\n * called outside an agent run (e.g. before `prepareRun` or in a non-agent\n * code path). Callers must tolerate the field absence; use the helper\n * `requireRequestRunContext()` if missing context is a programming error.\n */\nexport function getRequestRunContext(): RequestRunContext | undefined {\n const store = als.getStore();\n if (!store) return undefined;\n return store.run;\n}\n\n/**\n * Ensure a `RequestRunContext` exists on the active request store and\n * return it. Used by the agent-chat handler to attach run state once it\n * starts processing a chat request. Returns `undefined` if there is no\n * active request store (caller should not be invoking this outside ALS).\n */\nexport function ensureRequestRunContext(): RequestRunContext | undefined {\n const store = als.getStore();\n if (!store) return undefined;\n if (!store.run) store.run = {};\n return store.run;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"terminal-plugin.d.ts","sourceRoot":"","sources":["../../src/terminal/terminal-plugin.ts"],"names":[],"mappings":"AA6DA,MAAM,WAAW,qBAAqB;IACpC,yEAAyE;IACzE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0FAA0F;IAC1F,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,oFAAoF;IACpF,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,yDAAyD;IACzD,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACtD;AASD,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,qBAA0B,IACxD,UAAU,GAAG,mBAiL5B;AAED,mDAAmD;AACnD,eAAO,MAAM,qBAAqB,aApLR,GAAG,kBAoL8B,CAAC"}
1
+ {"version":3,"file":"terminal-plugin.d.ts","sourceRoot":"","sources":["../../src/terminal/terminal-plugin.ts"],"names":[],"mappings":"AA6DA,MAAM,WAAW,qBAAqB;IACpC,yEAAyE;IACzE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0FAA0F;IAC1F,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,oFAAoF;IACpF,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,yDAAyD;IACzD,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACtD;AASD,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,qBAA0B,IACxD,UAAU,GAAG,mBAoL5B;AAED,mDAAmD;AACnD,eAAO,MAAM,qBAAqB,aAvLR,GAAG,kBAuL8B,CAAC"}
@@ -158,12 +158,13 @@ export function createTerminalPlugin(options = {}) {
158
158
  delete process.env.__AGENT_TERMINAL_RUNNING; // guard:allow-env-mutation — terminal subprocess boot failed, clearing boot-time sentinel so a later plugin retry can start cleanly
159
159
  // Distinguish "node-pty not installed" (expected when the user opts
160
160
  // out of the terminal feature) from real failures (port conflict,
161
- // native binding mismatch). Native deps are optional log as info
162
- // so the dev console isn't filled with red noise.
161
+ // native binding mismatch). Native deps are optional, so keep the
162
+ // default dev console quiet unless terminal debugging is enabled.
163
163
  const code = err?.code;
164
164
  const missingPty = code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
165
165
  if (missingPty) {
166
- if (!_ptyMissingLogged) {
166
+ if (!_ptyMissingLogged &&
167
+ (process.env.DEBUG || process.env.AGENT_TERMINAL_DEBUG === "1")) {
167
168
  console.log("[terminal] node-pty not installed — embedded terminal disabled. " +
168
169
  "Install with `pnpm add node-pty` to enable.");
169
170
  _ptyMissingLogged = true;
@@ -1 +1 @@
1
- {"version":3,"file":"terminal-plugin.js","sourceRoot":"","sources":["../../src/terminal/terminal-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,QAAQ,EACR,yBAAyB,GAC1B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C;;;;;;;;GAQG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,IAAI,CAAC;AAExC,6EAA6E;AAC7E,oEAAoE;AACpE,4EAA4E;AAC5E,0EAA0E;AAC1E,2EAA2E;AAC3E,uEAAuE;AACvE,sBAAsB;AACtB,CAAC,SAAS,yBAAyB;IACjC,IAAI,CAAC,aAAa,EAAE;QAAE,OAAO;IAC7B,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC3C,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,uBAAuB,CAAC,CAAC;QACpD,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACp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";\nimport { isNodeRuntime } from \"../shared/runtime.js\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { createRequire } from \"node:module\";\n/**\n * Nitro Plugin — Agent Terminal\n *\n * Starts a PTY WebSocket server alongside the app so the <AgentTerminal />\n * component can connect to a real CLI. Mounts a discovery endpoint at\n * /_agent-native/agent-terminal-info for the client component.\n *\n * Skips activation when running inside a frame (FRAME_PORT is set).\n */\n\nimport { defineEventHandler } from \"h3\";\n\n// ─── module-load self-heal: chmod node-pty's spawn-helper ─────────────────\n// pnpm can extract node-pty's prebuilds tarball without running the\n// post-install that chmods spawn-helper, leaving it as `-rw-r--r--` instead\n// of `-rwxr-xr-x`. Every PTY spawn then fails with `posix_spawnp failed`.\n// Run the fix synchronously at module load (static imports, sync fs calls)\n// so by the time ANY plugin worker starts spawning PTYs, the helper is\n// already executable.\n(function fixSpawnHelperPermissions() {\n if (!isNodeRuntime()) return;\n try {\n const req = createRequire(import.meta.url);\n const ptyPkg = req.resolve(\"node-pty/package.json\");\n const ptyDir = path.dirname(ptyPkg);\n const helper = path.join(\n ptyDir,\n \"prebuilds\",\n `${process.platform}-${process.arch}`,\n \"spawn-helper\",\n );\n if (fs.existsSync(helper)) {\n const mode = fs.statSync(helper).mode;\n if (!(mode & 0o100)) {\n fs.chmodSync(helper, 0o755);\n console.log(\n `[terminal] Fixed non-executable node-pty spawn-helper at ${helper}`,\n );\n }\n }\n } catch (err) {\n // node-pty not installed → stay silent here; createTerminalPlugin emits\n // the \"install node-pty\" message when the PTY server actually fails to\n // start. Logging twice for the same root cause just adds noise.\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code === \"MODULE_NOT_FOUND\" || code === \"ERR_MODULE_NOT_FOUND\") return;\n console.warn(\n \"[terminal] Could not verify node-pty spawn-helper permissions:\",\n (err as Error).message,\n );\n }\n})();\n\nexport interface TerminalPluginOptions {\n /** CLI command to run. Defaults to AGENT_CLI_COMMAND env or 'builder' */\n command?: string;\n /** Port for the WebSocket server. Defaults to AGENT_TERMINAL_PORT env or auto-assigned */\n port?: number;\n /** Enable in production. Defaults to AGENT_TERMINAL_ENABLED env or false in prod */\n enabledInProduction?: boolean;\n /** Auth check for WebSocket connections in production */\n authCheck?: (req: any) => boolean | Promise<boolean>;\n}\n\n// Vite's dev server can initialize Nitro plugins more than once during boot.\n// Module-scope flags ensure the \"node-pty not installed\" / \"Disabled in\n// production\" / \"Frame detected\" notices each fire at most once per process.\nlet _ptyMissingLogged = false;\nlet _disabledLogged = false;\nlet _frameDetectedLogged = false;\n\nexport function createTerminalPlugin(options: TerminalPluginOptions = {}) {\n return async (nitroApp: any) => {\n markDefaultPluginProvided(nitroApp, \"terminal\");\n // Terminal requires Node.js (PTY, child_process) — skip on edge runtimes\n if (!isNodeRuntime()) return;\n\n // Always mount /_agent-native/available-clis so the client doesn't get 404s\n getH3App(nitroApp).use(\n \"/_agent-native/available-clis\",\n defineEventHandler(async () => {\n try {\n const { CLI_REGISTRY, commandExists } =\n await import(\"./cli-registry.js\");\n const results = [];\n for (const [cmd, entry] of Object.entries(CLI_REGISTRY)) {\n results.push({\n command: cmd,\n label: entry.label,\n available: await commandExists(cmd),\n });\n }\n return results;\n } catch {\n return [];\n }\n }),\n );\n\n // Skip if running inside a frame\n if (process.env.FRAME_PORT) {\n if (!_frameDetectedLogged) {\n console.log(\"[terminal] Frame detected, skipping embedded terminal\");\n _frameDetectedLogged = true;\n }\n return;\n }\n\n const isProd = process.env.NODE_ENV === \"production\";\n const enabled =\n options.enabledInProduction ??\n (process.env.AGENT_TERMINAL_ENABLED === \"true\" || !isProd);\n\n if (!enabled) {\n if (!_disabledLogged) {\n console.log(\n \"[terminal] Disabled in production (set AGENT_TERMINAL_ENABLED=true to enable)\",\n );\n _disabledLogged = true;\n }\n // Mount a disabled info endpoint\n getH3App(nitroApp).use(\n \"/_agent-native/agent-terminal-info\",\n defineEventHandler(() => ({ available: false })),\n );\n return;\n }\n\n // Require authCheck in production to prevent unauthenticated shell access\n if (isProd && !options.authCheck) {\n console.error(\n \"[terminal] FATAL: authCheck is required when enabling the terminal in production. \" +\n \"Pass an authCheck function to createTerminalPlugin().\",\n );\n getH3App(nitroApp).use(\n \"/_agent-native/agent-terminal-info\",\n defineEventHandler(() => ({\n available: false,\n error: \"Terminal requires authCheck in production\",\n })),\n );\n return;\n }\n\n // Skip if a PTY server is already running (prevents leak on HMR rebuild)\n if (process.env.__AGENT_TERMINAL_RUNNING === \"true\") {\n const existingPort = process.env.AGENT_TERMINAL_PORT;\n console.log(\n `[terminal] PTY server already running on port ${existingPort}, skipping`,\n );\n getH3App(nitroApp).use(\n \"/_agent-native/agent-terminal-info\",\n defineEventHandler(() => ({\n available: true,\n wsPort: existingPort ? parseInt(existingPort, 10) : 0,\n command:\n options.command || process.env.AGENT_CLI_COMMAND || \"builder\",\n })),\n );\n return;\n }\n\n const command =\n options.command || process.env.AGENT_CLI_COMMAND || \"builder\";\n const port =\n options.port ??\n (process.env.AGENT_TERMINAL_PORT\n ? parseInt(process.env.AGENT_TERMINAL_PORT, 10)\n : 0);\n\n // Mark as running BEFORE the async server start. The previous code only\n // set this AFTER `await createPtyWebSocketServer(...)`, which left a\n // TOCTOU window where two concurrent plugin invocations would both pass\n // the running-check, both spawn a server, and end up fighting for the\n // CLI's PTY pool — leading to `posix_spawnp failed` floods.\n process.env.__AGENT_TERMINAL_RUNNING = \"true\"; // guard:allow-env-mutation — process-wide running flag set once at boot, before any HTTP request handling, to coordinate concurrent plugin invocations\n\n try {\n const { createPtyWebSocketServer } = await import(\"./pty-server.js\");\n\n const result = await createPtyWebSocketServer({\n appDir: process.cwd(),\n command,\n port,\n authCheck: isProd ? options.authCheck : undefined,\n logPrefix: \"[terminal]\",\n });\n\n // Store port for other consumers\n process.env.AGENT_TERMINAL_PORT = String(result.port); // guard:allow-env-mutation — terminal subprocess port published once at boot, not per-request\n\n // Mount discovery endpoint\n getH3App(nitroApp).use(\n \"/_agent-native/agent-terminal-info\",\n defineEventHandler(() => ({\n available: true,\n wsPort: result.port,\n command,\n })),\n );\n\n // Cleanup on shutdown (use once to avoid listener leak on hot-reload)\n const cleanup = () => result.close();\n process.once(\"SIGTERM\", cleanup);\n process.once(\"SIGINT\", cleanup);\n process.once(\"exit\", cleanup);\n\n if (process.env.DEBUG)\n console.log(\n `[terminal] Agent terminal ready (command: ${command}, port: ${result.port})`,\n );\n } catch (err) {\n // Clear the running flag so a retry can spawn a fresh server\n delete process.env.__AGENT_TERMINAL_RUNNING; // guard:allow-env-mutation — terminal subprocess boot failed, clearing boot-time sentinel so a later plugin retry can start cleanly\n\n // Distinguish \"node-pty not installed\" (expected when the user opts\n // out of the terminal feature) from real failures (port conflict,\n // native binding mismatch). Native deps are optional — log as info\n // so the dev console isn't filled with red noise.\n const code = (err as NodeJS.ErrnoException)?.code;\n const missingPty =\n code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\";\n if (missingPty) {\n if (!_ptyMissingLogged) {\n console.log(\n \"[terminal] node-pty not installed — embedded terminal disabled. \" +\n \"Install with `pnpm add node-pty` to enable.\",\n );\n _ptyMissingLogged = true;\n }\n } else {\n console.error(\"[terminal] Failed to start PTY server:\", err);\n console.error(\n \"[terminal] If node-pty is installed but PTY fails to spawn, \" +\n \"try `pnpm rebuild node-pty` (common after switching Node \" +\n \"versions via fnm/nvm).\",\n );\n }\n\n // Mount a fallback info endpoint\n getH3App(nitroApp).use(\n \"/_agent-native/agent-terminal-info\",\n defineEventHandler(() => ({\n available: false,\n error: missingPty ? \"node-pty not installed\" : \"PTY server failed\",\n })),\n );\n }\n };\n}\n\n/** Pre-configured terminal plugin with defaults */\nexport const defaultTerminalPlugin = createTerminalPlugin();\n"]}
1
+ {"version":3,"file":"terminal-plugin.js","sourceRoot":"","sources":["../../src/terminal/terminal-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,QAAQ,EACR,yBAAyB,GAC1B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,s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,CAAC;oBACD,OAAO,CAAC,GAAG,CACT,kEAAkE;wBAChE,6CAA6C,CAChD,CAAC;oBACF,iBAAiB,GAAG,IAAI,CAAC;gBAC3B,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,KAAK,CAAC,wCAAwC,EAAE,GAAG,CAAC,CAAC;gBAC7D,OAAO,CAAC,KAAK,CACX,8DAA8D;oBAC5D,2DAA2D;oBAC3D,wBAAwB,CAC3B,CAAC;YACJ,CAAC;YAED,iCAAiC;YACjC,QAAQ,CAAC,QAAQ,CAAC,CAAC,GAAG,CACpB,oCAAoC,EACpC,kBAAkB,CAAC,GAAG,EAAE,CAAC,CAAC;gBACxB,SAAS,EAAE,KAAK;gBAChB,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,mBAAmB;aACnE,CAAC,CAAC,CACJ,CAAC;QACJ,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAED,mDAAmD;AACnD,MAAM,CAAC,MAAM,qBAAqB,GAAG,oBAAoB,EAAE,CAAC","sourcesContent":["import {\n getH3App,\n markDefaultPluginProvided,\n} from \"../server/framework-request-handler.js\";\nimport { isNodeRuntime } from \"../shared/runtime.js\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { createRequire } from \"node:module\";\n/**\n * Nitro Plugin — Agent Terminal\n *\n * Starts a PTY WebSocket server alongside the app so the <AgentTerminal />\n * component can connect to a real CLI. Mounts a discovery endpoint at\n * /_agent-native/agent-terminal-info for the client component.\n *\n * Skips activation when running inside a frame (FRAME_PORT is set).\n */\n\nimport { defineEventHandler } from \"h3\";\n\n// ─── module-load self-heal: chmod node-pty's spawn-helper ─────────────────\n// pnpm can extract node-pty's prebuilds tarball without running the\n// post-install that chmods spawn-helper, leaving it as `-rw-r--r--` instead\n// of `-rwxr-xr-x`. Every PTY spawn then fails with `posix_spawnp failed`.\n// Run the fix synchronously at module load (static imports, sync fs calls)\n// so by the time ANY plugin worker starts spawning PTYs, the helper is\n// already executable.\n(function fixSpawnHelperPermissions() {\n if (!isNodeRuntime()) return;\n try {\n const req = createRequire(import.meta.url);\n const ptyPkg = req.resolve(\"node-pty/package.json\");\n const ptyDir = path.dirname(ptyPkg);\n const helper = path.join(\n ptyDir,\n \"prebuilds\",\n `${process.platform}-${process.arch}`,\n \"spawn-helper\",\n );\n if (fs.existsSync(helper)) {\n const mode = fs.statSync(helper).mode;\n if (!(mode & 0o100)) {\n fs.chmodSync(helper, 0o755);\n console.log(\n `[terminal] Fixed non-executable node-pty spawn-helper at ${helper}`,\n );\n }\n }\n } catch (err) {\n // node-pty not installed → stay silent here; createTerminalPlugin emits\n // the \"install node-pty\" message when the PTY server actually fails to\n // start. Logging twice for the same root cause just adds noise.\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code === \"MODULE_NOT_FOUND\" || code === \"ERR_MODULE_NOT_FOUND\") return;\n console.warn(\n \"[terminal] Could not verify node-pty spawn-helper permissions:\",\n (err as Error).message,\n );\n }\n})();\n\nexport interface TerminalPluginOptions {\n /** CLI command to run. Defaults to AGENT_CLI_COMMAND env or 'builder' */\n command?: string;\n /** Port for the WebSocket server. Defaults to AGENT_TERMINAL_PORT env or auto-assigned */\n port?: number;\n /** Enable in production. Defaults to AGENT_TERMINAL_ENABLED env or false in prod */\n enabledInProduction?: boolean;\n /** Auth check for WebSocket connections in production */\n authCheck?: (req: any) => boolean | Promise<boolean>;\n}\n\n// Vite's dev server can initialize Nitro plugins more than once during boot.\n// Module-scope flags ensure the \"node-pty not installed\" / \"Disabled in\n// production\" / \"Frame detected\" notices each fire at most once per process.\nlet _ptyMissingLogged = false;\nlet _disabledLogged = false;\nlet _frameDetectedLogged = false;\n\nexport function createTerminalPlugin(options: TerminalPluginOptions = {}) {\n return async (nitroApp: any) => {\n markDefaultPluginProvided(nitroApp, \"terminal\");\n // Terminal requires Node.js (PTY, child_process) — skip on edge runtimes\n if (!isNodeRuntime()) return;\n\n // Always mount /_agent-native/available-clis so the client doesn't get 404s\n getH3App(nitroApp).use(\n \"/_agent-native/available-clis\",\n defineEventHandler(async () => {\n try {\n const { CLI_REGISTRY, commandExists } =\n await import(\"./cli-registry.js\");\n const results = [];\n for (const [cmd, entry] of Object.entries(CLI_REGISTRY)) {\n results.push({\n command: cmd,\n label: entry.label,\n available: await commandExists(cmd),\n });\n }\n return results;\n } catch {\n return [];\n }\n }),\n );\n\n // Skip if running inside a frame\n if (process.env.FRAME_PORT) {\n if (!_frameDetectedLogged) {\n console.log(\"[terminal] Frame detected, skipping embedded terminal\");\n _frameDetectedLogged = true;\n }\n return;\n }\n\n const isProd = process.env.NODE_ENV === \"production\";\n const enabled =\n options.enabledInProduction ??\n (process.env.AGENT_TERMINAL_ENABLED === \"true\" || !isProd);\n\n if (!enabled) {\n if (!_disabledLogged) {\n console.log(\n \"[terminal] Disabled in production (set AGENT_TERMINAL_ENABLED=true to enable)\",\n );\n _disabledLogged = true;\n }\n // Mount a disabled info endpoint\n getH3App(nitroApp).use(\n \"/_agent-native/agent-terminal-info\",\n defineEventHandler(() => ({ available: false })),\n );\n return;\n }\n\n // Require authCheck in production to prevent unauthenticated shell access\n if (isProd && !options.authCheck) {\n console.error(\n \"[terminal] FATAL: authCheck is required when enabling the terminal in production. \" +\n \"Pass an authCheck function to createTerminalPlugin().\",\n );\n getH3App(nitroApp).use(\n \"/_agent-native/agent-terminal-info\",\n defineEventHandler(() => ({\n available: false,\n error: \"Terminal requires authCheck in production\",\n })),\n );\n return;\n }\n\n // Skip if a PTY server is already running (prevents leak on HMR rebuild)\n if (process.env.__AGENT_TERMINAL_RUNNING === \"true\") {\n const existingPort = process.env.AGENT_TERMINAL_PORT;\n console.log(\n `[terminal] PTY server already running on port ${existingPort}, skipping`,\n );\n getH3App(nitroApp).use(\n \"/_agent-native/agent-terminal-info\",\n defineEventHandler(() => ({\n available: true,\n wsPort: existingPort ? parseInt(existingPort, 10) : 0,\n command:\n options.command || process.env.AGENT_CLI_COMMAND || \"builder\",\n })),\n );\n return;\n }\n\n const command =\n options.command || process.env.AGENT_CLI_COMMAND || \"builder\";\n const port =\n options.port ??\n (process.env.AGENT_TERMINAL_PORT\n ? parseInt(process.env.AGENT_TERMINAL_PORT, 10)\n : 0);\n\n // Mark as running BEFORE the async server start. The previous code only\n // set this AFTER `await createPtyWebSocketServer(...)`, which left a\n // TOCTOU window where two concurrent plugin invocations would both pass\n // the running-check, both spawn a server, and end up fighting for the\n // CLI's PTY pool — leading to `posix_spawnp failed` floods.\n process.env.__AGENT_TERMINAL_RUNNING = \"true\"; // guard:allow-env-mutation — process-wide running flag set once at boot, before any HTTP request handling, to coordinate concurrent plugin invocations\n\n try {\n const { createPtyWebSocketServer } = await import(\"./pty-server.js\");\n\n const result = await createPtyWebSocketServer({\n appDir: process.cwd(),\n command,\n port,\n authCheck: isProd ? options.authCheck : undefined,\n logPrefix: \"[terminal]\",\n });\n\n // Store port for other consumers\n process.env.AGENT_TERMINAL_PORT = String(result.port); // guard:allow-env-mutation — terminal subprocess port published once at boot, not per-request\n\n // Mount discovery endpoint\n getH3App(nitroApp).use(\n \"/_agent-native/agent-terminal-info\",\n defineEventHandler(() => ({\n available: true,\n wsPort: result.port,\n command,\n })),\n );\n\n // Cleanup on shutdown (use once to avoid listener leak on hot-reload)\n const cleanup = () => result.close();\n process.once(\"SIGTERM\", cleanup);\n process.once(\"SIGINT\", cleanup);\n process.once(\"exit\", cleanup);\n\n if (process.env.DEBUG)\n console.log(\n `[terminal] Agent terminal ready (command: ${command}, port: ${result.port})`,\n );\n } catch (err) {\n // Clear the running flag so a retry can spawn a fresh server\n delete process.env.__AGENT_TERMINAL_RUNNING; // guard:allow-env-mutation — terminal subprocess boot failed, clearing boot-time sentinel so a later plugin retry can start cleanly\n\n // Distinguish \"node-pty not installed\" (expected when the user opts\n // out of the terminal feature) from real failures (port conflict,\n // native binding mismatch). Native deps are optional, so keep the\n // default dev console quiet unless terminal debugging is enabled.\n const code = (err as NodeJS.ErrnoException)?.code;\n const missingPty =\n code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\";\n if (missingPty) {\n if (\n !_ptyMissingLogged &&\n (process.env.DEBUG || process.env.AGENT_TERMINAL_DEBUG === \"1\")\n ) {\n console.log(\n \"[terminal] node-pty not installed — embedded terminal disabled. \" +\n \"Install with `pnpm add node-pty` to enable.\",\n );\n _ptyMissingLogged = true;\n }\n } else {\n console.error(\"[terminal] Failed to start PTY server:\", err);\n console.error(\n \"[terminal] If node-pty is installed but PTY fails to spawn, \" +\n \"try `pnpm rebuild node-pty` (common after switching Node \" +\n \"versions via fnm/nvm).\",\n );\n }\n\n // Mount a fallback info endpoint\n getH3App(nitroApp).use(\n \"/_agent-native/agent-terminal-info\",\n defineEventHandler(() => ({\n available: false,\n error: missingPty ? \"node-pty not installed\" : \"PTY server failed\",\n })),\n );\n }\n };\n}\n\n/** Pre-configured terminal plugin with defaults */\nexport const defaultTerminalPlugin = createTerminalPlugin();\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.12.22",
3
+ "version": "0.12.24",
4
4
  "type": "module",
5
5
  "description": "Framework for agent-native application development — where AI agents and UI share state via files",
6
6
  "license": "MIT",