@jami-studio/core 0.92.31 → 0.92.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/core/CHANGELOG.md +6 -0
  3. package/corpus/core/package.json +1 -1
  4. package/corpus/core/src/deploy/build.ts +4193 -4127
  5. package/corpus/core/src/file-upload/types.ts +9 -0
  6. package/corpus/templates/analytics/changelog/2026-07-11-tracking-and-session-replay-ingest-endpoints-are-reachable-f.md +6 -0
  7. package/corpus/templates/analytics/package.json +9 -0
  8. package/corpus/templates/clips/actions/create-recording.ts +16 -1
  9. package/corpus/templates/clips/app/components/recorder/recorder-engine.ts +60 -14
  10. package/corpus/templates/clips/app/routes/record.tsx +35 -9
  11. package/corpus/templates/clips/changelog/2026-07-11-uploads-now-stream-straight-to-s3-compatible-storage-r2-s3-m.md +6 -0
  12. package/corpus/templates/clips/server/lib/s3-upload-provider.ts +256 -0
  13. package/corpus/templates/clips/server/lib/streaming-upload-mode.ts +9 -3
  14. package/corpus/templates/clips/server/lib/upload-chunk-limits.ts +19 -0
  15. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/chunk.post.ts +15 -4
  16. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/reset-chunks.post.ts +49 -1
  17. package/dist/collab/struct-routes.d.ts +1 -1
  18. package/dist/deploy/build.d.ts +21 -1
  19. package/dist/deploy/build.d.ts.map +1 -1
  20. package/dist/deploy/build.js +736 -676
  21. package/dist/deploy/build.js.map +1 -1
  22. package/dist/file-upload/types.d.ts +9 -0
  23. package/dist/file-upload/types.d.ts.map +1 -1
  24. package/dist/file-upload/types.js.map +1 -1
  25. package/dist/observability/routes.d.ts +5 -5
  26. package/dist/progress/routes.d.ts +1 -1
  27. package/dist/provider-api/corpus-jobs.d.ts +2 -2
  28. package/package.json +1 -1
@@ -421,19 +421,19 @@ export const CLOUDFLARE_WORKER_NODE_BUILTIN_STUB_MODULES = {
421
421
  "export const createRequire = () => globalThis.require ?? ((specifier) => { throw new Error('Cannot require: ' + specifier); });",
422
422
  ]),
