@agent-native/core 0.7.50 → 0.7.52

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 (121) hide show
  1. package/dist/a2a/agent-card.d.ts.map +1 -1
  2. package/dist/a2a/agent-card.js +21 -16
  3. package/dist/a2a/agent-card.js.map +1 -1
  4. package/dist/a2a/artifact-response.d.ts.map +1 -1
  5. package/dist/a2a/artifact-response.js +109 -5
  6. package/dist/a2a/artifact-response.js.map +1 -1
  7. package/dist/a2a/auth-policy.d.ts +10 -0
  8. package/dist/a2a/auth-policy.d.ts.map +1 -0
  9. package/dist/a2a/auth-policy.js +34 -0
  10. package/dist/a2a/auth-policy.js.map +1 -0
  11. package/dist/a2a/handlers.d.ts.map +1 -1
  12. package/dist/a2a/handlers.js +5 -4
  13. package/dist/a2a/handlers.js.map +1 -1
  14. package/dist/a2a/index.d.ts +1 -0
  15. package/dist/a2a/index.d.ts.map +1 -1
  16. package/dist/a2a/index.js +1 -0
  17. package/dist/a2a/index.js.map +1 -1
  18. package/dist/a2a/server.d.ts.map +1 -1
  19. package/dist/a2a/server.js +27 -14
  20. package/dist/a2a/server.js.map +1 -1
  21. package/dist/client/resources/ResourceEditor.d.ts.map +1 -1
  22. package/dist/client/resources/ResourceEditor.js +2 -4
  23. package/dist/client/resources/ResourceEditor.js.map +1 -1
  24. package/dist/client/settings/AgentsSection.d.ts.map +1 -1
  25. package/dist/client/settings/AgentsSection.js +4 -6
  26. package/dist/client/settings/AgentsSection.js.map +1 -1
  27. package/dist/deploy/build.d.ts.map +1 -1
  28. package/dist/deploy/build.js +8 -0
  29. package/dist/deploy/build.js.map +1 -1
  30. package/dist/deploy/route-discovery.d.ts.map +1 -1
  31. package/dist/deploy/route-discovery.js +11 -2
  32. package/dist/deploy/route-discovery.js.map +1 -1
  33. package/dist/deploy/workspace-deploy.js +32 -3
  34. package/dist/deploy/workspace-deploy.js.map +1 -1
  35. package/dist/integrations/a2a-continuation-processor.d.ts.map +1 -1
  36. package/dist/integrations/a2a-continuation-processor.js +17 -11
  37. package/dist/integrations/a2a-continuation-processor.js.map +1 -1
  38. package/dist/integrations/a2a-continuations-store.d.ts +2 -1
  39. package/dist/integrations/a2a-continuations-store.d.ts.map +1 -1
  40. package/dist/integrations/a2a-continuations-store.js +33 -4
  41. package/dist/integrations/a2a-continuations-store.js.map +1 -1
  42. package/dist/integrations/plugin.d.ts.map +1 -1
  43. package/dist/integrations/plugin.js +2 -1
  44. package/dist/integrations/plugin.js.map +1 -1
  45. package/dist/integrations/webhook-handler.d.ts.map +1 -1
  46. package/dist/integrations/webhook-handler.js +11 -1
  47. package/dist/integrations/webhook-handler.js.map +1 -1
  48. package/dist/onboarding/plugin.d.ts.map +1 -1
  49. package/dist/onboarding/plugin.js +2 -1
  50. package/dist/onboarding/plugin.js.map +1 -1
  51. package/dist/org/plugin.d.ts.map +1 -1
  52. package/dist/org/plugin.js +2 -1
  53. package/dist/org/plugin.js.map +1 -1
  54. package/dist/resources/handlers.d.ts.map +1 -1
  55. package/dist/resources/handlers.js +2 -3
  56. package/dist/resources/handlers.js.map +1 -1
  57. package/dist/resources/metadata.d.ts +5 -0
  58. package/dist/resources/metadata.d.ts.map +1 -1
  59. package/dist/resources/metadata.js +17 -2
  60. package/dist/resources/metadata.js.map +1 -1
  61. package/dist/resources/store.d.ts.map +1 -1
  62. package/dist/resources/store.js +2 -1
  63. package/dist/resources/store.js.map +1 -1
  64. package/dist/scripts/call-agent.js +2 -2
  65. package/dist/scripts/call-agent.js.map +1 -1
  66. package/dist/server/action-routes.d.ts.map +1 -1
  67. package/dist/server/action-routes.js +5 -11
  68. package/dist/server/action-routes.js.map +1 -1
  69. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  70. package/dist/server/agent-chat-plugin.js +2 -1
  71. package/dist/server/agent-chat-plugin.js.map +1 -1
  72. package/dist/server/agent-discovery.d.ts.map +1 -1
  73. package/dist/server/agent-discovery.js +7 -4
  74. package/dist/server/agent-discovery.js.map +1 -1
  75. package/dist/server/auth-plugin.d.ts.map +1 -1
  76. package/dist/server/auth-plugin.js +2 -1
  77. package/dist/server/auth-plugin.js.map +1 -1
  78. package/dist/server/auth.d.ts.map +1 -1
  79. package/dist/server/auth.js +13 -12
  80. package/dist/server/auth.js.map +1 -1
  81. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  82. package/dist/server/core-routes-plugin.js +9 -29
  83. package/dist/server/core-routes-plugin.js.map +1 -1
  84. package/dist/server/cors-origins.d.ts +10 -0
  85. package/dist/server/cors-origins.d.ts.map +1 -0
  86. package/dist/server/cors-origins.js +34 -0
  87. package/dist/server/cors-origins.js.map +1 -0
  88. package/dist/server/create-server.d.ts.map +1 -1
  89. package/dist/server/create-server.js +10 -29
  90. package/dist/server/create-server.js.map +1 -1
  91. package/dist/server/framework-request-handler.d.ts +11 -0
  92. package/dist/server/framework-request-handler.d.ts.map +1 -1
  93. package/dist/server/framework-request-handler.js +24 -1
  94. package/dist/server/framework-request-handler.js.map +1 -1
  95. package/dist/server/resources-plugin.d.ts.map +1 -1
  96. package/dist/server/resources-plugin.js +2 -1
  97. package/dist/server/resources-plugin.js.map +1 -1
  98. package/dist/terminal/terminal-plugin.d.ts.map +1 -1
  99. package/dist/terminal/terminal-plugin.js +2 -1
  100. package/dist/terminal/terminal-plugin.js.map +1 -1
  101. package/dist/vite/index.d.ts +1 -1
  102. package/dist/vite/index.d.ts.map +1 -1
  103. package/dist/vite/index.js +1 -1
  104. package/dist/vite/index.js.map +1 -1
  105. package/docs/content/a2a-protocol.md +75 -6
  106. package/docs/content/creating-templates.md +10 -0
  107. package/docs/content/dispatch.md +94 -0
  108. package/docs/content/getting-started.md +8 -0
  109. package/docs/content/key-concepts.md +16 -0
  110. package/docs/content/messaging.md +45 -13
  111. package/docs/content/multi-app-workspace.md +10 -2
  112. package/docs/content/notifications.md +1 -1
  113. package/docs/content/observability.md +184 -0
  114. package/docs/content/onboarding.md +7 -2
  115. package/docs/content/template-dispatch.md +3 -1
  116. package/docs/content/tools.md +95 -1
  117. package/docs/content/tracking.md +1 -1
  118. package/docs/content/what-is-agent-native.md +3 -1
  119. package/docs/content/workspace-management.md +5 -5
  120. package/docs/content/workspace.md +2 -0
  121. package/package.json +1 -1
