@agent-native/core 0.0.0-beta-20260820052446 → 0.0.0-beta-20260820094341

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.
@@ -63,7 +63,8 @@ interface EditorSidebarProps {
63
63
  aspectRatio?: AspectRatio;
64
64
  /** Active deck design system used by slide content tokens. */
65
65
  designSystem?: DesignSystemData;
66
- /** The next slide while the agent is preparing its HTML. */
66
+ /** The next slide while the agent is preparing its HTML. Omitted when the
67
+ * agent is filling a placeholder that already has a row in this rail. */
67
68
  generatingSlide?: { index: number };
68
69
  generatingSlideSelected?: boolean;
69
70
  onSelectGeneratingSlide?: () => void;
@@ -75,8 +76,15 @@ interface EditorSidebarProps {
75
76
  /** Clears `describeSlideId` in the parent when the popover closes. */
76
77
  onCloseDescribe: () => void;
77
78
  /** Reports add-slide generation state up so the toolbar's New Slide button
78
- * can disable itself while a request is in flight. */
79
- onAddSlideGeneratingChange?: (generating: boolean) => void;
79
+ * can disable itself while a request is in flight. `targetSlideId` is the
80
+ * placeholder the agent was asked to fill, so the parent can mark that row
81
+ * as the AI-active one instead of appending a second generating row. */
82
+ onAddSlideGeneratingChange?: (
83
+ generating: boolean,
84
+ targetSlideId: string | null,
85
+ ) => void;
86
+ /** Slide the agent is filling in place, marked as AI-active in the rail. */
87
+ aiGeneratingSlideId?: string | null;
80
88
  /** Resolves once a just-inserted blank slide has actually reached the
81
89
  * server, so the agent's update-slide request can't race the add-slide
82
90
  * persistence. */
@@ -199,6 +207,7 @@ function SortableSlideThumb({
199
207
  onOverflowChange,
200
208
  readOnly = false,
201
209
  aiEditing = false,
210
+ isFillingPlaceholder = false,
202
211
  canDelete = true,
203
212
  hasSlideClipboard = false,
204
213
  onCutSlide,
@@ -219,7 +228,11 @@ function SortableSlideThumb({
219
228
  aspectRatio?: AspectRatio;
220
229
  designSystem?: DesignSystemData;
221
230
  onOverflowChange: (info: SlideOverflowInfo) => void;
231
+ /** A recent edit attributed to the agent — a lingering highlight, not a live signal. */
222
232
  aiEditing?: boolean;
233
+ /** This exact slide is the placeholder the agent is filling right now — the
234
+ * one case where the shimmer belongs even without live presence. */
235
+ isFillingPlaceholder?: boolean;
223
236
  /** False when this is the deck's last remaining slide — Cut/Delete stay enabled elsewhere but must not remove it. */
224
237
  canDelete?: boolean;
225
238
  hasSlideClipboard?: boolean;
@@ -255,7 +268,11 @@ function SortableSlideThumb({
255
268
  const humanPresenceUsers = presenceUsers.filter(
256
269
  (user) => !isAgentPresenceUser(user),
257
270
  );
258
- const showAiMarker = aiEditing || agentPresent;
271
+ const showAiMarker = aiEditing || agentPresent || isFillingPlaceholder;
272
+ // Narrower than the badge above: `aiEditing` also covers a slide's lingering
273
+ // post-edit highlight, which is "recently done," not "in progress." The
274
+ // shimmer should only run while the agent is actually live on this slide.
275
+ const showGeneratingShimmer = agentPresent || isFillingPlaceholder;
259
276
 
260
277
  return (
261
278
  <div ref={setNodeRef} style={style}>
@@ -331,6 +348,12 @@ function SortableSlideThumb({
331
348
  designSystem={designSystem}
332
349
  onOverflowChange={onOverflowChange}
333
350
  />
351
+ {showGeneratingShimmer && (
352
+ <div
353
+ aria-hidden="true"
354
+ className="slide-thumbnail-ai-shimmer pointer-events-none absolute inset-0 z-10"
355
+ />
356
+ )}
334
357
  {slide.skipped && (
335
358
  // guard:allow-raw-color — dims an arbitrary-colored slide render, not app chrome; must stay black regardless of theme
336
359
  <div className="absolute inset-0 z-10 flex items-center justify-center bg-black/40">
@@ -454,6 +477,7 @@ export default function EditorSidebar({
454
477
  describeSlideId,
455
478
  onCloseDescribe,
456
479
  onAddSlideGeneratingChange,
480
+ aiGeneratingSlideId,
457
481
  onAwaitAddSlidePersisted,
458
482
  onRemoveFailedSlide,
459
483
  addSlideAgentSubmit,
@@ -662,6 +686,7 @@ export default function EditorSidebar({
662
686
  aspectRatio={aspectRatio}
663
687
  designSystem={designSystem}
664
688
  aiEditing={aiEditedSlideIds.has(slide.id)}
689
+ isFillingPlaceholder={slide.id === aiGeneratingSlideId}
665
690
  canDelete={slides.length > 1}
666
691
  hasSlideClipboard={hasSlideClipboard}
667
692
  onCutSlide={onCutSlide}
@@ -706,12 +731,12 @@ export default function EditorSidebar({
706
731
  slideCount={slides.length}
707
732
  targetSlideId={describeSlideId}
708
733
  agentSubmit={async (message, context) => {
709
- onAddSlideGeneratingChange?.(true);
734
+ onAddSlideGeneratingChange?.(true, describeSlideId);
710
735
  try {
711
736
  await onAwaitAddSlidePersisted?.();
712
737
  } catch (error) {
713
738
  console.error("Failed to persist new slide:", error);
714
- onAddSlideGeneratingChange?.(false);
739
+ onAddSlideGeneratingChange?.(false, null);
715
740
  // The popover already closed (AddSlidePopover doesn't wait on
716
741
  // this async callback), so the typed prompt is gone either
717
742
  // way. Only remove the placeholder if it's still untouched —
@@ -1167,6 +1167,35 @@ button[title="Open agent sidebar"] {
1167
1167
  }
1168
1168
  }
1169
1169
 
1170
+ /* Sweeps across a slide thumbnail while the agent is generating its content.
1171
+ Sits above the rendered slide so it reads as "in progress" instead of a
1172
+ static placeholder for the length of the generation run. */
1173
+ .slide-thumbnail-ai-shimmer {
1174
+ background: linear-gradient(
1175
+ 100deg,
1176
+ transparent 30%,
1177
+ rgba(255, 255, 255, 0.16) 50%,
1178
+ transparent 70%
1179
+ );
1180
+ background-size: 200% 100%;
1181
+ animation: slide-thumbnail-shimmer 1.6s ease-in-out infinite;
1182
+ }
1183
+
1184
+ @keyframes slide-thumbnail-shimmer {
1185
+ from {
1186
+ background-position: 150% 0;
1187
+ }
1188
+ to {
1189
+ background-position: -50% 0;
1190
+ }
1191
+ }
1192
+
1193
+ @media (prefers-reduced-motion: reduce) {
1194
+ .slide-thumbnail-ai-shimmer {
1195
+ animation: none;
1196
+ }
1197
+ }
1198
+
1170
1199
  .image-overlay-btn {
1171
1200
  display: flex;
1172
1201
  align-items: center;
@@ -26,6 +26,31 @@ export function shouldShowNewDeckGeneratingProgress({
26
26
  return generating && isNewDeckCreation;
27
27
  }
28
28
 
29
+ /** The blank placeholder "New slide" inserted and handed to the agent to fill.
30
+ * While one is live the rail marks that existing row as AI-active; appending
31
+ * the synthetic generating row too would read as a second, duplicate slide.
32
+ * Returns null once the placeholder leaves the deck, or once its content is
33
+ * no longer the blank stand-in: the fill is done, presence/recent-edit
34
+ * tracking picks up that slide's own marker from there, and if the same run
35
+ * goes on to `add-slide` more slides (a multi-slide request), those are
36
+ * genuinely new and should get the trailing generating row again. */
37
+ export function slideBeingFilledInPlace({
38
+ addSlideGenerating,
39
+ addSlideTargetId,
40
+ slides,
41
+ blankContent,
42
+ }: {
43
+ addSlideGenerating: boolean;
44
+ addSlideTargetId: string | null;
45
+ slides: { id: string; content: string }[];
46
+ blankContent: string;
47
+ }): string | null {
48
+ if (!addSlideGenerating || !addSlideTargetId) return null;
49
+ const target = slides.find((slide) => slide.id === addSlideTargetId);
50
+ if (!target || target.content !== blankContent) return null;
51
+ return addSlideTargetId;
52
+ }
53
+
29
54
  export function shouldClearNewDeckGeneratingState({
30
55
  generating,
31
56
  generationStarted,
@@ -65,6 +65,7 @@ import { Button } from "@/components/ui/button";
65
65
  import {
66
66
  clearSlideEditingActive,
67
67
  deckIdFromPathname,
68
+ defaultSlideContent,
68
69
  hasUnsavedDeckChanges,
69
70
  markSlideEditingActive,
70
71
  type Slide,
@@ -100,6 +101,7 @@ import {
100
101
  shouldClearNewDeckGeneratingState,
101
102
  shouldShowNewDeckGeneratingOverlay,
102
103
  shouldShowNewDeckGeneratingProgress,
104
+ slideBeingFilledInPlace,
103
105
  } from "@/lib/generation-state";
104
106
  import { isMissingUploadProviderError } from "@/lib/image-drop-to-agent";
105
107
  import {
@@ -172,6 +174,14 @@ export default function DeckEditor() {
172
174
  const [activeSlideId, setActiveSlideId] = useState<string | null>(null);
173
175
  const [inlineEditActive, setInlineEditActive] = useState(false);
174
176
  const [addSlideGenerating, setAddSlideGenerating] = useState(false);
177
+ // The blank placeholder the agent was asked to fill in place. The rail must
178
+ // light THAT row up as AI-active instead of appending a synthetic generating
179
+ // row, which reads as a second, duplicate slide.
180
+ const [addSlideTargetId, setAddSlideTargetId] = useState<string | null>(null);
181
+ const endAddSlideGeneration = useCallback(() => {
182
+ setAddSlideGenerating(false);
183
+ setAddSlideTargetId(null);
184
+ }, []);
175
185
  const [generatingSlideSelected, setGeneratingSlideSelected] = useState(false);
176
186
  const { hasUnsavedChanges: hasUnsavedSave } = useSaveState();
177
187
  const hasPendingDeckEdits =
@@ -207,17 +217,37 @@ export default function DeckEditor() {
207
217
  // tracking correct across a remount.
208
218
  const { generating: addSlideAgentGenerating, submit: addSlideAgentSubmit } =
209
219
  useAgentGenerating();
220
+ // Neither hook above is actually scoped to THIS run until its own submit()
221
+ // call has fired: before that, `activeTabRef` inside useAgentGenerating is
222
+ // still null, so both hooks report on ANY chat activity system-wide, same
223
+ // as the broad instance. The target is set (and the popover's persistence
224
+ // wait starts) well before that submit call, so an unrelated run finishing
225
+ // during that wait could otherwise satisfy either "seen true" guard below
226
+ // and clear the freshly-set target before this run ever sent a request.
227
+ // Both cleanup effects stay inert until this flips true.
228
+ const addSlideRequestSentRef = useRef(false);
210
229
  const sawAddSlideAgentGeneratingRef = useRef(false);
211
230
  useEffect(() => {
231
+ if (!addSlideRequestSentRef.current) return;
212
232
  if (addSlideAgentGenerating) {
213
233
  sawAddSlideAgentGeneratingRef.current = true;
214
234
  return;
215
235
  }
216
236
  if (addSlideGenerating && sawAddSlideAgentGeneratingRef.current) {
217
237
  sawAddSlideAgentGeneratingRef.current = false;
218
- setAddSlideGenerating(false);
238
+ endAddSlideGeneration();
219
239
  }
220
- }, [addSlideGenerating, addSlideAgentGenerating]);
240
+ }, [addSlideGenerating, addSlideAgentGenerating, endAddSlideGeneration]);
241
+ // Same guard for the broad `generating` signal below, which is never scoped
242
+ // to this run at all (by design — it reflects ANY agent chat activity).
243
+ const sawGeneratingRef = useRef(false);
244
+ const submitAddSlideAgent = useCallback(
245
+ (message: string, context: string) => {
246
+ addSlideRequestSentRef.current = true;
247
+ addSlideAgentSubmit(message, context);
248
+ },
249
+ [addSlideAgentSubmit],
250
+ );
221
251
  // Generation intent can arrive after this route mounts because the user
222
252
  // answers pre-generation questions from the empty editor.
223
253
  const wasNewDeckCreation = useRef(searchParams.get("generating") === "1");
@@ -371,10 +401,18 @@ export default function DeckEditor() {
371
401
  });
372
402
 
373
403
  const showQuestionFlow = Boolean(questionFlowQuestions?.length);
404
+ const fillingPlaceholderSlideId = slideBeingFilledInPlace({
405
+ addSlideGenerating,
406
+ addSlideTargetId,
407
+ slides: deck?.slides ?? [],
408
+ blankContent: defaultSlideContent.blank,
409
+ });
374
410
  const generatingSlideVisible =
375
411
  canEdit &&
376
412
  !showQuestionFlow &&
377
- (isNewDeckGenerating || addSlideGenerating || showNewDeckGeneratingOverlay);
413
+ (isNewDeckGenerating ||
414
+ (addSlideGenerating && !fillingPlaceholderSlideId) ||
415
+ showNewDeckGeneratingOverlay);
378
416
  const showCurrentSlideEditor =
379
417
  !generatingSlideSelected &&
380
418
  !showNewDeckGeneratingOverlay &&
@@ -385,10 +423,20 @@ export default function DeckEditor() {
385
423
  }, [generatingSlideVisible]);
386
424
 
387
425
  // The add-slide request is finished once the agent stops generating, so the
388
- // rail's placeholder must not outlive it.
426
+ // rail's placeholder must not outlive it. Mirrors the "seen true first"
427
+ // guard above so this backstop can't fire while `generating` just hasn't
428
+ // caught up with a run that hasn't started sending yet.
389
429
  useEffect(() => {
390
- if (!generating) setAddSlideGenerating(false);
391
- }, [generating]);
430
+ if (!addSlideRequestSentRef.current) return;
431
+ if (generating) {
432
+ sawGeneratingRef.current = true;
433
+ return;
434
+ }
435
+ if (addSlideGenerating && sawGeneratingRef.current) {
436
+ sawGeneratingRef.current = false;
437
+ endAddSlideGeneration();
438
+ }
439
+ }, [generating, addSlideGenerating, endAddSlideGeneration]);
392
440
 
393
441
  // Below `md` the rail is a drawer behind a full-viewport dimming scrim; at
394
442
  // `md` and up it's docked with no scrim. `sidebarOpen` is seeded from the
@@ -1606,8 +1654,22 @@ export default function DeckEditor() {
1606
1654
  onCloseDescribe={() => setDescribeSlideId(null)}
1607
1655
  onAwaitAddSlidePersisted={() => flushDeckSave(id)}
1608
1656
  onRemoveFailedSlide={(slideId) => deleteSlide(id, slideId)}
1609
- addSlideAgentSubmit={addSlideAgentSubmit}
1610
- onAddSlideGeneratingChange={setAddSlideGenerating}
1657
+ addSlideAgentSubmit={submitAddSlideAgent}
1658
+ onAddSlideGeneratingChange={(isGenerating, targetSlideId) => {
1659
+ if (isGenerating) {
1660
+ // A new run starts clean: neither guard's "seen true"
1661
+ // state may carry over from an unrelated chat run, or
1662
+ // from whatever state the previous add-slide run left
1663
+ // behind, or the auto-clear effects below could fire on
1664
+ // stale state before this run even sends its request.
1665
+ sawGeneratingRef.current = false;
1666
+ sawAddSlideAgentGeneratingRef.current = false;
1667
+ addSlideRequestSentRef.current = false;
1668
+ }
1669
+ setAddSlideGenerating(isGenerating);
1670
+ setAddSlideTargetId(isGenerating ? targetSlideId : null);
1671
+ }}
1672
+ aiGeneratingSlideId={fillingPlaceholderSlideId}
1611
1673
  onSelectSlide={(slideId) => {
1612
1674
  setGeneratingSlideSelected(false);
1613
1675
  setActiveSlideId(slideId);
@@ -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;
65
66
  states: {
66
67
  clientId: number;
67
68
  state: string;
68
69
  }[];
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;
80
81
  users: {
81
82
  clientId: number;
82
83
  lastSeen: number;
83
84
  }[];
84
- error?: undefined;
85
85
  }>>;
@@ -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;
14
15
  count: number;
15
16
  updated?: undefined;
16
- error?: undefined;
17
17
  ok?: undefined;
18
18
  } | {
19
- count?: undefined;
20
- updated: number;
21
19
  error?: undefined;
20
+ updated: number;
22
21
  ok?: undefined;
23
- } | {
24
22
  count?: undefined;
23
+ } | {
25
24
  updated?: undefined;
26
25
  error: string;
27
26
  ok?: undefined;
28
- } | {
29
27
  count?: undefined;
30
- updated?: undefined;
28
+ } | {
31
29
  error?: undefined;
30
+ updated?: undefined;
32
31
  ok: boolean;
32
+ count?: undefined;
33
33
  }>>;
@@ -41,27 +41,27 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
41
41
  thumbsUpRate: number;
42
42
  avgEvalScore: number;
43
43
  } | {
44
- error?: undefined;
45
- ok?: undefined;
46
44
  summary: import("./types.js").TraceSummary;
47
45
  spans: import("./types.js").TraceSpan[];
48
46
  id?: undefined;
49
- } | {
50
47
  error?: undefined;
51
48
  ok?: undefined;
49
+ } | {
52
50
  summary?: undefined;
53
51
  spans?: undefined;
54
52
  id: string;
55
- } | {
53
+ error?: undefined;
56
54
  ok?: undefined;
55
+ } | {
57
56
  summary?: undefined;
58
57
  spans?: undefined;
59
58
  id?: undefined;
60
59
  error: any;
60
+ ok?: undefined;
61
61
  } | {
62
- error?: undefined;
63
62
  summary?: undefined;
64
63
  spans?: undefined;
65
64
  id?: undefined;
65
+ error?: undefined;
66
66
  ok: boolean;
67
67
  }>>;
@@ -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
  }>>;
@@ -37,17 +37,17 @@ export declare function createWriteSecretHandler(): import("h3").EventHandlerWit
37
37
  ok?: undefined;
38
38
  status?: undefined;
39
39
  } | {
40
- error?: undefined;
41
40
  ok: boolean;
42
41
  status: string;
42
+ error?: undefined;
43
43
  } | {
44
44
  ok?: undefined;
45
45
  error: string;
46
46
  removed?: undefined;
47
47
  } | {
48
- error?: undefined;
49
48
  ok: boolean;
50
49
  removed: boolean;
50
+ error?: undefined;
51
51
  }>>;
52
52
  /**
53
53
  * POST /_agent-native/secrets/:key/test — validate an optional candidate value
@@ -58,13 +58,13 @@ export declare function createTestSecretHandler(): import("h3").EventHandlerWith
58
58
  error: string;
59
59
  note?: undefined;
60
60
  } | {
61
- error?: undefined;
62
61
  ok: boolean;
63
62
  note?: undefined;
64
- } | {
65
63
  error?: undefined;
64
+ } | {
66
65
  ok: boolean;
67
66
  note: string;
67
+ error?: undefined;
68
68
  } | {
69
69
  note?: undefined;
70
70
  ok: boolean;
@@ -95,11 +95,11 @@ export interface AdHocSecretPayload {
95
95
  export declare function createAdHocSecretHandler(): import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<AdHocSecretPayload[] | {
96
96
  error: string;
97
97
  } | {
98
- error?: undefined;
99
98
  ok: boolean;
100
99
  key: string;
101
- } | {
102
100
  error?: undefined;
101
+ } | {
103
102
  ok: boolean;
104
103
  removed: boolean;
104
+ error?: undefined;
105
105
  }>>;
@@ -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
  }
@@ -60,6 +60,7 @@ import { getConfiguredAppBasePath } from "./app-base-path.js";
60
60
  import { getAppProductionUrl } from "./app-url.js";
61
61
  import { readAnalyticsAnonymousId, readFirstTouchAttribution, signupAttributionFromCookieHeader, } from "./attribution.js";
62
62
  import { getAuthLoginMode } from "./auth-login-mode.js";
63
+ import { injectBetaOptOutPersistence } from "./beta-opt-out-html.js";
63
64
  import { createBetterAuthSessionForEmail, ensureGoogleAuthIdentity, getAuthSecret, getBetterAuth, getBetterAuthSync, isDeployPreview, } from "./better-auth-instance.js";
64
65
  import { BUILDER_CONNECT_PARAM, BUILDER_RELAY_PATH, BUILDER_RELAY_STATE_PARAM, verifyBuilderConnectTokenAndGetOwner, verifyBuilderPreviewRelayStateForCallback, } from "./builder-browser.js";
65
66
  import { resolveAuthCookieNamespace } from "./cookie-namespace.js";
@@ -346,7 +347,9 @@ export function getConfiguredLoginHtml(event) {
346
347
  const queryStart = url.indexOf("?");
347
348
  const rawPath = queryStart >= 0 ? url.slice(0, queryStart) : url;
348
349
  const loginHtml = config.getLoginHtml?.(event, rawPath) ?? config.loginHtml ?? null;
349
- return loginHtml ? injectLoginSocialImageMeta(loginHtml, event) : null;
350
+ return loginHtml
351
+ ? injectLoginSocialImageMeta(injectBetaOptOutPersistence(loginHtml), event)
352
+ : null;
350
353
  }
351
354
  /**
352
355
  * True only when the request originates from the local machine — the raw
@@ -1934,7 +1937,7 @@ function injectLoginSocialImageMeta(loginHtml, event) {
1934
1937
  loginHtml.slice(headCloseIdx));
1935
1938
  }
1936
1939
  function loginHtmlResponse(loginHtml, event) {
1937
- return new Response(injectAnalyticsIntoHtml(injectLoginSocialImageMeta(loginHtml, event)), {
1940
+ return new Response(injectAnalyticsIntoHtml(injectLoginSocialImageMeta(injectBetaOptOutPersistence(loginHtml), event)), {
1938
1941
  status: 200,
1939
1942
  headers: {
1940
1943
  "Content-Type": "text/html; charset=utf-8",
@@ -0,0 +1,7 @@
1
+ export declare const BETA_OPT_OUT_PERSISTENCE_MARKER = "Persist the beta opt-out before authentication";
2
+ /**
3
+ * Custom auth pages do not necessarily use the framework onboarding shell.
4
+ * Keep the production switcher's one-time opt-out behavior at the shared auth
5
+ * response boundary so those pages cannot drop the handoff before sign-in.
6
+ */
7
+ export declare function injectBetaOptOutPersistence(loginHtml: string): string;
@@ -0,0 +1,190 @@
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
+ export const BETA_OPT_OUT_PERSISTENCE_MARKER = "Persist the beta opt-out before authentication";
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>
137
+ // ${BETA_OPT_OUT_PERSISTENCE_MARKER}.
138
+ (function __anPersistBetaOptOut() {
139
+ try {
140
+ var optOutUrl = new URL(window.location.href);
141
+ var optOutValue = optOutUrl.searchParams.get(${JSON.stringify(BETA_OPT_OUT_QUERY_PARAM)});
142
+ if (optOutValue === null) return;
143
+ var optOutExpiry = Number(optOutValue);
144
+ var optOutStorageReady = false;
145
+ try {
146
+ if (Number.isFinite(optOutExpiry) && optOutExpiry > Date.now()) {
147
+ window.localStorage.setItem(
148
+ ${JSON.stringify(BETA_OPT_OUT_STORAGE_KEY)},
149
+ String(optOutExpiry),
150
+ );
151
+ }
152
+ optOutStorageReady = true;
153
+ } catch (error) {
154
+ void error;
155
+ }
156
+ if (optOutStorageReady) {
157
+ optOutUrl.searchParams.delete(${JSON.stringify(BETA_OPT_OUT_QUERY_PARAM)});
158
+ window.history.replaceState(null, '', optOutUrl.toString());
159
+ }
160
+ } catch (error) {
161
+ void error;
162
+ }
163
+ })();
164
+ </script>`;
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>");
185
+ }
186
+ if (!html.includes(ENVIRONMENT_SWITCHER_SCRIPT_MARKER)) {
187
+ html = insertBeforeClosingTag(html, environmentSwitcherScript, "</body>");
188
+ }
189
+ return html;
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));
@@ -26,8 +26,8 @@ export declare function createRealtimeTokenHandler(): import("h3").EventHandlerW
26
26
  expiresAt?: undefined;
27
27
  ttlSeconds?: undefined;
28
28
  } | {
29
- error?: undefined;
30
29
  token: string;
31
30
  expiresAt: string;
32
31
  ttlSeconds: number;
32
+ error?: undefined;
33
33
  }>>;
@@ -20,6 +20,6 @@ export declare function createTranscribeVoiceHandler(): import("h3").EventHandle
20
20
  error: string;
21
21
  text?: undefined;
22
22
  } | {
23
- error?: undefined;
24
23
  text: string;
24
+ error?: undefined;
25
25
  }>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.0.0-beta-20260820052446",
3
+ "version": "0.0.0-beta-20260820094341",
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": {
@@ -427,8 +427,8 @@
427
427
  "y-protocols": "^1.0.7",
428
428
  "yjs": "^13.6.32",
429
429
  "zod": "^4.3.6",
430
- "@agent-native/recap-cli": "0.5.5",
431
- "@agent-native/toolkit": "^0.16.7"
430
+ "@agent-native/toolkit": "^0.16.7",
431
+ "@agent-native/recap-cli": "0.5.5"
432
432
  },
433
433
  "devDependencies": {
434
434
  "@ai-sdk/anthropic": "^3.0.71",