@agent-native/core 0.164.23 → 0.164.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,6 +27,8 @@ export declare const appConfig: z.ZodObject<{
27
27
  id: z.ZodOptional<z.ZodString>;
28
28
  workspaceId: z.ZodOptional<z.ZodString>;
29
29
  name: z.ZodOptional<z.ZodString>;
30
+ pingMessage: z.ZodDefault<z.ZodString>;
31
+ healthStrictSchema: z.ZodDefault<z.ZodBoolean>;
30
32
  url: z.ZodOptional<z.ZodString>;
31
33
  packageName: z.ZodOptional<z.ZodString>;
32
34
  template: z.ZodOptional<z.ZodString>;
@@ -51,6 +51,21 @@ export const appConfig = z.object({
51
51
  env: ["APP_NAME"],
52
52
  doc: "User-facing display name of this app.",
53
53
  }),
54
+ pingMessage: z
55
+ .string()
56
+ .min(1)
57
+ .default("pong")
58
+ .meta({
59
+ env: ["PING_MESSAGE"],
60
+ doc: "Message returned by the framework ping route.",
61
+ }),
62
+ healthStrictSchema: z
63
+ .boolean()
64
+ .default(false)
65
+ .meta({
66
+ env: ["AGENT_NATIVE_HEALTH_STRICT_SCHEMA"],
67
+ doc: "Return HTTP 503 when the framework health schema probe is not ready.",
68
+ }),
54
69
  /**
55
70
  * The app's canonical public URL — what a user sees in a share link, an
56
71
  * email, or a JWT issuer claim.
@@ -28,6 +28,8 @@ export declare const appConfigSchema: z.ZodObject<{
28
28
  id: z.ZodOptional<z.ZodString>;
29
29
  workspaceId: z.ZodOptional<z.ZodString>;
30
30
  name: z.ZodOptional<z.ZodString>;
31
+ pingMessage: z.ZodDefault<z.ZodString>;
32
+ healthStrictSchema: z.ZodDefault<z.ZodBoolean>;
31
33
  url: z.ZodOptional<z.ZodString>;
32
34
  packageName: z.ZodOptional<z.ZodString>;
33
35
  template: z.ZodOptional<z.ZodString>;
@@ -62,11 +62,11 @@ export declare const postAwareness: import("h3").EventHandlerWithFetch<import("h
62
62
  error: string;
63
63
  states?: undefined;
64
64
  } | {
65
- error?: undefined;
66
65
  states: {
67
66
  clientId: number;
68
67
  state: string;
69
68
  }[];
69
+ error?: undefined;
70
70
  }>>;
71
71
  /**
72
72
  * GET /_agent-native/collab/:docId/users
@@ -77,9 +77,9 @@ export declare const getActiveUsers: import("h3").EventHandlerWithFetch<import("
77
77
  error: string;
78
78
  users?: undefined;
79
79
  } | {
80
- error?: undefined;
81
80
  users: {
82
81
  clientId: number;
83
82
  lastSeen: number;
84
83
  }[];
84
+ error?: undefined;
85
85
  }>>;
@@ -137,13 +137,13 @@ export declare function screenMemoryMcpToolDefinitions(): ({
137
137
  inputSchema: {
138
138
  type: string;
139
139
  properties: {
140
+ count?: undefined;
140
141
  query?: undefined;
141
142
  minutes?: undefined;
142
143
  limit?: undefined;
143
144
  clientHint?: undefined;
144
145
  timestamp?: undefined;
145
146
  chapterId?: undefined;
146
- count?: undefined;
147
147
  startAt?: undefined;
148
148
  endAt?: undefined;
149
149
  reason?: undefined;
@@ -159,6 +159,7 @@ export declare function screenMemoryMcpToolDefinitions(): ({
159
159
  inputSchema: {
160
160
  type: string;
161
161
  properties: {
162
+ count?: undefined;
162
163
  query: {
163
164
  type: string;
164
165
  description: string;
@@ -174,7 +175,6 @@ export declare function screenMemoryMcpToolDefinitions(): ({
174
175
  clientHint?: undefined;
175
176
  timestamp?: undefined;
176
177
  chapterId?: undefined;
177
- count?: undefined;
178
178
  startAt?: undefined;
179
179
  endAt?: undefined;
180
180
  reason?: undefined;
@@ -190,6 +190,7 @@ export declare function screenMemoryMcpToolDefinitions(): ({
190
190
  inputSchema: {
191
191
  type: string;
192
192
  properties: {
193
+ count?: undefined;
193
194
  minutes: {
194
195
  type: string;
195
196
  description: string;
@@ -199,7 +200,6 @@ export declare function screenMemoryMcpToolDefinitions(): ({
199
200
  clientHint?: undefined;
200
201
  timestamp?: undefined;
201
202
  chapterId?: undefined;
202
- count?: undefined;
203
203
  startAt?: undefined;
204
204
  endAt?: undefined;
205
205
  reason?: undefined;
@@ -216,6 +216,7 @@ export declare function screenMemoryMcpToolDefinitions(): ({
216
216
  type: string;
217
217
  required: string[];
218
218
  properties: {
219
+ count?: undefined;
219
220
  query: {
220
221
  type: string;
221
222
  description: string;
@@ -234,7 +235,6 @@ export declare function screenMemoryMcpToolDefinitions(): ({
234
235
  };
235
236
  timestamp?: undefined;
236
237
  chapterId?: undefined;
237
- count?: undefined;
238
238
  startAt?: undefined;
239
239
  endAt?: undefined;
240
240
  reason?: undefined;
@@ -250,6 +250,7 @@ export declare function screenMemoryMcpToolDefinitions(): ({
250
250
  type: string;
251
251
  required: string[];
252
252
  properties: {
253
+ count?: undefined;
253
254
  query?: undefined;
254
255
  minutes?: undefined;
255
256
  limit?: undefined;
@@ -263,7 +264,6 @@ export declare function screenMemoryMcpToolDefinitions(): ({
263
264
  description: string;
264
265
  };
265
266
  chapterId?: undefined;
266
- count?: undefined;
267
267
  startAt?: undefined;
268
268
  endAt?: undefined;
269
269
  includeMicrophone?: undefined;
@@ -314,13 +314,13 @@ export declare function screenMemoryMcpToolDefinitions(): ({
314
314
  type: string;
315
315
  required: string[];
316
316
  properties: {
317
+ count?: undefined;
317
318
  query?: undefined;
318
319
  minutes?: undefined;
319
320
  limit?: undefined;
320
321
  clientHint?: undefined;
321
322
  timestamp?: undefined;
322
323
  chapterId?: undefined;
323
- count?: undefined;
324
324
  startAt: {
325
325
  type: string;
326
326
  description: string;
@@ -349,13 +349,13 @@ export declare function screenMemoryMcpToolDefinitions(): ({
349
349
  type: string;
350
350
  required: string[];
351
351
  properties: {
352
+ count?: undefined;
352
353
  query?: undefined;
353
354
  minutes?: undefined;
354
355
  limit?: undefined;
355
356
  clientHint?: undefined;
356
357
  timestamp?: undefined;
357
358
  chapterId?: undefined;
358
- count?: undefined;
359
359
  startAt?: undefined;
360
360
  endAt?: undefined;
361
361
  reason?: undefined;
@@ -11,23 +11,23 @@
11
11
  * DELETE /_agent-native/notifications/:id — delete
12
12
  */
13
13
  export declare function createNotificationsHandler(): import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<"" | import("./types.js").Notification[] | {
14
- error?: undefined;
15
14
  count: number;
16
15
  updated?: undefined;
16
+ error?: undefined;
17
17
  ok?: undefined;
18
18
  } | {
19
- error?: undefined;
19
+ count?: undefined;
20
20
  updated: number;
21
+ error?: undefined;
21
22
  ok?: undefined;
22
- count?: undefined;
23
23
  } | {
24
+ count?: undefined;
24
25
  updated?: undefined;
25
26
  error: string;
26
27
  ok?: undefined;
27
- count?: undefined;
28
28
  } | {
29
- error?: undefined;
29
+ count?: undefined;
30
30
  updated?: undefined;
31
+ error?: undefined;
31
32
  ok: boolean;
32
- count?: undefined;
33
33
  }>>;
@@ -41,14 +41,14 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
41
41
  thumbsUpRate: number;
42
42
  avgEvalScore: number;
43
43
  } | {
44
- error?: undefined;
45
44
  ok?: undefined;
45
+ error?: undefined;
46
46
  summary: import("./types.js").TraceSummary;
47
47
  spans: import("./types.js").TraceSpan[];
48
48
  id?: undefined;
49
49
  } | {
50
- error?: undefined;
51
50
  ok?: undefined;
51
+ error?: undefined;
52
52
  summary?: undefined;
53
53
  spans?: undefined;
54
54
  id: string;
@@ -15,6 +15,6 @@ export declare function createProgressHandler(): import("h3").EventHandlerWithFe
15
15
  error: string;
16
16
  ok?: undefined;
17
17
  } | {
18
- error?: undefined;
19
18
  ok: boolean;
19
+ error?: undefined;
20
20
  }>>;
