@jami-studio/core 0.92.21 → 0.92.22

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.
@@ -1,5 +1,11 @@
1
1
  # @agent-native/core
2
2
 
3
+ ## 0.92.22
4
+
5
+ ### Patch Changes
6
+
7
+ - be9682d: Fix permanently hanging framework routes on Cloudflare Workers: nitro doesn't await async plugins, so plugin-init and default-bootstrap promises are created during an app's first request — when that request responds before they settle (e.g. an auth route that doesn't match the pending inits' paths), workerd freezes their pending I/O forever and every later request's readiness gate awaits a promise that can never settle (observed: authed action requests hanging >90s after a get-session request initialized the app). Init promises are now tied to the creating request's lifetime via ctx.waitUntil, and readiness-gate awaits are bounded (20s) on workerd so a frozen init degrades to a retryable response instead of a permanent hang.
8
+
3
9
  ## 0.92.21
4
10
 
5
11
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.92.21",
3
+ "version": "0.92.22",
4
4
  "description": "Framework for agent-native application development — where AI agents and UI share SQL state, actions, and context",
5
5
  "homepage": "https://github.com/studio-jami/jami-studio#readme",
6
6
  "bugs": {
@@ -17,6 +17,7 @@ import { setResponseHeader, setResponseStatus } from "h3";
17
17
  import { getMissingDefaultPlugins } from "../deploy/route-discovery.js";
18
18
  import { getConfiguredAppBasePath } from "./app-base-path.js";
19
19
  import { captureError } from "./capture-error.js";
20
+ import { isCloudflareRuntime } from "../shared/runtime.js";
20
21
 
21
22
  const BOOTSTRAPPED = new WeakSet<object>();
22
23
  const IN_BOOTSTRAP = new WeakSet<object>();
@@ -44,6 +45,56 @@ function pathMatchesPrefix(reqPath: string, prefix: string): boolean {
44
45
  return reqPath === prefix || reqPath.startsWith(prefix + "/");
45
46
  }
46
47
 
48
+ /**
49
+ * Cloudflare Workers (workerd) cancels pending I/O owned by a request the
50
+ * moment its response returns — a promise created during request A that
51
+ * hasn't settled by then FREEZES forever. Plugin-init and bootstrap promises
52
+ * are created during an app's first request and awaited by later requests'
53
+ * readiness gates, so an early-responding first request (e.g. an auth route
54
+ * that doesn't match the pending inits' paths) permanently wedges every
55
+ * later framework-route request. Tie the promise to the creating request's
56
+ * `waitUntil` so its I/O stays alive until it settles.
57
+ */
58
+ function extendRequestLifetimeOverInit(promise: Promise<unknown>): void {
59
+ try {
60
+ (
61
+ globalThis as {
62
+ __cf_ctx?: { waitUntil?: (p: Promise<unknown>) => void };
63
+ }
64
+ ).__cf_ctx?.waitUntil?.(promise);
65
+ } catch {
66
+ /* not on Cloudflare or ctx unavailable — nothing to extend */
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Bound a readiness-gate await on workerd. Insurance against any init
72
+ * promise that still froze (e.g. created before __cf_ctx existed): a
73
+ * bounded wait turns a permanently hung request into a slow one that
74
+ * proceeds — the route either works (init actually finished) or 404/503s
75
+ * (retryable) instead of hanging until the runtime kills the request.
76
+ */
77
+ async function awaitBounded(promise: Promise<unknown>): Promise<void> {
78
+ if (!isCloudflareRuntime()) {
79
+ await promise;
80
+ return;
81
+ }
82
+ let timer: ReturnType<typeof setTimeout> | undefined;
83
+ const timeout = new Promise<void>((resolve) => {
84
+ timer = setTimeout(() => {
85
+ console.warn(
86
+ "[agent-native] readiness gate timed out waiting for plugin init (20s) — proceeding; the init promise may have been frozen by a prior request's completion",
87
+ );
88
+ resolve();
89
+ }, 20_000);
90
+ });
91
+ try {
92
+ await Promise.race([promise, timeout]);
93
+ } finally {
94
+ if (timer) clearTimeout(timer);
95
+ }
96
+ }
97
+
47
98
  function supportsAppBasePathMount(path: string): boolean {
48
99
  return (
49
100
  pathMatchesPrefix(path, FRAMEWORK_PREFIX) ||
@@ -143,6 +194,9 @@ export function getH3App(nitroApp: any): H3AppShim {
143
194
  });
144
195
  },
145
196
  );
197
+ extendRequestLifetimeOverInit(
198
+ nitroApp[BOOTSTRAP_PROMISE_KEY] as Promise<unknown>,
199
+ );
146
200
 
147
201
  // Readiness gate: Nitro v3 doesn't await async plugins, so routes
148
202
  // registered inside an async plugin may not exist when the first
@@ -257,7 +311,7 @@ async function awaitFrameworkRoutesReadyForRequest(
257
311
  ): Promise<void> {
258
312
  if (!nitroApp) return;
259
313
  const bootstrapPromise = nitroApp[BOOTSTRAP_PROMISE_KEY];
260
- if (bootstrapPromise) await bootstrapPromise;
314
+ if (bootstrapPromise) await awaitBounded(bootstrapPromise);
261
315
  await awaitPluginsReady(nitroApp, reqPath);
262
316
  }
263
317
 
@@ -306,6 +360,7 @@ export function trackPluginInit(
306
360
  promise: safe,
307
361
  paths: options.paths?.filter(Boolean),
308
362
  };
363
+ extendRequestLifetimeOverInit(safe);
309
364
  const existing = nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined;
310
365
  if (existing) {
311
366
  existing.push(entry);
@@ -426,7 +481,7 @@ export async function awaitPluginsReady(
426
481
  : entries;
427
482
 
428
483
  if (relevant.length) {
429
- await Promise.all(relevant.map((entry) => entry.promise));
484
+ await Promise.all(relevant.map((entry) => awaitBounded(entry.promise)));
430
485
  const completed = new Set(relevant);
431
486
  const latest =
432
487
  (nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined) ?? [];
@@ -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;AAShD,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;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AQ,EAAE,GAAG,GAAG,SAAS,CA6EjD;AA0CD;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,QAAQ,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAOjE;AAmBD;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,GAAG,EACb,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,EACtB,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;CAAO,GACjC,IAAI,CAwCN;AA6FD;;;GAGG;AACH,wBAAsB,iBAAiB,CACrC,QAAQ,EAAE,GAAG,EACb,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,IAAI,CAAC,CAqBf;AAwTD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,GAAG,CAAC,CAyBd;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
@@ -2,6 +2,7 @@ import { setResponseHeader, setResponseStatus } from "h3";
2
2
  import { getMissingDefaultPlugins } from "../deploy/route-discovery.js";
3
3
  import { getConfiguredAppBasePath } from "./app-base-path.js";
4
4
  import { captureError } from "./capture-error.js";
5
+ import { isCloudflareRuntime } from "../shared/runtime.js";
5
6
  const BOOTSTRAPPED = new WeakSet();
6
7
  const IN_BOOTSTRAP = new WeakSet();
7
8
  const FRAMEWORK_PREFIX = "/_agent-native";
@@ -19,6 +20,51 @@ function getAppBasePath() {
19
20
  function pathMatchesPrefix(reqPath, prefix) {
20
21
  return reqPath === prefix || reqPath.startsWith(prefix + "/");
21
22
  }
23
+ /**
24
+ * Cloudflare Workers (workerd) cancels pending I/O owned by a request the
25
+ * moment its response returns — a promise created during request A that
26
+ * hasn't settled by then FREEZES forever. Plugin-init and bootstrap promises
27
+ * are created during an app's first request and awaited by later requests'
28
+ * readiness gates, so an early-responding first request (e.g. an auth route
29
+ * that doesn't match the pending inits' paths) permanently wedges every
30
+ * later framework-route request. Tie the promise to the creating request's
31
+ * `waitUntil` so its I/O stays alive until it settles.
32
+ */
33
+ function extendRequestLifetimeOverInit(promise) {
34
+ try {
35
+ globalThis.__cf_ctx?.waitUntil?.(promise);
36
+ }
37
+ catch {
38
+ /* not on Cloudflare or ctx unavailable — nothing to extend */
39
+ }
40
+ }
41
+ /**
42
+ * Bound a readiness-gate await on workerd. Insurance against any init
43
+ * promise that still froze (e.g. created before __cf_ctx existed): a
44
+ * bounded wait turns a permanently hung request into a slow one that
45
+ * proceeds — the route either works (init actually finished) or 404/503s
46
+ * (retryable) instead of hanging until the runtime kills the request.
47
+ */
48
+ async function awaitBounded(promise) {
49
+ if (!isCloudflareRuntime()) {
50
+ await promise;
51
+ return;
52
+ }
53
+ let timer;
54
+ const timeout = new Promise((resolve) => {
55
+ timer = setTimeout(() => {
56
+ console.warn("[agent-native] readiness gate timed out waiting for plugin init (20s) — proceeding; the init promise may have been frozen by a prior request's completion");
57
+ resolve();
58
+ }, 20_000);
59
+ });
60
+ try {
61
+ await Promise.race([promise, timeout]);
62
+ }
63
+ finally {
64
+ if (timer)
65
+ clearTimeout(timer);
66
+ }
67
+ }
22
68
  function supportsAppBasePathMount(path) {
23
69
  return (pathMatchesPrefix(path, FRAMEWORK_PREFIX) ||
24
70
  pathMatchesPrefix(path, WELL_KNOWN_PREFIX));
@@ -93,6 +139,7 @@ export function getH3App(nitroApp) {
93
139
  tags: { phase: "default-plugin-bootstrap" },
94
140
  });
95
141
  });
142
+ extendRequestLifetimeOverInit(nitroApp[BOOTSTRAP_PROMISE_KEY]);
96
143
  // Readiness gate: Nitro v3 doesn't await async plugins, so routes
97
144
  // registered inside an async plugin may not exist when the first
98
145
  // request arrives. These middleware entries hold framework routes
@@ -194,7 +241,7 @@ async function awaitFrameworkRoutesReadyForRequest(nitroApp, reqPath) {
194
241
  return;
195
242
  const bootstrapPromise = nitroApp[BOOTSTRAP_PROMISE_KEY];
196
243
  if (bootstrapPromise)
197
- await bootstrapPromise;
244
+ await awaitBounded(bootstrapPromise);
198
245
  await awaitPluginsReady(nitroApp, reqPath);
199
246
  }
200
247
  /**
@@ -234,6 +281,7 @@ export function trackPluginInit(nitroApp, promise, options = {}) {
234
281
  promise: safe,
235
282
  paths: options.paths?.filter(Boolean),
236
283
  };
284
+ extendRequestLifetimeOverInit(safe);
237
285
  const existing = nitroApp[PLUGIN_READY_KEY];
238
286
  if (existing) {
239
287
  existing.push(entry);
@@ -320,7 +368,7 @@ export async function awaitPluginsReady(nitroApp, reqPath) {
320
368
  : true)
321
369
  : entries;
322
370
  if (relevant.length) {
323
- await Promise.all(relevant.map((entry) => entry.promise));
371
+ await Promise.all(relevant.map((entry) => awaitBounded(entry.promise)));
324
372
  const completed = new Set(relevant);
325
373
  const latest = nitroApp[PLUGIN_READY_KEY] ?? [];
326
374
  nitroApp[PLUGIN_READY_KEY] = latest.filter((entry) => !completed.has(entry));
@@ -1 +1 @@
1
- {"version":3,"file":"framework-request-handler.js","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AAE1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,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,M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exposes its h3 app as `nitroApp.h3`. We register framework routes\r\n * directly on it as middleware (`nitroApp.h3[\"~middleware\"]`), giving each\r\n * plugin a path-prefix-matched handler that runs before any file-based route.\r\n *\r\n * Plugins call `getH3App(nitroApp).use(path, handler)` exactly like h3 v1's\r\n * `app.use()` — the wrapper translates that into v2 middleware registration.\r\n *\r\n * Default plugins that the template doesn't provide are auto-mounted on the\r\n * first call to `getH3App()` per nitroApp instance.\r\n */\r\nimport type { EventHandler, H3Event } from \"h3\";\r\nimport { setResponseHeader, setResponseStatus } from \"h3\";\r\n\r\nimport { getMissingDefaultPlugins } from \"../deploy/route-discovery.js\";\r\nimport { getConfiguredAppBasePath } from \"./app-base-path.js\";\r\nimport { captureError } from \"./capture-error.js\";\r\n\r\nconst BOOTSTRAPPED = new WeakSet<object>();\r\nconst IN_BOOTSTRAP = new WeakSet<object>();\r\nconst FRAMEWORK_PREFIX = \"/_agent-native\";\r\nconst WELL_KNOWN_PREFIX = \"/.well-known\";\r\nconst APP_SHIM_KEY = \"_agentNativeH3Shim\";\r\nconst BOOTSTRAP_PROMISE_KEY = \"_agentNativeBootstrapPromise\";\r\nconst PLUGIN_READY_KEY = \"_agentNativePluginReadyPromise\";\r\nconst PLUGIN_READY_PLACEHOLDERS_KEY = \"_agentNativePluginReadyPlaceholders\";\r\nconst PLUGIN_FAILED_KEY = \"_agentNativePluginInitFailures\";\r\nconst PROVIDED_PLUGIN_STEMS_KEY = \"_agentNativeProvidedPluginStems\";\r\nconst MIDDLEWARE_DISPATCHER_PATCHED_KEY =\r\n \"_agentNativeMiddlewareDispatcherPatched\";\r\n\r\ninterface PluginReadyEntry {\r\n promise: Promise<void>;\r\n paths?: string[];\r\n}\r\n\r\nfunction getAppBasePath(): string {\r\n return getConfiguredAppBasePath();\r\n}\r\n\r\nfunction pathMatchesPrefix(reqPath: string, prefix: string): boolean {\r\n return reqPath === prefix || reqPath.startsWith(prefix + \"/\");\r\n}\r\n\r\nfunction supportsAppBasePathMount(path: string): boolean {\r\n return (\r\n pathMatchesPrefix(path, FRAMEWORK_PREFIX) ||\r\n pathMatchesPrefix(path, WELL_KNOWN_PREFIX)\r\n );\r\n}\r\n\r\nfunction resolveMountMatch(\r\n reqPath: string,\r\n path: string,\r\n): { mountPath: string; strippedPath: string } | null {\r\n if (pathMatchesPrefix(reqPath, path)) {\r\n return { mountPath: path, strippedPath: reqPath.slice(path.length) || \"/\" };\r\n }\r\n\r\n const appBasePath = getAppBasePath();\r\n if (!appBasePath || !supportsAppBasePathMount(path)) return null;\r\n\r\n const prefixedPath = `${appBasePath}${path}`;\r\n if (!pathMatchesPrefix(reqPath, prefixedPath)) return null;\r\n return {\r\n mountPath: prefixedPath,\r\n strippedPath: reqPath.slice(prefixedPath.length) || \"/\",\r\n };\r\n}\r\n\r\n/**\r\n * Wrapper around Nitro's h3 instance that exposes a v1-style `.use()` API\r\n * for registering path-prefix middleware.\r\n */\r\nexport interface H3AppShim {\r\n use(path: string, handler: EventHandler): void;\r\n use(handler: EventHandler): void;\r\n}\r\n\r\n/**\r\n * Mark a default plugin slot as supplied by the app/template before the\r\n * framework default bootstrap runs.\r\n *\r\n * Bundled serverless functions often don't have the original\r\n * `server/plugins/*.ts` tree on disk at runtime, so filesystem route discovery\r\n * can falsely conclude a template plugin is missing. Explicit plugin factories\r\n * call this synchronously before awaiting bootstrap so the framework does not\r\n * auto-mount a generic default over the app's custom implementation.\r\n */\r\nexport function markDefaultPluginProvided(nitroApp: any, stem: string): void {\r\n if (!nitroApp || !stem) return;\r\n const existing = nitroApp[PROVIDED_PLUGIN_STEMS_KEY] as\r\n | Set<string>\r\n | undefined;\r\n const provided = existing ?? new Set<string>();\r\n provided.add(stem);\r\n nitroApp[PROVIDED_PLUGIN_STEMS_KEY] = provided;\r\n}\r\n\r\n/**\r\n * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this\r\n * to register routes via `.use(path, handler)`.\r\n *\r\n * On the first call per nitroApp, we kick off auto-mounting any missing\r\n * default plugins. User-facing plugin factories (createAgentChatPlugin,\r\n * createAuthPlugin, etc.) await this bootstrap via `awaitBootstrap()` so the\r\n * default plugins finish registering middleware before requests arrive.\r\n */\r\nexport function getH3App(nitroApp: any): H3AppShim {\r\n if (!nitroApp) throw new Error(\"getH3App: nitroApp is required\");\r\n ensureGlobalMiddlewareDispatch(nitroApp);\r\n\r\n // Reuse the cached shim if we've wrapped this nitroApp before\r\n const cached = nitroApp[APP_SHIM_KEY] as H3AppShim | undefined;\r\n if (cached) return cached;\r\n\r\n const shim: H3AppShim = {\r\n use(arg1: string | EventHandler, arg2?: EventHandler) {\r\n const path = typeof arg1 === \"string\" ? arg1 : \"\";\r\n const handler = (typeof arg1 === \"string\" ? arg2 : arg1) as EventHandler;\r\n if (typeof handler !== \"function\") {\r\n throw new Error(\"getH3App.use: handler must be a function\");\r\n }\r\n registerMiddleware(nitroApp, path, handler);\r\n },\r\n };\r\n\r\n nitroApp[APP_SHIM_KEY] = shim;\r\n\r\n if (!BOOTSTRAPPED.has(nitroApp)) {\r\n BOOTSTRAPPED.add(nitroApp);\r\n nitroApp[BOOTSTRAP_PROMISE_KEY] = bootstrapDefaultPlugins(nitroApp).catch(\r\n (err) => {\r\n console.warn(\r\n \"[agent-native] Failed to auto-mount default plugins:\",\r\n (err as Error).message,\r\n );\r\n captureError(err, {\r\n route: \"default-plugin-bootstrap\",\r\n tags: { phase: \"default-plugin-bootstrap\" },\r\n });\r\n },\r\n );\r\n\r\n // Readiness gate: Nitro v3 doesn't await async plugins, so routes\r\n // registered inside an async plugin may not exist when the first\r\n // request arrives. These middleware entries hold framework routes\r\n // until default-plugin bootstrap and tracked plugin inits complete.\r\n const readinessGate = (async (event: H3Event) => {\r\n const eventAny = event as any;\r\n await awaitFrameworkRoutesReadyForRequest(\r\n nitroApp,\r\n eventAny.context?._mountedPathname ?? event.url?.pathname ?? \"\",\r\n );\r\n // Fall through — the actual route handler runs next.\r\n return undefined;\r\n }) as EventHandler;\r\n registerMiddleware(nitroApp, FRAMEWORK_PREFIX, readinessGate, {\r\n prepend: true,\r\n });\r\n registerMiddleware(nitroApp, WELL_KNOWN_PREFIX, readinessGate, {\r\n prepend: true,\r\n });\r\n\r\n // Primary gate: Nitro bridges this `request` hook to h3's `config.onRequest`,\r\n // which h3 awaits BEFORE `handler()` snapshots middleware and resolves the\r\n // route. The middleware gate above runs too late on production dispatchers —\r\n // its await finishes after the snapshot, so a route registered during async\r\n // init is missing from the request and 404s. The middleware gate stays as a\r\n // fallback for runtimes where `onRequest` isn't wired.\r\n nitroApp.hooks?.hook?.(\"request\", async (event: H3Event) => {\r\n const reqPath = event.url?.pathname ?? \"\";\r\n if (\r\n resolveMountMatch(reqPath, FRAMEWORK_PREFIX) ||\r\n resolveMountMatch(reqPath, WELL_KNOWN_PREFIX)\r\n ) {\r\n await awaitFrameworkRoutesReadyForRequest(nitroApp, reqPath);\r\n }\r\n });\r\n }\r\n\r\n return shim;\r\n}\r\n\r\n/**\r\n * Nitro 3 production builds generate a route dispatcher by overriding h3's\r\n * internal `~getMiddleware()` hook. Some generated dispatchers return only\r\n * route-rule middleware and skip the global `h3[\"~middleware\"]` array that\r\n * `getH3App().use()` appends to. Wrap the dispatcher once so framework routes\r\n * registered at runtime are still part of request dispatch.\r\n */\r\nfunction ensureGlobalMiddlewareDispatch(nitroApp: any): void {\r\n const h3 = nitroApp?.h3;\r\n if (!h3) return;\r\n const current = h3[\"~getMiddleware\"];\r\n if (h3[MIDDLEWARE_DISPATCHER_PATCHED_KEY] === current) return;\r\n\r\n const original = typeof current === \"function\" ? current.bind(h3) : undefined;\r\n\r\n const wrappedGetMiddleware = (event: H3Event, route: unknown) => {\r\n const originalResult = original ? original(event, route) : [];\r\n const originalList = Array.isArray(originalResult)\r\n ? originalResult\r\n : originalResult\r\n ? [originalResult]\r\n : [];\r\n const globalMiddleware = Array.isArray(h3[\"~middleware\"])\r\n ? h3[\"~middleware\"]\r\n : [];\r\n if (globalMiddleware.length === 0) return originalList;\r\n\r\n const alreadyIncluded = new Set(originalList);\r\n const missingGlobal = globalMiddleware.filter(\r\n (middleware) => !alreadyIncluded.has(middleware),\r\n );\r\n return missingGlobal.length\r\n ? [...missingGlobal, ...originalList]\r\n : originalList;\r\n };\r\n\r\n h3[\"~getMiddleware\"] = wrappedGetMiddleware;\r\n h3[MIDDLEWARE_DISPATCHER_PATCHED_KEY] = wrappedGetMiddleware;\r\n}\r\n\r\n/**\r\n * Wait for the framework's default-plugin bootstrap to complete.\r\n *\r\n * Called by user-facing plugin factories (`createAgentChatPlugin`, etc.) at\r\n * the top of their plugin function, so that by the time the function returns\r\n * — and Nitro starts accepting requests — all default plugins have finished\r\n * registering their middleware.\r\n *\r\n * No-op when called from inside the bootstrap itself (avoids deadlock when a\r\n * default plugin happens to be running as part of bootstrap).\r\n */\r\nexport async function awaitBootstrap(nitroApp: any): Promise<void> {\r\n if (!nitroApp || IN_BOOTSTRAP.has(nitroApp)) return;\r\n // Trigger bootstrap if it hasn't been already (idempotent — getH3App\r\n // creates the shim and kicks off bootstrap on first call).\r\n getH3App(nitroApp);\r\n const promise = nitroApp[BOOTSTRAP_PROMISE_KEY];\r\n if (promise) await promise;\r\n}\r\n\r\n/**\r\n * Wait until framework routes are safe to dispatch.\r\n *\r\n * Request-time gates must wait for both phases:\r\n * 1. default-plugin bootstrap, which discovers and starts missing plugins\r\n * 2. async plugin init promises, which register routes such as A2A cards\r\n */\r\nasync function awaitFrameworkRoutesReadyForRequest(\r\n nitroApp: any,\r\n reqPath: string,\r\n): Promise<void> {\r\n if (!nitroApp) return;\r\n const bootstrapPromise = nitroApp[BOOTSTRAP_PROMISE_KEY];\r\n if (bootstrapPromise) await bootstrapPromise;\r\n await awaitPluginsReady(nitroApp, reqPath);\r\n}\r\n\r\n/**\r\n * Track an async plugin's initialization promise. Nitro v3 calls plugins\r\n * synchronously and doesn't await async return values, so routes registered\r\n * inside an async plugin may not be ready when the first request arrives.\r\n *\r\n * Call this from the TOP of any async plugin so that the readiness gate\r\n * (installed by getH3App) can hold /_agent-native requests until the plugin\r\n * finishes mounting its routes.\r\n */\r\nexport function trackPluginInit(\r\n nitroApp: any,\r\n promise: Promise<void>,\r\n options: { paths?: string[] } = {},\r\n): void {\r\n if (!nitroApp) return;\r\n // Ensure the readiness gate exists even when the tracked plugin is the first\r\n // framework code to run in a serverless isolate. Otherwise an immediate\r\n // first request can fall through before the plugin registers its routes.\r\n getH3App(nitroApp);\r\n // Attach a no-op catch so the promise doesn't surface as an unhandled\r\n // rejection when Nitro v3 drops the async return value. The actual error\r\n // is still observable when awaitPluginsReady() re-awaits the promise.\r\n const safe = promise.catch((err) => {\r\n console.error(\r\n \"[agent-native] Plugin init failed:\",\r\n (err as Error).message || err,\r\n );\r\n // Record the failure so the readiness gate can return a retryable 503 for\r\n // this plugin's routes instead of letting them fall through to a bare\r\n // \"Cannot find any route matching\" 404. That bare 404 is what kept biting\r\n // external MCP clients (pi/codex/claude) and the connect flow on cold /\r\n // propagating instances whose async init rejected (e.g. DB not yet\r\n // reachable): the route never registered, so the placeholder released into\r\n // a 404 the client couldn't recover from. A 503 is at least retryable.\r\n const failures = (nitroApp[PLUGIN_FAILED_KEY] ??= new Map<\r\n string,\r\n string\r\n >());\r\n const msg = (err as Error)?.message || String(err);\r\n for (const p of options.paths?.filter(Boolean) ?? []) failures.set(p, msg);\r\n });\r\n const entry: PluginReadyEntry = {\r\n promise: safe,\r\n paths: options.paths?.filter(Boolean),\r\n };\r\n const existing = nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined;\r\n if (existing) {\r\n existing.push(entry);\r\n } else {\r\n nitroApp[PLUGIN_READY_KEY] = [entry];\r\n }\r\n installPluginReadyPlaceholders(nitroApp, entry.paths);\r\n}\r\n\r\nfunction installPluginReadyPlaceholders(\r\n nitroApp: any,\r\n paths: string[] | undefined,\r\n): void {\r\n if (!paths?.length) return;\r\n const existing = nitroApp[PLUGIN_READY_PLACEHOLDERS_KEY] as\r\n | Set<string>\r\n | undefined;\r\n const installed = existing ?? new Set<string>();\r\n nitroApp[PLUGIN_READY_PLACEHOLDERS_KEY] = installed;\r\n\r\n for (const path of paths) {\r\n if (!path || installed.has(path)) continue;\r\n installed.add(path);\r\n registerMiddleware(\r\n nitroApp,\r\n path,\r\n (async (event: H3Event) => {\r\n const eventAny = event as any;\r\n const reqPath =\r\n eventAny.context?._mountedPathname ?? event.url?.pathname ?? path;\r\n await awaitFrameworkRoutesReadyForRequest(nitroApp, reqPath);\r\n // If this plugin's async init failed, its real route was never\r\n // registered. Return a retryable 503 instead of releasing into a bare\r\n // 404 (external MCP clients can't recover from a 404; a 503 is at least\r\n // a \"try again\" the client / next instance can act on).\r\n const failures = nitroApp[PLUGIN_FAILED_KEY] as\r\n | Map<string, string>\r\n | undefined;\r\n if (failures?.size) {\r\n for (const [failedPath, msg] of failures) {\r\n if (resolveMountMatch(reqPath, failedPath)) {\r\n setResponseStatus(event, 503);\r\n setResponseHeader(event, \"retry-after\", \"5\");\r\n return {\r\n error: `agent-native route is initializing or unavailable: ${msg}`,\r\n };\r\n }\r\n }\r\n }\r\n return undefined;\r\n }) as EventHandler,\r\n {\r\n prepend: true,\r\n },\r\n );\r\n }\r\n}\r\n\r\nfunction logFrameworkRouteError(args: {\r\n method: string | undefined;\r\n route: string;\r\n status: number;\r\n error: unknown;\r\n}): void {\r\n const error = args.error as any;\r\n const message = error?.message || String(args.error);\r\n const prefix = `[agent-native] ${args.method ?? \"\"} ${args.route} failed (${args.status})`;\r\n if (process.env.NODE_ENV === \"production\") {\r\n console.error(`${prefix}: ${message}`);\r\n return;\r\n }\r\n console.error(`${prefix}: ${message}`, error?.stack || args.error);\r\n}\r\n\r\nfunction isClientAbortError(error: unknown, event: H3Event): boolean {\r\n const err = error as any;\r\n const message = typeof err?.message === \"string\" ? err.message : \"\";\r\n const code = typeof err?.code === \"string\" ? err.code : \"\";\r\n const node = (event as any).node;\r\n return (\r\n message === \"aborted\" ||\r\n code === \"ECONNRESET\" ||\r\n node?.req?.destroyed === true ||\r\n node?.res?.destroyed === true\r\n );\r\n}\r\n\r\nfunction debugClientAbort(args: {\r\n method: string | undefined;\r\n route: string;\r\n error: unknown;\r\n}): void {\r\n if (process.env.NODE_ENV === \"production\") return;\r\n const err = args.error as any;\r\n const message = err?.message || String(args.error);\r\n console.debug?.(\r\n `[agent-native] ${args.method ?? \"\"} ${args.route} aborted by client: ${message}`,\r\n );\r\n}\r\n\r\n/**\r\n * Await all tracked plugin initializations. Called by the readiness gate\r\n * middleware before dispatching framework routes.\r\n */\r\nexport async function awaitPluginsReady(\r\n nitroApp: any,\r\n reqPath?: string,\r\n): Promise<void> {\r\n const entries = nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined;\r\n if (!entries?.length) return;\r\n\r\n const relevant = reqPath\r\n ? entries.filter((entry) =>\r\n entry.paths?.length\r\n ? entry.paths.some((path) => resolveMountMatch(reqPath, path))\r\n : true,\r\n )\r\n : entries;\r\n\r\n if (relevant.length) {\r\n await Promise.all(relevant.map((entry) => entry.promise));\r\n const completed = new Set(relevant);\r\n const latest =\r\n (nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined) ?? [];\r\n nitroApp[PLUGIN_READY_KEY] = latest.filter(\r\n (entry) => !completed.has(entry),\r\n );\r\n }\r\n}\r\n\r\n/**\r\n * Register a path-prefix middleware on Nitro's h3 instance.\r\n *\r\n * The middleware:\r\n * - Returns `next()` (continues) if the request path doesn't match.\r\n * - Otherwise dispatches to the handler. If the handler returns a value,\r\n * it short-circuits the request. If it returns undefined, next() runs.\r\n *\r\n * Path matching emulates h3 v1's `app.use(path, ...)` behavior:\r\n * - Exact-match prefix: `/foo` matches `/foo`, `/foo/bar`, but not `/foobar`\r\n * - Empty path: middleware runs on every request\r\n */\r\nfunction registerMiddleware(\r\n nitroApp: any,\r\n path: string,\r\n handler: EventHandler,\r\n options: { prepend?: boolean } = {},\r\n) {\r\n const h3 = nitroApp.h3;\r\n if (!h3 || !Array.isArray(h3[\"~middleware\"])) {\r\n throw new Error(\r\n \"[agent-native] Cannot register route: nitroApp.h3 is not available. \" +\r\n \"Make sure you're calling getH3App() from inside a Nitro plugin.\",\r\n );\r\n }\r\n\r\n const middleware = async (event: H3Event, next: () => any) => {\r\n let originalPathname: string | undefined;\r\n let originalEventPath: string | undefined;\r\n let hadEventPath = false;\r\n const restoreOriginalPath = () => {\r\n if (originalPathname !== undefined) {\r\n try {\r\n event.url.pathname = originalPathname;\r\n } catch {\r\n // ignore\r\n }\r\n originalPathname = undefined;\r\n }\r\n if (hadEventPath) {\r\n try {\r\n (event as any).path = originalEventPath;\r\n } catch {\r\n // ignore\r\n }\r\n } else {\r\n try {\r\n delete (event as any).path;\r\n } catch {\r\n // ignore\r\n }\r\n }\r\n };\r\n if (path) {\r\n const reqPath = event.url?.pathname ?? \"\";\r\n const match = resolveMountMatch(reqPath, path);\r\n if (!match) {\r\n return next();\r\n }\r\n // Strip the mount prefix from event.url.pathname so handlers that\r\n // dispatch sub-routes can read `event.path` (or `event.url.pathname`)\r\n // and see the path RELATIVE to their mount point — matching h3 v1's\r\n // `app.use(path, handler)` semantics.\r\n const eventAny = event as any;\r\n hadEventPath = \"path\" in eventAny;\r\n originalEventPath = eventAny.path;\r\n try {\r\n originalPathname = event.url.pathname;\r\n // Save the full path in context so handlers that need the original URL\r\n // (e.g. Better Auth, which extracts its own basePath prefix) can\r\n // reconstruct a Request with the un-stripped URL.\r\n eventAny.context = eventAny.context ?? {};\r\n eventAny.context._mountedPathname = originalPathname;\r\n eventAny.context._mountPrefix = match.mountPath;\r\n event.url.pathname = match.strippedPath;\r\n eventAny.path = `${match.strippedPath}${event.url.search || \"\"}`;\r\n } catch {\r\n // event.url is read-only on some runtimes — fall through. Handlers\r\n // that don't depend on prefix stripping (most of them) still work.\r\n }\r\n }\r\n try {\r\n const result = await handler(event);\r\n if (result === undefined) {\r\n // Restore the original pathname BEFORE calling next() so downstream\r\n // middleware sees the full URL — not the stripped mount-relative path.\r\n // Matches h3 v2's own sub-app middleware pattern where the restore\r\n // happens inside the next() callback, not after it returns.\r\n restoreOriginalPath();\r\n return next();\r\n }\r\n return result;\r\n } catch (err) {\r\n // Log 500s to the server console so they're debuggable, and respond\r\n // with JSON instead of the default HTML error page so clients can\r\n // surface error messages. This only applies to routes mounted under\r\n // the framework prefix (or middleware mounted at `/`, for which we\r\n // still want visibility).\r\n const reqPath = originalPathname ?? event.url?.pathname ?? \"\";\r\n const e = err as any;\r\n const status =\r\n typeof e?.statusCode === \"number\"\r\n ? e.statusCode\r\n : typeof e?.status === \"number\"\r\n ? e.status\r\n : 500;\r\n if (isClientAbortError(err, event)) {\r\n debugClientAbort({ method: event.method, route: reqPath, error: err });\r\n return undefined;\r\n }\r\n logFrameworkRouteError({\r\n method: event.method,\r\n route: reqPath,\r\n status,\r\n error: err,\r\n });\r\n // Forward 5xx to server-side Sentry — Nitro's own `error` hook may not\r\n // fire here because we convert the throw into a normal JSON response,\r\n // and a console.error alone is invisible in deployed environments.\r\n // 4xx are user-input errors (validation, auth) and aren't worth\r\n // alerting on. Lazy-loaded so the framework-request-handler module\r\n // doesn't pull @sentry/node into bundles that don't need it.\r\n if (status >= 500) {\r\n // Static `import` would create a cycle (sentry.ts imports auth.ts\r\n // which imports… eventually, framework-request-handler.ts).\r\n import(\"./sentry.js\")\r\n .then(({ captureRouteError, isServerSentryEnabled }) => {\r\n if (!isServerSentryEnabled()) return;\r\n captureRouteError(err, {\r\n route: reqPath,\r\n method: event.method,\r\n userAgent: (() => {\r\n try {\r\n return event.headers?.get(\"user-agent\") ?? undefined;\r\n } catch {\r\n return undefined;\r\n }\r\n })(),\r\n });\r\n })\r\n .catch(() => {\r\n // Sentry is observability — never let it break a response path.\r\n });\r\n }\r\n try {\r\n setResponseStatus(event, status);\r\n setResponseHeader(event, \"content-type\", \"application/json\");\r\n } catch {\r\n // Response already sent — best effort.\r\n }\r\n return {\r\n error: e?.message || \"Internal server error\",\r\n // Only surface the stack to clients when explicitly enabled.\r\n // `NODE_ENV !== \"production\"` was unsafe — preview deploys and\r\n // any host that forgets to set NODE_ENV=production leaked stack\r\n // traces (file paths, dependency versions, internal route\r\n // topology) to anonymous callers. Operators who want stacks in\r\n // dev set `AGENT_NATIVE_DEBUG_ERRORS=1` explicitly.\r\n ...(status >= 500 &&\r\n process.env.AGENT_NATIVE_DEBUG_ERRORS === \"1\" &&\r\n e?.stack\r\n ? { stack: e.stack }\r\n : {}),\r\n };\r\n } finally {\r\n // Restore the original pathname so downstream middleware sees the\r\n // full URL.\r\n restoreOriginalPath();\r\n }\r\n };\r\n\r\n if (options.prepend) {\r\n h3[\"~middleware\"].unshift(middleware);\r\n } else {\r\n h3[\"~middleware\"].push(middleware);\r\n }\r\n}\r\n\r\n/**\r\n * Auto-mount any default framework plugins that the template doesn't provide.\r\n *\r\n * Runs once per nitroApp on the first `getH3App()` call. Uses route-discovery\r\n * to find which default plugin stems are missing from `server/plugins/`, then\r\n * dynamically imports and mounts them. If a workspace core is present in the\r\n * ancestor chain, plugin slots the workspace core exports are mounted from\r\n * there instead of from @agent-native/core — this is the middle layer of the\r\n * three-layer inheritance model (app local > workspace core > framework).\r\n */\r\nasync function bootstrapDefaultPlugins(nitroApp: any): Promise<void> {\r\n IN_BOOTSTRAP.add(nitroApp);\r\n try {\r\n const cwd = process.cwd();\r\n const discoveredMissing = await getMissingDefaultPlugins(cwd);\r\n const provided = nitroApp[PROVIDED_PLUGIN_STEMS_KEY] as\r\n | Set<string>\r\n | undefined;\r\n const missing = provided\r\n ? discoveredMissing.filter((stem) => !provided.has(stem))\r\n : discoveredMissing;\r\n if (missing.length === 0) return;\r\n\r\n // Lazy import to avoid circular dependency at module load time\r\n const serverModule = await import(\"./index.js\");\r\n const terminalModule = await import(\"../terminal/terminal-plugin.js\");\r\n const integrationsModule = await import(\"../integrations/plugin.js\");\r\n const contextXrayModule = await import(\"../agent/context-xray/plugin.js\");\r\n const observationalMemoryModule =\r\n await import(\"../agent/observational-memory/plugin.js\");\r\n const orgModule = await import(\"../org/plugin.js\");\r\n const onboardingModule = await import(\"../onboarding/plugin.js\");\r\n\r\n const frameworkImpls: Record<\r\n string,\r\n ((nitroApp: any) => void | Promise<void>) | undefined\r\n > = {\r\n \"agent-chat\": (serverModule as any).defaultAgentChatPlugin,\r\n auth: (serverModule as any).defaultAuthPlugin,\r\n \"context-xray\": (contextXrayModule as any).defaultContextXrayPlugin,\r\n \"core-routes\": (serverModule as any).defaultCoreRoutesPlugin,\r\n integrations: (integrationsModule as any).defaultIntegrationsPlugin,\r\n \"observational-memory\": (observationalMemoryModule as any)\r\n .defaultObservationalMemoryPlugin,\r\n onboarding: (onboardingModule as any).defaultOnboardingPlugin,\r\n org: (orgModule as any).defaultOrgPlugin,\r\n resources: (serverModule as any).defaultResourcesPlugin,\r\n sentry: (serverModule as any).defaultSentryPlugin,\r\n terminal: (terminalModule as any).defaultTerminalPlugin,\r\n };\r\n\r\n // Workspace core layer: if the app is inside an enterprise monorepo with\r\n // `agent-native.workspaceCore` configured, pull in any plugin slots the\r\n // workspace core exports from its server entry. We dynamically import the\r\n // workspace core package at runtime.\r\n let workspaceImpls: Record<\r\n string,\r\n ((nitroApp: any) => void | Promise<void>) | undefined\r\n > = {};\r\n try {\r\n const { getWorkspaceCoreExports } =\r\n await import(\"../deploy/workspace-core.js\");\r\n const ws = await getWorkspaceCoreExports(cwd);\r\n if (ws && Object.keys(ws.plugins).length > 0) {\r\n try {\r\n const wsServerModule = await loadWorkspaceCoreServer(\r\n ws.packageName,\r\n ws.packageDir,\r\n );\r\n for (const [slot, exportName] of Object.entries(ws.plugins)) {\r\n if (!exportName) continue;\r\n const impl = (wsServerModule as any)[exportName];\r\n if (typeof impl === \"function\") {\r\n workspaceImpls[slot] = impl;\r\n }\r\n }\r\n if (process.env.DEBUG) {\r\n console.log(\r\n `[agent-native] Workspace core ${ws.packageName} provides plugin slots: ${Object.keys(workspaceImpls).join(\", \")}`,\r\n );\r\n }\r\n } catch (e) {\r\n const msg = (e as Error).message ?? \"\";\r\n // Common cause: workspace-core's package.json points \"./server\"\r\n // at a TS source file (the scaffold default), but Node can't\r\n // resolve relative `.js` imports inside it without a TS loader.\r\n // Tell the user to compile to dist/ rather than just dumping the\r\n // raw resolution error.\r\n const tsLoadHint = /\\.js' imported from .*\\.ts/.test(msg)\r\n ? \" — workspace-core src is TypeScript but isn't being compiled. \" +\r\n \"Run `pnpm --filter \" +\r\n ws.packageName +\r\n \" build` and point its `./server` export at dist/server/index.js.\"\r\n : \"\";\r\n console.warn(\r\n `[agent-native] Failed to load workspace core ${ws.packageName}/server: ${msg}${tsLoadHint}`,\r\n );\r\n }\r\n }\r\n } catch {\r\n // Workspace shared package isn't available (e.g. running on an edge\r\n // runtime without fs). Silently fall through to framework defaults.\r\n }\r\n\r\n if (process.env.DEBUG)\r\n console.log(\r\n `[agent-native] Auto-mounting ${missing.length} default plugin(s): ${missing.join(\", \")}`,\r\n );\r\n\r\n for (const stem of missing) {\r\n // Prefer workspace-core impl over framework default when both exist.\r\n const impl = workspaceImpls[stem] ?? frameworkImpls[stem];\r\n if (typeof impl === \"function\") {\r\n try {\r\n await impl(nitroApp);\r\n } catch (e) {\r\n console.warn(\r\n `[agent-native] Failed to auto-mount default plugin ${stem}:`,\r\n (e as Error).message,\r\n );\r\n captureError(e, {\r\n route: \"default-plugin-bootstrap\",\r\n tags: { phase: \"default-plugin-bootstrap\", plugin: stem },\r\n });\r\n }\r\n }\r\n }\r\n } finally {\r\n IN_BOOTSTRAP.delete(nitroApp);\r\n }\r\n}\r\n\r\n/**\r\n * Load a workspace-core's `/server` entry, transparently handling TS source.\r\n *\r\n * The scaffolded workspace-core template ships TS sources without a build\r\n * step (exports point at `./src/server/index.ts`), so plain `await import()`\r\n * blows up the moment Node hits a relative `.js` import inside (the standard\r\n * TS ESM convention) — and even before that, Node may resolve the package\r\n * relative to the framework's own location rather than the user's monorepo.\r\n *\r\n * We try Node's plain `import()` first (fastest path when the user has\r\n * compiled to dist/) and fall through to jiti on any error. jiti is anchored\r\n * to a real file inside the workspace-core's directory, so its module\r\n * resolution starts in the right node_modules tree (handles pnpm hoisting\r\n * and linked workspaces) AND handles TS source files + `.js` → `.ts` ESM\r\n * extension remapping.\r\n *\r\n * Edge runtimes without `fs` won't be able to load jiti at all; the outer\r\n * try/catch silently falls through to framework defaults in that case.\r\n */\r\nexport async function loadWorkspaceCoreServer(\r\n packageName: string,\r\n packageDir: string,\r\n): Promise<any> {\r\n let firstErr: unknown;\r\n try {\r\n return await import(/* @vite-ignore */ `${packageName}/server`);\r\n } catch (e) {\r\n firstErr = e;\r\n }\r\n\r\n try {\r\n const { createJiti } = await import(\"jiti\");\r\n const { pathToFileURL } = await import(\"node:url\");\r\n const path = await import(\"node:path\");\r\n // Anchor jiti to a real file inside the workspace-core package so its\r\n // module resolution starts in the right node_modules tree (handles pnpm\r\n // hoisting and linked workspaces).\r\n const anchor = pathToFileURL(\r\n path.join(packageDir, \"package.json\"),\r\n ).toString();\r\n const jiti = createJiti(anchor, { interopDefault: true });\r\n return await jiti.import(`${packageName}/server`);\r\n } catch (jitiErr) {\r\n // jiti also failed — rethrow the original Node error since it's usually\r\n // more informative about *why* the package wasn't resolvable.\r\n throw firstErr ?? jitiErr;\r\n }\r\n}\r\n\r\nexport { FRAMEWORK_PREFIX };\r\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;AAE1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE3D,MAAM,YAAY,GAAG,IAAI,OAAO,EAAU,CAAC;AAC3C,MAAM,YAAY,GAAG,IAAI,OAAO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AAC;YAAS,CAAC;QACT,YAAY,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAChC,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,WAAmB,EACnB,UAAkB;IAElB,IAAI,QAAiB,CAAC;IACtB,IAAI,CAAC;QACH,OAAO,MAAM,MAAM,CAAC,kBAAkB,CAAC,GAAG,WAAW,SAAS,CAAC,CAAC;IAClE,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,QAAQ,GAAG,CAAC,CAAC;IACf,CAAC;IAED,IAAI,CAAC;QACH,MAAM,EAAE,UAAU,EAAE,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC;QAC5C,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,CAAC;QACnD,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,CAAC;QACvC,sEAAsE;QACtE,wEAAwE;QACxE,mCAAmC;QACnC,MAAM,MAAM,GAAG,aAAa,CAC1B,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,cAAc,CAAC,CACtC,CAAC,QAAQ,EAAE,CAAC;QACb,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1D,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,WAAW,SAAS,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,OAAO,EAAE,CAAC;QACjB,wEAAwE;QACxE,8DAA8D;QAC9D,MAAM,QAAQ,IAAI,OAAO,CAAC;IAC5B,CAAC;AACH,CAAC;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC","sourcesContent":["/**\r\n * Framework request handler — registers framework routes on Nitro's h3 instance.\r\n *\r\n * Nitro 3 exposes its h3 app as `nitroApp.h3`. We register framework routes\r\n * directly on it as middleware (`nitroApp.h3[\"~middleware\"]`), giving each\r\n * plugin a path-prefix-matched handler that runs before any file-based route.\r\n *\r\n * Plugins call `getH3App(nitroApp).use(path, handler)` exactly like h3 v1's\r\n * `app.use()` — the wrapper translates that into v2 middleware registration.\r\n *\r\n * Default plugins that the template doesn't provide are auto-mounted on the\r\n * first call to `getH3App()` per nitroApp instance.\r\n */\r\nimport type { EventHandler, H3Event } from \"h3\";\r\nimport { setResponseHeader, setResponseStatus } from \"h3\";\r\n\r\nimport { getMissingDefaultPlugins } from \"../deploy/route-discovery.js\";\r\nimport { getConfiguredAppBasePath } from \"./app-base-path.js\";\r\nimport { captureError } from \"./capture-error.js\";\r\nimport { isCloudflareRuntime } from \"../shared/runtime.js\";\r\n\r\nconst BOOTSTRAPPED = new WeakSet<object>();\r\nconst IN_BOOTSTRAP = new WeakSet<object>();\r\nconst FRAMEWORK_PREFIX = \"/_agent-native\";\r\nconst WELL_KNOWN_PREFIX = \"/.well-known\";\r\nconst APP_SHIM_KEY = \"_agentNativeH3Shim\";\r\nconst BOOTSTRAP_PROMISE_KEY = \"_agentNativeBootstrapPromise\";\r\nconst PLUGIN_READY_KEY = \"_agentNativePluginReadyPromise\";\r\nconst PLUGIN_READY_PLACEHOLDERS_KEY = \"_agentNativePluginReadyPlaceholders\";\r\nconst PLUGIN_FAILED_KEY = \"_agentNativePluginInitFailures\";\r\nconst PROVIDED_PLUGIN_STEMS_KEY = \"_agentNativeProvidedPluginStems\";\r\nconst MIDDLEWARE_DISPATCHER_PATCHED_KEY =\r\n \"_agentNativeMiddlewareDispatcherPatched\";\r\n\r\ninterface PluginReadyEntry {\r\n promise: Promise<void>;\r\n paths?: string[];\r\n}\r\n\r\nfunction getAppBasePath(): string {\r\n return getConfiguredAppBasePath();\r\n}\r\n\r\nfunction pathMatchesPrefix(reqPath: string, prefix: string): boolean {\r\n return reqPath === prefix || reqPath.startsWith(prefix + \"/\");\r\n}\r\n\r\n/**\r\n * Cloudflare Workers (workerd) cancels pending I/O owned by a request the\r\n * moment its response returns — a promise created during request A that\r\n * hasn't settled by then FREEZES forever. Plugin-init and bootstrap promises\r\n * are created during an app's first request and awaited by later requests'\r\n * readiness gates, so an early-responding first request (e.g. an auth route\r\n * that doesn't match the pending inits' paths) permanently wedges every\r\n * later framework-route request. Tie the promise to the creating request's\r\n * `waitUntil` so its I/O stays alive until it settles.\r\n */\r\nfunction extendRequestLifetimeOverInit(promise: Promise<unknown>): void {\r\n try {\r\n (\r\n globalThis as {\r\n __cf_ctx?: { waitUntil?: (p: Promise<unknown>) => void };\r\n }\r\n ).__cf_ctx?.waitUntil?.(promise);\r\n } catch {\r\n /* not on Cloudflare or ctx unavailable — nothing to extend */\r\n }\r\n}\r\n\r\n/**\r\n * Bound a readiness-gate await on workerd. Insurance against any init\r\n * promise that still froze (e.g. created before __cf_ctx existed): a\r\n * bounded wait turns a permanently hung request into a slow one that\r\n * proceeds — the route either works (init actually finished) or 404/503s\r\n * (retryable) instead of hanging until the runtime kills the request.\r\n */\r\nasync function awaitBounded(promise: Promise<unknown>): Promise<void> {\r\n if (!isCloudflareRuntime()) {\r\n await promise;\r\n return;\r\n }\r\n let timer: ReturnType<typeof setTimeout> | undefined;\r\n const timeout = new Promise<void>((resolve) => {\r\n timer = setTimeout(() => {\r\n console.warn(\r\n \"[agent-native] readiness gate timed out waiting for plugin init (20s) — proceeding; the init promise may have been frozen by a prior request's completion\",\r\n );\r\n resolve();\r\n }, 20_000);\r\n });\r\n try {\r\n await Promise.race([promise, timeout]);\r\n } finally {\r\n if (timer) clearTimeout(timer);\r\n }\r\n}\r\n\r\nfunction supportsAppBasePathMount(path: string): boolean {\r\n return (\r\n pathMatchesPrefix(path, FRAMEWORK_PREFIX) ||\r\n pathMatchesPrefix(path, WELL_KNOWN_PREFIX)\r\n );\r\n}\r\n\r\nfunction resolveMountMatch(\r\n reqPath: string,\r\n path: string,\r\n): { mountPath: string; strippedPath: string } | null {\r\n if (pathMatchesPrefix(reqPath, path)) {\r\n return { mountPath: path, strippedPath: reqPath.slice(path.length) || \"/\" };\r\n }\r\n\r\n const appBasePath = getAppBasePath();\r\n if (!appBasePath || !supportsAppBasePathMount(path)) return null;\r\n\r\n const prefixedPath = `${appBasePath}${path}`;\r\n if (!pathMatchesPrefix(reqPath, prefixedPath)) return null;\r\n return {\r\n mountPath: prefixedPath,\r\n strippedPath: reqPath.slice(prefixedPath.length) || \"/\",\r\n };\r\n}\r\n\r\n/**\r\n * Wrapper around Nitro's h3 instance that exposes a v1-style `.use()` API\r\n * for registering path-prefix middleware.\r\n */\r\nexport interface H3AppShim {\r\n use(path: string, handler: EventHandler): void;\r\n use(handler: EventHandler): void;\r\n}\r\n\r\n/**\r\n * Mark a default plugin slot as supplied by the app/template before the\r\n * framework default bootstrap runs.\r\n *\r\n * Bundled serverless functions often don't have the original\r\n * `server/plugins/*.ts` tree on disk at runtime, so filesystem route discovery\r\n * can falsely conclude a template plugin is missing. Explicit plugin factories\r\n * call this synchronously before awaiting bootstrap so the framework does not\r\n * auto-mount a generic default over the app's custom implementation.\r\n */\r\nexport function markDefaultPluginProvided(nitroApp: any, stem: string): void {\r\n if (!nitroApp || !stem) return;\r\n const existing = nitroApp[PROVIDED_PLUGIN_STEMS_KEY] as\r\n | Set<string>\r\n | undefined;\r\n const provided = existing ?? new Set<string>();\r\n provided.add(stem);\r\n nitroApp[PROVIDED_PLUGIN_STEMS_KEY] = provided;\r\n}\r\n\r\n/**\r\n * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this\r\n * to register routes via `.use(path, handler)`.\r\n *\r\n * On the first call per nitroApp, we kick off auto-mounting any missing\r\n * default plugins. User-facing plugin factories (createAgentChatPlugin,\r\n * createAuthPlugin, etc.) await this bootstrap via `awaitBootstrap()` so the\r\n * default plugins finish registering middleware before requests arrive.\r\n */\r\nexport function getH3App(nitroApp: any): H3AppShim {\r\n if (!nitroApp) throw new Error(\"getH3App: nitroApp is required\");\r\n ensureGlobalMiddlewareDispatch(nitroApp);\r\n\r\n // Reuse the cached shim if we've wrapped this nitroApp before\r\n const cached = nitroApp[APP_SHIM_KEY] as H3AppShim | undefined;\r\n if (cached) return cached;\r\n\r\n const shim: H3AppShim = {\r\n use(arg1: string | EventHandler, arg2?: EventHandler) {\r\n const path = typeof arg1 === \"string\" ? arg1 : \"\";\r\n const handler = (typeof arg1 === \"string\" ? arg2 : arg1) as EventHandler;\r\n if (typeof handler !== \"function\") {\r\n throw new Error(\"getH3App.use: handler must be a function\");\r\n }\r\n registerMiddleware(nitroApp, path, handler);\r\n },\r\n };\r\n\r\n nitroApp[APP_SHIM_KEY] = shim;\r\n\r\n if (!BOOTSTRAPPED.has(nitroApp)) {\r\n BOOTSTRAPPED.add(nitroApp);\r\n nitroApp[BOOTSTRAP_PROMISE_KEY] = bootstrapDefaultPlugins(nitroApp).catch(\r\n (err) => {\r\n console.warn(\r\n \"[agent-native] Failed to auto-mount default plugins:\",\r\n (err as Error).message,\r\n );\r\n captureError(err, {\r\n route: \"default-plugin-bootstrap\",\r\n tags: { phase: \"default-plugin-bootstrap\" },\r\n });\r\n },\r\n );\r\n extendRequestLifetimeOverInit(\r\n nitroApp[BOOTSTRAP_PROMISE_KEY] as Promise<unknown>,\r\n );\r\n\r\n // Readiness gate: Nitro v3 doesn't await async plugins, so routes\r\n // registered inside an async plugin may not exist when the first\r\n // request arrives. These middleware entries hold framework routes\r\n // until default-plugin bootstrap and tracked plugin inits complete.\r\n const readinessGate = (async (event: H3Event) => {\r\n const eventAny = event as any;\r\n await awaitFrameworkRoutesReadyForRequest(\r\n nitroApp,\r\n eventAny.context?._mountedPathname ?? event.url?.pathname ?? \"\",\r\n );\r\n // Fall through — the actual route handler runs next.\r\n return undefined;\r\n }) as EventHandler;\r\n registerMiddleware(nitroApp, FRAMEWORK_PREFIX, readinessGate, {\r\n prepend: true,\r\n });\r\n registerMiddleware(nitroApp, WELL_KNOWN_PREFIX, readinessGate, {\r\n prepend: true,\r\n });\r\n\r\n // Primary gate: Nitro bridges this `request` hook to h3's `config.onRequest`,\r\n // which h3 awaits BEFORE `handler()` snapshots middleware and resolves the\r\n // route. The middleware gate above runs too late on production dispatchers —\r\n // its await finishes after the snapshot, so a route registered during async\r\n // init is missing from the request and 404s. The middleware gate stays as a\r\n // fallback for runtimes where `onRequest` isn't wired.\r\n nitroApp.hooks?.hook?.(\"request\", async (event: H3Event) => {\r\n const reqPath = event.url?.pathname ?? \"\";\r\n if (\r\n resolveMountMatch(reqPath, FRAMEWORK_PREFIX) ||\r\n resolveMountMatch(reqPath, WELL_KNOWN_PREFIX)\r\n ) {\r\n await awaitFrameworkRoutesReadyForRequest(nitroApp, reqPath);\r\n }\r\n });\r\n }\r\n\r\n return shim;\r\n}\r\n\r\n/**\r\n * Nitro 3 production builds generate a route dispatcher by overriding h3's\r\n * internal `~getMiddleware()` hook. Some generated dispatchers return only\r\n * route-rule middleware and skip the global `h3[\"~middleware\"]` array that\r\n * `getH3App().use()` appends to. Wrap the dispatcher once so framework routes\r\n * registered at runtime are still part of request dispatch.\r\n */\r\nfunction ensureGlobalMiddlewareDispatch(nitroApp: any): void {\r\n const h3 = nitroApp?.h3;\r\n if (!h3) return;\r\n const current = h3[\"~getMiddleware\"];\r\n if (h3[MIDDLEWARE_DISPATCHER_PATCHED_KEY] === current) return;\r\n\r\n const original = typeof current === \"function\" ? current.bind(h3) : undefined;\r\n\r\n const wrappedGetMiddleware = (event: H3Event, route: unknown) => {\r\n const originalResult = original ? original(event, route) : [];\r\n const originalList = Array.isArray(originalResult)\r\n ? originalResult\r\n : originalResult\r\n ? [originalResult]\r\n : [];\r\n const globalMiddleware = Array.isArray(h3[\"~middleware\"])\r\n ? h3[\"~middleware\"]\r\n : [];\r\n if (globalMiddleware.length === 0) return originalList;\r\n\r\n const alreadyIncluded = new Set(originalList);\r\n const missingGlobal = globalMiddleware.filter(\r\n (middleware) => !alreadyIncluded.has(middleware),\r\n );\r\n return missingGlobal.length\r\n ? [...missingGlobal, ...originalList]\r\n : originalList;\r\n };\r\n\r\n h3[\"~getMiddleware\"] = wrappedGetMiddleware;\r\n h3[MIDDLEWARE_DISPATCHER_PATCHED_KEY] = wrappedGetMiddleware;\r\n}\r\n\r\n/**\r\n * Wait for the framework's default-plugin bootstrap to complete.\r\n *\r\n * Called by user-facing plugin factories (`createAgentChatPlugin`, etc.) at\r\n * the top of their plugin function, so that by the time the function returns\r\n * — and Nitro starts accepting requests — all default plugins have finished\r\n * registering their middleware.\r\n *\r\n * No-op when called from inside the bootstrap itself (avoids deadlock when a\r\n * default plugin happens to be running as part of bootstrap).\r\n */\r\nexport async function awaitBootstrap(nitroApp: any): Promise<void> {\r\n if (!nitroApp || IN_BOOTSTRAP.has(nitroApp)) return;\r\n // Trigger bootstrap if it hasn't been already (idempotent — getH3App\r\n // creates the shim and kicks off bootstrap on first call).\r\n getH3App(nitroApp);\r\n const promise = nitroApp[BOOTSTRAP_PROMISE_KEY];\r\n if (promise) await promise;\r\n}\r\n\r\n/**\r\n * Wait until framework routes are safe to dispatch.\r\n *\r\n * Request-time gates must wait for both phases:\r\n * 1. default-plugin bootstrap, which discovers and starts missing plugins\r\n * 2. async plugin init promises, which register routes such as A2A cards\r\n */\r\nasync function awaitFrameworkRoutesReadyForRequest(\r\n nitroApp: any,\r\n reqPath: string,\r\n): Promise<void> {\r\n if (!nitroApp) return;\r\n const bootstrapPromise = nitroApp[BOOTSTRAP_PROMISE_KEY];\r\n if (bootstrapPromise) await awaitBounded(bootstrapPromise);\r\n await awaitPluginsReady(nitroApp, reqPath);\r\n}\r\n\r\n/**\r\n * Track an async plugin's initialization promise. Nitro v3 calls plugins\r\n * synchronously and doesn't await async return values, so routes registered\r\n * inside an async plugin may not be ready when the first request arrives.\r\n *\r\n * Call this from the TOP of any async plugin so that the readiness gate\r\n * (installed by getH3App) can hold /_agent-native requests until the plugin\r\n * finishes mounting its routes.\r\n */\r\nexport function trackPluginInit(\r\n nitroApp: any,\r\n promise: Promise<void>,\r\n options: { paths?: string[] } = {},\r\n): void {\r\n if (!nitroApp) return;\r\n // Ensure the readiness gate exists even when the tracked plugin is the first\r\n // framework code to run in a serverless isolate. Otherwise an immediate\r\n // first request can fall through before the plugin registers its routes.\r\n getH3App(nitroApp);\r\n // Attach a no-op catch so the promise doesn't surface as an unhandled\r\n // rejection when Nitro v3 drops the async return value. The actual error\r\n // is still observable when awaitPluginsReady() re-awaits the promise.\r\n const safe = promise.catch((err) => {\r\n console.error(\r\n \"[agent-native] Plugin init failed:\",\r\n (err as Error).message || err,\r\n );\r\n // Record the failure so the readiness gate can return a retryable 503 for\r\n // this plugin's routes instead of letting them fall through to a bare\r\n // \"Cannot find any route matching\" 404. That bare 404 is what kept biting\r\n // external MCP clients (pi/codex/claude) and the connect flow on cold /\r\n // propagating instances whose async init rejected (e.g. DB not yet\r\n // reachable): the route never registered, so the placeholder released into\r\n // a 404 the client couldn't recover from. A 503 is at least retryable.\r\n const failures = (nitroApp[PLUGIN_FAILED_KEY] ??= new Map<\r\n string,\r\n string\r\n >());\r\n const msg = (err as Error)?.message || String(err);\r\n for (const p of options.paths?.filter(Boolean) ?? []) failures.set(p, msg);\r\n });\r\n const entry: PluginReadyEntry = {\r\n promise: safe,\r\n paths: options.paths?.filter(Boolean),\r\n };\r\n extendRequestLifetimeOverInit(safe);\r\n const existing = nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined;\r\n if (existing) {\r\n existing.push(entry);\r\n } else {\r\n nitroApp[PLUGIN_READY_KEY] = [entry];\r\n }\r\n installPluginReadyPlaceholders(nitroApp, entry.paths);\r\n}\r\n\r\nfunction installPluginReadyPlaceholders(\r\n nitroApp: any,\r\n paths: string[] | undefined,\r\n): void {\r\n if (!paths?.length) return;\r\n const existing = nitroApp[PLUGIN_READY_PLACEHOLDERS_KEY] as\r\n | Set<string>\r\n | undefined;\r\n const installed = existing ?? new Set<string>();\r\n nitroApp[PLUGIN_READY_PLACEHOLDERS_KEY] = installed;\r\n\r\n for (const path of paths) {\r\n if (!path || installed.has(path)) continue;\r\n installed.add(path);\r\n registerMiddleware(\r\n nitroApp,\r\n path,\r\n (async (event: H3Event) => {\r\n const eventAny = event as any;\r\n const reqPath =\r\n eventAny.context?._mountedPathname ?? event.url?.pathname ?? path;\r\n await awaitFrameworkRoutesReadyForRequest(nitroApp, reqPath);\r\n // If this plugin's async init failed, its real route was never\r\n // registered. Return a retryable 503 instead of releasing into a bare\r\n // 404 (external MCP clients can't recover from a 404; a 503 is at least\r\n // a \"try again\" the client / next instance can act on).\r\n const failures = nitroApp[PLUGIN_FAILED_KEY] as\r\n | Map<string, string>\r\n | undefined;\r\n if (failures?.size) {\r\n for (const [failedPath, msg] of failures) {\r\n if (resolveMountMatch(reqPath, failedPath)) {\r\n setResponseStatus(event, 503);\r\n setResponseHeader(event, \"retry-after\", \"5\");\r\n return {\r\n error: `agent-native route is initializing or unavailable: ${msg}`,\r\n };\r\n }\r\n }\r\n }\r\n return undefined;\r\n }) as EventHandler,\r\n {\r\n prepend: true,\r\n },\r\n );\r\n }\r\n}\r\n\r\nfunction logFrameworkRouteError(args: {\r\n method: string | undefined;\r\n route: string;\r\n status: number;\r\n error: unknown;\r\n}): void {\r\n const error = args.error as any;\r\n const message = error?.message || String(args.error);\r\n const prefix = `[agent-native] ${args.method ?? \"\"} ${args.route} failed (${args.status})`;\r\n if (process.env.NODE_ENV === \"production\") {\r\n console.error(`${prefix}: ${message}`);\r\n return;\r\n }\r\n console.error(`${prefix}: ${message}`, error?.stack || args.error);\r\n}\r\n\r\nfunction isClientAbortError(error: unknown, event: H3Event): boolean {\r\n const err = error as any;\r\n const message = typeof err?.message === \"string\" ? err.message : \"\";\r\n const code = typeof err?.code === \"string\" ? err.code : \"\";\r\n const node = (event as any).node;\r\n return (\r\n message === \"aborted\" ||\r\n code === \"ECONNRESET\" ||\r\n node?.req?.destroyed === true ||\r\n node?.res?.destroyed === true\r\n );\r\n}\r\n\r\nfunction debugClientAbort(args: {\r\n method: string | undefined;\r\n route: string;\r\n error: unknown;\r\n}): void {\r\n if (process.env.NODE_ENV === \"production\") return;\r\n const err = args.error as any;\r\n const message = err?.message || String(args.error);\r\n console.debug?.(\r\n `[agent-native] ${args.method ?? \"\"} ${args.route} aborted by client: ${message}`,\r\n );\r\n}\r\n\r\n/**\r\n * Await all tracked plugin initializations. Called by the readiness gate\r\n * middleware before dispatching framework routes.\r\n */\r\nexport async function awaitPluginsReady(\r\n nitroApp: any,\r\n reqPath?: string,\r\n): Promise<void> {\r\n const entries = nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined;\r\n if (!entries?.length) return;\r\n\r\n const relevant = reqPath\r\n ? entries.filter((entry) =>\r\n entry.paths?.length\r\n ? entry.paths.some((path) => resolveMountMatch(reqPath, path))\r\n : true,\r\n )\r\n : entries;\r\n\r\n if (relevant.length) {\r\n await Promise.all(relevant.map((entry) => awaitBounded(entry.promise)));\r\n const completed = new Set(relevant);\r\n const latest =\r\n (nitroApp[PLUGIN_READY_KEY] as PluginReadyEntry[] | undefined) ?? [];\r\n nitroApp[PLUGIN_READY_KEY] = latest.filter(\r\n (entry) => !completed.has(entry),\r\n );\r\n }\r\n}\r\n\r\n/**\r\n * Register a path-prefix middleware on Nitro's h3 instance.\r\n *\r\n * The middleware:\r\n * - Returns `next()` (continues) if the request path doesn't match.\r\n * - Otherwise dispatches to the handler. If the handler returns a value,\r\n * it short-circuits the request. If it returns undefined, next() runs.\r\n *\r\n * Path matching emulates h3 v1's `app.use(path, ...)` behavior:\r\n * - Exact-match prefix: `/foo` matches `/foo`, `/foo/bar`, but not `/foobar`\r\n * - Empty path: middleware runs on every request\r\n */\r\nfunction registerMiddleware(\r\n nitroApp: any,\r\n path: string,\r\n handler: EventHandler,\r\n options: { prepend?: boolean } = {},\r\n) {\r\n const h3 = nitroApp.h3;\r\n if (!h3 || !Array.isArray(h3[\"~middleware\"])) {\r\n throw new Error(\r\n \"[agent-native] Cannot register route: nitroApp.h3 is not available. \" +\r\n \"Make sure you're calling getH3App() from inside a Nitro plugin.\",\r\n );\r\n }\r\n\r\n const middleware = async (event: H3Event, next: () => any) => {\r\n let originalPathname: string | undefined;\r\n let originalEventPath: string | undefined;\r\n let hadEventPath = false;\r\n const restoreOriginalPath = () => {\r\n if (originalPathname !== undefined) {\r\n try {\r\n event.url.pathname = originalPathname;\r\n } catch {\r\n // ignore\r\n }\r\n originalPathname = undefined;\r\n }\r\n if (hadEventPath) {\r\n try {\r\n (event as any).path = originalEventPath;\r\n } catch {\r\n // ignore\r\n }\r\n } else {\r\n try {\r\n delete (event as any).path;\r\n } catch {\r\n // ignore\r\n }\r\n }\r\n };\r\n if (path) {\r\n const reqPath = event.url?.pathname ?? \"\";\r\n const match = resolveMountMatch(reqPath, path);\r\n if (!match) {\r\n return next();\r\n }\r\n // Strip the mount prefix from event.url.pathname so handlers that\r\n // dispatch sub-routes can read `event.path` (or `event.url.pathname`)\r\n // and see the path RELATIVE to their mount point — matching h3 v1's\r\n // `app.use(path, handler)` semantics.\r\n const eventAny = event as any;\r\n hadEventPath = \"path\" in eventAny;\r\n originalEventPath = eventAny.path;\r\n try {\r\n originalPathname = event.url.pathname;\r\n // Save the full path in context so handlers that need the original URL\r\n // (e.g. Better Auth, which extracts its own basePath prefix) can\r\n // reconstruct a Request with the un-stripped URL.\r\n eventAny.context = eventAny.context ?? {};\r\n eventAny.context._mountedPathname = originalPathname;\r\n eventAny.context._mountPrefix = match.mountPath;\r\n event.url.pathname = match.strippedPath;\r\n eventAny.path = `${match.strippedPath}${event.url.search || \"\"}`;\r\n } catch {\r\n // event.url is read-only on some runtimes — fall through. Handlers\r\n // that don't depend on prefix stripping (most of them) still work.\r\n }\r\n }\r\n try {\r\n const result = await handler(event);\r\n if (result === undefined) {\r\n // Restore the original pathname BEFORE calling next() so downstream\r\n // middleware sees the full URL — not the stripped mount-relative path.\r\n // Matches h3 v2's own sub-app middleware pattern where the restore\r\n // happens inside the next() callback, not after it returns.\r\n restoreOriginalPath();\r\n return next();\r\n }\r\n return result;\r\n } catch (err) {\r\n // Log 500s to the server console so they're debuggable, and respond\r\n // with JSON instead of the default HTML error page so clients can\r\n // surface error messages. This only applies to routes mounted under\r\n // the framework prefix (or middleware mounted at `/`, for which we\r\n // still want visibility).\r\n const reqPath = originalPathname ?? event.url?.pathname ?? \"\";\r\n const e = err as any;\r\n const status =\r\n typeof e?.statusCode === \"number\"\r\n ? e.statusCode\r\n : typeof e?.status === \"number\"\r\n ? e.status\r\n : 500;\r\n if (isClientAbortError(err, event)) {\r\n debugClientAbort({ method: event.method, route: reqPath, error: err });\r\n return undefined;\r\n }\r\n logFrameworkRouteError({\r\n method: event.method,\r\n route: reqPath,\r\n status,\r\n error: err,\r\n });\r\n // Forward 5xx to server-side Sentry — Nitro's own `error` hook may not\r\n // fire here because we convert the throw into a normal JSON response,\r\n // and a console.error alone is invisible in deployed environments.\r\n // 4xx are user-input errors (validation, auth) and aren't worth\r\n // alerting on. Lazy-loaded so the framework-request-handler module\r\n // doesn't pull @sentry/node into bundles that don't need it.\r\n if (status >= 500) {\r\n // Static `import` would create a cycle (sentry.ts imports auth.ts\r\n // which imports… eventually, framework-request-handler.ts).\r\n import(\"./sentry.js\")\r\n .then(({ captureRouteError, isServerSentryEnabled }) => {\r\n if (!isServerSentryEnabled()) return;\r\n captureRouteError(err, {\r\n route: reqPath,\r\n method: event.method,\r\n userAgent: (() => {\r\n try {\r\n return event.headers?.get(\"user-agent\") ?? undefined;\r\n } catch {\r\n return undefined;\r\n }\r\n })(),\r\n });\r\n })\r\n .catch(() => {\r\n // Sentry is observability — never let it break a response path.\r\n });\r\n }\r\n try {\r\n setResponseStatus(event, status);\r\n setResponseHeader(event, \"content-type\", \"application/json\");\r\n } catch {\r\n // Response already sent — best effort.\r\n }\r\n return {\r\n error: e?.message || \"Internal server error\",\r\n // Only surface the stack to clients when explicitly enabled.\r\n // `NODE_ENV !== \"production\"` was unsafe — preview deploys and\r\n // any host that forgets to set NODE_ENV=production leaked stack\r\n // traces (file paths, dependency versions, internal route\r\n // topology) to anonymous callers. Operators who want stacks in\r\n // dev set `AGENT_NATIVE_DEBUG_ERRORS=1` explicitly.\r\n ...(status >= 500 &&\r\n process.env.AGENT_NATIVE_DEBUG_ERRORS === \"1\" &&\r\n e?.stack\r\n ? { stack: e.stack }\r\n : {}),\r\n };\r\n } finally {\r\n // Restore the original pathname so downstream middleware sees the\r\n // full URL.\r\n restoreOriginalPath();\r\n }\r\n };\r\n\r\n if (options.prepend) {\r\n h3[\"~middleware\"].unshift(middleware);\r\n } else {\r\n h3[\"~middleware\"].push(middleware);\r\n }\r\n}\r\n\r\n/**\r\n * Auto-mount any default framework plugins that the template doesn't provide.\r\n *\r\n * Runs once per nitroApp on the first `getH3App()` call. Uses route-discovery\r\n * to find which default plugin stems are missing from `server/plugins/`, then\r\n * dynamically imports and mounts them. If a workspace core is present in the\r\n * ancestor chain, plugin slots the workspace core exports are mounted from\r\n * there instead of from @agent-native/core — this is the middle layer of the\r\n * three-layer inheritance model (app local > workspace core > framework).\r\n */\r\nasync function bootstrapDefaultPlugins(nitroApp: any): Promise<void> {\r\n IN_BOOTSTRAP.add(nitroApp);\r\n try {\r\n const cwd = process.cwd();\r\n const discoveredMissing = await getMissingDefaultPlugins(cwd);\r\n const provided = nitroApp[PROVIDED_PLUGIN_STEMS_KEY] as\r\n | Set<string>\r\n | undefined;\r\n const missing = provided\r\n ? discoveredMissing.filter((stem) => !provided.has(stem))\r\n : discoveredMissing;\r\n if (missing.length === 0) return;\r\n\r\n // Lazy import to avoid circular dependency at module load time\r\n const serverModule = await import(\"./index.js\");\r\n const terminalModule = await import(\"../terminal/terminal-plugin.js\");\r\n const integrationsModule = await import(\"../integrations/plugin.js\");\r\n const contextXrayModule = await import(\"../agent/context-xray/plugin.js\");\r\n const observationalMemoryModule =\r\n await import(\"../agent/observational-memory/plugin.js\");\r\n const orgModule = await import(\"../org/plugin.js\");\r\n const onboardingModule = await import(\"../onboarding/plugin.js\");\r\n\r\n const frameworkImpls: Record<\r\n string,\r\n ((nitroApp: any) => void | Promise<void>) | undefined\r\n > = {\r\n \"agent-chat\": (serverModule as any).defaultAgentChatPlugin,\r\n auth: (serverModule as any).defaultAuthPlugin,\r\n \"context-xray\": (contextXrayModule as any).defaultContextXrayPlugin,\r\n \"core-routes\": (serverModule as any).defaultCoreRoutesPlugin,\r\n integrations: (integrationsModule as any).defaultIntegrationsPlugin,\r\n \"observational-memory\": (observationalMemoryModule as any)\r\n .defaultObservationalMemoryPlugin,\r\n onboarding: (onboardingModule as any).defaultOnboardingPlugin,\r\n org: (orgModule as any).defaultOrgPlugin,\r\n resources: (serverModule as any).defaultResourcesPlugin,\r\n sentry: (serverModule as any).defaultSentryPlugin,\r\n terminal: (terminalModule as any).defaultTerminalPlugin,\r\n };\r\n\r\n // Workspace core layer: if the app is inside an enterprise monorepo with\r\n // `agent-native.workspaceCore` configured, pull in any plugin slots the\r\n // workspace core exports from its server entry. We dynamically import the\r\n // workspace core package at runtime.\r\n let workspaceImpls: Record<\r\n string,\r\n ((nitroApp: any) => void | Promise<void>) | undefined\r\n > = {};\r\n try {\r\n const { getWorkspaceCoreExports } =\r\n await import(\"../deploy/workspace-core.js\");\r\n const ws = await getWorkspaceCoreExports(cwd);\r\n if (ws && Object.keys(ws.plugins).length > 0) {\r\n try {\r\n const wsServerModule = await loadWorkspaceCoreServer(\r\n ws.packageName,\r\n ws.packageDir,\r\n );\r\n for (const [slot, exportName] of Object.entries(ws.plugins)) {\r\n if (!exportName) continue;\r\n const impl = (wsServerModule as any)[exportName];\r\n if (typeof impl === \"function\") {\r\n workspaceImpls[slot] = impl;\r\n }\r\n }\r\n if (process.env.DEBUG) {\r\n console.log(\r\n `[agent-native] Workspace core ${ws.packageName} provides plugin slots: ${Object.keys(workspaceImpls).join(\", \")}`,\r\n );\r\n }\r\n } catch (e) {\r\n const msg = (e as Error).message ?? \"\";\r\n // Common cause: workspace-core's package.json points \"./server\"\r\n // at a TS source file (the scaffold default), but Node can't\r\n // resolve relative `.js` imports inside it without a TS loader.\r\n // Tell the user to compile to dist/ rather than just dumping the\r\n // raw resolution error.\r\n const tsLoadHint = /\\.js' imported from .*\\.ts/.test(msg)\r\n ? \" — workspace-core src is TypeScript but isn't being compiled. \" +\r\n \"Run `pnpm --filter \" +\r\n ws.packageName +\r\n \" build` and point its `./server` export at dist/server/index.js.\"\r\n : \"\";\r\n console.warn(\r\n `[agent-native] Failed to load workspace core ${ws.packageName}/server: ${msg}${tsLoadHint}`,\r\n );\r\n }\r\n }\r\n } catch {\r\n // Workspace shared package isn't available (e.g. running on an edge\r\n // runtime without fs). Silently fall through to framework defaults.\r\n }\r\n\r\n if (process.env.DEBUG)\r\n console.log(\r\n `[agent-native] Auto-mounting ${missing.length} default plugin(s): ${missing.join(\", \")}`,\r\n );\r\n\r\n for (const stem of missing) {\r\n // Prefer workspace-core impl over framework default when both exist.\r\n const impl = workspaceImpls[stem] ?? frameworkImpls[stem];\r\n if (typeof impl === \"function\") {\r\n try {\r\n await impl(nitroApp);\r\n } catch (e) {\r\n console.warn(\r\n `[agent-native] Failed to auto-mount default plugin ${stem}:`,\r\n (e as Error).message,\r\n );\r\n captureError(e, {\r\n route: \"default-plugin-bootstrap\",\r\n tags: { phase: \"default-plugin-bootstrap\", plugin: stem },\r\n });\r\n }\r\n }\r\n }\r\n } finally {\r\n IN_BOOTSTRAP.delete(nitroApp);\r\n }\r\n}\r\n\r\n/**\r\n * Load a workspace-core's `/server` entry, transparently handling TS source.\r\n *\r\n * The scaffolded workspace-core template ships TS sources without a build\r\n * step (exports point at `./src/server/index.ts`), so plain `await import()`\r\n * blows up the moment Node hits a relative `.js` import inside (the standard\r\n * TS ESM convention) — and even before that, Node may resolve the package\r\n * relative to the framework's own location rather than the user's monorepo.\r\n *\r\n * We try Node's plain `import()` first (fastest path when the user has\r\n * compiled to dist/) and fall through to jiti on any error. jiti is anchored\r\n * to a real file inside the workspace-core's directory, so its module\r\n * resolution starts in the right node_modules tree (handles pnpm hoisting\r\n * and linked workspaces) AND handles TS source files + `.js` → `.ts` ESM\r\n * extension remapping.\r\n *\r\n * Edge runtimes without `fs` won't be able to load jiti at all; the outer\r\n * try/catch silently falls through to framework defaults in that case.\r\n */\r\nexport async function loadWorkspaceCoreServer(\r\n packageName: string,\r\n packageDir: string,\r\n): Promise<any> {\r\n let firstErr: unknown;\r\n try {\r\n return await import(/* @vite-ignore */ `${packageName}/server`);\r\n } catch (e) {\r\n firstErr = e;\r\n }\r\n\r\n try {\r\n const { createJiti } = await import(\"jiti\");\r\n const { pathToFileURL } = await import(\"node:url\");\r\n const path = await import(\"node:path\");\r\n // Anchor jiti to a real file inside the workspace-core package so its\r\n // module resolution starts in the right node_modules tree (handles pnpm\r\n // hoisting and linked workspaces).\r\n const anchor = pathToFileURL(\r\n path.join(packageDir, \"package.json\"),\r\n ).toString();\r\n const jiti = createJiti(anchor, { interopDefault: true });\r\n return await jiti.import(`${packageName}/server`);\r\n } catch (jitiErr) {\r\n // jiti also failed — rethrow the original Node error since it's usually\r\n // more informative about *why* the package wasn't resolvable.\r\n throw firstErr ?? jitiErr;\r\n }\r\n}\r\n\r\nexport { FRAMEWORK_PREFIX };\r\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jami-studio/core",
3
- "version": "0.92.21",
3
+ "version": "0.92.22",
4
4
  "description": "Framework for agent-native application development — where AI agents and UI share SQL state, actions, and context",
5
5
  "homepage": "https://github.com/studio-jami/jami-studio#readme",
6
6
  "bugs": {