@@ -0,0 +1,10 @@
1
+ export interface CorsOriginOptions {
2
+ allowedOrigins?: string[];
3
+ allowAnyOriginWhenNoAllowlist?: boolean;
4
+ allowLocalhostWhenNoAllowlist?: boolean;
5
+ }
6
+ export declare function readCorsAllowedOrigins(): string[];
7
+ export declare function isTrustedNativeAppOrigin(origin: string): boolean;
8
+ export declare function isLocalhostOrigin(origin: string): boolean;
9
+ export declare function getAllowedCorsOrigin(origin: string | undefined, options?: CorsOriginOptions): string | null;
10
+ //# sourceMappingURL=cors-origins.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cors-origins.d.ts","sourceRoot":"","sources":["../../src/server/cors-origins.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,iBAAiB;IAChC,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,6BAA6B,CAAC,EAAE,OAAO,CAAC;IACxC,6BAA6B,CAAC,EAAE,OAAO,CAAC;CACzC;AAED,wBAAgB,sBAAsB,IAAI,MAAM,EAAE,CAKjD;AAED,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAEhE;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAEzD;AAED,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,GAAE,iBAAsB,GAC9B,MAAM,GAAG,IAAI,CAoBf"}
@@ -0,0 +1,34 @@
1
+ const LOCALHOST_ORIGIN_RE = /^https?:\/\/(localhost|127\.0\.0\.1|tauri\.localhost)(:\d+)?$/;
2
+ const NATIVE_APP_ORIGIN_RE = /^(tauri:\/\/(localhost|tauri\.localhost)|https?:\/\/tauri\.localhost(:\d+)?)$/;
3
+ export function readCorsAllowedOrigins() {
4
+ return (process.env.CORS_ALLOWED_ORIGINS ?? "")
5
+ .split(",")
6
+ .map((s) => s.trim())
7
+ .filter(Boolean);
8
+ }
9
+ export function isTrustedNativeAppOrigin(origin) {
10
+ return NATIVE_APP_ORIGIN_RE.test(origin);
11
+ }
12
+ export function isLocalhostOrigin(origin) {
13
+ return LOCALHOST_ORIGIN_RE.test(origin);
14
+ }
15
+ export function getAllowedCorsOrigin(origin, options = {}) {
16
+ if (!origin)
17
+ return null;
18
+ // Tauri's production WebView uses a private app origin. It is not a
19
+ // deploy-configured website origin, so keep it reachable even when an app
20
+ // also has CORS_ALLOWED_ORIGINS for browser embeds or previews.
21
+ if (isTrustedNativeAppOrigin(origin))
22
+ return origin;
23
+ const allowedOrigins = options.allowedOrigins ?? readCorsAllowedOrigins();
24
+ if (allowedOrigins.length > 0) {
25
+ return allowedOrigins.includes(origin) ? origin : null;
26
+ }
27
+ if (options.allowAnyOriginWhenNoAllowlist)
28
+ return origin;
29
+ if (options.allowLocalhostWhenNoAllowlist !== false) {
30
+ return isLocalhostOrigin(origin) ? origin : null;
31
+ }
32
+ return null;
33
+ }
34
+ //# sourceMappingURL=cors-origins.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cors-origins.js","sourceRoot":"","sources":["../../src/server/cors-origins.ts"],"names":[],"mappings":"AAAA,MAAM,mBAAmB,GACvB,+DAA+D,CAAC;AAElE,MAAM,oBAAoB,GACxB,+EAA+E,CAAC;AAQlF,MAAM,UAAU,sBAAsB;IACpC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,EAAE,CAAC;SAC5C,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;SACpB,MAAM,CAAC,OAAO,CAAC,CAAC;AACrB,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,MAAc;IACrD,OAAO,oBAAoB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,MAAc;IAC9C,OAAO,mBAAmB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC1C,CAAC;AAED,MAAM,UAAU,oBAAoB,CAClC,MAA0B,EAC1B,UAA6B,EAAE;IAE/B,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IAEzB,oEAAoE;IACpE,0EAA0E;IAC1E,gEAAgE;IAChE,IAAI,wBAAwB,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAC;IAEpD,MAAM,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,sBAAsB,EAAE,CAAC;IAC1E,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9B,OAAO,cAAc,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;IACzD,CAAC;IAED,IAAI,OAAO,CAAC,6BAA6B;QAAE,OAAO,MAAM,CAAC;IAEzD,IAAI,OAAO,CAAC,6BAA6B,KAAK,KAAK,EAAE,CAAC;QACpD,OAAO,iBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;IACnD,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["const LOCALHOST_ORIGIN_RE =\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|tauri\\.localhost)(:\\d+)?$/;\n\nconst NATIVE_APP_ORIGIN_RE =\n /^(tauri:\\/\\/(localhost|tauri\\.localhost)|https?:\\/\\/tauri\\.localhost(:\\d+)?)$/;\n\nexport interface CorsOriginOptions {\n allowedOrigins?: string[];\n allowAnyOriginWhenNoAllowlist?: boolean;\n allowLocalhostWhenNoAllowlist?: boolean;\n}\n\nexport function readCorsAllowedOrigins(): string[] {\n return (process.env.CORS_ALLOWED_ORIGINS ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n}\n\nexport function isTrustedNativeAppOrigin(origin: string): boolean {\n return NATIVE_APP_ORIGIN_RE.test(origin);\n}\n\nexport function isLocalhostOrigin(origin: string): boolean {\n return LOCALHOST_ORIGIN_RE.test(origin);\n}\n\nexport function getAllowedCorsOrigin(\n origin: string | undefined,\n options: CorsOriginOptions = {},\n): string | null {\n if (!origin) return null;\n\n // Tauri's production WebView uses a private app origin. It is not a\n // deploy-configured website origin, so keep it reachable even when an app\n // also has CORS_ALLOWED_ORIGINS for browser embeds or previews.\n if (isTrustedNativeAppOrigin(origin)) return origin;\n\n const allowedOrigins = options.allowedOrigins ?? readCorsAllowedOrigins();\n if (allowedOrigins.length > 0) {\n return allowedOrigins.includes(origin) ? origin : null;\n }\n\n if (options.allowAnyOriginWhenNoAllowlist) return origin;\n\n if (options.allowLocalhostWhenNoAllowlist !== false) {\n return isLocalhostOrigin(origin) ? origin : null;\n }\n\n return null;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"create-server.d.ts","sourceRoot":"","sources":["../../src/server/create-server.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,YAAY,EAOb,MAAM,IAAI,CAAC;AAMZ,MAAM,WAAW,YAAY;IAC3B,8DAA8D;IAC9D,GAAG,EAAE,MAAM,CAAC;IACZ,4CAA4C;IAC5C,KAAK,EAAE,MAAM,CAAC;IACd,2DAA2D;IAC3D,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,oFAAoF;IACpF,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,mBAAmB;IAClC,gFAAgF;IAChF,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,KAAK,CAAC;IACvC,6EAA6E;IAC7E,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,qFAAqF;IACrF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mEAAm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AEG;AACH,wBAAsB,aAAa,CACjC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,KAAK,CAAC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,GAC1C,OAAO,CAAC,IAAI,CAAC,CAoDf;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,UAAU,CAAC,OAAO,SAAS,CAAC,CAAC;IAClC,MAAM,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC;CACzC;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,OAAO,GAAE,mBAAwB,GAChC,kBAAkB,CA8KpB"}
@@ -2,6 +2,7 @@ import { createApp, createRouter, defineEventHandler, getMethod, getRequestHeade
2
2
  import path from "path";
3
3
  import { agentEnv } from "../shared/agent-env.js";
4
4
  import { readBody } from "../server/h3-helpers.js";
5
+ import { getAllowedCorsOrigin, readCorsAllowedOrigins, } from "./cors-origins.js";
5
6
  import { isEnvVarWriteAllowed } from "./env-var-writes.js";
6
7
  /**
7
8
  * Parse a .env file into key-value pairs, preserving comments and empty lines for roundtrip.
@@ -101,17 +102,13 @@ export function createServer(options = {}) {
101
102
  });
102
103
  // CORS middleware
103
104
  if (options.cors !== false) {
104
- const allowedOrigins = process.env.CORS_ALLOWED_ORIGINS
105
- ? process.env.CORS_ALLOWED_ORIGINS.split(",").map((o) => o.trim())
106
- : null;
105
+ const allowedOrigins = readCorsAllowedOrigins();
107
106
  const isProduction = process.env.NODE_ENV === "production";
108
107
  /**
109
- * Localhost-style origins that we treat as same-trust in development.
110
- * When CORS_ALLOWED_ORIGINS is unset we still allow these (desktop tray
111
- * windows on a sibling port, the docs site at localhost:5173, etc.) but
112
- * in production an unset allowlist means no cross-origin credentials.
108
+ * When CORS_ALLOWED_ORIGINS is unset, production only allows trusted
109
+ * localhost/native desktop origins. Development keeps the legacy "echo
110
+ * any origin" behavior so local tools and docs previews keep working.
113
111
  */
114
- const LOCALHOST_RE = /^https?:\/\/(localhost|127\.0\.0\.1|tauri\.localhost)(:\d+)?$/;
115
112
  app.use(defineEventHandler((event) => {
116
113
  const requestOrigin = getRequestHeader(event, "origin");
117
114
  const method = getMethod(event);
@@ -123,27 +120,11 @@ export function createServer(options = {}) {
123
120
  * permissive enough that some clients followed through with the
124
121
  * credentialed request.
125
122
  */
126
- let allowedOrigin = null;
127
- if (allowedOrigins && allowedOrigins.length > 0) {
128
- if (requestOrigin && allowedOrigins.includes(requestOrigin)) {
129
- allowedOrigin = requestOrigin;
130
- }
131
- // Origin not in the explicit allowlist — emit no ACAO header.
132
- }
133
- else if (requestOrigin) {
134
- // No allowlist configured. In production we refuse credentialed
135
- // cross-origin requests except from localhost (desktop tray app
136
- // dev usage); in dev we allow any origin echo.
137
- if (isProduction) {
138
- if (LOCALHOST_RE.test(requestOrigin)) {
139
- allowedOrigin = requestOrigin;
140
- }
141
- // else: production + no allowlist + non-localhost origin → no ACAO
142
- }
143
- else {
144
- allowedOrigin = requestOrigin;
145
- }
146
- }
123
+ const allowedOrigin = getAllowedCorsOrigin(requestOrigin, {
124
+ allowedOrigins,
125
+ allowAnyOriginWhenNoAllowlist: !isProduction,
126
+ allowLocalhostWhenNoAllowlist: true,
127
+ });
147
128
  // No origin header at all (same-origin fetch, server-to-server) and
148
129
  // no allowlist → fall through with `*`-equivalent behaviour: omit
149
130
  // ACAO entirely and let the browser apply its same-origin default.
@@ -1 +1 @@
1
- {"version":3,"file":"create-server.js","sourceRoot":"","sources":["../../src/server/create-server.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,IAAI,CAAC;AACZ,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAClD,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACn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AAC,GAAG,CAAC,EAAE,CAAC;QAC/C,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import {\n createApp,\n createRouter,\n defineEventHandler,\n getMethod,\n getRequestHeader,\n setResponseHeader,\n setResponseStatus,\n type H3Event,\n} from \"h3\";\nimport path from \"path\";\nimport { agentEnv } from \"../shared/agent-env.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { isEnvVarWriteAllowed } from \"./env-var-writes.js\";\n\nexport interface EnvKeyConfig {\n /** Environment variable name (e.g. \"HUBSPOT_ACCESS_TOKEN\") */\n key: string;\n /** Human-readable label (e.g. \"HubSpot\") */\n label: string;\n /** Whether this key is required for the app to function */\n required?: boolean;\n /** Optional UI hint shown next to the field describing where to find this value. */\n helpText?: string;\n}\n\nexport interface CreateServerOptions {\n /** CORS options. Ignored (H3 handles CORS via middleware). Default: enabled. */\n cors?: Record<string, unknown> | false;\n /** JSON body parser limit. Kept for API compatibility (H3 uses readBody). */\n jsonLimit?: string;\n /** Custom ping message. Default: reads PING_MESSAGE env var, falls back to \"pong\" */\n pingMessage?: string;\n /** Disable the /_agent-native/ping health check. Default: false */\n disablePing?: boolean;\n /** Env key configuration for the settings UI. Enables /_agent-native/env-status and /_agent-native/env-vars routes. */\n envKeys?: EnvKeyConfig[];\n}\n\n/**\n * Parse a .env file into key-value pairs, preserving comments and empty lines for roundtrip.\n */\nfunction parseEnvFile(content: string): Map<string, string> {\n const vars = new Map<string, string>();\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eqIndex = trimmed.indexOf(\"=\");\n if (eqIndex === -1) continue;\n const key = trimmed.slice(0, eqIndex).trim();\n let value = trimmed.slice(eqIndex + 1).trim();\n // Strip surrounding quotes\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n vars.set(key, value);\n }\n return vars;\n}\n\n/**\n * Upsert vars into a .env file, preserving existing structure.\n */\nexport async function upsertEnvFile(\n envPath: string,\n vars: Array<{ key: string; value: string }>,\n): Promise<void> {\n // Sanitize: reject values that could inject additional env vars\n for (const { key, value } of vars) {\n if (/[\\n\\r\\0]/.test(value)) {\n throw new Error(\n `Invalid env var value for ${key}: must not contain newlines or control characters`,\n );\n }\n }\n\n const fs = await import(\"fs\");\n\n let content = \"\";\n try {\n content = fs.readFileSync(envPath, \"utf-8\");\n } catch {\n // File doesn't exist yet\n }\n\n const lines = content.split(\"\\n\");\n const remaining = new Map(vars.map((v) => [v.key, v.value]));\n\n // Update existing lines in place\n const updated = lines.map((line) => {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) return line;\n const eqIndex = trimmed.indexOf(\"=\");\n if (eqIndex === -1) return line;\n const key = trimmed.slice(0, eqIndex).trim();\n if (remaining.has(key)) {\n const value = remaining.get(key)!;\n remaining.delete(key);\n return `${key}=${value}`;\n }\n return line;\n });\n\n // Append new vars\n for (const [key, value] of remaining) {\n updated.push(`${key}=${value}`);\n }\n\n // Ensure trailing newline\n let result = updated.join(\"\\n\");\n if (!result.endsWith(\"\\n\")) result += \"\\n\";\n\n try {\n fs.mkdirSync(path.dirname(envPath), { recursive: true });\n fs.writeFileSync(envPath, result);\n } catch {\n // Edge runtimes don't have writable filesystem — skip silently\n }\n}\n\nexport interface CreateServerResult {\n app: ReturnType<typeof createApp>;\n router: ReturnType<typeof createRouter>;\n}\n\n/**\n * Create a pre-configured H3 app with standard agent-native setup:\n * - CORS headers via middleware\n * - /_agent-native/ping health check\n * - /_agent-native/env-status and /_agent-native/env-vars (when envKeys is provided)\n *\n * Returns { app, router } — mount routes on `router`.\n */\nexport function createServer(\n options: CreateServerOptions = {},\n): CreateServerResult {\n const app = createApp({\n onError(error, event) {\n // Suppress connection-reset errors — client disconnected mid-request (tab close, reload)\n const err = error as NodeJS.ErrnoException;\n const code = err?.code || (err?.cause as NodeJS.ErrnoException)?.code;\n if (code === \"ECONNRESET\" || code === \"ECONNABORTED\") return;\n if (err?.message === \"aborted\") return;\n console.error(\n `[agent-native] Server error: ${event.method} ${event.path}`,\n error,\n );\n },\n });\n\n // CORS middleware\n if (options.cors !== false) {\n const allowedOrigins = process.env.CORS_ALLOWED_ORIGINS\n ? process.env.CORS_ALLOWED_ORIGINS.split(\",\").map((o) => o.trim())\n : null;\n const isProduction = process.env.NODE_ENV === \"production\";\n\n /**\n * Localhost-style origins that we treat as same-trust in development.\n * When CORS_ALLOWED_ORIGINS is unset we still allow these (desktop tray\n * windows on a sibling port, the docs site at localhost:5173, etc.) but\n * in production an unset allowlist means no cross-origin credentials.\n */\n const LOCALHOST_RE =\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|tauri\\.localhost)(:\\d+)?$/;\n\n app.use(\n defineEventHandler((event) => {\n const requestOrigin = getRequestHeader(event, \"origin\");\n const method = getMethod(event);\n\n /**\n * Decide whether the requesting origin is allowed. We never fall back\n * to \"the first allowlist entry\" when the origin isn't in the list —\n * that previously sent `Access-Control-Allow-Origin: <other-origin>`\n * with credentials enabled to attacker-controlled origins, which was\n * permissive enough that some clients followed through with the\n * credentialed request.\n */\n let allowedOrigin: string | null = null;\n if (allowedOrigins && allowedOrigins.length > 0) {\n if (requestOrigin && allowedOrigins.includes(requestOrigin)) {\n allowedOrigin = requestOrigin;\n }\n // Origin not in the explicit allowlist — emit no ACAO header.\n } else if (requestOrigin) {\n // No allowlist configured. In production we refuse credentialed\n // cross-origin requests except from localhost (desktop tray app\n // dev usage); in dev we allow any origin echo.\n if (isProduction) {\n if (LOCALHOST_RE.test(requestOrigin)) {\n allowedOrigin = requestOrigin;\n }\n // else: production + no allowlist + non-localhost origin → no ACAO\n } else {\n allowedOrigin = requestOrigin;\n }\n }\n // No origin header at all (same-origin fetch, server-to-server) and\n // no allowlist → fall through with `*`-equivalent behaviour: omit\n // ACAO entirely and let the browser apply its same-origin default.\n\n if (allowedOrigin) {\n setResponseHeader(\n event,\n \"Access-Control-Allow-Origin\",\n allowedOrigin,\n );\n setResponseHeader(event, \"Vary\", \"Origin\");\n // A specific origin means we can honor credentialed requests\n // (fetch with `credentials: \"include\"` — used by desktop tray\n // apps that share a same-site cookie with the web app). The\n // wildcard `*` is spec-incompatible with credentials, so only\n // set this when we're echoing a concrete origin.\n setResponseHeader(event, \"Access-Control-Allow-Credentials\", \"true\");\n } else if (!requestOrigin) {\n // No origin header — preserve the legacy permissive behaviour for\n // tools/scripts that hit the API directly (no credentialed CORS\n // semantics apply when there's no Origin).\n setResponseHeader(event, \"Access-Control-Allow-Origin\", \"*\");\n }\n\n setResponseHeader(\n event,\n \"Access-Control-Allow-Methods\",\n \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n );\n setResponseHeader(\n event,\n \"Access-Control-Allow-Headers\",\n \"Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF\",\n );\n\n if (method === \"OPTIONS\") {\n // Reject preflights from disallowed cross-origin callers. We only\n // 204 if either (a) there was no Origin header (same-origin or\n // direct script invocation) or (b) the origin was in the allowlist\n // / dev fallback above. Otherwise we 403 so the browser surfaces\n // a hard CORS failure rather than blindly retrying with credentials.\n if (requestOrigin && !allowedOrigin) {\n return new Response(null, { status: 403 });\n }\n return new Response(null, { status: 204 });\n }\n }),\n );\n }\n\n const router = createRouter();\n app.use(router);\n\n // Health check\n if (!options.disablePing) {\n router.get(\n \"/_agent-native/ping\",\n defineEventHandler(() => {\n const message =\n options.pingMessage ?? process.env.PING_MESSAGE ?? \"pong\";\n return { message };\n }),\n );\n }\n\n // Env key management routes\n if (options.envKeys) {\n const envKeys = options.envKeys;\n\n router.get(\n \"/_agent-native/env-status\",\n defineEventHandler(() => {\n return envKeys.map((cfg) => ({\n key: cfg.key,\n label: cfg.label,\n required: cfg.required ?? false,\n configured: !!process.env[cfg.key],\n ...(cfg.helpText ? { helpText: cfg.helpText } : {}),\n }));\n }),\n );\n\n router.post(\n \"/_agent-native/env-vars\",\n defineEventHandler(async (event: H3Event) => {\n // Env vars are deployment-wide globals — see isEnvVarWriteAllowed\n // above. Disable the endpoint on any multi-tenant deploy.\n if (!isEnvVarWriteAllowed()) {\n setResponseStatus(event, 403);\n return {\n error:\n \"env-vars endpoint disabled on multi-tenant deployments. Use saveCredential(key, value, { userEmail, orgId, scope: 'org' }) to store per-org credentials.\",\n };\n }\n\n const body = await readBody(event);\n const { vars } = body as {\n vars?: Array<{ key: string; value: string }>;\n };\n\n if (!Array.isArray(vars) || vars.length === 0) {\n setResponseStatus(event, 400);\n return { error: \"vars array required\" };\n }\n\n // Only allow keys that are in the env config\n const allowedKeys = new Set(envKeys.map((k) => k.key));\n const filtered = vars.filter((v) => allowedKeys.has(v.key));\n if (filtered.length === 0) {\n setResponseStatus(event, 400);\n return { error: \"No recognized env keys in request\" };\n }\n\n // Write to .env file\n const envPath = path.join(process.cwd(), \".env\");\n await upsertEnvFile(envPath, filtered);\n\n // Update process.env so the app picks up the new values immediately\n for (const { key, value } of filtered) {\n process.env[key] = value;\n }\n\n // Notify parent (Builder or frame) via postMessage\n agentEnv.setVars(filtered);\n\n return { saved: filtered.map((v) => v.key) };\n }),\n );\n }\n\n return { app, router };\n}\n"]}
1
+ {"version":3,"file":"create-server.js","sourceRoot":"","sources":["../../src/server/create-server.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,IAAI,CAAC;AACZ,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAClD,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EACL,oBAAoB,EACpB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAC3B,O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,GAAG,CAAC,CAAC;gBAC9B,OAAO,EAAE,KAAK,EAAE,mCAAmC,EAAE,CAAC;YACxD,CAAC;YAED,qBAAqB;YACrB,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,CAAC,CAAC;YACjD,MAAM,aAAa,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAEvC,oEAAoE;YACpE,KAAK,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,QAAQ,EAAE,CAAC;gBACtC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;YAC3B,CAAC;YAED,mDAAmD;YACnD,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YAE3B,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/C,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import {\n createApp,\n createRouter,\n defineEventHandler,\n getMethod,\n getRequestHeader,\n setResponseHeader,\n setResponseStatus,\n type H3Event,\n} from \"h3\";\nimport path from \"path\";\nimport { agentEnv } from \"../shared/agent-env.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport {\n getAllowedCorsOrigin,\n readCorsAllowedOrigins,\n} from \"./cors-origins.js\";\nimport { isEnvVarWriteAllowed } from \"./env-var-writes.js\";\n\nexport interface EnvKeyConfig {\n /** Environment variable name (e.g. \"HUBSPOT_ACCESS_TOKEN\") */\n key: string;\n /** Human-readable label (e.g. \"HubSpot\") */\n label: string;\n /** Whether this key is required for the app to function */\n required?: boolean;\n /** Optional UI hint shown next to the field describing where to find this value. */\n helpText?: string;\n}\n\nexport interface CreateServerOptions {\n /** CORS options. Ignored (H3 handles CORS via middleware). Default: enabled. */\n cors?: Record<string, unknown> | false;\n /** JSON body parser limit. Kept for API compatibility (H3 uses readBody). */\n jsonLimit?: string;\n /** Custom ping message. Default: reads PING_MESSAGE env var, falls back to \"pong\" */\n pingMessage?: string;\n /** Disable the /_agent-native/ping health check. Default: false */\n disablePing?: boolean;\n /** Env key configuration for the settings UI. Enables /_agent-native/env-status and /_agent-native/env-vars routes. */\n envKeys?: EnvKeyConfig[];\n}\n\n/**\n * Parse a .env file into key-value pairs, preserving comments and empty lines for roundtrip.\n */\nfunction parseEnvFile(content: string): Map<string, string> {\n const vars = new Map<string, string>();\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eqIndex = trimmed.indexOf(\"=\");\n if (eqIndex === -1) continue;\n const key = trimmed.slice(0, eqIndex).trim();\n let value = trimmed.slice(eqIndex + 1).trim();\n // Strip surrounding quotes\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n vars.set(key, value);\n }\n return vars;\n}\n\n/**\n * Upsert vars into a .env file, preserving existing structure.\n */\nexport async function upsertEnvFile(\n envPath: string,\n vars: Array<{ key: string; value: string }>,\n): Promise<void> {\n // Sanitize: reject values that could inject additional env vars\n for (const { key, value } of vars) {\n if (/[\\n\\r\\0]/.test(value)) {\n throw new Error(\n `Invalid env var value for ${key}: must not contain newlines or control characters`,\n );\n }\n }\n\n const fs = await import(\"fs\");\n\n let content = \"\";\n try {\n content = fs.readFileSync(envPath, \"utf-8\");\n } catch {\n // File doesn't exist yet\n }\n\n const lines = content.split(\"\\n\");\n const remaining = new Map(vars.map((v) => [v.key, v.value]));\n\n // Update existing lines in place\n const updated = lines.map((line) => {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) return line;\n const eqIndex = trimmed.indexOf(\"=\");\n if (eqIndex === -1) return line;\n const key = trimmed.slice(0, eqIndex).trim();\n if (remaining.has(key)) {\n const value = remaining.get(key)!;\n remaining.delete(key);\n return `${key}=${value}`;\n }\n return line;\n });\n\n // Append new vars\n for (const [key, value] of remaining) {\n updated.push(`${key}=${value}`);\n }\n\n // Ensure trailing newline\n let result = updated.join(\"\\n\");\n if (!result.endsWith(\"\\n\")) result += \"\\n\";\n\n try {\n fs.mkdirSync(path.dirname(envPath), { recursive: true });\n fs.writeFileSync(envPath, result);\n } catch {\n // Edge runtimes don't have writable filesystem — skip silently\n }\n}\n\nexport interface CreateServerResult {\n app: ReturnType<typeof createApp>;\n router: ReturnType<typeof createRouter>;\n}\n\n/**\n * Create a pre-configured H3 app with standard agent-native setup:\n * - CORS headers via middleware\n * - /_agent-native/ping health check\n * - /_agent-native/env-status and /_agent-native/env-vars (when envKeys is provided)\n *\n * Returns { app, router } — mount routes on `router`.\n */\nexport function createServer(\n options: CreateServerOptions = {},\n): CreateServerResult {\n const app = createApp({\n onError(error, event) {\n // Suppress connection-reset errors — client disconnected mid-request (tab close, reload)\n const err = error as NodeJS.ErrnoException;\n const code = err?.code || (err?.cause as NodeJS.ErrnoException)?.code;\n if (code === \"ECONNRESET\" || code === \"ECONNABORTED\") return;\n if (err?.message === \"aborted\") return;\n console.error(\n `[agent-native] Server error: ${event.method} ${event.path}`,\n error,\n );\n },\n });\n\n // CORS middleware\n if (options.cors !== false) {\n const allowedOrigins = readCorsAllowedOrigins();\n const isProduction = process.env.NODE_ENV === \"production\";\n\n /**\n * When CORS_ALLOWED_ORIGINS is unset, production only allows trusted\n * localhost/native desktop origins. Development keeps the legacy \"echo\n * any origin\" behavior so local tools and docs previews keep working.\n */\n app.use(\n defineEventHandler((event) => {\n const requestOrigin = getRequestHeader(event, \"origin\");\n const method = getMethod(event);\n\n /**\n * Decide whether the requesting origin is allowed. We never fall back\n * to \"the first allowlist entry\" when the origin isn't in the list —\n * that previously sent `Access-Control-Allow-Origin: <other-origin>`\n * with credentials enabled to attacker-controlled origins, which was\n * permissive enough that some clients followed through with the\n * credentialed request.\n */\n const allowedOrigin = getAllowedCorsOrigin(requestOrigin, {\n allowedOrigins,\n allowAnyOriginWhenNoAllowlist: !isProduction,\n allowLocalhostWhenNoAllowlist: true,\n });\n // No origin header at all (same-origin fetch, server-to-server) and\n // no allowlist → fall through with `*`-equivalent behaviour: omit\n // ACAO entirely and let the browser apply its same-origin default.\n\n if (allowedOrigin) {\n setResponseHeader(\n event,\n \"Access-Control-Allow-Origin\",\n allowedOrigin,\n );\n setResponseHeader(event, \"Vary\", \"Origin\");\n // A specific origin means we can honor credentialed requests\n // (fetch with `credentials: \"include\"` — used by desktop tray\n // apps that share a same-site cookie with the web app). The\n // wildcard `*` is spec-incompatible with credentials, so only\n // set this when we're echoing a concrete origin.\n setResponseHeader(event, \"Access-Control-Allow-Credentials\", \"true\");\n } else if (!requestOrigin) {\n // No origin header — preserve the legacy permissive behaviour for\n // tools/scripts that hit the API directly (no credentialed CORS\n // semantics apply when there's no Origin).\n setResponseHeader(event, \"Access-Control-Allow-Origin\", \"*\");\n }\n\n setResponseHeader(\n event,\n \"Access-Control-Allow-Methods\",\n \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n );\n setResponseHeader(\n event,\n \"Access-Control-Allow-Headers\",\n \"Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF\",\n );\n\n if (method === \"OPTIONS\") {\n // Reject preflights from disallowed cross-origin callers. We only\n // 204 if either (a) there was no Origin header (same-origin or\n // direct script invocation) or (b) the origin was in the allowlist\n // / dev fallback above. Otherwise we 403 so the browser surfaces\n // a hard CORS failure rather than blindly retrying with credentials.\n if (requestOrigin && !allowedOrigin) {\n return new Response(null, { status: 403 });\n }\n return new Response(null, { status: 204 });\n }\n }),\n );\n }\n\n const router = createRouter();\n app.use(router);\n\n // Health check\n if (!options.disablePing) {\n router.get(\n \"/_agent-native/ping\",\n defineEventHandler(() => {\n const message =\n options.pingMessage ?? process.env.PING_MESSAGE ?? \"pong\";\n return { message };\n }),\n );\n }\n\n // Env key management routes\n if (options.envKeys) {\n const envKeys = options.envKeys;\n\n router.get(\n \"/_agent-native/env-status\",\n defineEventHandler(() => {\n return envKeys.map((cfg) => ({\n key: cfg.key,\n label: cfg.label,\n required: cfg.required ?? false,\n configured: !!process.env[cfg.key],\n ...(cfg.helpText ? { helpText: cfg.helpText } : {}),\n }));\n }),\n );\n\n router.post(\n \"/_agent-native/env-vars\",\n defineEventHandler(async (event: H3Event) => {\n // Env vars are deployment-wide globals — see isEnvVarWriteAllowed\n // above. Disable the endpoint on any multi-tenant deploy.\n if (!isEnvVarWriteAllowed()) {\n setResponseStatus(event, 403);\n return {\n error:\n \"env-vars endpoint disabled on multi-tenant deployments. Use saveCredential(key, value, { userEmail, orgId, scope: 'org' }) to store per-org credentials.\",\n };\n }\n\n const body = await readBody(event);\n const { vars } = body as {\n vars?: Array<{ key: string; value: string }>;\n };\n\n if (!Array.isArray(vars) || vars.length === 0) {\n setResponseStatus(event, 400);\n return { error: \"vars array required\" };\n }\n\n // Only allow keys that are in the env config\n const allowedKeys = new Set(envKeys.map((k) => k.key));\n const filtered = vars.filter((v) => allowedKeys.has(v.key));\n if (filtered.length === 0) {\n setResponseStatus(event, 400);\n return { error: \"No recognized env keys in request\" };\n }\n\n // Write to .env file\n const envPath = path.join(process.cwd(), \".env\");\n await upsertEnvFile(envPath, filtered);\n\n // Update process.env so the app picks up the new values immediately\n for (const { key, value } of filtered) {\n process.env[key] = value;\n }\n\n // Notify parent (Builder or frame) via postMessage\n agentEnv.setVars(filtered);\n\n return { saved: filtered.map((v) => v.key) };\n }),\n );\n }\n\n return { app, router };\n}\n"]}
@@ -21,6 +21,17 @@ export interface H3AppShim {
21
21
  use(path: string, handler: EventHandler): void;
22
22
  use(handler: EventHandler): void;
23
23
  }
24
+ /**
25
+ * Mark a default plugin slot as supplied by the app/template before the
26
+ * framework default bootstrap runs.
27
+ *
28
+ * Bundled serverless functions often don't have the original
29
+ * `server/plugins/*.ts` tree on disk at runtime, so filesystem route discovery
30
+ * can falsely conclude a template plugin is missing. Explicit plugin factories
31
+ * call this synchronously before awaiting bootstrap so the framework does not
32
+ * auto-mount a generic default over the app's custom implementation.
33
+ */
34
+ export declare function markDefaultPluginProvided(nitroApp: any, stem: string): void;
24
35
  /**
25
36
  * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this
26
37
  * to register routes via `.use(path, handler)`.
@@ -1 +1 @@
1
- {"version":3,"file":"framework-request-handler.d.ts","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,YAAY,EAAW,MAAM,IAAI,CAAC;AAMhD,QAAA,MAAM,gBAAgB,mBAAmB,CAAC;AAiD1C;;;GAGG;AACH,MAAM,WAAW,SAAS;IACxB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;IAC/C,GAAG,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;CAClC;AAED;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CAAC,QAAQ,EAAE,GAAG,GAAG,SAAS,CA6CjD;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,QAAQ,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAOjE;AAgBD;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAiB3E;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CAAC,QAAQ,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAMpE;AAgQD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,GAAG,CAAC,CAyBd;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
1
+ {"version":3,"file":"framework-request-handler.d.ts","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,YAAY,EAAW,MAAM,IAAI,CAAC;AAMhD,QAAA,MAAM,gBAAgB,mBAAmB,CAAC;AAkD1C;;;GAGG;AACH,MAAM,WAAW,SAAS;IACxB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;IAC/C,GAAG,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;CAClC;AAED;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAQ3E;AAED;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CAAC,QAAQ,EAAE,GAAG,GAAG,SAAS,CA6CjD;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,QAAQ,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAOjE;AAgBD;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAiB3E;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CAAC,QAAQ,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAMpE;AAsQD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,GAAG,CAAC,CAyBd;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
@@ -7,6 +7,7 @@ const WELL_KNOWN_PREFIX = "/.well-known";
7
7
  const APP_SHIM_KEY = "_agentNativeH3Shim";
8
8
  const BOOTSTRAP_PROMISE_KEY = "_agentNativeBootstrapPromise";
9
9
  const PLUGIN_READY_KEY = "_agentNativePluginReadyPromise";
10
+ const PROVIDED_PLUGIN_STEMS_KEY = "_agentNativeProvidedPluginStems";
10
11
  function normalizeAppBasePath(value) {
11
12
  if (!value || value === "/")
12
13
  return "";
@@ -40,6 +41,24 @@ function resolveMountMatch(reqPath, path) {
40
41
  strippedPath: reqPath.slice(prefixedPath.length) || "/",
41
42
  };
42
43
  }
44
+ /**
45
+ * Mark a default plugin slot as supplied by the app/template before the
46
+ * framework default bootstrap runs.
47
+ *
48
+ * Bundled serverless functions often don't have the original
49
+ * `server/plugins/*.ts` tree on disk at runtime, so filesystem route discovery
50
+ * can falsely conclude a template plugin is missing. Explicit plugin factories
51
+ * call this synchronously before awaiting bootstrap so the framework does not
52
+ * auto-mount a generic default over the app's custom implementation.
53
+ */
54
+ export function markDefaultPluginProvided(nitroApp, stem) {
55
+ if (!nitroApp || !stem)
56
+ return;
57
+ const existing = nitroApp[PROVIDED_PLUGIN_STEMS_KEY];
58
+ const provided = existing ?? new Set();
59
+ provided.add(stem);
60
+ nitroApp[PROVIDED_PLUGIN_STEMS_KEY] = provided;
61
+ }
43
62
  /**
44
63
  * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this
45
64
  * to register routes via `.use(path, handler)`.
@@ -307,7 +326,11 @@ async function bootstrapDefaultPlugins(nitroApp) {
307
326
  IN_BOOTSTRAP.add(nitroApp);
308
327
  try {
309
328
  const cwd = process.cwd();
310
- const missing = await getMissingDefaultPlugins(cwd);
329
+ const discoveredMissing = await getMissingDefaultPlugins(cwd);
330
+ const provided = nitroApp[PROVIDED_PLUGIN_STEMS_KEY];
331
+ const missing = provided
332
+ ? discoveredMissing.filter((stem) => !provided.has(stem))
333
+ : discoveredMissing;
311
334
  if (missing.length === 0)
312
335
  return;
313
336
  // Lazy import to avoid circular dependency at module load time
@@ -1 +1 @@
1
- {"version":3,"file":"framework-request-handler.js","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"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CAAC;QACnD,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,CAAC;QACvC,sEAAsE;QACtE,wEAAwE;QACxE,mCAAmC;QACnC,MAAM,MAAM,GAAG,aAAa,CAC1B,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,cAAc,CAAC,CACtC,CAAC,QAAQ,EAAE,CAAC;QACb,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1D,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,WAAW,SAAS,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,OAAO,EAAE,CAAC;QACjB,wEAAwE;QACxE,8DAA8D;QAC9D,MAAM,QAAQ,IAAI,OAAO,CAAC;IAC5B,CAAC;AACH,CAAC;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC","sourcesContent":["/**\n * Framework request handler — registers framework routes on Nitro's h3 instance.\n *\n * Nitro 3 exposes its h3 app as `nitroApp.h3`. We register framework routes\n * directly on it as middleware (`nitroApp.h3[\"~middleware\"]`), giving each\n * plugin a path-prefix-matched handler that runs before any file-based route.\n *\n * Plugins call `getH3App(nitroApp).use(path, handler)` exactly like h3 v1's\n * `app.use()` — the wrapper translates that into v2 middleware registration.\n *\n * Default plugins that the template doesn't provide are auto-mounted on the\n * first call to `getH3App()` per nitroApp instance.\n */\nimport type { EventHandler, H3Event } from \"h3\";\nimport { setResponseHeader, setResponseStatus } from \"h3\";\nimport { getMissingDefaultPlugins } from \"../deploy/route-discovery.js\";\n\nconst BOOTSTRAPPED = new WeakSet<object>();\nconst IN_BOOTSTRAP = new WeakSet<object>();\nconst FRAMEWORK_PREFIX = \"/_agent-native\";\nconst WELL_KNOWN_PREFIX = \"/.well-known\";\nconst APP_SHIM_KEY = \"_agentNativeH3Shim\";\nconst BOOTSTRAP_PROMISE_KEY = \"_agentNativeBootstrapPromise\";\nconst PLUGIN_READY_KEY = \"_agentNativePluginReadyPromise\";\n\nfunction normalizeAppBasePath(value: string | undefined): string {\n if (!value || value === \"/\") return \"\";\n const trimmed = value.trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return `/${trimmed.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\")}`;\n}\n\nfunction getAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\nfunction pathMatchesPrefix(reqPath: string, prefix: string): boolean {\n return reqPath === prefix || reqPath.startsWith(prefix + \"/\");\n}\n\nfunction supportsAppBasePathMount(path: string): boolean {\n return (\n pathMatchesPrefix(path, FRAMEWORK_PREFIX) ||\n pathMatchesPrefix(path, WELL_KNOWN_PREFIX)\n );\n}\n\nfunction resolveMountMatch(\n reqPath: string,\n path: string,\n): { mountPath: string; strippedPath: string } | null {\n if (pathMatchesPrefix(reqPath, path)) {\n return { mountPath: path, strippedPath: reqPath.slice(path.length) || \"/\" };\n }\n\n const appBasePath = getAppBasePath();\n if (!appBasePath || !supportsAppBasePathMount(path)) return null;\n\n const prefixedPath = `${appBasePath}${path}`;\n if (!pathMatchesPrefix(reqPath, prefixedPath)) return null;\n return {\n mountPath: prefixedPath,\n strippedPath: reqPath.slice(prefixedPath.length) || \"/\",\n };\n}\n\n/**\n * Wrapper around Nitro's h3 instance that exposes a v1-style `.use()` API\n * for registering path-prefix middleware.\n */\nexport interface H3AppShim {\n use(path: string, handler: EventHandler): void;\n use(handler: EventHandler): void;\n}\n\n/**\n * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this\n * to register routes via `.use(path, handler)`.\n *\n * On the first call per nitroApp, we kick off auto-mounting any missing\n * default plugins. User-facing plugin factories (createAgentChatPlugin,\n * createAuthPlugin, etc.) await this bootstrap via `awaitBootstrap()` so the\n * default plugins finish registering middleware before requests arrive.\n */\nexport function getH3App(nitroApp: any): H3AppShim {\n if (!nitroApp) throw new Error(\"getH3App: nitroApp is required\");\n\n // Reuse the cached shim if we've wrapped this nitroApp before\n const cached = nitroApp[APP_SHIM_KEY] as H3AppShim | undefined;\n if (cached) return cached;\n\n const shim: H3AppShim = {\n use(arg1: string | EventHandler, arg2?: EventHandler) {\n const path = typeof arg1 === \"string\" ? arg1 : \"\";\n const handler = (typeof arg1 === \"string\" ? arg2 : arg1) as EventHandler;\n if (typeof handler !== \"function\") {\n throw new Error(\"getH3App.use: handler must be a function\");\n }\n registerMiddleware(nitroApp, path, handler);\n },\n };\n\n nitroApp[APP_SHIM_KEY] = shim;\n\n if (!BOOTSTRAPPED.has(nitroApp)) {\n BOOTSTRAPPED.add(nitroApp);\n nitroApp[BOOTSTRAP_PROMISE_KEY] = bootstrapDefaultPlugins(nitroApp).catch(\n (err) => {\n console.warn(\n \"[agent-native] Failed to auto-mount default plugins:\",\n (err as Error).message,\n );\n },\n );\n\n // Readiness gate: Nitro v3 doesn't await async plugins, so routes\n // registered inside an async plugin may not exist when the first\n // request arrives. These middleware entries hold framework routes\n // until default-plugin bootstrap and tracked plugin inits complete.\n const readinessGate = (async (event: H3Event) => {\n await awaitFrameworkRoutesReady(nitroApp);\n // Fall through — the actual route handler runs next.\n return undefined;\n }) as EventHandler;\n registerMiddleware(nitroApp, FRAMEWORK_PREFIX, readinessGate);\n registerMiddleware(nitroApp, WELL_KNOWN_PREFIX, readinessGate);\n }\n\n return shim;\n}\n\n/**\n * Wait for the framework's default-plugin bootstrap to complete.\n *\n * Called by user-facing plugin factories (`createAgentChatPlugin`, etc.) at\n * the top of their plugin function, so that by the time the function returns\n * — and Nitro starts accepting requests — all default plugins have finished\n * registering their middleware.\n *\n * No-op when called from inside the bootstrap itself (avoids deadlock when a\n * default plugin happens to be running as part of bootstrap).\n */\nexport async function awaitBootstrap(nitroApp: any): Promise<void> {\n if (!nitroApp || IN_BOOTSTRAP.has(nitroApp)) return;\n // Trigger bootstrap if it hasn't been already (idempotent — getH3App\n // creates the shim and kicks off bootstrap on first call).\n getH3App(nitroApp);\n const promise = nitroApp[BOOTSTRAP_PROMISE_KEY];\n if (promise) await promise;\n}\n\n/**\n * Wait until framework routes are safe to dispatch.\n *\n * Request-time gates must wait for both phases:\n * 1. default-plugin bootstrap, which discovers and starts missing plugins\n * 2. async plugin init promises, which register routes such as A2A cards\n */\nasync function awaitFrameworkRoutesReady(nitroApp: any): Promise<void> {\n if (!nitroApp) return;\n const bootstrapPromise = nitroApp[BOOTSTRAP_PROMISE_KEY];\n if (bootstrapPromise) await bootstrapPromise;\n await awaitPluginsReady(nitroApp);\n}\n\n/**\n * Track an async plugin's initialization promise. Nitro v3 calls plugins\n * synchronously and doesn't await async return values, so routes registered\n * inside an async plugin may not be ready when the first request arrives.\n *\n * Call this from the TOP of any async plugin so that the readiness gate\n * (installed by getH3App) can hold /_agent-native requests until the plugin\n * finishes mounting its routes.\n */\nexport function trackPluginInit(nitroApp: any, promise: Promise<void>): void {\n if (!nitroApp) return;\n // Attach a no-op catch so the promise doesn't surface as an unhandled\n // rejection when Nitro v3 drops the async return value. The actual error\n // is still observable when awaitPluginsReady() re-awaits the promise.\n const safe = promise.catch((err) => {\n console.error(\n \"[agent-native] Plugin init failed:\",\n (err as Error).message || err,\n );\n });\n const existing = nitroApp[PLUGIN_READY_KEY] as Promise<void>[] | undefined;\n if (existing) {\n existing.push(safe);\n } else {\n nitroApp[PLUGIN_READY_KEY] = [safe];\n }\n}\n\n/**\n * Await all tracked plugin initializations. Called by the readiness gate\n * middleware before dispatching framework routes.\n */\nexport async function awaitPluginsReady(nitroApp: any): Promise<void> {\n const promises = nitroApp[PLUGIN_READY_KEY] as Promise<void>[] | undefined;\n if (promises?.length) {\n await Promise.all(promises);\n nitroApp[PLUGIN_READY_KEY] = [];\n }\n}\n\n/**\n * Register a path-prefix middleware on Nitro's h3 instance.\n *\n * The middleware:\n * - Returns `next()` (continues) if the request path doesn't match.\n * - Otherwise dispatches to the handler. If the handler returns a value,\n * it short-circuits the request. If it returns undefined, next() runs.\n *\n * Path matching emulates h3 v1's `app.use(path, ...)` behavior:\n * - Exact-match prefix: `/foo` matches `/foo`, `/foo/bar`, but not `/foobar`\n * - Empty path: middleware runs on every request\n */\nfunction registerMiddleware(\n nitroApp: any,\n path: string,\n handler: EventHandler,\n) {\n const h3 = nitroApp.h3;\n if (!h3 || !Array.isArray(h3[\"~middleware\"])) {\n throw new Error(\n \"[agent-native] Cannot register route: nitroApp.h3 is not available. \" +\n \"Make sure you're calling getH3App() from inside a Nitro plugin.\",\n );\n }\n\n const middleware = async (event: H3Event, next: () => any) => {\n let originalPathname: string | undefined;\n let originalEventPath: string | undefined;\n let hadEventPath = false;\n const restoreOriginalPath = () => {\n if (originalPathname !== undefined) {\n try {\n event.url.pathname = originalPathname;\n } catch {\n // ignore\n }\n originalPathname = undefined;\n }\n if (hadEventPath) {\n try {\n (event as any).path = originalEventPath;\n } catch {\n // ignore\n }\n } else {\n try {\n delete (event as any).path;\n } catch {\n // ignore\n }\n }\n };\n if (path) {\n const reqPath = event.url?.pathname ?? \"\";\n const match = resolveMountMatch(reqPath, path);\n if (!match) {\n return next();\n }\n // Strip the mount prefix from event.url.pathname so handlers that\n // dispatch sub-routes can read `event.path` (or `event.url.pathname`)\n // and see the path RELATIVE to their mount point — matching h3 v1's\n // `app.use(path, handler)` semantics.\n const eventAny = event as any;\n hadEventPath = \"path\" in eventAny;\n originalEventPath = eventAny.path;\n try {\n originalPathname = event.url.pathname;\n // Save the full path in context so handlers that need the original URL\n // (e.g. Better Auth, which extracts its own basePath prefix) can\n // reconstruct a Request with the un-stripped URL.\n eventAny.context = eventAny.context ?? {};\n eventAny.context._mountedPathname = originalPathname;\n eventAny.context._mountPrefix = match.mountPath;\n event.url.pathname = match.strippedPath;\n eventAny.path = `${match.strippedPath}${event.url.search || \"\"}`;\n } catch {\n // event.url is read-only on some runtimes — fall through. Handlers\n // that don't depend on prefix stripping (most of them) still work.\n }\n }\n try {\n const result = await handler(event);\n if (result === undefined) {\n // Restore the original pathname BEFORE calling next() so downstream\n // middleware sees the full URL — not the stripped mount-relative path.\n // Matches h3 v2's own sub-app middleware pattern where the restore\n // happens inside the next() callback, not after it returns.\n restoreOriginalPath();\n return next();\n }\n return result;\n } catch (err) {\n // Log 500s to the server console so they're debuggable, and respond\n // with JSON instead of the default HTML error page so clients can\n // surface error messages. This only applies to routes mounted under\n // the framework prefix (or middleware mounted at `/`, for which we\n // still want visibility).\n const reqPath = originalPathname ?? event.url?.pathname ?? \"\";\n const e = err as any;\n const status =\n typeof e?.statusCode === \"number\"\n ? e.statusCode\n : typeof e?.status === \"number\"\n ? e.status\n : 500;\n console.error(\n `[agent-native] ${event.method ?? \"\"} ${reqPath} failed (${status}):`,\n e?.stack || e?.message || e,\n );\n try {\n setResponseStatus(event, status);\n setResponseHeader(event, \"content-type\", \"application/json\");\n } catch {\n // Response already sent — best effort.\n }\n return {\n error: e?.message || \"Internal server error\",\n // Only surface the stack to clients when explicitly enabled.\n // `NODE_ENV !== \"production\"` was unsafe — preview deploys and\n // any host that forgets to set NODE_ENV=production leaked stack\n // traces (file paths, dependency versions, internal route\n // topology) to anonymous callers. Operators who want stacks in\n // dev set `AGENT_NATIVE_DEBUG_ERRORS=1` explicitly.\n ...(status >= 500 &&\n process.env.AGENT_NATIVE_DEBUG_ERRORS === \"1\" &&\n e?.stack\n ? { stack: e.stack }\n : {}),\n };\n } finally {\n // Restore the original pathname so downstream middleware sees the\n // full URL.\n restoreOriginalPath();\n }\n };\n\n h3[\"~middleware\"].push(middleware);\n}\n\n/**\n * Auto-mount any default framework plugins that the template doesn't provide.\n *\n * Runs once per nitroApp on the first `getH3App()` call. Uses route-discovery\n * to find which default plugin stems are missing from `server/plugins/`, then\n * dynamically imports and mounts them. If a workspace core is present in the\n * ancestor chain, plugin slots the workspace core exports are mounted from\n * there instead of from @agent-native/core — this is the middle layer of the\n * three-layer inheritance model (app local > workspace core > framework).\n */\nasync function bootstrapDefaultPlugins(nitroApp: any): Promise<void> {\n IN_BOOTSTRAP.add(nitroApp);\n try {\n const cwd = process.cwd();\n const missing = await getMissingDefaultPlugins(cwd);\n if (missing.length === 0) return;\n\n // Lazy import to avoid circular dependency at module load time\n const serverModule = await import(\"./index.js\");\n const terminalModule = await import(\"../terminal/terminal-plugin.js\");\n const integrationsModule = await import(\"../integrations/plugin.js\");\n const orgModule = await import(\"../org/plugin.js\");\n const onboardingModule = await import(\"../onboarding/plugin.js\");\n\n const frameworkImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {\n \"agent-chat\": (serverModule as any).defaultAgentChatPlugin,\n auth: (serverModule as any).defaultAuthPlugin,\n \"core-routes\": (serverModule as any).defaultCoreRoutesPlugin,\n integrations: (integrationsModule as any).defaultIntegrationsPlugin,\n onboarding: (onboardingModule as any).defaultOnboardingPlugin,\n org: (orgModule as any).defaultOrgPlugin,\n resources: (serverModule as any).defaultResourcesPlugin,\n terminal: (terminalModule as any).defaultTerminalPlugin,\n };\n\n // Workspace core layer: if the app is inside an enterprise monorepo with\n // `agent-native.workspaceCore` configured, pull in any plugin slots the\n // workspace core exports from its server entry. We dynamically import the\n // workspace core package at runtime.\n let workspaceImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {};\n try {\n const { getWorkspaceCoreExports } =\n await import(\"../deploy/workspace-core.js\");\n const ws = await getWorkspaceCoreExports(cwd);\n if (ws && Object.keys(ws.plugins).length > 0) {\n try {\n const wsServerModule = await loadWorkspaceCoreServer(\n ws.packageName,\n ws.packageDir,\n );\n for (const [slot, exportName] of Object.entries(ws.plugins)) {\n if (!exportName) continue;\n const impl = (wsServerModule as any)[exportName];\n if (typeof impl === \"function\") {\n workspaceImpls[slot] = impl;\n }\n }\n if (process.env.DEBUG) {\n console.log(\n `[agent-native] Workspace core ${ws.packageName} provides plugin slots: ${Object.keys(workspaceImpls).join(\", \")}`,\n );\n }\n } catch (e) {\n const msg = (e as Error).message ?? \"\";\n // Common cause: workspace-core's package.json points \"./server\"\n // at a TS source file (the scaffold default), but Node can't\n // resolve relative `.js` imports inside it without a TS loader.\n // Tell the user to compile to dist/ rather than just dumping the\n // raw resolution error.\n const tsLoadHint = /\\.js' imported from .*\\.ts/.test(msg)\n ? \" — workspace-core src is TypeScript but isn't being compiled. \" +\n \"Run `pnpm --filter \" +\n ws.packageName +\n \" build` and point its `./server` export at dist/server/index.js.\"\n : \"\";\n console.warn(\n `[agent-native] Failed to load workspace core ${ws.packageName}/server: ${msg}${tsLoadHint}`,\n );\n }\n }\n } catch {\n // Workspace shared package isn't available (e.g. running on an edge\n // runtime without fs). Silently fall through to framework defaults.\n }\n\n if (process.env.DEBUG)\n console.log(\n `[agent-native] Auto-mounting ${missing.length} default plugin(s): ${missing.join(\", \")}`,\n );\n\n for (const stem of missing) {\n // Prefer workspace-core impl over framework default when both exist.\n const impl = workspaceImpls[stem] ?? frameworkImpls[stem];\n if (typeof impl === \"function\") {\n try {\n await impl(nitroApp);\n } catch (e) {\n console.warn(\n `[agent-native] Failed to auto-mount default plugin ${stem}:`,\n (e as Error).message,\n );\n }\n }\n }\n } finally {\n IN_BOOTSTRAP.delete(nitroApp);\n }\n}\n\n/**\n * Load a workspace-core's `/server` entry, transparently handling TS source.\n *\n * The scaffolded workspace-core template ships TS sources without a build\n * step (exports point at `./src/server/index.ts`), so plain `await import()`\n * blows up the moment Node hits a relative `.js` import inside (the standard\n * TS ESM convention) — and even before that, Node may resolve the package\n * relative to the framework's own location rather than the user's monorepo.\n *\n * We try Node's plain `import()` first (fastest path when the user has\n * compiled to dist/) and fall through to jiti on any error. jiti is anchored\n * to a real file inside the workspace-core's directory, so its module\n * resolution starts in the right node_modules tree (handles pnpm hoisting\n * and linked workspaces) AND handles TS source files + `.js` → `.ts` ESM\n * extension remapping.\n *\n * Edge runtimes without `fs` won't be able to load jiti at all; the outer\n * try/catch silently falls through to framework defaults in that case.\n */\nexport async function loadWorkspaceCoreServer(\n packageName: string,\n packageDir: string,\n): Promise<any> {\n let firstErr: unknown;\n try {\n return await import(/* @vite-ignore */ `${packageName}/server`);\n } catch (e) {\n firstErr = e;\n }\n\n try {\n const { createJiti } = await import(\"jiti\");\n const { pathToFileURL } = await import(\"node:url\");\n const path = await import(\"node:path\");\n // Anchor jiti to a real file inside the workspace-core package so its\n // module resolution starts in the right node_modules tree (handles pnpm\n // hoisting and linked workspaces).\n const anchor = pathToFileURL(\n path.join(packageDir, \"package.json\"),\n ).toString();\n const jiti = createJiti(anchor, { interopDefault: true });\n return await jiti.import(`${packageName}/server`);\n } catch (jitiErr) {\n // jiti also failed — rethrow the original Node error since it's usually\n // more informative about *why* the package wasn't resolvable.\n throw firstErr ?? jitiErr;\n }\n}\n\nexport { FRAMEWORK_PREFIX };\n"]}
1
+ {"version":3,"file":"framework-request-handler.js","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AAC1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAExE,MAAM,YAAY,GAAG,IAAI,OAAO,EAAU,CAAC;AAC3C,MAAM,YAAY,GAAG,IAAI,OAAO,EAAU,CAAC;AAC3C,MAAM,gBAAgB,GAAG,gBAAgB,CAAC;AAC1C,MAAM,iBAAiB,GAAG,cAAc,CAAC;AACzC,MAAM,YAAY,GAAG,oBAAoB,CAAC;AAC1C,MAAM,qBAAqB,GAAG,8BAA8B,CAAC;AAC7D,MAAM,gBAAgB,GAAG,gCAAgC,CAAC;AAC1D,MAAM,yBAAyB,GAAG,iCAAiC,CAAC;AAEpE,SAAS,oBAAoB,CAAC,KAAyB;IACrD,IAAI,CAAC,KAAK,IAAI,KAAK,KAAK,GAAG;QAAE,OAAO,EAAE,CAAC;IACvC,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAC7B,IAAI,CAAC,OAAO,IAAI,OAAO,KAAK,GAAG;QAAE,OAAO,EAAE,CAAC;IAC3C,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,M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;QACxE,mCAAmC;QACnC,MAAM,MAAM,GAAG,aAAa,CAC1B,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,cAAc,CAAC,CACtC,CAAC,QAAQ,EAAE,CAAC;QACb,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1D,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,WAAW,SAAS,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,OAAO,EAAE,CAAC;QACjB,wEAAwE;QACxE,8DAA8D;QAC9D,MAAM,QAAQ,IAAI,OAAO,CAAC;IAC5B,CAAC;AACH,CAAC;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC","sourcesContent":["/**\n * Framework request handler — registers framework routes on Nitro's h3 instance.\n *\n * Nitro 3 exposes its h3 app as `nitroApp.h3`. We register framework routes\n * directly on it as middleware (`nitroApp.h3[\"~middleware\"]`), giving each\n * plugin a path-prefix-matched handler that runs before any file-based route.\n *\n * Plugins call `getH3App(nitroApp).use(path, handler)` exactly like h3 v1's\n * `app.use()` — the wrapper translates that into v2 middleware registration.\n *\n * Default plugins that the template doesn't provide are auto-mounted on the\n * first call to `getH3App()` per nitroApp instance.\n */\nimport type { EventHandler, H3Event } from \"h3\";\nimport { setResponseHeader, setResponseStatus } from \"h3\";\nimport { getMissingDefaultPlugins } from \"../deploy/route-discovery.js\";\n\nconst BOOTSTRAPPED = new WeakSet<object>();\nconst IN_BOOTSTRAP = new WeakSet<object>();\nconst FRAMEWORK_PREFIX = \"/_agent-native\";\nconst WELL_KNOWN_PREFIX = \"/.well-known\";\nconst APP_SHIM_KEY = \"_agentNativeH3Shim\";\nconst BOOTSTRAP_PROMISE_KEY = \"_agentNativeBootstrapPromise\";\nconst PLUGIN_READY_KEY = \"_agentNativePluginReadyPromise\";\nconst PROVIDED_PLUGIN_STEMS_KEY = \"_agentNativeProvidedPluginStems\";\n\nfunction normalizeAppBasePath(value: string | undefined): string {\n if (!value || value === \"/\") return \"\";\n const trimmed = value.trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return `/${trimmed.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\")}`;\n}\n\nfunction getAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\nfunction pathMatchesPrefix(reqPath: string, prefix: string): boolean {\n return reqPath === prefix || reqPath.startsWith(prefix + \"/\");\n}\n\nfunction supportsAppBasePathMount(path: string): boolean {\n return (\n pathMatchesPrefix(path, FRAMEWORK_PREFIX) ||\n pathMatchesPrefix(path, WELL_KNOWN_PREFIX)\n );\n}\n\nfunction resolveMountMatch(\n reqPath: string,\n path: string,\n): { mountPath: string; strippedPath: string } | null {\n if (pathMatchesPrefix(reqPath, path)) {\n return { mountPath: path, strippedPath: reqPath.slice(path.length) || \"/\" };\n }\n\n const appBasePath = getAppBasePath();\n if (!appBasePath || !supportsAppBasePathMount(path)) return null;\n\n const prefixedPath = `${appBasePath}${path}`;\n if (!pathMatchesPrefix(reqPath, prefixedPath)) return null;\n return {\n mountPath: prefixedPath,\n strippedPath: reqPath.slice(prefixedPath.length) || \"/\",\n };\n}\n\n/**\n * Wrapper around Nitro's h3 instance that exposes a v1-style `.use()` API\n * for registering path-prefix middleware.\n */\nexport interface H3AppShim {\n use(path: string, handler: EventHandler): void;\n use(handler: EventHandler): void;\n}\n\n/**\n * Mark a default plugin slot as supplied by the app/template before the\n * framework default bootstrap runs.\n *\n * Bundled serverless functions often don't have the original\n * `server/plugins/*.ts` tree on disk at runtime, so filesystem route discovery\n * can falsely conclude a template plugin is missing. Explicit plugin factories\n * call this synchronously before awaiting bootstrap so the framework does not\n * auto-mount a generic default over the app's custom implementation.\n */\nexport function markDefaultPluginProvided(nitroApp: any, stem: string): void {\n if (!nitroApp || !stem) return;\n const existing = nitroApp[PROVIDED_PLUGIN_STEMS_KEY] as\n | Set<string>\n | undefined;\n const provided = existing ?? new Set<string>();\n provided.add(stem);\n nitroApp[PROVIDED_PLUGIN_STEMS_KEY] = provided;\n}\n\n/**\n * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this\n * to register routes via `.use(path, handler)`.\n *\n * On the first call per nitroApp, we kick off auto-mounting any missing\n * default plugins. User-facing plugin factories (createAgentChatPlugin,\n * createAuthPlugin, etc.) await this bootstrap via `awaitBootstrap()` so the\n * default plugins finish registering middleware before requests arrive.\n */\nexport function getH3App(nitroApp: any): H3AppShim {\n if (!nitroApp) throw new Error(\"getH3App: nitroApp is required\");\n\n // Reuse the cached shim if we've wrapped this nitroApp before\n const cached = nitroApp[APP_SHIM_KEY] as H3AppShim | undefined;\n if (cached) return cached;\n\n const shim: H3AppShim = {\n use(arg1: string | EventHandler, arg2?: EventHandler) {\n const path = typeof arg1 === \"string\" ? arg1 : \"\";\n const handler = (typeof arg1 === \"string\" ? arg2 : arg1) as EventHandler;\n if (typeof handler !== \"function\") {\n throw new Error(\"getH3App.use: handler must be a function\");\n }\n registerMiddleware(nitroApp, path, handler);\n },\n };\n\n nitroApp[APP_SHIM_KEY] = shim;\n\n if (!BOOTSTRAPPED.has(nitroApp)) {\n BOOTSTRAPPED.add(nitroApp);\n nitroApp[BOOTSTRAP_PROMISE_KEY] = bootstrapDefaultPlugins(nitroApp).catch(\n (err) => {\n console.warn(\n \"[agent-native] Failed to auto-mount default plugins:\",\n (err as Error).message,\n );\n },\n );\n\n // Readiness gate: Nitro v3 doesn't await async plugins, so routes\n // registered inside an async plugin may not exist when the first\n // request arrives. These middleware entries hold framework routes\n // until default-plugin bootstrap and tracked plugin inits complete.\n const readinessGate = (async (event: H3Event) => {\n await awaitFrameworkRoutesReady(nitroApp);\n // Fall through — the actual route handler runs next.\n return undefined;\n }) as EventHandler;\n registerMiddleware(nitroApp, FRAMEWORK_PREFIX, readinessGate);\n registerMiddleware(nitroApp, WELL_KNOWN_PREFIX, readinessGate);\n }\n\n return shim;\n}\n\n/**\n * Wait for the framework's default-plugin bootstrap to complete.\n *\n * Called by user-facing plugin factories (`createAgentChatPlugin`, etc.) at\n * the top of their plugin function, so that by the time the function returns\n * — and Nitro starts accepting requests — all default plugins have finished\n * registering their middleware.\n *\n * No-op when called from inside the bootstrap itself (avoids deadlock when a\n * default plugin happens to be running as part of bootstrap).\n */\nexport async function awaitBootstrap(nitroApp: any): Promise<void> {\n if (!nitroApp || IN_BOOTSTRAP.has(nitroApp)) return;\n // Trigger bootstrap if it hasn't been already (idempotent — getH3App\n // creates the shim and kicks off bootstrap on first call).\n getH3App(nitroApp);\n const promise = nitroApp[BOOTSTRAP_PROMISE_KEY];\n if (promise) await promise;\n}\n\n/**\n * Wait until framework routes are safe to dispatch.\n *\n * Request-time gates must wait for both phases:\n * 1. default-plugin bootstrap, which discovers and starts missing plugins\n * 2. async plugin init promises, which register routes such as A2A cards\n */\nasync function awaitFrameworkRoutesReady(nitroApp: any): Promise<void> {\n if (!nitroApp) return;\n const bootstrapPromise = nitroApp[BOOTSTRAP_PROMISE_KEY];\n if (bootstrapPromise) await bootstrapPromise;\n await awaitPluginsReady(nitroApp);\n}\n\n/**\n * Track an async plugin's initialization promise. Nitro v3 calls plugins\n * synchronously and doesn't await async return values, so routes registered\n * inside an async plugin may not be ready when the first request arrives.\n *\n * Call this from the TOP of any async plugin so that the readiness gate\n * (installed by getH3App) can hold /_agent-native requests until the plugin\n * finishes mounting its routes.\n */\nexport function trackPluginInit(nitroApp: any, promise: Promise<void>): void {\n if (!nitroApp) return;\n // Attach a no-op catch so the promise doesn't surface as an unhandled\n // rejection when Nitro v3 drops the async return value. The actual error\n // is still observable when awaitPluginsReady() re-awaits the promise.\n const safe = promise.catch((err) => {\n console.error(\n \"[agent-native] Plugin init failed:\",\n (err as Error).message || err,\n );\n });\n const existing = nitroApp[PLUGIN_READY_KEY] as Promise<void>[] | undefined;\n if (existing) {\n existing.push(safe);\n } else {\n nitroApp[PLUGIN_READY_KEY] = [safe];\n }\n}\n\n/**\n * Await all tracked plugin initializations. Called by the readiness gate\n * middleware before dispatching framework routes.\n */\nexport async function awaitPluginsReady(nitroApp: any): Promise<void> {\n const promises = nitroApp[PLUGIN_READY_KEY] as Promise<void>[] | undefined;\n if (promises?.length) {\n await Promise.all(promises);\n nitroApp[PLUGIN_READY_KEY] = [];\n }\n}\n\n/**\n * Register a path-prefix middleware on Nitro's h3 instance.\n *\n * The middleware:\n * - Returns `next()` (continues) if the request path doesn't match.\n * - Otherwise dispatches to the handler. If the handler returns a value,\n * it short-circuits the request. If it returns undefined, next() runs.\n *\n * Path matching emulates h3 v1's `app.use(path, ...)` behavior:\n * - Exact-match prefix: `/foo` matches `/foo`, `/foo/bar`, but not `/foobar`\n * - Empty path: middleware runs on every request\n */\nfunction registerMiddleware(\n nitroApp: any,\n path: string,\n handler: EventHandler,\n) {\n const h3 = nitroApp.h3;\n if (!h3 || !Array.isArray(h3[\"~middleware\"])) {\n throw new Error(\n \"[agent-native] Cannot register route: nitroApp.h3 is not available. \" +\n \"Make sure you're calling getH3App() from inside a Nitro plugin.\",\n );\n }\n\n const middleware = async (event: H3Event, next: () => any) => {\n let originalPathname: string | undefined;\n let originalEventPath: string | undefined;\n let hadEventPath = false;\n const restoreOriginalPath = () => {\n if (originalPathname !== undefined) {\n try {\n event.url.pathname = originalPathname;\n } catch {\n // ignore\n }\n originalPathname = undefined;\n }\n if (hadEventPath) {\n try {\n (event as any).path = originalEventPath;\n } catch {\n // ignore\n }\n } else {\n try {\n delete (event as any).path;\n } catch {\n // ignore\n }\n }\n };\n if (path) {\n const reqPath = event.url?.pathname ?? \"\";\n const match = resolveMountMatch(reqPath, path);\n if (!match) {\n return next();\n }\n // Strip the mount prefix from event.url.pathname so handlers that\n // dispatch sub-routes can read `event.path` (or `event.url.pathname`)\n // and see the path RELATIVE to their mount point — matching h3 v1's\n // `app.use(path, handler)` semantics.\n const eventAny = event as any;\n hadEventPath = \"path\" in eventAny;\n originalEventPath = eventAny.path;\n try {\n originalPathname = event.url.pathname;\n // Save the full path in context so handlers that need the original URL\n // (e.g. Better Auth, which extracts its own basePath prefix) can\n // reconstruct a Request with the un-stripped URL.\n eventAny.context = eventAny.context ?? {};\n eventAny.context._mountedPathname = originalPathname;\n eventAny.context._mountPrefix = match.mountPath;\n event.url.pathname = match.strippedPath;\n eventAny.path = `${match.strippedPath}${event.url.search || \"\"}`;\n } catch {\n // event.url is read-only on some runtimes — fall through. Handlers\n // that don't depend on prefix stripping (most of them) still work.\n }\n }\n try {\n const result = await handler(event);\n if (result === undefined) {\n // Restore the original pathname BEFORE calling next() so downstream\n // middleware sees the full URL — not the stripped mount-relative path.\n // Matches h3 v2's own sub-app middleware pattern where the restore\n // happens inside the next() callback, not after it returns.\n restoreOriginalPath();\n return next();\n }\n return result;\n } catch (err) {\n // Log 500s to the server console so they're debuggable, and respond\n // with JSON instead of the default HTML error page so clients can\n // surface error messages. This only applies to routes mounted under\n // the framework prefix (or middleware mounted at `/`, for which we\n // still want visibility).\n const reqPath = originalPathname ?? event.url?.pathname ?? \"\";\n const e = err as any;\n const status =\n typeof e?.statusCode === \"number\"\n ? e.statusCode\n : typeof e?.status === \"number\"\n ? e.status\n : 500;\n console.error(\n `[agent-native] ${event.method ?? \"\"} ${reqPath} failed (${status}):`,\n e?.stack || e?.message || e,\n );\n try {\n setResponseStatus(event, status);\n setResponseHeader(event, \"content-type\", \"application/json\");\n } catch {\n // Response already sent — best effort.\n }\n return {\n error: e?.message || \"Internal server error\",\n // Only surface the stack to clients when explicitly enabled.\n // `NODE_ENV !== \"production\"` was unsafe — preview deploys and\n // any host that forgets to set NODE_ENV=production leaked stack\n // traces (file paths, dependency versions, internal route\n // topology) to anonymous callers. Operators who want stacks in\n // dev set `AGENT_NATIVE_DEBUG_ERRORS=1` explicitly.\n ...(status >= 500 &&\n process.env.AGENT_NATIVE_DEBUG_ERRORS === \"1\" &&\n e?.stack\n ? { stack: e.stack }\n : {}),\n };\n } finally {\n // Restore the original pathname so downstream middleware sees the\n // full URL.\n restoreOriginalPath();\n }\n };\n\n h3[\"~middleware\"].push(middleware);\n}\n\n/**\n * Auto-mount any default framework plugins that the template doesn't provide.\n *\n * Runs once per nitroApp on the first `getH3App()` call. Uses route-discovery\n * to find which default plugin stems are missing from `server/plugins/`, then\n * dynamically imports and mounts them. If a workspace core is present in the\n * ancestor chain, plugin slots the workspace core exports are mounted from\n * there instead of from @agent-native/core — this is the middle layer of the\n * three-layer inheritance model (app local > workspace core > framework).\n */\nasync function bootstrapDefaultPlugins(nitroApp: any): Promise<void> {\n IN_BOOTSTRAP.add(nitroApp);\n try {\n const cwd = process.cwd();\n const discoveredMissing = await getMissingDefaultPlugins(cwd);\n const provided = nitroApp[PROVIDED_PLUGIN_STEMS_KEY] as\n | Set<string>\n | undefined;\n const missing = provided\n ? discoveredMissing.filter((stem) => !provided.has(stem))\n : discoveredMissing;\n if (missing.length === 0) return;\n\n // Lazy import to avoid circular dependency at module load time\n const serverModule = await import(\"./index.js\");\n const terminalModule = await import(\"../terminal/terminal-plugin.js\");\n const integrationsModule = await import(\"../integrations/plugin.js\");\n const orgModule = await import(\"../org/plugin.js\");\n const onboardingModule = await import(\"../onboarding/plugin.js\");\n\n const frameworkImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {\n \"agent-chat\": (serverModule as any).defaultAgentChatPlugin,\n auth: (serverModule as any).defaultAuthPlugin,\n \"core-routes\": (serverModule as any).defaultCoreRoutesPlugin,\n integrations: (integrationsModule as any).defaultIntegrationsPlugin,\n onboarding: (onboardingModule as any).defaultOnboardingPlugin,\n org: (orgModule as any).defaultOrgPlugin,\n resources: (serverModule as any).defaultResourcesPlugin,\n terminal: (terminalModule as any).defaultTerminalPlugin,\n };\n\n // Workspace core layer: if the app is inside an enterprise monorepo with\n // `agent-native.workspaceCore` configured, pull in any plugin slots the\n // workspace core exports from its server entry. We dynamically import the\n // workspace core package at runtime.\n let workspaceImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {};\n try {\n const { getWorkspaceCoreExports } =\n await import(\"../deploy/workspace-core.js\");\n const ws = await getWorkspaceCoreExports(cwd);\n if (ws && Object.keys(ws.plugins).length > 0) {\n try {\n const wsServerModule = await loadWorkspaceCoreServer(\n ws.packageName,\n ws.packageDir,\n );\n for (const [slot, exportName] of Object.entries(ws.plugins)) {\n if (!exportName) continue;\n const impl = (wsServerModule as any)[exportName];\n if (typeof impl === \"function\") {\n workspaceImpls[slot] = impl;\n }\n }\n if (process.env.DEBUG) {\n console.log(\n `[agent-native] Workspace core ${ws.packageName} provides plugin slots: ${Object.keys(workspaceImpls).join(\", \")}`,\n );\n }\n } catch (e) {\n const msg = (e as Error).message ?? \"\";\n // Common cause: workspace-core's package.json points \"./server\"\n // at a TS source file (the scaffold default), but Node can't\n // resolve relative `.js` imports inside it without a TS loader.\n // Tell the user to compile to dist/ rather than just dumping the\n // raw resolution error.\n const tsLoadHint = /\\.js' imported from .*\\.ts/.test(msg)\n ? \" — workspace-core src is TypeScript but isn't being compiled. \" +\n \"Run `pnpm --filter \" +\n ws.packageName +\n \" build` and point its `./server` export at dist/server/index.js.\"\n : \"\";\n console.warn(\n `[agent-native] Failed to load workspace core ${ws.packageName}/server: ${msg}${tsLoadHint}`,\n );\n }\n }\n } catch {\n // Workspace shared package isn't available (e.g. running on an edge\n // runtime without fs). Silently fall through to framework defaults.\n }\n\n if (process.env.DEBUG)\n console.log(\n `[agent-native] Auto-mounting ${missing.length} default plugin(s): ${missing.join(\", \")}`,\n );\n\n for (const stem of missing) {\n // Prefer workspace-core impl over framework default when both exist.\n const impl = workspaceImpls[stem] ?? frameworkImpls[stem];\n if (typeof impl === \"function\") {\n try {\n await impl(nitroApp);\n } catch (e) {\n console.warn(\n `[agent-native] Failed to auto-mount default plugin ${stem}:`,\n (e as Error).message,\n );\n }\n }\n }\n } finally {\n IN_BOOTSTRAP.delete(nitroApp);\n }\n}\n\n/**\n * Load a workspace-core's `/server` entry, transparently handling TS source.\n *\n * The scaffolded workspace-core template ships TS sources without a build\n * step (exports point at `./src/server/index.ts`), so plain `await import()`\n * blows up the moment Node hits a relative `.js` import inside (the standard\n * TS ESM convention) — and even before that, Node may resolve the package\n * relative to the framework's own location rather than the user's monorepo.\n *\n * We try Node's plain `import()` first (fastest path when the user has\n * compiled to dist/) and fall through to jiti on any error. jiti is anchored\n * to a real file inside the workspace-core's directory, so its module\n * resolution starts in the right node_modules tree (handles pnpm hoisting\n * and linked workspaces) AND handles TS source files + `.js` → `.ts` ESM\n * extension remapping.\n *\n * Edge runtimes without `fs` won't be able to load jiti at all; the outer\n * try/catch silently falls through to framework defaults in that case.\n */\nexport async function loadWorkspaceCoreServer(\n packageName: string,\n packageDir: string,\n): Promise<any> {\n let firstErr: unknown;\n try {\n return await import(/* @vite-ignore */ `${packageName}/server`);\n } catch (e) {\n firstErr = e;\n }\n\n try {\n const { createJiti } = await import(\"jiti\");\n const { pathToFileURL } = await import(\"node:url\");\n const path = await import(\"node:path\");\n // Anchor jiti to a real file inside the workspace-core package so its\n // module resolution starts in the right node_modules tree (handles pnpm\n // hoisting and linked workspaces).\n const anchor = pathToFileURL(\n path.join(packageDir, \"package.json\"),\n ).toString();\n const jiti = createJiti(anchor, { interopDefault: true });\n return await jiti.import(`${packageName}/server`);\n } catch (jitiErr) {\n // jiti also failed — rethrow the original Node error since it's usually\n // more informative about *why* the package wasn't resolvable.\n throw firstErr ?? jitiErr;\n }\n}\n\nexport { FRAMEWORK_PREFIX };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"resources-plugin.d.ts","sourceRoot":"","sources":["../../src/server/resources-plugin.ts"],"names":[],"mappings":"AAYA,KAAK,cAAc,GAAG,CAAC,QAAQ,EAAE,GAAG,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE9D;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,IAAI,cAAc,CA0DtD;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,EAAE,cAAwC,CAAC"}
1
+ {"version":3,"file":"resources-plugin.d.ts","sourceRoot":"","sources":["../../src/server/resources-plugin.ts"],"names":[],"mappings":"AAeA,KAAK,cAAc,GAAG,CAAC,QAAQ,EAAE,GAAG,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE9D;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,IAAI,cAAc,CA2DtD;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,EAAE,cAAwC,CAAC"}
@@ -1,4 +1,4 @@
1
- import { getH3App } from "./framework-request-handler.js";
1
+ import { getH3App, markDefaultPluginProvided, } from "./framework-request-handler.js";
2
2
  import { defineEventHandler, setResponseStatus, getMethod } from "h3";
3
3
  import { handleListResources, handleGetResourceTree, handleGetResource, handleCreateResource, handleUpdateResource, handleDeleteResource, handleUploadResource, } from "../resources/handlers.js";
4
4
  /**
@@ -15,6 +15,7 @@ import { handleListResources, handleGetResourceTree, handleGetResource, handleCr
15
15
  */
16
16
  export function createResourcesPlugin() {
17
17
  return async (nitroApp) => {
18
+ markDefaultPluginProvided(nitroApp, "resources");
18
19
  // Mount specific sub-routes BEFORE the catch-all
19
20
  getH3App(nitroApp).use("/_agent-native/resources/tree", defineEventHandler(async (event) => {
20
21
  if (getMethod(event) !== "GET") {
@@ -1 +1 @@
1
- {"version":3,"file":"resources-plugin.js","sourceRoot":"","sources":["../../src/server/resources-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AACtE,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,0BAA0B,CAAC;AAIlC;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,qBAAqB;IACnC,OAAO,KAAK,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gBAC/B,IAAI,MAAM,KAAK,KAAK;oBAAE,OAAO,mBAAmB,CAAC,KAAK,CAAC,CAAC;gBACxD,IAAI,MAAM,KAAK,MAAM;oBAAE,OAAO,oBAAoB,CAAC,KAAK,CAAC,CAAC;gBAC1D,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;gBAC9B,OAAO,EAAE,KAAK,EAAE,oBAAoB,EAAE,CAAC;YACzC,CAAC;YAED,4CAA4C;YAC5C,IAAI,OAAO,KAAK,MAAM,IAAI,OAAO,KAAK,QAAQ;gBAAE,OAAO;YAEvD,qDAAqD;YACrD,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,CAAC;YAEhE,IAAI,MAAM,KAAK,KAAK;gBAAE,OAAO,iBAAiB,CAAC,KAAK,CAAC,CAAC;YACtD,IAAI,MAAM,KAAK,KAAK;gBAAE,OAAO,oBAAoB,CAAC,KAAK,CAAC,CAAC;YACzD,IAAI,MAAM,KAAK,QAAQ;gBAAE,OAAO,oBAAoB,CAAC,KAAK,CAAC,CAAC;YAE5D,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;YAC9B,OAAO,EAAE,KAAK,EAAE,oBAAoB,EAAE,CAAC;QACzC,CAAC,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAmB,qBAAqB,EAAE,CAAC","sourcesContent":["import { getH3App } from \"./framework-request-handler.js\";\nimport { defineEventHandler, setResponseStatus, getMethod } from \"h3\";\nimport {\n handleListResources,\n handleGetResourceTree,\n handleGetResource,\n handleCreateResource,\n handleUpdateResource,\n handleDeleteResource,\n handleUploadResource,\n} from \"../resources/handlers.js\";\n\ntype NitroPluginDef = (nitroApp: any) => void | Promise<void>;\n\n/**\n * Creates a Nitro plugin that mounts all resource CRUD routes.\n *\n * Routes:\n * GET /_agent-native/resources — list resources\n * POST /_agent-native/resources — create resource\n * GET /_agent-native/resources/tree — get resource tree\n * POST /_agent-native/resources/upload — upload file\n * GET /_agent-native/resources/:id — get resource by ID\n * PUT /_agent-native/resources/:id — update resource\n * DELETE /_agent-native/resources/:id — delete resource\n */\nexport function createResourcesPlugin(): NitroPluginDef {\n return async (nitroApp: any) => {\n // Mount specific sub-routes BEFORE the catch-all\n\n getH3App(nitroApp).use(\n \"/_agent-native/resources/tree\",\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n return handleGetResourceTree(event);\n }),\n );\n\n getH3App(nitroApp).use(\n \"/_agent-native/resources/upload\",\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n return handleUploadResource(event);\n }),\n );\n\n // Catch-all for /_agent-native/resources and /_agent-native/resources/:id\n getH3App(nitroApp).use(\n \"/_agent-native/resources\",\n defineEventHandler(async (event) => {\n const method = getMethod(event);\n // h3 strips the mount prefix, so event.path is \"/\" or \"/:id\"\n const raw = (event.path || \"/\").split(\"?\")[0];\n const subPath = raw.replace(/^\\//, \"\");\n\n // No sub-path: /_agent-native/resources — list or create\n if (!subPath || subPath === \"\") {\n if (method === \"GET\") return handleListResources(event);\n if (method === \"POST\") return handleCreateResource(event);\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Already handled by dedicated routes above\n if (subPath === \"tree\" || subPath === \"upload\") return;\n\n // /_agent-native/resources/:id — get, update, delete\n event.context.params = { ...event.context.params, id: subPath };\n\n if (method === \"GET\") return handleGetResource(event);\n if (method === \"PUT\") return handleUpdateResource(event);\n if (method === \"DELETE\") return handleDeleteResource(event);\n\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }),\n );\n };\n}\n\n/**\n * Default resources plugin — mount with no configuration needed.\n *\n * Usage in templates:\n * ```ts\n * // server/plugins/resources.ts\n * import { defaultResourcesPlugin } from \"@agent-native/core/server\";\n * export default defaultResourcesPlugin;\n * ```\n */\nexport const defaultResourcesPlugin: NitroPluginDef = createResourcesPlugin();\n"]}
1
+ {"version":3,"file":"resources-plugin.js","sourceRoot":"","sources":["../../src/server/resources-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,QAAQ,EACR,yBAAyB,GAC1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AACtE,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,0BAA0B,CAAC;AAIlC;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,qBAAqB;IACnC,OAAO,KAAK,EAAE,QAAa,EAAE,EAAE;QAC7B,yBAAyB,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;QACjD,iDAAiD;QAEjD,QAAQ,CAAC,QAAQ,CAAC,CAAC,GAAG,CACpB,+BAA+B,EAC/B,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;YACjC,IAAI,SAAS,CAAC,KAAK,CAAC,KAAK,KAAK,EAAE,CAAC;gBAC/B,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;gBAC9B,OAAO,EAAE,KAAK,EAAE,oBAAoB,EAAE,CAAC;YACzC,CAAC;YACD,OAAO,qBAAqB,CAAC,KAAK,CAAC,CAAC;QACtC,CAAC,CAAC,CACH,CAAC;QAEF,QAAQ,CAAC,QAAQ,CAAC,CAAC,GAAG,CACpB,iCAAiC,EACjC,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;YACjC,IAAI,SAAS,CAAC,KAAK,CAAC,KAAK,MAAM,EAAE,CAAC;gBAChC,iBAAiB,CAAC,KAAK,EAAE,G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OAAO,oBAAoB,CAAC,KAAK,CAAC,CAAC;YACzD,IAAI,MAAM,KAAK,QAAQ;gBAAE,OAAO,oBAAoB,CAAC,KAAK,CAAC,CAAC;YAE5D,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;YAC9B,OAAO,EAAE,KAAK,EAAE,oBAAoB,EAAE,CAAC;QACzC,CAAC,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAmB,qBAAqB,EAAE,CAAC","sourcesContent":["import {\n getH3App,\n markDefaultPluginProvided,\n} from \"./framework-request-handler.js\";\nimport { defineEventHandler, setResponseStatus, getMethod } from \"h3\";\nimport {\n handleListResources,\n handleGetResourceTree,\n handleGetResource,\n handleCreateResource,\n handleUpdateResource,\n handleDeleteResource,\n handleUploadResource,\n} from \"../resources/handlers.js\";\n\ntype NitroPluginDef = (nitroApp: any) => void | Promise<void>;\n\n/**\n * Creates a Nitro plugin that mounts all resource CRUD routes.\n *\n * Routes:\n * GET /_agent-native/resources — list resources\n * POST /_agent-native/resources — create resource\n * GET /_agent-native/resources/tree — get resource tree\n * POST /_agent-native/resources/upload — upload file\n * GET /_agent-native/resources/:id — get resource by ID\n * PUT /_agent-native/resources/:id — update resource\n * DELETE /_agent-native/resources/:id — delete resource\n */\nexport function createResourcesPlugin(): NitroPluginDef {\n return async (nitroApp: any) => {\n markDefaultPluginProvided(nitroApp, \"resources\");\n // Mount specific sub-routes BEFORE the catch-all\n\n getH3App(nitroApp).use(\n \"/_agent-native/resources/tree\",\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n return handleGetResourceTree(event);\n }),\n );\n\n getH3App(nitroApp).use(\n \"/_agent-native/resources/upload\",\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n return handleUploadResource(event);\n }),\n );\n\n // Catch-all for /_agent-native/resources and /_agent-native/resources/:id\n getH3App(nitroApp).use(\n \"/_agent-native/resources\",\n defineEventHandler(async (event) => {\n const method = getMethod(event);\n // h3 strips the mount prefix, so event.path is \"/\" or \"/:id\"\n const raw = (event.path || \"/\").split(\"?\")[0];\n const subPath = raw.replace(/^\\//, \"\");\n\n // No sub-path: /_agent-native/resources — list or create\n if (!subPath || subPath === \"\") {\n if (method === \"GET\") return handleListResources(event);\n if (method === \"POST\") return handleCreateResource(event);\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Already handled by dedicated routes above\n if (subPath === \"tree\" || subPath === \"upload\") return;\n\n // /_agent-native/resources/:id — get, update, delete\n event.context.params = { ...event.context.params, id: subPath };\n\n if (method === \"GET\") return handleGetResource(event);\n if (method === \"PUT\") return handleUpdateResource(event);\n if (method === \"DELETE\") return handleDeleteResource(event);\n\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }),\n );\n };\n}\n\n/**\n * Default resources plugin — mount with no configuration needed.\n *\n * Usage in templates:\n * ```ts\n * // server/plugins/resources.ts\n * import { defaultResourcesPlugin } from \"@agent-native/core/server\";\n * export default defaultResourcesPlugin;\n * ```\n */\nexport const defaultResourcesPlugin: NitroPluginDef = createResourcesPlugin();\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"terminal-plugin.d.ts","sourceRoot":"","sources":["../../src/terminal/terminal-plugin.ts"],"names":[],"mappings":"AA0DA,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,mBAgL5B;AAED,mDAAmD;AACnD,eAAO,MAAM,qBAAqB,aAnLR,GAAG,kBAmL8B,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,mBAiL5B;AAED,mDAAmD;AACnD,eAAO,MAAM,qBAAqB,aApLR,GAAG,kBAoL8B,CAAC"}
@@ -1,4 +1,4 @@
1
- import { getH3App } from "../server/framework-request-handler.js";
1
+ import { getH3App, markDefaultPluginProvided, } from "../server/framework-request-handler.js";
2
2
  import { isNodeRuntime } from "../shared/runtime.js";
3
3
  import * as fs from "node:fs";
4
4
  import * as path from "node:path";
@@ -54,6 +54,7 @@ let _disabledLogged = false;
54
54
  let _frameDetectedLogged = false;
55
55
  export function createTerminalPlugin(options = {}) {
56
56
  return async (nitroApp) => {
57
+ markDefaultPluginProvided(nitroApp, "terminal");
57
58
  // Terminal requires Node.js (PTY, child_process) — skip on edge runtimes
58
59
  if (!isNodeRuntime())
59
60
  return;