423
423
  net: cloudflareNodeBuiltinStubSource("net", ["Socket", "connect", "createConnection", "createServer", "isIP"], [
424
- `export const isIP = (value) => {
425
- const input = String(value ?? "");
426
- const ipv4Parts = input.split(".");
427
- if (
428
- ipv4Parts.length === 4 &&
429
- ipv4Parts.every((part) => /^\\d{1,3}$/.test(part) && Number(part) >= 0 && Number(part) <= 255)
430
- ) {
431
- return 4;
432
- }
433
- if (input.includes(":") && /^[0-9A-Fa-f:.]+$/.test(input)) {
434
- return 6;
435
- }
436
- return 0;
424
+ `export const isIP = (value) => {
425
+ const input = String(value ?? "");
426
+ const ipv4Parts = input.split(".");
427
+ if (
428
+ ipv4Parts.length === 4 &&
429
+ ipv4Parts.every((part) => /^\\d{1,3}$/.test(part) && Number(part) >= 0 && Number(part) <= 255)
430
+ ) {
431
+ return 4;
432
+ }
433
+ if (input.includes(":") && /^[0-9A-Fa-f:.]+$/.test(input)) {
434
+ return 6;
435
+ }
436
+ return 0;
437
437
  };`,
438
438
  ]),
439
439
  os: cloudflareNodeBuiltinStubSource("os", [
@@ -522,15 +522,75 @@ export const CLOUDFLARE_WORKER_NODE_BUILTIN_STUB_MODULES = {
522
522
  * unified workspace deployments. Must stay dependency-free beyond core's
523
523
  * lean `global-scope` subpath so nothing registry-touching evaluates before
524
524
  * the scope id is set (ESM evaluates imports depth-first in order).
525
+ *
526
+ * `envDefaults` bakes the per-app workspace env (workspace-apps manifest,
527
+ * app id, base path, audience, route-access lists) into the module as
528
+ * `process.env` DEFAULTS. Cloudflare workerd has no filesystem and no
529
+ * ambient build env, so without this the runtime falls back as if the app
530
+ * were standalone — `loadWorkspaceAppsManifest()` returns null and agent
531
+ * discovery targets the builtin hosted prod URLs instead of the sibling
532
+ * apps mounted on this origin (ask_app/call-agent "internal error"). The
533
+ * Netlify preset already bakes the same keys in its generated function
534
+ * entry (`setBasePathEnv`); this is the Cloudflare-preset equivalent.
535
+ * Defaults never override real runtime env: the worker's per-request
536
+ * bindings copy assigns binding keys on top, and baked keys only apply
537
+ * when the key is absent.
525
538
  */
526
- export function generateScopeInitSource(appScopeId) {
527
- return `// AUTO-GENERATED by @agent-native/core deploy build
528
- // Scope globalThis-pinned framework registries to this app's module graph.
529
- // Evaluated FIRST in the worker entry's import graph so the scope is set
530
- // before any registry module initializes. See core shared/global-scope.
531
- import { setGlobalScopeId } from "@agent-native/core/global-scope";
532
- setGlobalScopeId(${JSON.stringify(appScopeId)});
533
- `;
539
+ export function generateScopeInitSource(appScopeId, envDefaults) {
540
+ const entries = Object.entries(envDefaults ?? {}).filter(([, value]) => typeof value === "string" && value !== "");
541
+ const envBlock = entries.length
542
+ ? `
543
+ // Baked per-app workspace env defaults (runtime bindings still win).
544
+ {
545
+ const processRef = (globalThis.process ??= { env: {} });
546
+ processRef.env ??= {};
547
+ const defaults = ${JSON.stringify(Object.fromEntries(entries))};
548
+ for (const key of Object.keys(defaults)) {
549
+ if (processRef.env[key] === undefined) processRef.env[key] = defaults[key];
550
+ }
551
+ }
552
+ `
553
+ : "";
554
+ return `// AUTO-GENERATED by @agent-native/core deploy build
555
+ // Scope globalThis-pinned framework registries to this app's module graph.
556
+ // Evaluated FIRST in the worker entry's import graph so the scope is set
557
+ // before any registry module initializes. See core shared/global-scope.
558
+ import { setGlobalScopeId } from "@agent-native/core/global-scope";
559
+ setGlobalScopeId(${JSON.stringify(appScopeId)});
560
+ ${envBlock}`;
561
+ }
562
+ /**
563
+ * Snapshot the per-app workspace env keys that must survive into the edge
564
+ * runtime. Called at build time (workspace-deploy sets these in the child
565
+ * build env); the result is baked into `_scope-init.js` as process.env
566
+ * defaults for runtimes with no filesystem/ambient env (workerd).
567
+ */
568
+ export function workspaceEnvDefaultsFromBuildEnv(env = process.env) {
569
+ if (env.AGENT_NATIVE_WORKSPACE !== "1")
570
+ return {};
571
+ const keys = [
572
+ "AGENT_NATIVE_WORKSPACE",
573
+ "AGENT_NATIVE_WORKSPACE_APP_ID",
574
+ "APP_BASE_PATH",
575
+ "AGENT_NATIVE_WORKSPACE_APP_AUDIENCE",
576
+ "AGENT_NATIVE_WORKSPACE_APP_PUBLIC_PATHS",
577
+ "AGENT_NATIVE_WORKSPACE_APP_PROTECTED_PATHS",
578
+ "AGENT_NATIVE_WORKSPACE_APPS_JSON",
579
+ "VITE_AGENT_NATIVE_WORKSPACE",
580
+ "VITE_AGENT_NATIVE_WORKSPACE_APP_ID",
581
+ "VITE_APP_BASE_PATH",
582
+ "VITE_AGENT_NATIVE_WORKSPACE_APP_AUDIENCE",
583
+ "VITE_AGENT_NATIVE_WORKSPACE_APP_PUBLIC_PATHS",
584
+ "VITE_AGENT_NATIVE_WORKSPACE_APP_PROTECTED_PATHS",
585
+ "VITE_AGENT_NATIVE_WORKSPACE_APPS_JSON",
586
+ ];
587
+ const defaults = {};
588
+ for (const key of keys) {
589
+ const value = env[key];
590
+ if (typeof value === "string" && value !== "")
591
+ defaults[key] = value;
592
+ }
593
+ return defaults;
534
594
  }
535
595
  /**
536
596
  * Derive the workspace app id from a mounted app base path ("/assets" →
@@ -562,16 +622,16 @@ function isNodeOnlyPlugin(filePath) {
562
622
  }
563
623
  export function generateProvidedPluginsNitroPluginSource(pluginStems) {
564
624
  const stems = [...new Set(pluginStems.filter(Boolean))].sort();
565
- return `// AUTO-GENERATED by @agent-native/core deploy build
566
- import { markDefaultPluginProvided } from "${EDGE_SERVER_ENTRYPOINT}";
567
-
568
- const pluginStems = ${JSON.stringify(stems)};
569
-
570
- export default function markBuildDiscoveredPlugins(nitroApp) {
571
- for (const stem of pluginStems) {
572
- markDefaultPluginProvided(nitroApp, stem);
573
- }
574
- }
625
+ return `// AUTO-GENERATED by @agent-native/core deploy build
626
+ import { markDefaultPluginProvided } from "${EDGE_SERVER_ENTRYPOINT}";
627
+
628
+ const pluginStems = ${JSON.stringify(stems)};
629
+
630
+ export default function markBuildDiscoveredPlugins(nitroApp) {
631
+ for (const stem of pluginStems) {
632
+ markDefaultPluginProvided(nitroApp, stem);
633
+ }
634
+ }
575
635
  `;
576
636
  }
577
637
  async function writeProvidedPluginsNitroPlugin() {
@@ -624,20 +684,20 @@ export function generateWorkerEntry(routes, pluginPaths, defaultPluginStems = []
624
684
  routeImports.push(`import ${varName} from ${JSON.stringify(r.absPath)};`);
625
685
  routeRegistrations.push(` app.on(${JSON.stringify(r.method.toUpperCase())}, ${JSON.stringify(r.route)}, ${varName});`);
626
686
  if (r.method.toLowerCase() === "get") {
627
- routeRegistrations.push(` app.on("HEAD", ${JSON.stringify(r.route)}, defineEventHandler(async (event) => {
628
- const originalReq = event.req;
629
- event.req = requestWithMethod(event.req, "GET");
630
- try {
631
- const result = await ${varName}(event);
632
- const response = result instanceof Response ? result : toResponse(result, event);
633
- return new Response(null, {
634
- status: response.status,
635
- statusText: response.statusText,
636
- headers: response.headers,
637
- });
638
- } finally {
639
- event.req = originalReq;
640
- }
687
+ routeRegistrations.push(` app.on("HEAD", ${JSON.stringify(r.route)}, defineEventHandler(async (event) => {
688
+ const originalReq = event.req;
689
+ event.req = requestWithMethod(event.req, "GET");
690
+ try {
691
+ const result = await ${varName}(event);
692
+ const response = result instanceof Response ? result : toResponse(result, event);
693
+ return new Response(null, {
694
+ status: response.status,
695
+ statusText: response.statusText,
696
+ headers: response.headers,
697
+ });
698
+ } finally {
699
+ event.req = originalReq;
700
+ }
641
701
  }));`);
642
702
  }
643
703
  }
@@ -650,15 +710,15 @@ export function generateWorkerEntry(routes, pluginPaths, defaultPluginStems = []
650
710
  actionImports.push(`import ${varName} from ${JSON.stringify(a.absPath)};`);
651
711
  // Mirror the runtime mount (action-routes.ts): `path = http?.path ?? name`.
652
712
  const routePath = `/_agent-native/actions/${a.path ?? a.name}`;
653
- actionRegistrations.push(` app.on(${JSON.stringify(a.method.toUpperCase())}, ${JSON.stringify(routePath)}, defineEventHandler(async (event) => {
654
- const params = ${a.method === "get" ? "parseActionSearchParams(event.url.searchParams)" : "(await readBody(event)) ?? {}"};
655
- try {
656
- const result = await ${varName}.run(params, { caller: "http" });
657
- if (typeof result === "string") { try { return JSON.parse(result); } catch { return result; } }
658
- return result;
659
- } catch (err) {
660
- return new Response(JSON.stringify({ error: err?.message || "Action failed" }), { status: err?.message?.startsWith("Invalid action parameters") ? 400 : 500, headers: { "Content-Type": "application/json" } });
661
- }
713
+ actionRegistrations.push(` app.on(${JSON.stringify(a.method.toUpperCase())}, ${JSON.stringify(routePath)}, defineEventHandler(async (event) => {
714
+ const params = ${a.method === "get" ? "parseActionSearchParams(event.url.searchParams)" : "(await readBody(event)) ?? {}"};
715
+ try {
716
+ const result = await ${varName}.run(params, { caller: "http" });
717
+ if (typeof result === "string") { try { return JSON.parse(result); } catch { return result; } }
718
+ return result;
719
+ } catch (err) {
720
+ return new Response(JSON.stringify({ error: err?.message || "Action failed" }), { status: err?.message?.startsWith("Invalid action parameters") ? 400 : 500, headers: { "Content-Type": "application/json" } });
721
+ }
662
722
  }));`);
663
723
  }
664
724
  // Filter out Node-only plugins
@@ -670,8 +730,8 @@ export function generateWorkerEntry(routes, pluginPaths, defaultPluginStems = []
670
730
  const varName = `plugin_${i}`;
671
731
  providedPluginStems.add(path.basename(edgePlugins[i], path.extname(edgePlugins[i])));
672
732
  pluginImports.push(`import ${varName} from ${JSON.stringify(edgePlugins[i])};`);
673
- pluginCalls.push(` if (typeof ${varName} === "function") {
674
- await ${varName}(nitroApp);
733
+ pluginCalls.push(` if (typeof ${varName} === "function") {
734
+ await ${varName}(nitroApp);
675
735
  }`);
676
736
  }
677
737
  // Auto-mounted default plugins (for slots the template doesn't override
@@ -694,8 +754,8 @@ export function generateWorkerEntry(routes, pluginPaths, defaultPluginStems = []
694
754
  continue;
695
755
  pluginImports.push(`import { ${defaultExportName} as ${varName} } from "${EDGE_SERVER_ENTRYPOINT}";`);
696
756
  }
697
- pluginCalls.push(` if (typeof ${varName} === "function") {
698
- await ${varName}(nitroApp);
757
+ pluginCalls.push(` if (typeof ${varName} === "function") {
758
+ await ${varName}(nitroApp);
699
759
  }`);
700
760
  }
701
761
  const generatedPluginMarks = providedPluginStems.size > 0
@@ -709,523 +769,523 @@ export function generateWorkerEntry(routes, pluginPaths, defaultPluginStems = []
709
769
  if (generatedPluginMarks.length > 0) {
710
770
  pluginImports.unshift(`import { markDefaultPluginProvided as markGeneratedPluginProvided } from "${EDGE_SERVER_ENTRYPOINT}";`);
711
771
  }
712
- return `
713
- // Auto-generated worker entry point for ${preset}
714
- ${appScopeId ? 'import "./_scope-init.js";\n' : ""}import { H3, defineEventHandler, readBody, toResponse } from "h3";
715
- ${includeReactRouterSsr ? 'import { createRequestHandler } from "react-router";' : ""}
716
- ${includeReactRouterSsr ? 'import * as serverBuild from "./server-build.js";' : ""}
717
-
718
- function normalizeAppBasePath(value) {
719
- if (!value || value === "/") return "";
720
- const trimmed = String(value).trim();
721
- if (!trimmed || trimmed === "/") return "";
722
- return "/" + trimmed.replace(/^\\/+/, "").replace(/\\/+$/, "");
723
- }
724
-
725
- function getAppBasePath() {
726
- const builtAppBasePath = ${JSON.stringify(builtAppBasePath)};
727
- return normalizeAppBasePath(
728
- globalThis.process?.env?.VITE_APP_BASE_PATH ||
729
- globalThis.process?.env?.APP_BASE_PATH ||
730
- builtAppBasePath,
731
- );
732
- }
733
-
734
- function stripAppBasePath(pathname) {
735
- const basePath = getAppBasePath();
736
- if (!basePath) return pathname;
737
- if (pathname === basePath) return "/";
738
- if (pathname.startsWith(basePath + "/")) {
739
- return pathname.slice(basePath.length) || "/";
740
- }
741
- return pathname;
742
- }
743
-
744
- function parseActionSearchParams(searchParams) {
745
- const params = {};
746
- for (const [rawKey, value] of searchParams.entries()) {
747
- const isArrayKey = rawKey.endsWith("[]");
748
- // The core client serializes arrays as key[]=value so one-item arrays
749
- // survive GET action parsing in generated worker deployments.
750
- const key = isArrayKey ? rawKey.slice(0, -2) : rawKey;
751
- const current = params[key];
752
- if (current === undefined) {
753
- params[key] = isArrayKey ? [value] : value;
754
- } else if (Array.isArray(current)) {
755
- current.push(value);
756
- } else {
757
- params[key] = [current, value];
758
- }
759
- }
760
- return params;
761
- }
762
-
763
- function isApiPath(pathname) {
764
- return pathname === "/api" || pathname.startsWith("/api/");
765
- }
766
-
767
- function isFrameworkPath(pathname) {
768
- return (
769
- pathname === "/_agent-native" || pathname.startsWith("/_agent-native/")
770
- );
771
- }
772
-
773
- function requestWithMountedApiPrefixStripped(request) {
774
- const basePath = getAppBasePath();
775
- if (!basePath) return request;
776
- const url = new URL(request.url);
777
- const strippedPathname = stripAppBasePath(url.pathname);
778
- if (strippedPathname === url.pathname) {
779
- return request;
780
- }
781
- if (!isApiPath(strippedPathname) && !isFrameworkPath(strippedPathname)) {
782
- return request;
783
- }
784
- url.pathname = strippedPathname;
785
- return new Request(url, request);
786
- }
787
-
788
- function prefixMountedPath(path, basePath) {
789
- if (!basePath || !path.startsWith("/") || path.startsWith("//")) return path;
790
- if (path === basePath || path.startsWith(basePath + "/")) return path;
791
- return basePath + path;
792
- }
793
-
794
- function prefixMountedHtml(html, basePath) {
795
- if (!basePath) return html;
796
- return html
797
- .replace(
798
- /\\b(href|src|action|formaction|poster)=(["'])(\\/(?!\\/)[^"']*)\\2/g,
799
- (_match, attr, quote, path) =>
800
- attr + "=" + quote + prefixMountedPath(path, basePath) + quote,
801
- )
802
- .replace(/url\\((["']?)(\\/(?!\\/)[^)'" ]+)\\1\\)/g, (_match, quote, path) => {
803
- const q = quote || "";
804
- return "url(" + q + prefixMountedPath(path, basePath) + q + ")";
805
- });
806
- }
807
-
808
- function firstNonEmpty() {
809
- for (const value of arguments) {
810
- const trimmed = typeof value === "string" ? value.trim() : "";
811
- if (trimmed) return trimmed;
812
- }
813
- }
814
-
815
- function getSentryClientConfigScript() {
816
- const env = globalThis.process?.env || {};
817
- const key = firstNonEmpty(env.SENTRY_CLIENT_KEY, env.VITE_SENTRY_CLIENT_KEY);
818
- const projectId = firstNonEmpty(
819
- env.SENTRY_PROJECT_ID,
820
- env.VITE_SENTRY_PROJECT_ID,
821
- );
822
- const host = firstNonEmpty(
823
- env.SENTRY_INGEST_HOST,
824
- env.VITE_SENTRY_INGEST_HOST,
825
- );
826
- const dsn =
827
- firstNonEmpty(
828
- env.SENTRY_CLIENT_DSN,
829
- env.VITE_SENTRY_CLIENT_DSN,
830
- env.VITE_SENTRY_DSN,
831
- env.SENTRY_DSN,
832
- ) || (key && projectId && host ? "https://" + key + "@" + host + "/" + projectId : undefined);
833
- if (!dsn) return null;
834
- const config = {
835
- sentryDsn: dsn,
836
- sentryEnvironment:
837
- firstNonEmpty(
838
- env.SENTRY_ENVIRONMENT,
839
- env.NETLIFY_CONTEXT,
840
- env.VERCEL_ENV,
841
- env.NODE_ENV,
842
- ) || "production",
843
- };
844
- return (
845
- '<script data-agent-native-sentry-config>' +
846
- 'window.__AGENT_NATIVE_CONFIG__=Object.assign({},window.__AGENT_NATIVE_CONFIG__,' +
847
- JSON.stringify(config) +
848
- ");</script>"
849
- );
850
- }
851
-
852
- function injectHeadScript(html, script) {
853
- if (!script) return html;
854
- const headCloseIdx = html.indexOf("</head>");
855
- if (headCloseIdx === -1) return html;
856
- return html.slice(0, headCloseIdx) + script + html.slice(headCloseIdx);
857
- }
858
-
859
- const DEFAULT_SSR_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CACHE_CONTROL)};
860
- const DEFAULT_SSR_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CDN_CACHE_CONTROL)};
861
- const DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL)};
862
- const DEFAULT_SPECULATION_RULES_PATH = ${JSON.stringify(DEFAULT_SPECULATION_RULES_PATH)};
863
- const IMMUTABLE_ASSET_CACHE_CONTROL = ${JSON.stringify(IMMUTABLE_ASSET_CACHE_CONTROL)};
864
- const IMMUTABLE_ASSET_PATHS = new Set(${JSON.stringify([...new Set(immutableAssetPaths)].sort())});
865
- const AGENT_NATIVE_SOCIAL_IMAGE_PATH = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_PATH)};
866
- const AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER)};
867
- const AGENT_NATIVE_SOCIAL_IMAGE_ALT = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_ALT)};
868
- const AGENT_NATIVE_SOCIAL_IMAGE_TYPE = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_TYPE)};
869
- const AGENT_NATIVE_SOCIAL_IMAGE_WIDTH = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_WIDTH)};
870
- const AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT)};
871
- const OG_IMAGE_META_RE = /<meta\\b(?=[^>]*\\bproperty=(["'])og:image\\1)[^>]*>/i;
872
- const TWITTER_CARD_META_RE = /<meta\\b(?=[^>]*\\bname=(["'])twitter:card\\1)[^>]*>/i;
873
- const TWITTER_IMAGE_META_RE = /<meta\\b(?=[^>]*\\bname=(["'])twitter:image\\1)[^>]*>/i;
874
-
875
- function withAgentNativeSocialImageCacheBuster(image) {
876
- const separator = image.includes("?") ? "&" : "?";
877
- return image + separator + "v=" + encodeURIComponent(AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER);
878
- }
879
-
880
- function defaultSocialImageUrl(request, basePath) {
881
- return withAgentNativeSocialImageCacheBuster(
882
- new URL(prefixMountedPath(AGENT_NATIVE_SOCIAL_IMAGE_PATH, basePath), request.url).toString()
883
- );
884
- }
885
-
886
- function injectDefaultSocialImageMeta(html, imageUrl) {
887
- const headCloseIdx = html.indexOf("</head>");
888
- if (headCloseIdx === -1) return html;
889
-
890
- const hasAnySocialImage =
891
- OG_IMAGE_META_RE.test(html) || TWITTER_IMAGE_META_RE.test(html);
892
- const tags = [];
893
-
894
- if (!hasAnySocialImage) {
895
- tags.push('<meta property="og:image" content="' + imageUrl + '">');
896
- tags.push('<meta property="og:image:secure_url" content="' + imageUrl + '">');
897
- tags.push('<meta property="og:image:type" content="' + AGENT_NATIVE_SOCIAL_IMAGE_TYPE + '">');
898
- tags.push('<meta property="og:image:width" content="' + AGENT_NATIVE_SOCIAL_IMAGE_WIDTH + '">');
899
- tags.push('<meta property="og:image:height" content="' + AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT + '">');
900
- tags.push('<meta property="og:image:alt" content="' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '">');
901
- }
902
- if (!TWITTER_CARD_META_RE.test(html)) {
903
- tags.push('<meta name="twitter:card" content="summary_large_image">');
904
- }
905
- if (!hasAnySocialImage) {
906
- tags.push('<meta name="twitter:image" content="' + imageUrl + '">');
907
- tags.push('<meta name="twitter:image:alt" content="' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '">');
908
- }
909
-
910
- if (tags.length === 0) return html;
911
- return html.slice(0, headCloseIdx) + tags.join("") + html.slice(headCloseIdx);
912
- }
913
-
914
- function isSsrHtmlOrDataResponse(headers, status, pathname) {
915
- if (status < 200 || status >= 400) return false;
916
- const contentType = (headers.get("content-type") || "").toLowerCase();
917
- if (contentType.includes("text/html")) return true;
918
- return pathname.endsWith(".data") && contentType.includes("text/x-script");
919
- }
920
-
921
- /**
922
- * Apply the SSR cache policy to the response headers.
923
- *
924
- * SSR IS A PUBLIC, HARD-CDN-CACHED SHELL — SERVED IDENTICALLY TO EVERYONE.
925
- * Every SSR HTML / React Router .data response gets the same public
926
- * stale-while-revalidate policy for ALL visitors, authenticated or not. The SSR
927
- * output is impersonal (the handler never reads the request's session/cookies),
928
- * so it is safe to hard-cache one shared copy at the edge. Do NOT reintroduce
929
- * per-user / cookie-based cache variation here (no private, no no-store, no
930
- * "authenticated then don't cache" branch) — that makes every logged-in
931
- * visitor's pages uncacheable. Per-user state is resolved client-side instead.
932
- */
933
- function applyDefaultSsrCacheHeader(headers, status, pathname) {
934
- if (!isSsrHtmlOrDataResponse(headers, status, pathname)) return;
935
-
936
- headers.set("cache-control", DEFAULT_SSR_CACHE_CONTROL);
937
- headers.set("cdn-cache-control", DEFAULT_SSR_CDN_CACHE_CONTROL);
938
- // Netlify function responses are dynamic by default and can otherwise show
939
- // Cache-Status fwd=bypass even with Cache-Control: public. Keep this
940
- // Netlify-specific header so SSR HTML/.data are served from the shared
941
- // durable CDN cache instead of stampeding origin — for every visitor.
942
- headers.set("netlify-cdn-cache-control", DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL);
943
- }
944
-
945
- function applyDefaultSpeculationRulesHeader(headers, status, basePath) {
946
- if (status < 200 || status >= 400) return;
947
- if (headers.has("speculation-rules")) return;
948
-
949
- const contentType = (headers.get("content-type") || "").toLowerCase();
950
- if (!contentType.includes("text/html")) return;
951
-
952
- // Cloudflare Speed Brain injects Speculation-Rules when origin omits this
953
- // header. Those browser prefetches carry Sec-Purpose: prefetch and
954
- // Cloudflare can return 503 before the request reaches origin. Publish an
955
- // explicit no-op ruleset by default; apps can still provide their own header.
956
- headers.set("speculation-rules", '"' + prefixMountedPath(DEFAULT_SPECULATION_RULES_PATH, basePath) + '"');
957
- }
958
- function isImmutableAssetRequest(request) {
959
- const pathname = stripAppBasePath(new URL(request.url).pathname);
960
- return IMMUTABLE_ASSET_PATHS.has(pathname);
961
- }
962
-
963
- function applyImmutableAssetCacheHeaders(response, request) {
964
- if (!isImmutableAssetRequest(request)) return response;
965
- if (!((response.status >= 200 && response.status < 300) || response.status === 304)) {
966
- return response;
967
- }
968
- const headers = new Headers(response.headers);
969
- headers.set("Cache-Control", IMMUTABLE_ASSET_CACHE_CONTROL);
970
- headers.set("CDN-Cache-Control", IMMUTABLE_ASSET_CACHE_CONTROL);
971
- headers.set("Netlify-CDN-Cache-Control", IMMUTABLE_ASSET_CACHE_CONTROL);
972
- return new Response(response.body, {
973
- status: response.status,
974
- statusText: response.statusText,
975
- headers,
976
- });
977
- }
978
-
979
- async function rewriteMountedResponse(response, basePath, pathname, request) {
980
- const sentryClientConfigScript = getSentryClientConfigScript();
981
- const headers = new Headers(response.headers);
982
- applyDefaultSsrCacheHeader(headers, response.status, pathname);
983
- applyDefaultSpeculationRulesHeader(headers, response.status, basePath);
984
-
985
- const location = headers.get("location");
986
- if (location?.startsWith("/") && !location.startsWith("//")) {
987
- headers.set("location", prefixMountedPath(location, basePath));
988
- }
989
-
990
- const contentType = headers.get("content-type") || "";
991
- if (!contentType.toLowerCase().includes("text/html") || !response.body) {
992
- return new Response(response.body, {
993
- status: response.status,
994
- statusText: response.statusText,
995
- headers,
996
- });
997
- }
998
-
999
- const html = await response.text();
1000
- headers.delete("content-length");
1001
- return new Response(
1002
- injectHeadScript(
1003
- injectDefaultSocialImageMeta(
1004
- prefixMountedHtml(html, basePath),
1005
- defaultSocialImageUrl(request, basePath),
1006
- ),
1007
- sentryClientConfigScript,
1008
- ),
1009
- {
1010
- status: response.status,
1011
- statusText: response.statusText,
1012
- headers,
1013
- },
1014
- );
1015
- }
1016
-
1017
- function requestWithMethod(request, method) {
1018
- return new Request(request.url, {
1019
- method,
1020
- headers: request.headers,
1021
- signal: request.signal,
1022
- });
1023
- }
1024
-
1025
- function requestWithPathname(request, pathname) {
1026
- const url = new URL(request.url);
1027
- if (url.pathname === pathname) return request;
1028
- url.pathname = pathname;
1029
- return new Request(url, request);
1030
- }
1031
-
1032
- function isStaticAppShellRequest(request) {
1033
- if (request.method !== "GET" && request.method !== "HEAD") return false;
1034
- const p = stripAppBasePath(new URL(request.url).pathname);
1035
- if (
1036
- p.startsWith("/.well-known/") ||
1037
- p.startsWith("/_agent-native/") ||
1038
- isApiPath(p) ||
1039
- p === "/favicon.ico" ||
1040
- p === "/favicon.png" ||
1041
- /\\.\\w+$/.test(p)
1042
- ) {
1043
- return false;
1044
- }
1045
- return true;
1046
- }
1047
-
1048
- async function fetchStaticAppShell(request, env) {
1049
- if (!env?.ASSETS || !isStaticAppShellRequest(request)) return null;
1050
- const basePath = getAppBasePath();
1051
- const p = stripAppBasePath(new URL(request.url).pathname);
1052
- // Workspace deployments serve each app's static files under its base path
1053
- // (/dispatch/index.html on the unified origin) — an unprefixed
1054
- // "/index.html" 404s against the shared ASSETS binding and authed deep
1055
- // links (e.g. /dispatch/overview) leaked h3's JSON 404 instead of the SPA
1056
- // shell. Try the base-path-prefixed shell first, fall back to the root
1057
- // shell for single-app deployments.
1058
- let response;
1059
- try {
1060
- if (basePath) {
1061
- response = await env.ASSETS.fetch(
1062
- requestWithPathname(
1063
- requestWithMethod(request, "GET"),
1064
- basePath + "/index.html",
1065
- ),
1066
- );
1067
- }
1068
- if (!response || response.status === 404) {
1069
- response = await env.ASSETS.fetch(
1070
- requestWithPathname(requestWithMethod(request, "GET"), "/index.html"),
1071
- );
1072
- }
1073
- } catch {
1074
- return null;
1075
- }
1076
- if (response.status === 404) return null;
1077
- if (request.method === "HEAD") {
1078
- return rewriteMountedResponse(
1079
- new Response(null, {
1080
- status: response.status,
1081
- statusText: response.statusText,
1082
- headers: response.headers,
1083
- }),
1084
- basePath,
1085
- p,
1086
- request,
1087
- );
1088
- }
1089
- return rewriteMountedResponse(response, basePath, p, request);
1090
- }
1091
-
1092
- // API route handlers
1093
- ${routeImports.join("\n")}
1094
-
1095
- // Action handlers (auto-discovered from actions/)
1096
- ${actionImports.join("\n")}
1097
-
1098
- // Server plugins
1099
- ${pluginImports.join("\n")}
1100
-
1101
- let _handler;
1102
-
1103
- async function getHandler() {
1104
- if (_handler) return _handler;
1105
-
1106
- const app = new H3();
1107
-
1108
- // Build a fake nitroApp surface so framework plugins (which expect
1109
- // \`nitroApp.h3["~middleware"]\`) can register routes via getH3App().
1110
- const noop = () => {};
1111
- const nitroApp = {
1112
- h3: app,
1113
- hooks: { hook: noop, callHook: noop, hookOnce: noop },
1114
- captureError: noop,
1115
- };
1116
-
1117
- // CORS — applied as global middleware via .use(handler)
1118
- app.use(defineEventHandler((event) => {
1119
- if (event.req.method === "OPTIONS") {
1120
- return new Response(null, {
1121
- status: 204,
1122
- headers: {
1123
- "Access-Control-Allow-Origin": "*",
1124
- "Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
1125
- "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend,X-Agent-Native-Embed-Target",
1126
- },
1127
- });
1128
- }
1129
- }));
1130
-
1131
- // Run plugins — they call getH3App(nitroApp).use(path, handler) which
1132
- // pushes path-prefix middleware onto app["~middleware"].
1133
- // Pre-mark every build-time plugin slot before any plugin awaits the runtime
1134
- // default bootstrap. Bundled serverless workers often lack server/plugins/
1135
- // on disk, so runtime discovery would otherwise auto-mount duplicate
1136
- // framework defaults before later custom plugins get a chance to mark
1137
- // themselves as provided.
1138
- ${generatedPluginMarks.map((stem) => ` markGeneratedPluginProvided(nitroApp, ${JSON.stringify(stem)});`).join("\n")}
1139
- ${pluginCalls.join("\n")}
1140
-
1141
- // Register API routes
1142
- ${routeRegistrations.join("\n")}
1143
-
1144
- // Register action routes (/_agent-native/actions/*)
1145
- ${actionRegistrations.join("\n")}
1146
-
772
+ return `
773
+ // Auto-generated worker entry point for ${preset}
774
+ ${appScopeId ? 'import "./_scope-init.js";\n' : ""}import { H3, defineEventHandler, readBody, toResponse } from "h3";
775
+ ${includeReactRouterSsr ? 'import { createRequestHandler } from "react-router";' : ""}
776
+ ${includeReactRouterSsr ? 'import * as serverBuild from "./server-build.js";' : ""}
777
+
778
+ function normalizeAppBasePath(value) {
779
+ if (!value || value === "/") return "";
780
+ const trimmed = String(value).trim();
781
+ if (!trimmed || trimmed === "/") return "";
782
+ return "/" + trimmed.replace(/^\\/+/, "").replace(/\\/+$/, "");
783
+ }
784
+
785
+ function getAppBasePath() {
786
+ const builtAppBasePath = ${JSON.stringify(builtAppBasePath)};
787
+ return normalizeAppBasePath(
788
+ globalThis.process?.env?.VITE_APP_BASE_PATH ||
789
+ globalThis.process?.env?.APP_BASE_PATH ||
790
+ builtAppBasePath,
791
+ );
792
+ }
793
+
794
+ function stripAppBasePath(pathname) {
795
+ const basePath = getAppBasePath();
796
+ if (!basePath) return pathname;
797
+ if (pathname === basePath) return "/";
798
+ if (pathname.startsWith(basePath + "/")) {
799
+ return pathname.slice(basePath.length) || "/";
800
+ }
801
+ return pathname;
802
+ }
803
+
804
+ function parseActionSearchParams(searchParams) {
805
+ const params = {};
806
+ for (const [rawKey, value] of searchParams.entries()) {
807
+ const isArrayKey = rawKey.endsWith("[]");
808
+ // The core client serializes arrays as key[]=value so one-item arrays
809
+ // survive GET action parsing in generated worker deployments.
810
+ const key = isArrayKey ? rawKey.slice(0, -2) : rawKey;
811
+ const current = params[key];
812
+ if (current === undefined) {
813
+ params[key] = isArrayKey ? [value] : value;
814
+ } else if (Array.isArray(current)) {
815
+ current.push(value);
816
+ } else {
817
+ params[key] = [current, value];
818
+ }
819
+ }
820
+ return params;
821
+ }
822
+
823
+ function isApiPath(pathname) {
824
+ return pathname === "/api" || pathname.startsWith("/api/");
825
+ }
826
+
827
+ function isFrameworkPath(pathname) {
828
+ return (
829
+ pathname === "/_agent-native" || pathname.startsWith("/_agent-native/")
830
+ );
831
+ }
832
+
833
+ function requestWithMountedApiPrefixStripped(request) {
834
+ const basePath = getAppBasePath();
835
+ if (!basePath) return request;
836
+ const url = new URL(request.url);
837
+ const strippedPathname = stripAppBasePath(url.pathname);
838
+ if (strippedPathname === url.pathname) {
839
+ return request;
840
+ }
841
+ if (!isApiPath(strippedPathname) && !isFrameworkPath(strippedPathname)) {
842
+ return request;
843
+ }
844
+ url.pathname = strippedPathname;
845
+ return new Request(url, request);
846
+ }
847
+
848
+ function prefixMountedPath(path, basePath) {
849
+ if (!basePath || !path.startsWith("/") || path.startsWith("//")) return path;
850
+ if (path === basePath || path.startsWith(basePath + "/")) return path;
851
+ return basePath + path;
852
+ }
853
+
854
+ function prefixMountedHtml(html, basePath) {
855
+ if (!basePath) return html;
856
+ return html
857
+ .replace(
858
+ /\\b(href|src|action|formaction|poster)=(["'])(\\/(?!\\/)[^"']*)\\2/g,
859
+ (_match, attr, quote, path) =>
860
+ attr + "=" + quote + prefixMountedPath(path, basePath) + quote,
861
+ )
862
+ .replace(/url\\((["']?)(\\/(?!\\/)[^)'" ]+)\\1\\)/g, (_match, quote, path) => {
863
+ const q = quote || "";
864
+ return "url(" + q + prefixMountedPath(path, basePath) + q + ")";
865
+ });
866
+ }
867
+
868
+ function firstNonEmpty() {
869
+ for (const value of arguments) {
870
+ const trimmed = typeof value === "string" ? value.trim() : "";
871
+ if (trimmed) return trimmed;
872
+ }
873
+ }
874
+
875
+ function getSentryClientConfigScript() {
876
+ const env = globalThis.process?.env || {};
877
+ const key = firstNonEmpty(env.SENTRY_CLIENT_KEY, env.VITE_SENTRY_CLIENT_KEY);
878
+ const projectId = firstNonEmpty(
879
+ env.SENTRY_PROJECT_ID,
880
+ env.VITE_SENTRY_PROJECT_ID,
881
+ );
882
+ const host = firstNonEmpty(
883
+ env.SENTRY_INGEST_HOST,
884
+ env.VITE_SENTRY_INGEST_HOST,
885
+ );
886
+ const dsn =
887
+ firstNonEmpty(
888
+ env.SENTRY_CLIENT_DSN,
889
+ env.VITE_SENTRY_CLIENT_DSN,
890
+ env.VITE_SENTRY_DSN,
891
+ env.SENTRY_DSN,
892
+ ) || (key && projectId && host ? "https://" + key + "@" + host + "/" + projectId : undefined);
893
+ if (!dsn) return null;
894
+ const config = {
895
+ sentryDsn: dsn,
896
+ sentryEnvironment:
897
+ firstNonEmpty(
898
+ env.SENTRY_ENVIRONMENT,
899
+ env.NETLIFY_CONTEXT,
900
+ env.VERCEL_ENV,
901
+ env.NODE_ENV,
902
+ ) || "production",
903
+ };
904
+ return (
905
+ '<script data-agent-native-sentry-config>' +
906
+ 'window.__AGENT_NATIVE_CONFIG__=Object.assign({},window.__AGENT_NATIVE_CONFIG__,' +
907
+ JSON.stringify(config) +
908
+ ");</script>"
909
+ );
910
+ }
911
+
912
+ function injectHeadScript(html, script) {
913
+ if (!script) return html;
914
+ const headCloseIdx = html.indexOf("</head>");
915
+ if (headCloseIdx === -1) return html;
916
+ return html.slice(0, headCloseIdx) + script + html.slice(headCloseIdx);
917
+ }
918
+
919
+ const DEFAULT_SSR_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CACHE_CONTROL)};
920
+ const DEFAULT_SSR_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CDN_CACHE_CONTROL)};
921
+ const DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL)};
922
+ const DEFAULT_SPECULATION_RULES_PATH = ${JSON.stringify(DEFAULT_SPECULATION_RULES_PATH)};
923
+ const IMMUTABLE_ASSET_CACHE_CONTROL = ${JSON.stringify(IMMUTABLE_ASSET_CACHE_CONTROL)};
924
+ const IMMUTABLE_ASSET_PATHS = new Set(${JSON.stringify([...new Set(immutableAssetPaths)].sort())});
925
+ const AGENT_NATIVE_SOCIAL_IMAGE_PATH = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_PATH)};
926
+ const AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER)};
927
+ const AGENT_NATIVE_SOCIAL_IMAGE_ALT = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_ALT)};
928
+ const AGENT_NATIVE_SOCIAL_IMAGE_TYPE = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_TYPE)};
929
+ const AGENT_NATIVE_SOCIAL_IMAGE_WIDTH = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_WIDTH)};
930
+ const AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT = ${JSON.stringify(AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT)};
931
+ const OG_IMAGE_META_RE = /<meta\\b(?=[^>]*\\bproperty=(["'])og:image\\1)[^>]*>/i;
932
+ const TWITTER_CARD_META_RE = /<meta\\b(?=[^>]*\\bname=(["'])twitter:card\\1)[^>]*>/i;
933
+ const TWITTER_IMAGE_META_RE = /<meta\\b(?=[^>]*\\bname=(["'])twitter:image\\1)[^>]*>/i;
934
+
935
+ function withAgentNativeSocialImageCacheBuster(image) {
936
+ const separator = image.includes("?") ? "&" : "?";
937
+ return image + separator + "v=" + encodeURIComponent(AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER);
938
+ }
939
+
940
+ function defaultSocialImageUrl(request, basePath) {
941
+ return withAgentNativeSocialImageCacheBuster(
942
+ new URL(prefixMountedPath(AGENT_NATIVE_SOCIAL_IMAGE_PATH, basePath), request.url).toString()
943
+ );
944
+ }
945
+
946
+ function injectDefaultSocialImageMeta(html, imageUrl) {
947
+ const headCloseIdx = html.indexOf("</head>");
948
+ if (headCloseIdx === -1) return html;
949
+
950
+ const hasAnySocialImage =
951
+ OG_IMAGE_META_RE.test(html) || TWITTER_IMAGE_META_RE.test(html);
952
+ const tags = [];
953
+
954
+ if (!hasAnySocialImage) {
955
+ tags.push('<meta property="og:image" content="' + imageUrl + '">');
956
+ tags.push('<meta property="og:image:secure_url" content="' + imageUrl + '">');
957
+ tags.push('<meta property="og:image:type" content="' + AGENT_NATIVE_SOCIAL_IMAGE_TYPE + '">');
958
+ tags.push('<meta property="og:image:width" content="' + AGENT_NATIVE_SOCIAL_IMAGE_WIDTH + '">');
959
+ tags.push('<meta property="og:image:height" content="' + AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT + '">');
960
+ tags.push('<meta property="og:image:alt" content="' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '">');
961
+ }
962
+ if (!TWITTER_CARD_META_RE.test(html)) {
963
+ tags.push('<meta name="twitter:card" content="summary_large_image">');
964
+ }
965
+ if (!hasAnySocialImage) {
966
+ tags.push('<meta name="twitter:image" content="' + imageUrl + '">');
967
+ tags.push('<meta name="twitter:image:alt" content="' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '">');
968
+ }
969
+
970
+ if (tags.length === 0) return html;
971
+ return html.slice(0, headCloseIdx) + tags.join("") + html.slice(headCloseIdx);
972
+ }
973
+
974
+ function isSsrHtmlOrDataResponse(headers, status, pathname) {
975
+ if (status < 200 || status >= 400) return false;
976
+ const contentType = (headers.get("content-type") || "").toLowerCase();
977
+ if (contentType.includes("text/html")) return true;
978
+ return pathname.endsWith(".data") && contentType.includes("text/x-script");
979
+ }
980
+
981
+ /**
982
+ * Apply the SSR cache policy to the response headers.
983
+ *
984
+ * SSR IS A PUBLIC, HARD-CDN-CACHED SHELL — SERVED IDENTICALLY TO EVERYONE.
985
+ * Every SSR HTML / React Router .data response gets the same public
986
+ * stale-while-revalidate policy for ALL visitors, authenticated or not. The SSR
987
+ * output is impersonal (the handler never reads the request's session/cookies),
988
+ * so it is safe to hard-cache one shared copy at the edge. Do NOT reintroduce
989
+ * per-user / cookie-based cache variation here (no private, no no-store, no
990
+ * "authenticated then don't cache" branch) — that makes every logged-in
991
+ * visitor's pages uncacheable. Per-user state is resolved client-side instead.
992
+ */
993
+ function applyDefaultSsrCacheHeader(headers, status, pathname) {
994
+ if (!isSsrHtmlOrDataResponse(headers, status, pathname)) return;
995
+
996
+ headers.set("cache-control", DEFAULT_SSR_CACHE_CONTROL);
997
+ headers.set("cdn-cache-control", DEFAULT_SSR_CDN_CACHE_CONTROL);
998
+ // Netlify function responses are dynamic by default and can otherwise show
999
+ // Cache-Status fwd=bypass even with Cache-Control: public. Keep this
1000
+ // Netlify-specific header so SSR HTML/.data are served from the shared
1001
+ // durable CDN cache instead of stampeding origin — for every visitor.
1002
+ headers.set("netlify-cdn-cache-control", DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL);
1003
+ }
1004
+
1005
+ function applyDefaultSpeculationRulesHeader(headers, status, basePath) {
1006
+ if (status < 200 || status >= 400) return;
1007
+ if (headers.has("speculation-rules")) return;
1008
+
1009
+ const contentType = (headers.get("content-type") || "").toLowerCase();
1010
+ if (!contentType.includes("text/html")) return;
1011
+
1012
+ // Cloudflare Speed Brain injects Speculation-Rules when origin omits this
1013
+ // header. Those browser prefetches carry Sec-Purpose: prefetch and
1014
+ // Cloudflare can return 503 before the request reaches origin. Publish an
1015
+ // explicit no-op ruleset by default; apps can still provide their own header.
1016
+ headers.set("speculation-rules", '"' + prefixMountedPath(DEFAULT_SPECULATION_RULES_PATH, basePath) + '"');
1017
+ }
1018
+ function isImmutableAssetRequest(request) {
1019
+ const pathname = stripAppBasePath(new URL(request.url).pathname);
1020
+ return IMMUTABLE_ASSET_PATHS.has(pathname);
1021
+ }
1022
+
1023
+ function applyImmutableAssetCacheHeaders(response, request) {
1024
+ if (!isImmutableAssetRequest(request)) return response;
1025
+ if (!((response.status >= 200 && response.status < 300) || response.status === 304)) {
1026
+ return response;
1027
+ }
1028
+ const headers = new Headers(response.headers);
1029
+ headers.set("Cache-Control", IMMUTABLE_ASSET_CACHE_CONTROL);
1030
+ headers.set("CDN-Cache-Control", IMMUTABLE_ASSET_CACHE_CONTROL);
1031
+ headers.set("Netlify-CDN-Cache-Control", IMMUTABLE_ASSET_CACHE_CONTROL);
1032
+ return new Response(response.body, {
1033
+ status: response.status,
1034
+ statusText: response.statusText,
1035
+ headers,
1036
+ });
1037
+ }
1038
+
1039
+ async function rewriteMountedResponse(response, basePath, pathname, request) {
1040
+ const sentryClientConfigScript = getSentryClientConfigScript();
1041
+ const headers = new Headers(response.headers);
1042
+ applyDefaultSsrCacheHeader(headers, response.status, pathname);
1043
+ applyDefaultSpeculationRulesHeader(headers, response.status, basePath);
1044
+
1045
+ const location = headers.get("location");
1046
+ if (location?.startsWith("/") && !location.startsWith("//")) {
1047
+ headers.set("location", prefixMountedPath(location, basePath));
1048
+ }
1049
+
1050
+ const contentType = headers.get("content-type") || "";
1051
+ if (!contentType.toLowerCase().includes("text/html") || !response.body) {
1052
+ return new Response(response.body, {
1053
+ status: response.status,
1054
+ statusText: response.statusText,
1055
+ headers,
1056
+ });
1057
+ }
1058
+
1059
+ const html = await response.text();
1060
+ headers.delete("content-length");
1061
+ return new Response(
1062
+ injectHeadScript(
1063
+ injectDefaultSocialImageMeta(
1064
+ prefixMountedHtml(html, basePath),
1065
+ defaultSocialImageUrl(request, basePath),
1066
+ ),
1067
+ sentryClientConfigScript,
1068
+ ),
1069
+ {
1070
+ status: response.status,
1071
+ statusText: response.statusText,
1072
+ headers,
1073
+ },
1074
+ );
1075
+ }
1076
+
1077
+ function requestWithMethod(request, method) {
1078
+ return new Request(request.url, {
1079
+ method,
1080
+ headers: request.headers,
1081
+ signal: request.signal,
1082
+ });
1083
+ }
1084
+
1085
+ function requestWithPathname(request, pathname) {
1086
+ const url = new URL(request.url);
1087
+ if (url.pathname === pathname) return request;
1088
+ url.pathname = pathname;
1089
+ return new Request(url, request);
1090
+ }
1091
+
1092
+ function isStaticAppShellRequest(request) {
1093
+ if (request.method !== "GET" && request.method !== "HEAD") return false;
1094
+ const p = stripAppBasePath(new URL(request.url).pathname);
1095
+ if (
1096
+ p.startsWith("/.well-known/") ||
1097
+ p.startsWith("/_agent-native/") ||
1098
+ isApiPath(p) ||
1099
+ p === "/favicon.ico" ||
1100
+ p === "/favicon.png" ||
1101
+ /\\.\\w+$/.test(p)
1102
+ ) {
1103
+ return false;
1104
+ }
1105
+ return true;
1106
+ }
1107
+
1108
+ async function fetchStaticAppShell(request, env) {
1109
+ if (!env?.ASSETS || !isStaticAppShellRequest(request)) return null;
1110
+ const basePath = getAppBasePath();
1111
+ const p = stripAppBasePath(new URL(request.url).pathname);
1112
+ // Workspace deployments serve each app's static files under its base path
1113
+ // (/dispatch/index.html on the unified origin) — an unprefixed
1114
+ // "/index.html" 404s against the shared ASSETS binding and authed deep
1115
+ // links (e.g. /dispatch/overview) leaked h3's JSON 404 instead of the SPA
1116
+ // shell. Try the base-path-prefixed shell first, fall back to the root
1117
+ // shell for single-app deployments.
1118
+ let response;
1119
+ try {
1120
+ if (basePath) {
1121
+ response = await env.ASSETS.fetch(
1122
+ requestWithPathname(
1123
+ requestWithMethod(request, "GET"),
1124
+ basePath + "/index.html",
1125
+ ),
1126
+ );
1127
+ }
1128
+ if (!response || response.status === 404) {
1129
+ response = await env.ASSETS.fetch(
1130
+ requestWithPathname(requestWithMethod(request, "GET"), "/index.html"),
1131
+ );
1132
+ }
1133
+ } catch {
1134
+ return null;
1135
+ }
1136
+ if (response.status === 404) return null;
1137
+ if (request.method === "HEAD") {
1138
+ return rewriteMountedResponse(
1139
+ new Response(null, {
1140
+ status: response.status,
1141
+ statusText: response.statusText,
1142
+ headers: response.headers,
1143
+ }),
1144
+ basePath,
1145
+ p,
1146
+ request,
1147
+ );
1148
+ }
1149
+ return rewriteMountedResponse(response, basePath, p, request);
1150
+ }
1151
+
1152
+ // API route handlers
1153
+ ${routeImports.join("\n")}
1154
+
1155
+ // Action handlers (auto-discovered from actions/)
1156
+ ${actionImports.join("\n")}
1157
+
1158
+ // Server plugins
1159
+ ${pluginImports.join("\n")}
1160
+
1161
+ let _handler;
1162
+
1163
+ async function getHandler() {
1164
+ if (_handler) return _handler;
1165
+
1166
+ const app = new H3();
1167
+
1168
+ // Build a fake nitroApp surface so framework plugins (which expect
1169
+ // \`nitroApp.h3["~middleware"]\`) can register routes via getH3App().
1170
+ const noop = () => {};
1171
+ const nitroApp = {
1172
+ h3: app,
1173
+ hooks: { hook: noop, callHook: noop, hookOnce: noop },
1174
+ captureError: noop,
1175
+ };
1176
+
1177
+ // CORS — applied as global middleware via .use(handler)
1178
+ app.use(defineEventHandler((event) => {
1179
+ if (event.req.method === "OPTIONS") {
1180
+ return new Response(null, {
1181
+ status: 204,
1182
+ headers: {
1183
+ "Access-Control-Allow-Origin": "*",
1184
+ "Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
1185
+ "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend,X-Agent-Native-Embed-Target",
1186
+ },
1187
+ });
1188
+ }
1189
+ }));
1190
+
1191
+ // Run plugins — they call getH3App(nitroApp).use(path, handler) which
1192
+ // pushes path-prefix middleware onto app["~middleware"].
1193
+ // Pre-mark every build-time plugin slot before any plugin awaits the runtime
1194
+ // default bootstrap. Bundled serverless workers often lack server/plugins/
1195
+ // on disk, so runtime discovery would otherwise auto-mount duplicate
1196
+ // framework defaults before later custom plugins get a chance to mark
1197
+ // themselves as provided.
1198
+ ${generatedPluginMarks.map((stem) => ` markGeneratedPluginProvided(nitroApp, ${JSON.stringify(stem)});`).join("\n")}
1199
+ ${pluginCalls.join("\n")}
1200
+
1201
+ // Register API routes
1202
+ ${routeRegistrations.join("\n")}
1203
+
1204
+ // Register action routes (/_agent-native/actions/*)
1205
+ ${actionRegistrations.join("\n")}
1206
+
1147
1207
  ${includeReactRouterSsr
1148
- ? ` // SSR catch-all for React Router
1149
- const rrHandler = createRequestHandler(() => serverBuild);
1150
- app.all("/**", defineEventHandler(async (event) => {
1151
- const basePath = getAppBasePath();
1152
- const p = stripAppBasePath(new URL(event.req.url).pathname);
1153
- if (
1154
- p.startsWith("/.well-known/") ||
1155
- p.startsWith("/_agent-native/") ||
1156
- isApiPath(p) ||
1157
- p === "/favicon.ico" ||
1158
- p === "/favicon.png" ||
1159
- (/\\.\\w+$/.test(p) && !p.endsWith(".data"))
1160
- ) {
1161
- return new Response(null, { status: 404 });
1162
- }
1163
- const request = requestWithPathname(event.req, p);
1164
- if (event.req.method === "HEAD") {
1165
- const getRequest = requestWithMethod(request, "GET");
1166
- const response = await rrHandler(getRequest);
1167
- return rewriteMountedResponse(
1168
- new Response(null, {
1169
- status: response.status,
1170
- statusText: response.statusText,
1171
- headers: response.headers,
1172
- }),
1173
- basePath,
1174
- p,
1175
- getRequest
1176
- );
1177
- }
1178
- return rewriteMountedResponse(await rrHandler(request), basePath, p, request);
1208
+ ? ` // SSR catch-all for React Router
1209
+ const rrHandler = createRequestHandler(() => serverBuild);
1210
+ app.all("/**", defineEventHandler(async (event) => {
1211
+ const basePath = getAppBasePath();
1212
+ const p = stripAppBasePath(new URL(event.req.url).pathname);
1213
+ if (
1214
+ p.startsWith("/.well-known/") ||
1215
+ p.startsWith("/_agent-native/") ||
1216
+ isApiPath(p) ||
1217
+ p === "/favicon.ico" ||
1218
+ p === "/favicon.png" ||
1219
+ (/\\.\\w+$/.test(p) && !p.endsWith(".data"))
1220
+ ) {
1221
+ return new Response(null, { status: 404 });
1222
+ }
1223
+ const request = requestWithPathname(event.req, p);
1224
+ if (event.req.method === "HEAD") {
1225
+ const getRequest = requestWithMethod(request, "GET");
1226
+ const response = await rrHandler(getRequest);
1227
+ return rewriteMountedResponse(
1228
+ new Response(null, {
1229
+ status: response.status,
1230
+ statusText: response.statusText,
1231
+ headers: response.headers,
1232
+ }),
1233
+ basePath,
1234
+ p,
1235
+ getRequest
1236
+ );
1237
+ }
1238
+ return rewriteMountedResponse(await rrHandler(request), basePath, p, request);
1179
1239
  }));`
1180
- : ""}
1181
-
1182
- _handler = app.fetch.bind(app);
1183
- return _handler;
1184
- }
1185
-
1186
- export default {
1187
- async fetch(request, env, ctx) {
1188
- // Expose env and ctx bindings globally for compatibility
1189
- if (ctx) globalThis.__cf_ctx = ctx;
1190
- if (env) {
1191
- globalThis.process = globalThis.process || { env: {} };
1192
- globalThis.process.env = globalThis.process.env || {};
1193
- // Expose D1/KV/R2 bindings on globalThis.__cf_env for the db layer
1194
- globalThis.__cf_env = env;
1195
- for (const [key, value] of Object.entries(env)) {
1196
- if (typeof value === "string") {
1197
- globalThis.process.env[key] = value;
1198
- }
1199
- }
1200
- }
1201
-
1202
- // Try serving static assets first (CF Pages advanced mode).
1203
- // Only attempt this for GET/HEAD — the ASSETS binding is a static file
1204
- // server and returns 405 for any other method, which would short-circuit
1205
- // API calls (PUT/POST/DELETE to /_agent-native/*) before they reach our
1206
- // h3 middleware.
1207
- if (env?.ASSETS && (request.method === "GET" || request.method === "HEAD")) {
1208
- try {
1209
- const assetResponse = await env.ASSETS.fetch(request);
1210
- if (assetResponse.status !== 404) {
1211
- return applyImmutableAssetCacheHeaders(assetResponse, request);
1212
- }
1213
- } catch {
1214
- // Asset fetch failed — fall through to SSR
1215
- }
1216
- }
1217
-
1218
- const handler = await getHandler();
1219
- const response = await handler(requestWithMountedApiPrefixStripped(request));
1240
+ : ""}
1241
+
1242
+ _handler = app.fetch.bind(app);
1243
+ return _handler;
1244
+ }
1245
+
1246
+ export default {
1247
+ async fetch(request, env, ctx) {
1248
+ // Expose env and ctx bindings globally for compatibility
1249
+ if (ctx) globalThis.__cf_ctx = ctx;
1250
+ if (env) {
1251
+ globalThis.process = globalThis.process || { env: {} };
1252
+ globalThis.process.env = globalThis.process.env || {};
1253
+ // Expose D1/KV/R2 bindings on globalThis.__cf_env for the db layer
1254
+ globalThis.__cf_env = env;
1255
+ for (const [key, value] of Object.entries(env)) {
1256
+ if (typeof value === "string") {
1257
+ globalThis.process.env[key] = value;
1258
+ }
1259
+ }
1260
+ }
1261
+
1262
+ // Try serving static assets first (CF Pages advanced mode).
1263
+ // Only attempt this for GET/HEAD — the ASSETS binding is a static file
1264
+ // server and returns 405 for any other method, which would short-circuit
1265
+ // API calls (PUT/POST/DELETE to /_agent-native/*) before they reach our
1266
+ // h3 middleware.
1267
+ if (env?.ASSETS && (request.method === "GET" || request.method === "HEAD")) {
1268
+ try {
1269
+ const assetResponse = await env.ASSETS.fetch(request);
1270
+ if (assetResponse.status !== 404) {
1271
+ return applyImmutableAssetCacheHeaders(assetResponse, request);
1272
+ }
1273
+ } catch {
1274
+ // Asset fetch failed — fall through to SSR
1275
+ }
1276
+ }
1277
+
1278
+ const handler = await getHandler();
1279
+ const response = await handler(requestWithMountedApiPrefixStripped(request));
1220
1280
  ${includeReactRouterSsr
1221
1281
  ? " return response;"
1222
- : ` if (response.status === 404) {
1223
- const shellResponse = await fetchStaticAppShell(request, env);
1224
- if (shellResponse) return shellResponse;
1225
- }
1226
- return response;`}
1227
- }
1228
- };
1282
+ : ` if (response.status === 404) {
1283
+ const shellResponse = await fetchStaticAppShell(request, env);
1284
+ if (shellResponse) return shellResponse;
1285
+ }
1286
+ return response;`}
1287
+ }
1288
+ };
1229
1289
  `;
1230
1290
  }
1231
1291
  function escapeHtmlAttribute(value) {
@@ -1377,35 +1437,35 @@ function writeCloudflarePagesStaticShell({ serverDir, distDir, tmpDir, }) {
1377
1437
  const outFile = path.join(distDir, "index.html");
1378
1438
  const renderScript = path.join(tmpDir, "render-cloudflare-static-shell.mjs");
1379
1439
  const basePath = normalizeConfiguredAppBasePath();
1380
- fs.writeFileSync(renderScript, `
1381
- import fs from "node:fs";
1382
- import { createRequire } from "node:module";
1383
- import { pathToFileURL } from "node:url";
1384
-
1385
- const cwd = ${JSON.stringify(cwd)};
1386
- const serverEntry = ${JSON.stringify(serverEntry)};
1387
- const outFile = ${JSON.stringify(outFile)};
1388
- const basePath = ${JSON.stringify(basePath)};
1389
-
1390
- const requireFromApp = createRequire(cwd + "/package.json");
1391
- const reactRouterEntry = requireFromApp.resolve("react-router");
1392
- const { createRequestHandler } = await import(pathToFileURL(reactRouterEntry).href);
1393
- const serverBuild = await import(pathToFileURL(serverEntry).href);
1394
- const handler = createRequestHandler(serverBuild, "production");
1395
- const pathname = basePath ? basePath + "/" : "/";
1396
- const response = await handler(
1397
- new Request(new URL(pathname, "https://agent-native.local"), {
1398
- headers: { "X-React-Router-SPA-Mode": "yes" },
1399
- }),
1400
- );
1401
- const html = await response.text();
1402
-
1403
- if (!html || !html.includes("__reactRouterContext") || !html.includes("entry.client")) {
1404
- throw new Error("React Router did not render a usable Cloudflare Pages static shell");
1405
- }
1406
-
1407
- fs.writeFileSync(outFile, html);
1408
- process.exit(0);
1440
+ fs.writeFileSync(renderScript, `
1441
+ import fs from "node:fs";
1442
+ import { createRequire } from "node:module";
1443
+ import { pathToFileURL } from "node:url";
1444
+
1445
+ const cwd = ${JSON.stringify(cwd)};
1446
+ const serverEntry = ${JSON.stringify(serverEntry)};
1447
+ const outFile = ${JSON.stringify(outFile)};
1448
+ const basePath = ${JSON.stringify(basePath)};
1449
+
1450
+ const requireFromApp = createRequire(cwd + "/package.json");
1451
+ const reactRouterEntry = requireFromApp.resolve("react-router");
1452
+ const { createRequestHandler } = await import(pathToFileURL(reactRouterEntry).href);
1453
+ const serverBuild = await import(pathToFileURL(serverEntry).href);
1454
+ const handler = createRequestHandler(serverBuild, "production");
1455
+ const pathname = basePath ? basePath + "/" : "/";
1456
+ const response = await handler(
1457
+ new Request(new URL(pathname, "https://agent-native.local"), {
1458
+ headers: { "X-React-Router-SPA-Mode": "yes" },
1459
+ }),
1460
+ );
1461
+ const html = await response.text();
1462
+
1463
+ if (!html || !html.includes("__reactRouterContext") || !html.includes("entry.client")) {
1464
+ throw new Error("React Router did not render a usable Cloudflare Pages static shell");
1465
+ }
1466
+
1467
+ fs.writeFileSync(outFile, html);
1468
+ process.exit(0);
1409
1469
  `);
1410
1470
  try {
1411
1471
  execFileSync(process.execPath, [renderScript], {
@@ -1506,7 +1566,7 @@ async function buildCloudflarePages() {
1506
1566
  const tmpEntry = path.join(tmpDir, "index.js");
1507
1567
  fs.writeFileSync(tmpEntry, adjustedEntry);
1508
1568
  if (appScopeId) {
1509
- fs.writeFileSync(path.join(tmpDir, "_scope-init.js"), generateScopeInitSource(appScopeId));
1569
+ fs.writeFileSync(path.join(tmpDir, "_scope-init.js"), generateScopeInitSource(appScopeId, workspaceEnvDefaultsFromBuildEnv()));
1510
1570
  }
1511
1571
  if (includeReactRouterSsr) {
1512
1572
  copyDir(serverDir, path.join(tmpDir, "server"));
@@ -2191,76 +2251,76 @@ export function emitSingleTemplateNetlifyBackgroundFunction(projectCwd) {
2191
2251
  // copied bundle does NOT re-register the catch-all `config.path`.
2192
2252
  fs.rmSync(path.join(dest, "server.mjs"), { force: true });
2193
2253
  const processRunPath = JSON.stringify(AGENT_CHAT_PROCESS_RUN_PATH);
2194
- const entry = `// Mark this isolate as the durable background runtime BEFORE the handler
2195
- // bundle is imported, so isInBackgroundFunctionRuntime() reliably returns true
2196
- // in this function. The deployed Lambda name is NOT guaranteed to end in
2197
- // "-background" (Netlify may mangle/prefix it), so we cannot depend on
2198
- // AWS_LAMBDA_FUNCTION_NAME alone. A globalThis flag (NOT process.env) avoids the
2199
- // no-env-mutation guard and carries no cross-request state — it is a static,
2200
- // set-once isolate marker read back by isInBackgroundFunctionRuntime().
2201
- globalThis.__AGENT_NATIVE_BACKGROUND_RUNTIME__ = true;
2202
-
2203
- // The framework route the Nitro router dispatches to (the _process-run plugin).
2204
- const PROCESS_RUN_PATH = ${processRunPath};
2205
-
2206
- let cachedHandler;
2207
-
2208
- // Netlify v2 invokes this as (request, context). The Nitro netlify handler is a
2209
- // Web-standard \`async (Request) => Response\` (see nitro/presets/netlify/runtime).
2210
- // This function declares NO custom \`config.path\`, so it is reached at its
2211
- // DEFAULT url (/.netlify/functions/${backgroundName}). The Nitro router only
2212
- // knows the framework route, so we REWRITE the incoming pathname to
2213
- // PROCESS_RUN_PATH before delegating. Method, ALL headers (the HMAC
2214
- // Authorization: Bearer MUST survive — the plugin verifies it) and the body are
2215
- // preserved by cloning the incoming Request with only its URL pathname set.
2216
- export default async function handler(request, context) {
2217
- try {
2218
- cachedHandler ??= (await import("./main.mjs")).default;
2219
- const url = new URL(request.url);
2220
- url.pathname = PROCESS_RUN_PATH;
2221
- // Read the body once and pass it through. GET/HEAD have no body.
2222
- const method = request.method || "POST";
2223
- const hasBody = method !== "GET" && method !== "HEAD";
2224
- const body = hasBody ? await request.text() : undefined;
2225
- const rewritten = new Request(url.toString(), {
2226
- method,
2227
- headers: request.headers,
2228
- body,
2229
- });
2230
- // Netlify Functions v2 invokes the handler as (request, context); the Nitro
2231
- // netlify handler accepts (request[, context]). Pass context through so a
2232
- // handler that uses it (e.g. waitUntil) does not trip over an undefined arg
2233
- // before it ever routes the request.
2234
- return await cachedHandler(rewritten, context);
2235
- } catch (err) {
2236
- // Netlify already returned 202 for this background invocation and DISCARDS
2237
- // this return, so a throw here is otherwise INVISIBLE — it would only surface
2238
- // downstream as the reaper's "worker never claimed the run". Log it loudly
2239
- // for the function log; the FOREGROUND circuit-breaker (production-agent.ts)
2240
- // is what recovers the run by executing it inline when no worker claims.
2241
- console.error(
2242
- "[agent-background] wrapper failed before reaching the route:",
2243
- (err && err.stack) || err,
2244
- );
2245
- throw err;
2246
- }
2247
- }
2248
-
2249
- export const config = {
2250
- name: "agent background handler",
2251
- generator: "agent-native build",
2252
- // background: true makes Netlify invoke this ASYNCHRONOUSLY (immediate HTTP
2253
- // 202 ack) with the 15-minute budget (Netlify docs:
2254
- // build/functions/background-functions + build/functions/api). We declare NO
2255
- // custom path, so the function keeps its DEFAULT url
2256
- // /.netlify/functions/${backgroundName}; the Nitro \`server\` /* catch-all
2257
- // already excludes /.netlify/* so that default url is never shadowed by the
2258
- // synchronous function. The foreground dispatches to that default url.
2259
- background: true,
2260
- nodeBundler: "none",
2261
- includedFiles: ["**"],
2262
- preferStatic: false,
2263
- };
2254
+ const entry = `// Mark this isolate as the durable background runtime BEFORE the handler
2255
+ // bundle is imported, so isInBackgroundFunctionRuntime() reliably returns true
2256
+ // in this function. The deployed Lambda name is NOT guaranteed to end in
2257
+ // "-background" (Netlify may mangle/prefix it), so we cannot depend on
2258
+ // AWS_LAMBDA_FUNCTION_NAME alone. A globalThis flag (NOT process.env) avoids the
2259
+ // no-env-mutation guard and carries no cross-request state — it is a static,
2260
+ // set-once isolate marker read back by isInBackgroundFunctionRuntime().
2261
+ globalThis.__AGENT_NATIVE_BACKGROUND_RUNTIME__ = true;
2262
+
2263
+ // The framework route the Nitro router dispatches to (the _process-run plugin).
2264
+ const PROCESS_RUN_PATH = ${processRunPath};
2265
+
2266
+ let cachedHandler;
2267
+
2268
+ // Netlify v2 invokes this as (request, context). The Nitro netlify handler is a
2269
+ // Web-standard \`async (Request) => Response\` (see nitro/presets/netlify/runtime).
2270
+ // This function declares NO custom \`config.path\`, so it is reached at its
2271
+ // DEFAULT url (/.netlify/functions/${backgroundName}). The Nitro router only
2272
+ // knows the framework route, so we REWRITE the incoming pathname to
2273
+ // PROCESS_RUN_PATH before delegating. Method, ALL headers (the HMAC
2274
+ // Authorization: Bearer MUST survive — the plugin verifies it) and the body are
2275
+ // preserved by cloning the incoming Request with only its URL pathname set.
2276
+ export default async function handler(request, context) {
2277
+ try {
2278
+ cachedHandler ??= (await import("./main.mjs")).default;
2279
+ const url = new URL(request.url);
2280
+ url.pathname = PROCESS_RUN_PATH;
2281
+ // Read the body once and pass it through. GET/HEAD have no body.
2282
+ const method = request.method || "POST";
2283
+ const hasBody = method !== "GET" && method !== "HEAD";
2284
+ const body = hasBody ? await request.text() : undefined;
2285
+ const rewritten = new Request(url.toString(), {
2286
+ method,
2287
+ headers: request.headers,
2288
+ body,
2289
+ });
2290
+ // Netlify Functions v2 invokes the handler as (request, context); the Nitro
2291
+ // netlify handler accepts (request[, context]). Pass context through so a
2292
+ // handler that uses it (e.g. waitUntil) does not trip over an undefined arg
2293
+ // before it ever routes the request.
2294
+ return await cachedHandler(rewritten, context);
2295
+ } catch (err) {
2296
+ // Netlify already returned 202 for this background invocation and DISCARDS
2297
+ // this return, so a throw here is otherwise INVISIBLE — it would only surface
2298
+ // downstream as the reaper's "worker never claimed the run". Log it loudly
2299
+ // for the function log; the FOREGROUND circuit-breaker (production-agent.ts)
2300
+ // is what recovers the run by executing it inline when no worker claims.
2301
+ console.error(
2302
+ "[agent-background] wrapper failed before reaching the route:",
2303
+ (err && err.stack) || err,
2304
+ );
2305
+ throw err;
2306
+ }
2307
+ }
2308
+
2309
+ export const config = {
2310
+ name: "agent background handler",
2311
+ generator: "agent-native build",
2312
+ // background: true makes Netlify invoke this ASYNCHRONOUSLY (immediate HTTP
2313
+ // 202 ack) with the 15-minute budget (Netlify docs:
2314
+ // build/functions/background-functions + build/functions/api). We declare NO
2315
+ // custom path, so the function keeps its DEFAULT url
2316
+ // /.netlify/functions/${backgroundName}; the Nitro \`server\` /* catch-all
2317
+ // already excludes /.netlify/* so that default url is never shadowed by the
2318
+ // synchronous function. The foreground dispatches to that default url.
2319
+ background: true,
2320
+ nodeBundler: "none",
2321
+ includedFiles: ["**"],
2322
+ preferStatic: false,
2323
+ };
2264
2324
  `;
2265
2325
  fs.writeFileSync(path.join(dest, `${backgroundName}.mjs`), entry);
2266
2326
  console.log(`[build] Emitted durable-background function "${backgroundName}" into the ` +
@@ -2984,11 +3044,11 @@ async function buildWithNitro() {
2984
3044
  : null;
2985
3045
  const agentsBundleModuleSource = () => {
2986
3046
  const bundle = readAgentsBundleFromFs(cwd, nitroWorkspaceSource);
2987
- return `// AUTO-GENERATED by @agent-native/core deploy build (Nitro virtual)
2988
- // Contains the inlined AGENTS.md + .agents/skills/ content from the template,
2989
- // merged with the workspace core's AGENTS.md + skills/ when present.
2990
- const bundle = ${JSON.stringify(bundle)};
2991
- export default bundle;
3047
+ return `// AUTO-GENERATED by @agent-native/core deploy build (Nitro virtual)
3048
+ // Contains the inlined AGENTS.md + .agents/skills/ content from the template,
3049
+ // merged with the workspace core's AGENTS.md + skills/ when present.
3050
+ const bundle = ${JSON.stringify(bundle)};
3051
+ export default bundle;
2992
3052
  `;
2993
3053
  };
2994
3054
  // Path aliases used by templates (mirrors tsconfig + Vite config). Nitro