@@ -1,19 +1,33 @@
1
1
  import { autoMountAuth } from "./auth.js";
2
2
  import { runBetterAuthMigrations } from "./better-auth-migrations.js";
3
- import { getH3App, awaitBootstrap, markDefaultPluginProvided, trackPluginInit, } from "./framework-request-handler.js";
3
+ import { FRAMEWORK_AUTH_EARLY_PATHS, awaitBootstrap, getH3App, markDefaultPluginProvided, markFrameworkRoutesReadyBeforeBootstrap, trackPluginInit, } from "./framework-request-handler.js";
4
4
  export function createAuthPlugin(options) {
5
5
  return (nitroApp) => {
6
6
  markDefaultPluginProvided(nitroApp, "auth");
7
+ const isByoa = Boolean(options?.getSession);
8
+ const app = getH3App(nitroApp);
7
9
  const initPromise = (async () => {
10
+ // A BYOA provider owns its session lookup and login HTML. Mount it
11
+ // immediately so a transient database outage in Better Auth or another
12
+ // default plugin cannot make the custom sign-in document unavailable.
13
+ if (isByoa) {
14
+ // The guard is mounted synchronously by the BYOA branch above. Only
15
+ // after that synchronous registration is it safe to let these paths
16
+ // skip unrelated bootstrap work.
17
+ const mountPromise = autoMountAuth(app, options);
18
+ markFrameworkRoutesReadyBeforeBootstrap(nitroApp, FRAMEWORK_AUTH_EARLY_PATHS);
19
+ await mountPromise;
20
+ return;
21
+ }
8
22
  await awaitBootstrap(nitroApp);
9
23
  // guard:allow-boot-data-work — local/long-lived runtimes provision auth
10
24
  // before mounting routes; production functions are rejected by the
11
25
  // migration runner and use the release job instead.
12
26
  await runBetterAuthMigrations(nitroApp);
13
- await autoMountAuth(getH3App(nitroApp), options);
27
+ await autoMountAuth(app, options);
14
28
  })();
15
29
  trackPluginInit(nitroApp, initPromise, {
16
- paths: ["/_agent-native/auth"],
30
+ paths: [...FRAMEWORK_AUTH_EARLY_PATHS],
17
31
  });
18
32
  };
19
33
  }
@@ -1,14 +1,139 @@
1
- import { BETA_OPT_OUT_QUERY_PARAM, BETA_OPT_OUT_STORAGE_KEY, } from "../shared/environment-lanes.js";
1
+ import { BETA_OPT_OUT_DURATION_MS, BETA_OPT_OUT_QUERY_PARAM, BETA_OPT_OUT_STORAGE_KEY, ENVIRONMENT_BETA_HOSTS, } from "../shared/environment-lanes.js";
2
2
  export const BETA_OPT_OUT_PERSISTENCE_MARKER = "Persist the beta opt-out before authentication";
3
- /**
4
- * Custom auth pages do not necessarily use the framework onboarding shell.
5
- * Keep the production switcher's one-time opt-out behavior at the shared auth
6
- * response boundary so those pages cannot drop the handoff before sign-in.
7
- */
8
- export function injectBetaOptOutPersistence(loginHtml) {
9
- if (loginHtml.includes(BETA_OPT_OUT_PERSISTENCE_MARKER))
10
- return loginHtml;
11
- const script = `<script data-agent-native-beta-opt-out>
3
+ const ENVIRONMENT_SWITCHER_MARKER = 'data-agent-native-environment-switcher="1"';
4
+ const ENVIRONMENT_SWITCHER_STYLE_MARKER = 'data-agent-native-environment-switcher-style="1"';
5
+ const ENVIRONMENT_SWITCHER_SCRIPT_MARKER = 'data-agent-native-environment-switcher-script="1"';
6
+ const EXISTING_ENVIRONMENT_SWITCHER_RE = /\bid=["']environment-switcher["']/;
7
+ function insertBeforeClosingTag(html, fragment, closingTag) {
8
+ const closeIndex = html.indexOf(closingTag);
9
+ if (closeIndex < 0)
10
+ return html + fragment;
11
+ return html.slice(0, closeIndex) + fragment + html.slice(closeIndex);
12
+ }
13
+ const environmentSwitcherMarkup = `<div class="environment-switcher" id="environment-switcher" ${ENVIRONMENT_SWITCHER_MARKER} hidden>
14
+ <button type="button" class="environment-badge" id="environment-badge" aria-expanded="false" aria-controls="environment-popover">beta</button>
15
+ <div class="environment-popover" id="environment-popover" role="dialog" aria-labelledby="environment-popover-title" hidden>
16
+ <div class="environment-popover-title" id="environment-popover-title">You're on Agent Native Beta</div>
17
+ <div class="environment-popover-copy">Choose where you want to continue.</div>
18
+ <a class="environment-production-link" id="environment-production-link" href="">Switch to production</a>
19
+ </div>
20
+ </div>`;
21
+ const environmentSwitcherStyles = `<style ${ENVIRONMENT_SWITCHER_STYLE_MARKER}>
22
+ color-scheme: dark;
23
+ .environment-switcher {
24
+ position: fixed;
25
+ right: max(0.75rem, env(safe-area-inset-right));
26
+ bottom: max(0.75rem, env(safe-area-inset-bottom));
27
+ z-index: 100;
28
+ }
29
+ .environment-switcher[hidden],
30
+ .environment-popover[hidden] { display: none; }
31
+ .environment-badge {
32
+ display: inline-flex;
33
+ align-items: center;
34
+ justify-content: center;
35
+ height: 1.5rem;
36
+ min-width: 0;
37
+ padding: 0 0.5rem;
38
+ background: CanvasText;
39
+ color: Canvas;
40
+ border: 1px solid color-mix(in srgb, Canvas 16%, transparent);
41
+ border-radius: 0.75rem;
42
+ box-shadow: 0 2px 8px color-mix(in srgb, CanvasText 25%, transparent);
43
+ font: inherit;
44
+ font-size: 0.6875rem;
45
+ font-weight: 600;
46
+ letter-spacing: 0.03125rem;
47
+ line-height: 1;
48
+ text-transform: uppercase;
49
+ cursor: pointer;
50
+ }
51
+ .environment-badge:hover,
52
+ .environment-badge[aria-expanded="true"] {
53
+ background: color-mix(in srgb, CanvasText 85%, Canvas);
54
+ }
55
+ .environment-badge:focus-visible,
56
+ .environment-production-link:focus-visible {
57
+ outline: 2px solid LinkText;
58
+ outline-offset: 2px;
59
+ }
60
+ .environment-popover {
61
+ position: absolute;
62
+ right: 0;
63
+ bottom: calc(100% + 0.5rem);
64
+ width: min(17.5rem, calc(100vw - 1.5rem));
65
+ padding: 1.25rem;
66
+ background: Canvas;
67
+ color: CanvasText;
68
+ border: 1px solid color-mix(in srgb, CanvasText 12%, transparent);
69
+ border-radius: 0.75rem;
70
+ box-shadow: 0 18px 50px color-mix(in srgb, CanvasText 42%, transparent);
71
+ }
72
+ .environment-popover-title { margin-bottom: 0.25rem; font-size: 0.875rem; font-weight: 600; line-height: 1.25rem; }
73
+ .environment-popover-copy { margin-bottom: 1rem; color: GrayText; font-size: 0.875rem; line-height: 1.25rem; }
74
+ .environment-production-link {
75
+ display: flex;
76
+ align-items: center;
77
+ justify-content: center;
78
+ min-height: 2rem;
79
+ padding: 0.375rem 0.75rem;
80
+ color: CanvasText;
81
+ border: 1px solid color-mix(in srgb, CanvasText 16%, transparent);
82
+ border-radius: 0.375rem;
83
+ font-size: 0.8125rem;
84
+ text-decoration: none;
85
+ }
86
+ .environment-production-link:hover {
87
+ background: color-mix(in srgb, CanvasText 12%, Canvas);
88
+ }
89
+ </style>`;
90
+ const environmentSwitcherScript = `<script ${ENVIRONMENT_SWITCHER_SCRIPT_MARKER}>
91
+ (function __anInitEnvironmentBadge() {
92
+ var switcher = document.getElementById('environment-switcher');
93
+ var button = document.getElementById('environment-badge');
94
+ var popover = document.getElementById('environment-popover');
95
+ var productionLink = document.getElementById('environment-production-link');
96
+ if (!switcher || !button || !popover || !productionLink) return;
97
+ if (window.parent !== window) return;
98
+
99
+ var betaHosts = ${JSON.stringify(ENVIRONMENT_BETA_HOSTS)};
100
+ var hostname = (window.location.hostname || '').toLowerCase().replace(/\\.$/, '');
101
+ var productionHost = hostname.indexOf('beta.') === 0 ? hostname.slice(5) : '';
102
+ if (!productionHost || betaHosts[productionHost] !== hostname) return;
103
+
104
+ try {
105
+ var productionUrl = new URL(window.location.href);
106
+ productionUrl.protocol = 'https:';
107
+ productionUrl.hostname = productionHost;
108
+ productionUrl.port = '';
109
+ productionUrl.searchParams.set(
110
+ ${JSON.stringify(BETA_OPT_OUT_QUERY_PARAM)},
111
+ String(Date.now() + ${BETA_OPT_OUT_DURATION_MS}),
112
+ );
113
+ productionLink.href = productionUrl.toString();
114
+ } catch (error) {
115
+ void error;
116
+ return;
117
+ }
118
+
119
+ function setOpen(open) {
120
+ popover.hidden = !open;
121
+ button.setAttribute('aria-expanded', String(open));
122
+ }
123
+
124
+ switcher.hidden = false;
125
+ button.addEventListener('click', function() {
126
+ setOpen(popover.hidden);
127
+ });
128
+ document.addEventListener('click', function(event) {
129
+ if (!switcher.contains(event.target)) setOpen(false);
130
+ });
131
+ document.addEventListener('keydown', function(event) {
132
+ if (event.key === 'Escape') setOpen(false);
133
+ });
134
+ })();
135
+ </script>`;
136
+ const betaOptOutPersistenceScript = `<script data-agent-native-beta-opt-out>
12
137
  // ${BETA_OPT_OUT_PERSISTENCE_MARKER}.
13
138
  (function __anPersistBetaOptOut() {
14
139
  try {
@@ -37,17 +162,29 @@ export function injectBetaOptOutPersistence(loginHtml) {
37
162
  }
38
163
  })();
39
164
  </script>`;
40
- const bodyCloseIndex = loginHtml.indexOf("</body>");
41
- if (bodyCloseIndex >= 0) {
42
- return (loginHtml.slice(0, bodyCloseIndex) +
43
- script +
44
- loginHtml.slice(bodyCloseIndex));
165
+ /**
166
+ * Custom auth pages do not necessarily use the framework onboarding shell.
167
+ * Keep the production switcher's one-time opt-out behavior at the shared auth
168
+ * response boundary so those pages cannot drop the handoff before sign-in.
169
+ */
170
+ export function injectBetaOptOutPersistence(loginHtml) {
171
+ let html = loginHtml;
172
+ if (!html.includes(BETA_OPT_OUT_PERSISTENCE_MARKER)) {
173
+ html = insertBeforeClosingTag(html, betaOptOutPersistenceScript, "</body>");
174
+ }
175
+ // The standard onboarding shell already owns this markup, style, and
176
+ // initializer. Custom login pages need the shared switcher, but adding a
177
+ // second copy would create duplicate IDs and event handlers.
178
+ if (EXISTING_ENVIRONMENT_SWITCHER_RE.test(html))
179
+ return html;
180
+ if (!html.includes(ENVIRONMENT_SWITCHER_STYLE_MARKER)) {
181
+ html = insertBeforeClosingTag(html, environmentSwitcherStyles, "</head>");
182
+ }
183
+ if (!html.includes(ENVIRONMENT_SWITCHER_MARKER)) {
184
+ html = insertBeforeClosingTag(html, environmentSwitcherMarkup, "</body>");
45
185
  }
46
- const headCloseIndex = loginHtml.indexOf("</head>");
47
- if (headCloseIndex >= 0) {
48
- return (loginHtml.slice(0, headCloseIndex) +
49
- script +
50
- loginHtml.slice(headCloseIndex));
186
+ if (!html.includes(ENVIRONMENT_SWITCHER_SCRIPT_MARKER)) {
187
+ html = insertBeforeClosingTag(html, environmentSwitcherScript, "</body>");
51
188
  }
52
- return loginHtml + script;
189
+ return html;
53
190
  }
@@ -51,7 +51,7 @@ import { probeDbPressure } from "./db-pressure.js";
51
51
  import { resolveDeployEnvironment, resolveServerRelease, } from "./deploy-environment.js";
52
52
  import { createEmbedStartRouteHandler } from "./embed-route.js";
53
53
  import { shouldReportError } from "./error-noise-filter.js";
54
- import { getH3App, awaitBootstrap, markDefaultPluginProvided, trackPluginInit, } from "./framework-request-handler.js";
54
+ import { FRAMEWORK_AUTH_EARLY_PATHS, getH3App, awaitBootstrap, markDefaultPluginProvided, markFrameworkRoutesReadyBeforeBootstrap, trackPluginInit, } from "./framework-request-handler.js";
55
55
  import { createGatewayAccessCheckHandler } from "./gateway-access-check.js";
56
56
  import { getAppBasePath, getOrigin } from "./google-oauth.js";
57
57
  import { createGoogleRealtimeSessionHandler } from "./google-realtime-session.js";
@@ -939,9 +939,21 @@ export function createCoreRoutesPlugin(options = {}) {
939
939
  });
940
940
  trackPluginInit(nitroApp, initPromise, {
941
941
  paths: [FRAMEWORK_ROUTE_PREFIX, "/mcp", "/.well-known"],
942
+ // Liveness and BYOA auth routes are mounted before the DB-dependent
943
+ // bootstrap below. The broad core entry must not hold those routes while
944
+ // an unrelated migration or connection pool is unavailable.
945
+ excludedPaths: [
946
+ `${FRAMEWORK_ROUTE_PREFIX}/ping`,
947
+ `${FRAMEWORK_ROUTE_PREFIX}/health`,
948
+ ...FRAMEWORK_AUTH_EARLY_PATHS,
949
+ ],
942
950
  });
943
951
  try {
944
952
  const P = FRAMEWORK_ROUTE_PREFIX;
953
+ markFrameworkRoutesReadyBeforeBootstrap(nitroApp, [
954
+ ...(!options.disablePing ? [`${P}/ping`] : []),
955
+ ...(!options.disableHealth ? [`${P}/health`] : []),
956
+ ]);
945
957
  // Keep the framework-owned S3-compatible provider available even when an
946
958
  // app does not mount the optional onboarding plugin. The settings CTA and
947
959
  // the upload route share this registry. An app may register its own
@@ -962,6 +974,52 @@ export function createCoreRoutesPlugin(options = {}) {
962
974
  }
963
975
  return EMPTY_SPECULATION_RULES;
964
976
  }));
977
+ // Keep liveness independent from the rest of framework bootstrap. A
978
+ // cold-start database failure must report a useful ping/health result,
979
+ // not prevent these handlers from being registered at all.
980
+ if (!options.disablePing) {
981
+ getH3App(nitroApp).use(`${P}/ping`, defineEventHandler((event) => {
982
+ const message = getAppConfig().app.pingMessage;
983
+ const configuration = event.url?.searchParams.get("configuration") === "1" ||
984
+ event.url?.searchParams.get("configuration") === "true";
985
+ if (!configuration)
986
+ return { message };
987
+ const requirements = {
988
+ ...(event.url?.searchParams.get("auth") === "0"
989
+ ? { authEnabled: false }
990
+ : {}),
991
+ ...(event.url?.searchParams.get("database") === "0"
992
+ ? { databaseRequired: false }
993
+ : {}),
994
+ };
995
+ return {
996
+ message,
997
+ configuration: getRuntimeConfigReport(process.env, requirements, {
998
+ phase: "runtime",
999
+ appName: getAppConfig().app.name,
1000
+ }),
1001
+ };
1002
+ }));
1003
+ }
1004
+ if (!options.disableHealth) {
1005
+ getH3App(nitroApp).use(`${P}/health`, defineEventHandler(async (event) => {
1006
+ setResponseHeader(event, "cache-control", "no-store");
1007
+ const schema = event.url?.searchParams.get("schema") === "1" ||
1008
+ event.url?.searchParams.get("schema") === "true";
1009
+ const strict = event.url?.searchParams.get("strict") === "1" ||
1010
+ event.url?.searchParams.get("strict") === "true" ||
1011
+ getAppConfig().app.healthStrictSchema;
1012
+ const pressure = event.url?.searchParams.get("pressure") === "1" ||
1013
+ event.url?.searchParams.get("pressure") === "true";
1014
+ const result = await runDbHealthProbe(getDbExec, {
1015
+ schema,
1016
+ pressure,
1017
+ });
1018
+ if (strict && !result.ready)
1019
+ setResponseStatus(event, 503);
1020
+ return result;
1021
+ }));
1022
+ }
965
1023
  await awaitBootstrap(nitroApp);
966
1024
  const runBootDatabaseWork = shouldRunCoreRouteBootDatabaseWork();
967
1025
  const { persistedEnvVars, builderDisconnected } = runBootDatabaseWork
@@ -1264,33 +1322,6 @@ export function createCoreRoutesPlugin(options = {}) {
1264
1322
  getH3App(nitroApp).use(route, createPollEventsHandler());
1265
1323
  }
1266
1324
  }
1267
- // Ping
1268
- if (!options.disablePing) {
1269
- getH3App(nitroApp).use(`${P}/ping`, defineEventHandler((event) => {
1270
- const message = process.env.PING_MESSAGE ?? "pong";
1271
- const configuration = event.url?.searchParams.get("configuration") === "1" ||
1272
- event.url?.searchParams.get("configuration") === "true";
1273
- if (!configuration)
1274
- return { message };
1275
- // Custom required keys must come from server-side app configuration;
1276
- // never let an anonymous caller turn this into an env-name oracle.
1277
- const requirements = {
1278
- ...(event.url?.searchParams.get("auth") === "0"
1279
- ? { authEnabled: false }
1280
- : {}),
1281
- ...(event.url?.searchParams.get("database") === "0"
1282
- ? { databaseRequired: false }
1283
- : {}),
1284
- };
1285
- return {
1286
- message,
1287
- configuration: getRuntimeConfigReport(process.env, requirements, {
1288
- phase: "runtime",
1289
- appName: process.env.APP_NAME,
1290
- }),
1291
- };
1292
- }));
1293
- }
1294
1325
  // ─── Durable sandbox execution processor ─────────────────────────
1295
1326
  // Self-fired by run-code's background queue (see
1296
1327
  // coding-tools/sandbox/background.ts): the enqueueing request POSTs here
@@ -1370,37 +1401,6 @@ export function createCoreRoutesPlugin(options = {}) {
1370
1401
  }, 30_000); // Check every 30s but only sweep once per 2min
1371
1402
  }, 25_000); // Start 25s after init (after the agent sweeps)
1372
1403
  })();
1373
- // Health + DB warmup — liveness probe that touches the database so
1374
- // uptime monitors and the keep-warm cron prevent a scale-to-zero
1375
- // serverless DB (e.g. Neon) from cold-starting on the next real
1376
- // request. Public, side-effect free, and never cached. Add ?schema=1
1377
- // for metadata-only schema checks, and ?strict=1 to turn a not-ready
1378
- // DB/schema probe into a failing HTTP status for monitors.
1379
- if (!options.disableHealth) {
1380
- getH3App(nitroApp).use(`${P}/health`, defineEventHandler(async (event) => {
1381
- setResponseHeader(event, "cache-control", "no-store");
1382
- const schema = event.url?.searchParams.get("schema") === "1" ||
1383
- event.url?.searchParams.get("schema") === "true";
1384
- const strict = event.url?.searchParams.get("strict") === "1" ||
1385
- event.url?.searchParams.get("strict") === "true" ||
1386
- process.env.AGENT_NATIVE_HEALTH_STRICT_SCHEMA === "true";
1387
- // Off by default: the one-minute warm cron does not need it, and
1388
- // an extra `pg_stat_activity` read every minute per app is waste.
1389
- // Pressure deliberately does NOT change `ready` or the status
1390
- // code — a pressured database is still serving, and an uptime
1391
- // monitor that pages on it would learn to ignore this route. The
1392
- // fleet audit reads the counters and decides.
1393
- const pressure = event.url?.searchParams.get("pressure") === "1" ||
1394
- event.url?.searchParams.get("pressure") === "true";
1395
- const result = await runDbHealthProbe(getDbExec, {
1396
- schema,
1397
- pressure,
1398
- });
1399
- if (strict && !result.ready)
1400
- setResponseStatus(event, 503);
1401
- return result;
1402
- }));
1403
- }
1404
1404
  getH3App(nitroApp).use(`${P}/debug/runtime`, defineEventHandler(async (event) => {
1405
1405
  setResponseHeader(event, "cache-control", "no-store");
1406
1406
  const session = await getSession(event).catch(() => null);
@@ -14,7 +14,7 @@ export interface CreateServerOptions {
14
14
  cors?: Record<string, unknown> | false;
15
15
  /** JSON body parser limit. Kept for API compatibility (H3 uses readBody). */
16
16
  jsonLimit?: string;
17
- /** Custom ping message. Default: reads PING_MESSAGE env var, falls back to "pong" */
17
+ /** Custom ping message. Default: reads the shared app config. */
18
18
  pingMessage?: string;
19
19
  /** Disable the /_agent-native/ping health check. Default: false */
20
20
  disablePing?: boolean;
@@ -1,4 +1,5 @@
1
1
  import { createApp, createRouter, defineEventHandler, getMethod, getRequestHeader, setResponseHeader, setResponseStatus, } from "h3";
2
+ import { getAppConfig } from "../app-config/index.js";
2
3
  import { getOrgContext } from "../org/context.js";
3
4
  import { readBody } from "../server/h3-helpers.js";
4
5
  import { EMBED_TARGET_HEADER } from "../shared/embed-auth.js";
@@ -109,7 +110,7 @@ export function createServer(options = {}) {
109
110
  // Health check
110
111
  if (!options.disablePing) {
111
112
  router.get("/_agent-native/ping", defineEventHandler((event) => {
112
- const message = options.pingMessage ?? process.env.PING_MESSAGE ?? "pong";
113
+ const message = options.pingMessage ?? getAppConfig().app.pingMessage;
113
114
  const configuration = event.url?.searchParams.get("configuration") === "1" ||
114
115
  event.url?.searchParams.get("configuration") === "true";
115
116
  if (!configuration)
@@ -128,7 +129,7 @@ export function createServer(options = {}) {
128
129
  message,
129
130
  configuration: getRuntimeConfigReport(process.env, requirements, {
130
131
  phase: "runtime",
131
- appName: process.env.APP_NAME,
132
+ appName: getAppConfig().app.name,
132
133
  }),
133
134
  };
134
135
  }));
@@ -71,17 +71,24 @@ function markEmbeddedPluginStems(nitroApp) {
71
71
  export async function mountAgentNativeEmbedded(nitroApp, options = {}) {
72
72
  configureAgentNativeEmbeddedEnvironment(options);
73
73
  markEmbeddedPluginStems(nitroApp);
74
+ // The auth plugin tracks its async initialization itself. Do not await the
75
+ // factory call here: with default Better Auth, its DB bootstrap can be the
76
+ // thing that is unavailable while public liveness routes still need to
77
+ // mount below.
78
+ createAuthPlugin(createAgentNativeEmbeddedAuthOptions(options.auth))(nitroApp);
79
+ // Mount framework auth and liveness before waiting on the host application's
80
+ // bootstrap. The embedded plugin tracks its full init as an unscoped promise,
81
+ // so early requests deliberately skip that promise.
82
+ if (options.coreRoutes !== false) {
83
+ await createCoreRoutesPlugin(options.coreRoutes ?? undefined)(nitroApp);
84
+ }
74
85
  await awaitBootstrap(nitroApp);
75
- await createAuthPlugin(createAgentNativeEmbeddedAuthOptions(options.auth))(nitroApp);
76
86
  if (options.sentry !== false) {
77
87
  await createSentryPlugin()(nitroApp);
78
88
  }
79
89
  if (options.org === true) {
80
90
  await createOrgPlugin()(nitroApp);
81
91
  }
82
- if (options.coreRoutes !== false) {
83
- await createCoreRoutesPlugin(options.coreRoutes ?? undefined)(nitroApp);
84
- }
85
92
  if (options.resources !== false) {
86
93
  await createResourcesPlugin()(nitroApp);
87
94
  }
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import type { EventHandler } from "h3";
15
15
  declare const FRAMEWORK_PREFIX = "/_agent-native";
16
+ export declare const FRAMEWORK_AUTH_EARLY_PATHS: readonly ["/_agent-native/auth", "/sign-in", "/_agent-native/sign-in", "/_agent-native/login", "/_agent-native/signup", "/login", "/signup"];
16
17
  /**
17
18
  * Wrapper around Nitro's h3 instance that exposes a v1-style `.use()` API
18
19
  * for registering path-prefix middleware.
@@ -32,6 +33,13 @@ export interface H3AppShim {
32
33
  * auto-mount a generic default over the app's custom implementation.
33
34
  */
34
35
  export declare function markDefaultPluginProvided(nitroApp: any, stem: string): void;
36
+ /**
37
+ * Mark routes that are mounted without waiting for unrelated default-plugin
38
+ * bootstrap. BYOA auth uses this for its cacheable login document: waiting
39
+ * for Better Auth or another DB-backed plugin turns an available login form
40
+ * into a serverless 502 during a cold-start database outage.
41
+ */
42
+ export declare function markFrameworkRoutesReadyBeforeBootstrap(nitroApp: any, paths: readonly string[]): void;
35
43
  /**
36
44
  * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this
37
45
  * to register routes via `.use(path, handler)`.
@@ -65,12 +73,15 @@ export declare function awaitBootstrap(nitroApp: any): Promise<void>;
65
73
  */
66
74
  export declare function trackPluginInit(nitroApp: any, promise: Promise<void>, options?: {
67
75
  paths?: string[];
76
+ excludedPaths?: string[];
68
77
  }): void;
69
78
  /**
70
79
  * Await all tracked plugin initializations. Called by the readiness gate
71
80
  * middleware before dispatching framework routes.
72
81
  */
73
- export declare function awaitPluginsReady(nitroApp: any, reqPath?: string): Promise<void>;
82
+ export declare function awaitPluginsReady(nitroApp: any, reqPath?: string, options?: {
83
+ skipUnscoped?: boolean;
84
+ }): Promise<void>;
74
85
  /**
75
86
  * Load a workspace-core's `/server` entry, transparently handling TS source.
76
87
  *
@@ -1,6 +1,7 @@
1
1
  import { setResponseHeader, setResponseStatus } from "h3";
2
2
  import { getMissingDefaultPlugins } from "../deploy/route-discovery.js";
3
3
  import { MCP_PUBLIC_ROUTE_PREFIX } from "../mcp/route-paths.js";
4
+ import { SIGN_IN_ENTRY_PATH, SIGN_IN_LEGACY_ENTRY_PATH, } from "../shared/sign-in-journey.js";
4
5
  import { getConfiguredAppBasePath } from "./app-base-path.js";
5
6
  import { captureError } from "./capture-error.js";
6
7
  import { createCsrfMiddleware } from "./csrf.js";
@@ -16,8 +17,23 @@ const PLUGIN_READY_KEY = "_agentNativePluginReadyPromise";
16
17
  const PLUGIN_READY_PLACEHOLDERS_KEY = "_agentNativePluginReadyPlaceholders";
17
18
  const PLUGIN_FAILED_KEY = "_agentNativePluginInitFailures";
18
19
  const PROVIDED_PLUGIN_STEMS_KEY = "_agentNativeProvidedPluginStems";
20
+ const EARLY_FRAMEWORK_PATHS_KEY = "_agentNativeEarlyFrameworkPaths";
19
21
  const MIDDLEWARE_DISPATCHER_PATCHED_KEY = "_agentNativeMiddlewareDispatcherPatched";
20
22
  const REQUEST_CONTEXT_BOUNDARY_KEY = "_agentNativeRequestContextBoundary";
23
+ const CANONICAL_AUTH_EARLY_PATHS = [
24
+ SIGN_IN_ENTRY_PATH,
25
+ "/login",
26
+ "/signup",
27
+ ];
28
+ export const FRAMEWORK_AUTH_EARLY_PATHS = [
29
+ `${FRAMEWORK_PREFIX}/auth`,
30
+ SIGN_IN_ENTRY_PATH,
31
+ SIGN_IN_LEGACY_ENTRY_PATH,
32
+ `${FRAMEWORK_PREFIX}/login`,
33
+ `${FRAMEWORK_PREFIX}/signup`,
34
+ "/login",
35
+ "/signup",
36
+ ];
21
37
  function getAppBasePath() {
22
38
  return getConfiguredAppBasePath();
23
39
  }
@@ -27,7 +43,8 @@ function pathMatchesPrefix(reqPath, prefix) {
27
43
  function supportsAppBasePathMount(path) {
28
44
  return (pathMatchesPrefix(path, FRAMEWORK_PREFIX) ||
29
45
  pathMatchesPrefix(path, WELL_KNOWN_PREFIX) ||
30
- pathMatchesPrefix(path, MCP_PUBLIC_ROUTE_PREFIX));
46
+ pathMatchesPrefix(path, MCP_PUBLIC_ROUTE_PREFIX) ||
47
+ CANONICAL_AUTH_EARLY_PATHS.some((authPath) => pathMatchesPrefix(path, authPath)));
31
48
  }
32
49
  function resolveMountMatch(reqPath, path) {
33
50
  if (pathMatchesPrefix(reqPath, path)) {
@@ -62,6 +79,23 @@ export function markDefaultPluginProvided(nitroApp, stem) {
62
79
  provided.add(stem);
63
80
  nitroApp[PROVIDED_PLUGIN_STEMS_KEY] = provided;
64
81
  }
82
+ /**
83
+ * Mark routes that are mounted without waiting for unrelated default-plugin
84
+ * bootstrap. BYOA auth uses this for its cacheable login document: waiting
85
+ * for Better Auth or another DB-backed plugin turns an available login form
86
+ * into a serverless 502 during a cold-start database outage.
87
+ */
88
+ export function markFrameworkRoutesReadyBeforeBootstrap(nitroApp, paths) {
89
+ if (!nitroApp)
90
+ return;
91
+ const existing = nitroApp[EARLY_FRAMEWORK_PATHS_KEY] ??
92
+ new Set();
93
+ for (const path of paths) {
94
+ if (path)
95
+ existing.add(path);
96
+ }
97
+ nitroApp[EARLY_FRAMEWORK_PATHS_KEY] = existing;
98
+ }
65
99
  /**
66
100
  * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this
67
101
  * to register routes via `.use(path, handler)`.
@@ -119,6 +153,9 @@ export function getH3App(nitroApp) {
119
153
  registerMiddleware(nitroApp, MCP_PUBLIC_ROUTE_PREFIX, readinessGate, {
120
154
  prepend: true,
121
155
  });
156
+ for (const path of CANONICAL_AUTH_EARLY_PATHS) {
157
+ registerMiddleware(nitroApp, path, readinessGate, { prepend: true });
158
+ }
122
159
  // CSRF (see csrf.ts): registered here — synchronously, on the very
123
160
  // first `getH3App()` call for this nitroApp — rather than inside
124
161
  // createCoreRoutesPlugin's own async init chain. Real deployments mount
@@ -152,7 +189,8 @@ export function getH3App(nitroApp) {
152
189
  const reqPath = event.url?.pathname ?? "";
153
190
  if (resolveMountMatch(reqPath, FRAMEWORK_PREFIX) ||
154
191
  resolveMountMatch(reqPath, WELL_KNOWN_PREFIX) ||
155
- resolveMountMatch(reqPath, MCP_PUBLIC_ROUTE_PREFIX)) {
192
+ resolveMountMatch(reqPath, MCP_PUBLIC_ROUTE_PREFIX) ||
193
+ FRAMEWORK_AUTH_EARLY_PATHS.some((path) => resolveMountMatch(reqPath, path))) {
156
194
  const startedAt = Date.now();
157
195
  try {
158
196
  await awaitFrameworkRoutesReadyForRequest(nitroApp, reqPath);
@@ -276,9 +314,15 @@ async function awaitFrameworkRoutesReadyForRequest(nitroApp, reqPath) {
276
314
  return await Promise.race([
277
315
  (async () => {
278
316
  const bootstrapPromise = nitroApp[BOOTSTRAP_PROMISE_KEY];
279
- if (bootstrapPromise)
317
+ const earlyPaths = nitroApp[EARLY_FRAMEWORK_PATHS_KEY];
318
+ const canDispatchBeforeBootstrap = Boolean(earlyPaths?.size &&
319
+ Array.from(earlyPaths).some((path) => resolveMountMatch(reqPath, path)));
320
+ if (bootstrapPromise && !canDispatchBeforeBootstrap) {
280
321
  await bootstrapPromise;
281
- await awaitPluginsReady(nitroApp, reqPath);
322
+ }
323
+ await awaitPluginsReady(nitroApp, reqPath, {
324
+ skipUnscoped: canDispatchBeforeBootstrap,
325
+ });
282
326
  return true;
283
327
  })(),
284
328
  new Promise((resolve) => {
@@ -341,6 +385,7 @@ export function trackPluginInit(nitroApp, promise, options = {}) {
341
385
  const entry = {
342
386
  promise: safe,
343
387
  paths: options.paths?.filter(Boolean),
388
+ excludedPaths: options.excludedPaths?.filter(Boolean),
344
389
  };
345
390
  const existing = nitroApp[PLUGIN_READY_KEY];
346
391
  if (existing) {
@@ -349,9 +394,9 @@ export function trackPluginInit(nitroApp, promise, options = {}) {
349
394
  else {
350
395
  nitroApp[PLUGIN_READY_KEY] = [entry];
351
396
  }
352
- installPluginReadyPlaceholders(nitroApp, entry.paths);
397
+ installPluginReadyPlaceholders(nitroApp, entry.paths, entry.excludedPaths);
353
398
  }
354
- function installPluginReadyPlaceholders(nitroApp, paths) {
399
+ function installPluginReadyPlaceholders(nitroApp, paths, excludedPaths) {
355
400
  if (!paths?.length)
356
401
  return;
357
402
  const existing = nitroApp[PLUGIN_READY_PLACEHOLDERS_KEY];
@@ -364,6 +409,9 @@ function installPluginReadyPlaceholders(nitroApp, paths) {
364
409
  registerMiddleware(nitroApp, path, (async (event) => {
365
410
  const eventAny = event;
366
411
  const reqPath = eventAny.context?._mountedPathname ?? event.url?.pathname ?? path;
412
+ if (excludedPaths?.some((excludedPath) => resolveMountMatch(reqPath, excludedPath))) {
413
+ return undefined;
414
+ }
367
415
  const ready = await awaitFrameworkRoutesReadyForRequest(nitroApp, reqPath);
368
416
  if (!ready) {
369
417
  // Boot is still running and we are out of budget. Answer now, while
@@ -425,14 +473,16 @@ function debugClientAbort(args) {
425
473
  * Await all tracked plugin initializations. Called by the readiness gate
426
474
  * middleware before dispatching framework routes.
427
475
  */
428
- export async function awaitPluginsReady(nitroApp, reqPath) {
476
+ export async function awaitPluginsReady(nitroApp, reqPath, options = {}) {
429
477
  const entries = nitroApp[PLUGIN_READY_KEY];
430
478
  if (!entries?.length)
431
479
  return;
432
480
  const relevant = reqPath
433
- ? entries.filter((entry) => entry.paths?.length
434
- ? entry.paths.some((path) => resolveMountMatch(reqPath, path))
435
- : true)
481
+ ? entries.filter((entry) => !(options.skipUnscoped && !entry.paths?.length) &&
482
+ !entry.excludedPaths?.some((path) => resolveMountMatch(reqPath, path)) &&
483
+ (entry.paths?.length
484
+ ? entry.paths.some((path) => resolveMountMatch(reqPath, path))
485
+ : true))
436
486
  : entries;
437
487
  if (relevant.length) {
438
488
  await Promise.all(relevant.map((entry) => entry.promise));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.164.23",
3
+ "version": "0.164.24",
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/BuilderIO/agent-native#readme",
6
6
  "bugs": {