@agent-native/core 0.16.3 → 0.17.1

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 (49) hide show
  1. package/dist/agent/production-agent.d.ts.map +1 -1
  2. package/dist/agent/production-agent.js +24 -1
  3. package/dist/agent/production-agent.js.map +1 -1
  4. package/dist/client/composer/TiptapComposer.d.ts.map +1 -1
  5. package/dist/client/composer/TiptapComposer.js +2 -3
  6. package/dist/client/composer/TiptapComposer.js.map +1 -1
  7. package/dist/client/settings/DemoModeSection.d.ts +16 -0
  8. package/dist/client/settings/DemoModeSection.d.ts.map +1 -0
  9. package/dist/client/settings/DemoModeSection.js +80 -0
  10. package/dist/client/settings/DemoModeSection.js.map +1 -0
  11. package/dist/client/settings/SettingsPanel.d.ts.map +1 -1
  12. package/dist/client/settings/SettingsPanel.js +4 -2
  13. package/dist/client/settings/SettingsPanel.js.map +1 -1
  14. package/dist/client/use-chat-threads.d.ts.map +1 -1
  15. package/dist/client/use-chat-threads.js +59 -19
  16. package/dist/client/use-chat-threads.js.map +1 -1
  17. package/dist/client/use-db-sync.d.ts.map +1 -1
  18. package/dist/client/use-db-sync.js +5 -0
  19. package/dist/client/use-db-sync.js.map +1 -1
  20. package/dist/demo/actions/toggle-demo-mode.d.ts +3 -0
  21. package/dist/demo/actions/toggle-demo-mode.d.ts.map +1 -0
  22. package/dist/demo/actions/toggle-demo-mode.js +21 -0
  23. package/dist/demo/actions/toggle-demo-mode.js.map +1 -0
  24. package/dist/demo/config.d.ts +9 -0
  25. package/dist/demo/config.d.ts.map +1 -0
  26. package/dist/demo/config.js +58 -0
  27. package/dist/demo/config.js.map +1 -0
  28. package/dist/demo/fetch-interceptor.d.ts +8 -0
  29. package/dist/demo/fetch-interceptor.d.ts.map +1 -0
  30. package/dist/demo/fetch-interceptor.js +174 -0
  31. package/dist/demo/fetch-interceptor.js.map +1 -0
  32. package/dist/demo/redact.d.ts +23 -0
  33. package/dist/demo/redact.d.ts.map +1 -0
  34. package/dist/demo/redact.js +0 -0
  35. package/dist/demo/redact.js.map +1 -0
  36. package/dist/server/action-discovery.d.ts.map +1 -1
  37. package/dist/server/action-discovery.js +1 -0
  38. package/dist/server/action-discovery.js.map +1 -1
  39. package/dist/server/auth.d.ts.map +1 -1
  40. package/dist/server/auth.js +13 -2
  41. package/dist/server/auth.js.map +1 -1
  42. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  43. package/dist/server/core-routes-plugin.js +28 -0
  44. package/dist/server/core-routes-plugin.js.map +1 -1
  45. package/dist/styles/agent-native.css +15 -0
  46. package/dist/vite/client.d.ts.map +1 -1
  47. package/dist/vite/client.js +6 -0
  48. package/dist/vite/client.js.map +1 -1
  49. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/demo/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAC;AAEtE,MAAM,MAAM,GAAG,KAAK,CAAC;AACrB,MAAM,KAAK,GAAG,IAAI,GAAG,EAA0C,CAAC;AAEhE,oEAAoE;AACpE,MAAM,UAAU,gBAAgB;IAC9B,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,KAAK,MAAM,CAAC;AAC1C,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB;IACrC,IAAI,gBAAgB,EAAE;QAAE,OAAO,IAAI,CAAC;IACpC,IAAI,CAAC;QACH,IAAI,UAAU,GAAG,GAAG,CAAC;QACrB,IAAI,CAAC;YACH,MAAM,EAAE,mBAAmB,EAAE,GAC3B,MAAM,MAAM,CAAC,8BAA8B,CAAC,CAAC;YAC/C,UAAU,GAAG,mBAAmB,EAAE,IAAI,OAAO,CAAC,GAAG,CAAC,gBAAgB,IAAI,GAAG,CAAC;QAC5E,CAAC;QAAC,MAAM,CAAC;YACP,mEAAmE;QACrE,CAAC;QACD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAClC,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG,CAAC,EAAE,GAAG,MAAM;YAAE,OAAO,GAAG,CAAC,KAAK,CAAC;QACnD,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,WAAW,CAAC,CAAC;QAC9C,MAAM,OAAO,GAAG,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;QACxC,KAAK,CAAC,GAAG,CAAC,UAAU,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC;QACnD,OAAO,OAAO,CAAC;IACjB,CAAC;IAAC,MAAM,CAAC;QACP,oEAAoE;QACpE,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["/**\n * Demo mode gate.\n *\n * Demo mode replaces real names, email addresses, and numbers in every action\n * result with deterministic fake data — for both the UI and what the agent\n * sees — while preserving IDs, dates, URLs, and structure so the app keeps\n * working. The redaction WALK (see ./redact.ts) is expensive on large\n * payloads, so callers MUST gate it behind this function and only walk when it\n * returns true.\n *\n * This gate itself is intentionally cheap:\n * - An env-forced deployment (a hosted demo site) short-circuits with zero\n * I/O — `DEMO_MODE=true`.\n * - The per-user runtime toggle lives in `application_state` under the\n * `demo-mode` key (`{ enabled: boolean }`), written by the settings UI and\n * the `toggle-demo-mode` agent action. It's read behind a short in-process\n * TTL cache keyed by user, so a tight agent tool-call loop doesn't hit the\n * DB on every result.\n */\nimport { readAppState } from \"../application-state/script-helpers.js\";\n\nconst TTL_MS = 3_000;\nconst cache = new Map<string, { value: boolean; at: number }>();\n\n/** Deployment-wide force (hosted demo site). Zero cost — no I/O. */\nexport function isDemoModeForced(): boolean {\n return process.env.DEMO_MODE === \"true\";\n}\n\n/**\n * Whether demo-mode redaction should run for the current request/user.\n * Cheap by design — safe to call before every action result; the expensive\n * walk only happens when this is true.\n */\nexport async function isDemoModeEnabled(): Promise<boolean> {\n if (isDemoModeForced()) return true;\n try {\n let sessionKey = \"_\";\n try {\n const { getRequestUserEmail } =\n await import(\"../server/request-context.js\");\n sessionKey = getRequestUserEmail() ?? process.env.AGENT_USER_EMAIL ?? \"_\";\n } catch {\n // request-context unavailable (CLI / non-server) — use default key\n }\n const now = Date.now();\n const hit = cache.get(sessionKey);\n if (hit && now - hit.at < TTL_MS) return hit.value;\n const state = await readAppState(\"demo-mode\");\n const enabled = state?.enabled === true;\n cache.set(sessionKey, { value: enabled, at: now });\n return enabled;\n } catch {\n // No request context / DB unavailable — fail closed (no redaction).\n return false;\n }\n}\n"]}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Install the demo-mode fetch interceptor and start polling demo status.
3
+ * Idempotent and browser-only — safe to call from any hook that runs in
4
+ * every template root (we call it from `useDbSync`). A no-op until demo
5
+ * mode is actually on.
6
+ */
7
+ export declare function ensureDemoModeFetchInterceptor(): void;
8
+ //# sourceMappingURL=fetch-interceptor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-interceptor.d.ts","sourceRoot":"","sources":["../../src/demo/fetch-interceptor.ts"],"names":[],"mappings":"AA2GA;;;;;GAKG;AACH,wBAAgB,8BAA8B,IAAI,IAAI,CAuErD"}
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Client-side demo-mode redaction.
3
+ *
4
+ * Why client-side and not (only) at the server action boundary: templates
5
+ * serve a lot of their UI data through their OWN custom Nitro `/api/*`
6
+ * handlers (e.g. mail's `/api/emails`, `/api/threads/:id/messages`,
7
+ * `/api/contacts`, `/api/apollo/person`), which never pass through the
8
+ * framework action runtime. On this stack (Nitro v3 / h3 v2) there is no
9
+ * single server hook that can safely rewrite every JSON body (the `response`
10
+ * hook hands you an immutable Web `Response` and returns `void`). Patching the
11
+ * browser's `fetch` is the one place that is BOTH universal (every template's
12
+ * reads — actions and custom routes alike — go through it) AND low-risk: it
13
+ * can only ever post-process JSON the app already parses for display, so it
14
+ * physically cannot break auth, SSE streams, SSR HTML, or binary downloads.
15
+ *
16
+ * The agent is handled separately and in-process (its action tool results are
17
+ * redacted in `production-agent.ts`), so it doesn't depend on this at all.
18
+ *
19
+ * Scope intentionally narrow:
20
+ * - Only same-document `GET` requests are redacted. Mutation responses
21
+ * (POST/PUT/PATCH/DELETE) pass through untouched so a draft you just
22
+ * typed isn't echoed back as fake data mid-demo.
23
+ * - Only `application/json` 2xx bodies. Streams (`text/event-stream`),
24
+ * HTML, and binary are skipped by content-type.
25
+ * - Framework infra endpoints (poll, events, the demo-status endpoint
26
+ * itself) are skipped — no PII and avoids self-recursion.
27
+ * - Any error during interception falls back to the original response.
28
+ */
29
+ import { redactDemoData } from "./redact.js";
30
+ import { agentNativePath } from "../client/api-path.js";
31
+ const STATUS_PATH = agentNativePath("/_agent-native/demo/status");
32
+ const SKIP_SUBSTRINGS = [
33
+ "/_agent-native/demo/status",
34
+ "/_agent-native/poll",
35
+ "/_agent-native/events",
36
+ // Never touch agent transport. The agent already gets in-process
37
+ // redaction of its tool results; faking its own transcript adds no demo
38
+ // value and must stay clear of the tool_use/tool_result protocol. Covers
39
+ // "/_agent-native/agent" (stream) and "/_agent-native/agent-chat"
40
+ // (thread history) and any sub-paths.
41
+ "/_agent-native/agent",
42
+ // Run-manager state read by the reconnect/recovery loop. Faking numeric
43
+ // run state here would make recovery think it's not progressing and
44
+ // exhaust its retries ("agent connection kept failing").
45
+ "/_agent-native/runs",
46
+ ];
47
+ let installed = false;
48
+ let pollTimer = null;
49
+ let demoEnabled = false;
50
+ let originalFetch = null;
51
+ // Set once the first demo-status check completes. We DO NOT block requests on
52
+ // it — if status isn't known yet a response is simply passed through
53
+ // un-redacted (a brief first-paint window) rather than delaying transport.
54
+ // Injecting latency into early GETs previously risked the agent's streaming
55
+ // reconnect logic; transport safety wins over redacting the first paint.
56
+ let firstStatusDone = false;
57
+ /** Reject after `ms` so a misclassified streaming body can never hang. */
58
+ function withTimeout(p, ms) {
59
+ return Promise.race([
60
+ p,
61
+ new Promise((_, reject) => setTimeout(() => reject(new Error("redact-timeout")), ms)),
62
+ ]);
63
+ }
64
+ function urlOf(input) {
65
+ try {
66
+ if (typeof input === "string")
67
+ return input;
68
+ if (input instanceof URL)
69
+ return input.href;
70
+ return input.url ?? "";
71
+ }
72
+ catch {
73
+ return "";
74
+ }
75
+ }
76
+ function methodOf(input, init) {
77
+ const m = init?.method ??
78
+ (typeof input !== "string" && !(input instanceof URL)
79
+ ? input.method
80
+ : undefined) ??
81
+ "GET";
82
+ return m.toUpperCase();
83
+ }
84
+ async function refreshDemoFlag() {
85
+ const f = originalFetch ?? fetch;
86
+ try {
87
+ const res = await f(STATUS_PATH, { credentials: "include" });
88
+ if (!res.ok)
89
+ return;
90
+ const json = (await res.json());
91
+ demoEnabled = json?.enabled === true || json?.forced === true;
92
+ }
93
+ catch {
94
+ // Status endpoint unreachable — leave the last known value.
95
+ }
96
+ finally {
97
+ firstStatusDone = true;
98
+ }
99
+ }
100
+ /**
101
+ * Install the demo-mode fetch interceptor and start polling demo status.
102
+ * Idempotent and browser-only — safe to call from any hook that runs in
103
+ * every template root (we call it from `useDbSync`). A no-op until demo
104
+ * mode is actually on.
105
+ */
106
+ export function ensureDemoModeFetchInterceptor() {
107
+ if (typeof window === "undefined")
108
+ return;
109
+ if (installed)
110
+ return;
111
+ installed = true;
112
+ originalFetch = window.fetch.bind(window);
113
+ const base = originalFetch;
114
+ window.fetch = async function patchedFetch(input, init) {
115
+ const res = await base(input, init);
116
+ // Fast path: anything that isn't a demo-enabled, plain GET returns the
117
+ // ORIGINAL response with zero body work and zero extra awaits — when
118
+ // demo mode is off this wrapper is byte-for-byte native fetch, so it
119
+ // cannot influence agent/run/stream transport.
120
+ if (!demoEnabled || !firstStatusDone)
121
+ return res;
122
+ if (methodOf(input, init) !== "GET")
123
+ return res;
124
+ if (!res.ok)
125
+ return res;
126
+ try {
127
+ const url = urlOf(input);
128
+ if (SKIP_SUBSTRINGS.some((s) => url.includes(s)))
129
+ return res;
130
+ // Only buffered, finite JSON. SSE / streaming / chunked-forever bodies
131
+ // never reach `redactDemoData`: streaming content-types are excluded,
132
+ // and the JSON read is hard-timeout-bounded so a misclassified stream
133
+ // degrades to "return the original response" instead of hanging the
134
+ // request (which is what tripped the reconnect/recovery loop).
135
+ const contentType = res.headers.get("content-type") ?? "";
136
+ if (!contentType.includes("application/json"))
137
+ return res;
138
+ if (contentType.includes("event-stream") ||
139
+ contentType.includes("ndjson") ||
140
+ contentType.includes("stream")) {
141
+ return res;
142
+ }
143
+ if (res.bodyUsed)
144
+ return res;
145
+ const data = await withTimeout(res.clone().json(), 3_000);
146
+ const redacted = redactDemoData(data);
147
+ const headers = new Headers(res.headers);
148
+ // Body is re-serialized — these would be wrong now.
149
+ headers.delete("content-length");
150
+ headers.delete("content-encoding");
151
+ return new Response(JSON.stringify(redacted), {
152
+ status: res.status,
153
+ statusText: res.statusText,
154
+ headers,
155
+ });
156
+ }
157
+ catch {
158
+ // Never let redaction break a request — fall back to the real
159
+ // response (its body stream is untouched; we only ever read a clone).
160
+ return res;
161
+ }
162
+ };
163
+ void refreshDemoFlag();
164
+ pollTimer = setInterval(() => void refreshDemoFlag(), 4_000);
165
+ if (typeof pollTimer === "object" && "unref" in pollTimer) {
166
+ try {
167
+ pollTimer.unref();
168
+ }
169
+ catch {
170
+ // unref unavailable in the browser — fine, interval is cheap.
171
+ }
172
+ }
173
+ }
174
+ //# sourceMappingURL=fetch-interceptor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-interceptor.js","sourceRoot":"","sources":["../../src/demo/fetch-interceptor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,MAAM,WAAW,GAAG,eAAe,CA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AI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE;gBAC5C,MAAM,EAAE,GAAG,CAAC,MAAM;gBAClB,UAAU,EAAE,GAAG,CAAC,UAAU;gBAC1B,OAAO;aACR,CAAC,CAAC;QACL,CAAC;QAAC,MAAM,CAAC;YACP,8DAA8D;YAC9D,sEAAsE;YACtE,OAAO,GAAG,CAAC;QACb,CAAC;IACH,CAAC,CAAC;IAEF,KAAK,eAAe,EAAE,CAAC;IACvB,SAAS,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,KAAK,eAAe,EAAE,EAAE,KAAK,CAAC,CAAC;IAC7D,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,OAAO,IAAI,SAAS,EAAE,CAAC;QAC1D,IAAI,CAAC;YACF,SAA8C,CAAC,KAAK,EAAE,CAAC;QAC1D,CAAC;QAAC,MAAM,CAAC;YACP,8DAA8D;QAChE,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/**\n * Client-side demo-mode redaction.\n *\n * Why client-side and not (only) at the server action boundary: templates\n * serve a lot of their UI data through their OWN custom Nitro `/api/*`\n * handlers (e.g. mail's `/api/emails`, `/api/threads/:id/messages`,\n * `/api/contacts`, `/api/apollo/person`), which never pass through the\n * framework action runtime. On this stack (Nitro v3 / h3 v2) there is no\n * single server hook that can safely rewrite every JSON body (the `response`\n * hook hands you an immutable Web `Response` and returns `void`). Patching the\n * browser's `fetch` is the one place that is BOTH universal (every template's\n * reads — actions and custom routes alike — go through it) AND low-risk: it\n * can only ever post-process JSON the app already parses for display, so it\n * physically cannot break auth, SSE streams, SSR HTML, or binary downloads.\n *\n * The agent is handled separately and in-process (its action tool results are\n * redacted in `production-agent.ts`), so it doesn't depend on this at all.\n *\n * Scope intentionally narrow:\n * - Only same-document `GET` requests are redacted. Mutation responses\n * (POST/PUT/PATCH/DELETE) pass through untouched so a draft you just\n * typed isn't echoed back as fake data mid-demo.\n * - Only `application/json` 2xx bodies. Streams (`text/event-stream`),\n * HTML, and binary are skipped by content-type.\n * - Framework infra endpoints (poll, events, the demo-status endpoint\n * itself) are skipped — no PII and avoids self-recursion.\n * - Any error during interception falls back to the original response.\n */\nimport { redactDemoData } from \"./redact.js\";\nimport { agentNativePath } from \"../client/api-path.js\";\n\nconst STATUS_PATH = agentNativePath(\"/_agent-native/demo/status\");\nconst SKIP_SUBSTRINGS = [\n \"/_agent-native/demo/status\",\n \"/_agent-native/poll\",\n \"/_agent-native/events\",\n // Never touch agent transport. The agent already gets in-process\n // redaction of its tool results; faking its own transcript adds no demo\n // value and must stay clear of the tool_use/tool_result protocol. Covers\n // \"/_agent-native/agent\" (stream) and \"/_agent-native/agent-chat\"\n // (thread history) and any sub-paths.\n \"/_agent-native/agent\",\n // Run-manager state read by the reconnect/recovery loop. Faking numeric\n // run state here would make recovery think it's not progressing and\n // exhaust its retries (\"agent connection kept failing\").\n \"/_agent-native/runs\",\n];\n\nlet installed = false;\nlet pollTimer: ReturnType<typeof setInterval> | null = null;\nlet demoEnabled = false;\nlet originalFetch: typeof fetch | null = null;\n\n// Set once the first demo-status check completes. We DO NOT block requests on\n// it — if status isn't known yet a response is simply passed through\n// un-redacted (a brief first-paint window) rather than delaying transport.\n// Injecting latency into early GETs previously risked the agent's streaming\n// reconnect logic; transport safety wins over redacting the first paint.\nlet firstStatusDone = false;\n\n/** Reject after `ms` so a misclassified streaming body can never hang. */\nfunction withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {\n return Promise.race([\n p,\n new Promise<T>((_, reject) =>\n setTimeout(() => reject(new Error(\"redact-timeout\")), ms),\n ),\n ]);\n}\n\nfunction urlOf(input: RequestInfo | URL): string {\n try {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.href;\n return (input as Request).url ?? \"\";\n } catch {\n return \"\";\n }\n}\n\nfunction methodOf(input: RequestInfo | URL, init?: RequestInit): string {\n const m =\n init?.method ??\n (typeof input !== \"string\" && !(input instanceof URL)\n ? (input as Request).method\n : undefined) ??\n \"GET\";\n return m.toUpperCase();\n}\n\nasync function refreshDemoFlag(): Promise<void> {\n const f = originalFetch ?? fetch;\n try {\n const res = await f(STATUS_PATH, { credentials: \"include\" });\n if (!res.ok) return;\n const json = (await res.json()) as {\n enabled?: boolean;\n forced?: boolean;\n } | null;\n demoEnabled = json?.enabled === true || json?.forced === true;\n } catch {\n // Status endpoint unreachable — leave the last known value.\n } finally {\n firstStatusDone = true;\n }\n}\n\n/**\n * Install the demo-mode fetch interceptor and start polling demo status.\n * Idempotent and browser-only — safe to call from any hook that runs in\n * every template root (we call it from `useDbSync`). A no-op until demo\n * mode is actually on.\n */\nexport function ensureDemoModeFetchInterceptor(): void {\n if (typeof window === \"undefined\") return;\n if (installed) return;\n installed = true;\n\n originalFetch = window.fetch.bind(window);\n const base = originalFetch;\n\n window.fetch = async function patchedFetch(\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n const res = await base(input, init);\n\n // Fast path: anything that isn't a demo-enabled, plain GET returns the\n // ORIGINAL response with zero body work and zero extra awaits — when\n // demo mode is off this wrapper is byte-for-byte native fetch, so it\n // cannot influence agent/run/stream transport.\n if (!demoEnabled || !firstStatusDone) return res;\n if (methodOf(input, init) !== \"GET\") return res;\n if (!res.ok) return res;\n\n try {\n const url = urlOf(input);\n if (SKIP_SUBSTRINGS.some((s) => url.includes(s))) return res;\n\n // Only buffered, finite JSON. SSE / streaming / chunked-forever bodies\n // never reach `redactDemoData`: streaming content-types are excluded,\n // and the JSON read is hard-timeout-bounded so a misclassified stream\n // degrades to \"return the original response\" instead of hanging the\n // request (which is what tripped the reconnect/recovery loop).\n const contentType = res.headers.get(\"content-type\") ?? \"\";\n if (!contentType.includes(\"application/json\")) return res;\n if (\n contentType.includes(\"event-stream\") ||\n contentType.includes(\"ndjson\") ||\n contentType.includes(\"stream\")\n ) {\n return res;\n }\n if (res.bodyUsed) return res;\n\n const data = await withTimeout(res.clone().json(), 3_000);\n const redacted = redactDemoData(data);\n\n const headers = new Headers(res.headers);\n // Body is re-serialized — these would be wrong now.\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n\n return new Response(JSON.stringify(redacted), {\n status: res.status,\n statusText: res.statusText,\n headers,\n });\n } catch {\n // Never let redaction break a request — fall back to the real\n // response (its body stream is untouched; we only ever read a clone).\n return res;\n }\n };\n\n void refreshDemoFlag();\n pollTimer = setInterval(() => void refreshDemoFlag(), 4_000);\n if (typeof pollTimer === \"object\" && \"unref\" in pollTimer) {\n try {\n (pollTimer as unknown as { unref: () => void }).unref();\n } catch {\n // unref unavailable in the browser — fine, interval is cheap.\n }\n }\n}\n"]}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Pure, dependency-free, deterministic demo-mode redactor.
3
+ *
4
+ * Replaces sensitive values (names, emails, free numbers) with stable fake
5
+ * substitutes so a demo looks coherent — the same input always maps to the
6
+ * same fake. Crucially, it NEVER rewrites identifiers, structural tokens, or
7
+ * timestamps: under-redaction is safe, corrupting an ID is not. The string
8
+ * redactor uses a protect-first strategy (mask IDs with opaque placeholders
9
+ * before any transform runs, restore them byte-identical afterwards), and the
10
+ * structure-aware walker additionally protects leaf values by key name.
11
+ */
12
+ export interface RedactOptions {
13
+ salt?: string;
14
+ }
15
+ export declare function redactDemoString(text: string, opts?: RedactOptions): string;
16
+ export declare function redactDemoData<T>(value: T, opts?: RedactOptions): T;
17
+ /**
18
+ * Clear the stable-mapping caches. Test-only — the caches are process-global
19
+ * (intentionally, so mappings stay stable for a tab's session), which would
20
+ * otherwise let one test's produced fakes leak into another's assertions.
21
+ */
22
+ export declare function __resetDemoRedactCacheForTests(): void;
23
+ //# sourceMappingURL=redact.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact.d.ts","sourceRoot":"","sources":["../../src/demo/redact.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,MAAM,WAAW,aAAa;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAoiBD,wBAAgB,gBAAgB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,SAAS,CAAC,CAAC;QAC3D,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,0EAA0E;IAC1E,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,UAAU,cAAc,CAAI,KAAQ,EAAE,IAAoB;IAC9D,MAAM,IAAI,GAAG,IAAI,EAAE,IAAI,IAAI,EAAE,CAAC;IAC9B,OAAO,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,OAAO,EAAU,EAAE,KAAK,CAAM,CAAC;AACjE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,8BAA8B;IAC5C,YAAY,CAAC,KAAK,EAAE,CAAC;IACrB,aAAa,CAAC,KAAK,EAAE,CAAC;AACxB,CAAC","sourcesContent":["/**\n * Pure, dependency-free, deterministic demo-mode redactor.\n *\n * Replaces sensitive values (names, emails, free numbers) with stable fake\n * substitutes so a demo looks coherent — the same input always maps to the\n * same fake. Crucially, it NEVER rewrites identifiers, structural tokens, or\n * timestamps: under-redaction is safe, corrupting an ID is not. The string\n * redactor uses a protect-first strategy (mask IDs with opaque placeholders\n * before any transform runs, restore them byte-identical afterwards), and the\n * structure-aware walker additionally protects leaf values by key name.\n */\n\nexport interface RedactOptions {\n salt?: string;\n}\n\n/* ------------------------------------------------------------------ *\n * Seeded hash + PRNG (xmur3 seed → mulberry32 stream)\n * ------------------------------------------------------------------ */\n\nfunction xmur3(str: string): () => number {\n let h = 1779033703 ^ str.length;\n for (let i = 0; i < str.length; i++) {\n h = Math.imul(h ^ str.charCodeAt(i), 3432918353);\n h = (h << 13) | (h >>> 19);\n }\n return function () {\n h = Math.imul(h ^ (h >>> 16), 2246822507);\n h = Math.imul(h ^ (h >>> 13), 3266489909);\n h ^= h >>> 16;\n return h >>> 0;\n };\n}\n\nfunction mulberry32(seed: number): () => number {\n let a = seed >>> 0;\n return function () {\n a = (a + 0x6d2b79f5) >>> 0;\n let t = a;\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n}\n\n/** Deterministic PRNG seeded by `value + salt`. */\nfunction seededRng(value: string, salt: string): () => number {\n const seedFn = xmur3(`${value}\u0000${salt}`);\n return mulberry32(seedFn());\n}\n\nfunction pick<T>(rng: () => number, pool: readonly T[]): T {\n return pool[Math.floor(rng() * pool.length) % pool.length];\n}\n\n/* ------------------------------------------------------------------ *\n * Stable mapping cache (bounded, TTL, leak-free)\n *\n * The fake values are already a pure deterministic function of\n * (kind, salt, original), so identical input is always stable. This cache\n * adds two things on top:\n *\n * 1. A consistent forward map so the same original keeps the same fake for\n * the life of the entry, even if the algorithm/salt is ever tuned.\n * 2. Idempotency: every fake we emit is remembered, so when a fake value\n * round-trips back through redaction (e.g. you edit a draft that's\n * already showing fake text, it autosaves, then refetches) it is passed\n * through UNCHANGED instead of being re-faked into something new. This\n * is what stops names/emails drifting on every edit.\n *\n * Leak-free by construction: no timers, a hard size cap, and lazy TTL purge\n * on write. Works the same per-tab in the browser and per-process on the\n * server. Memoizing a pure function across users is safe — output depends\n * only on input.\n * ------------------------------------------------------------------ */\n\nconst CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour\nconst CACHE_MAX = 5000;\n\n// original-key → { fake, at }. Insertion-ordered (Map) so the oldest key is\n// first — used for cap eviction.\nconst forwardCache = new Map<string, { value: string; at: number }>();\n// produced fake → last-seen timestamp (same bound/TTL policy).\nconst producedFakes = new Map<string, number>();\n\nfunction purge(map: Map<string, { at: number } | number>): void {\n const now = Date.now();\n for (const [k, v] of map) {\n const at = typeof v === \"number\" ? v : v.at;\n if (now - at > CACHE_TTL_MS) map.delete(k);\n else break; // insertion-ordered: first fresh entry ⇒ rest are fresher\n }\n while (map.size > CACHE_MAX) {\n const oldest = map.keys().next().value as string | undefined;\n if (oldest === undefined) break;\n map.delete(oldest);\n }\n}\n\nfunction rememberProduced(fake: string): string {\n if (fake.length === 0) return fake;\n producedFakes.delete(fake);\n producedFakes.set(fake, Date.now());\n if (producedFakes.size > CACHE_MAX) purge(producedFakes);\n return fake;\n}\n\nfunction isProducedFake(value: string): boolean {\n const at = producedFakes.get(value);\n if (at === undefined) return false;\n if (Date.now() - at > CACHE_TTL_MS) {\n producedFakes.delete(value);\n return false;\n }\n return true;\n}\n\n/**\n * Memoize a deterministic fake by (kind, salt, original). On a hit, the\n * entry's recency is refreshed (LRU-ish). The generated value is also\n * registered as a produced fake so it survives a round-trip unchanged.\n */\nfunction memoFake(\n kind: string,\n original: string,\n salt: string,\n gen: () => string,\n // Numbers opt out: a fake number collides with real numbers far too often\n // to safely treat \"looks like one we emitted\" as \"leave it alone\".\n idempotent = true,\n): string {\n // Already one of our fakes? Leave it exactly as-is (round-trip stable).\n if (idempotent && isProducedFake(original)) return original;\n\n const key = `${kind}\u0000${salt}\u0000${original}`;\n const hit = forwardCache.get(key);\n const now = Date.now();\n if (hit && now - hit.at <= CACHE_TTL_MS) {\n forwardCache.delete(key);\n forwardCache.set(key, { value: hit.value, at: now });\n return hit.value;\n }\n\n const value = gen();\n forwardCache.set(key, { value, at: now });\n if (forwardCache.size > CACHE_MAX) purge(forwardCache);\n if (idempotent) rememberProduced(value);\n return value;\n}\n\n/* ------------------------------------------------------------------ *\n * Curated name pools\n * ------------------------------------------------------------------ */\n\nconst FIRST_NAMES: readonly string[] = [\n \"Jane\",\n \"John\",\n \"Alex\",\n \"Maria\",\n \"Sam\",\n \"Olivia\",\n \"Liam\",\n \"Emma\",\n \"Noah\",\n \"Ava\",\n \"Lucas\",\n \"Mia\",\n \"Ethan\",\n \"Sofia\",\n \"Mason\",\n \"Isla\",\n \"Leo\",\n \"Aria\",\n \"Henry\",\n \"Zoe\",\n \"Owen\",\n \"Nora\",\n \"Caleb\",\n \"Lily\",\n \"Ryan\",\n \"Ruby\",\n \"Adam\",\n \"Chloe\",\n \"Eli\",\n \"Hazel\",\n \"Max\",\n \"Iris\",\n \"Ben\",\n \"Clara\",\n \"Theo\",\n \"Maya\",\n \"Felix\",\n \"Elena\",\n \"Jonah\",\n \"Greta\",\n];\n\nconst LAST_NAMES: readonly string[] = [\n \"Doe\",\n \"Smith\",\n \"Johnson\",\n \"Lee\",\n \"Brown\",\n \"Garcia\",\n \"Miller\",\n \"Davis\",\n \"Wilson\",\n \"Moore\",\n \"Taylor\",\n \"Anderson\",\n \"Thomas\",\n \"Jackson\",\n \"White\",\n \"Harris\",\n \"Martin\",\n \"Clark\",\n \"Lewis\",\n \"Walker\",\n \"Hall\",\n \"Young\",\n \"King\",\n \"Wright\",\n \"Hill\",\n \"Green\",\n \"Adams\",\n \"Baker\",\n \"Nelson\",\n \"Carter\",\n \"Mitchell\",\n \"Perez\",\n \"Roberts\",\n \"Turner\",\n \"Phillips\",\n \"Campbell\",\n \"Parker\",\n \"Evans\",\n \"Edwards\",\n \"Collins\",\n];\n\n/* ------------------------------------------------------------------ *\n * Fake value generators (deterministic in value + salt)\n * ------------------------------------------------------------------ */\n\nfunction fakeName(original: string, salt: string): string {\n return memoFake(\"name\", original, salt, () => {\n const rng = seededRng(`name:${original}`, salt);\n const first = pick(rng, FIRST_NAMES);\n const last = pick(rng, LAST_NAMES);\n return `${first} ${last}`;\n });\n}\n\n// Realistic-looking but safe stand-in domains: real consumer providers (the\n// local part is fake, so no real mailbox is implied) plus the canonical\n// reserved fictional-company domains (Contoso/Fabrikam/Northwind), which read\n// as real businesses but are intentional placeholders. No example.com.\nconst FAKE_EMAIL_DOMAINS: readonly string[] = [\n \"gmail.com\",\n \"outlook.com\",\n \"icloud.com\",\n \"yahoo.com\",\n \"proton.me\",\n \"hey.com\",\n \"fastmail.com\",\n \"contoso.com\",\n \"fabrikam.com\",\n \"northwind.com\",\n \"acme.io\",\n \"globex.net\",\n];\n\nfunction fakeEmail(original: string, salt: string): string {\n return memoFake(\"email\", original.toLowerCase(), salt, () => {\n const rng = seededRng(`email:${original.toLowerCase()}`, salt);\n const first = pick(rng, FIRST_NAMES).toLowerCase();\n const last = pick(rng, LAST_NAMES).toLowerCase();\n const domain = pick(rng, FAKE_EMAIL_DOMAINS);\n // Vary the local part so addresses don't all look templated.\n const shape = Math.floor(rng() * 6);\n let local: string;\n switch (shape) {\n case 0:\n local = `${first}.${last}`;\n break;\n case 1:\n local = `${first}${last}`;\n break;\n case 2:\n local = `${first[0]}${last}`;\n break;\n case 3:\n local = `${first}.${last}${1 + Math.floor(rng() * 89)}`;\n break;\n case 4:\n local = `${first}_${last}`;\n break;\n default:\n local = `${last}.${first}`;\n break;\n }\n return `${local}@${domain}`;\n });\n}\n\n/**\n * Replace every digit in `numericBody` with a freshly-generated digit while\n * preserving non-digit characters (grouping commas, decimal points) exactly.\n * The first digit is forced non-zero so the digit count is observable.\n */\nfunction fakeNumberBody(\n numericBody: string,\n original: string,\n salt: string,\n): string {\n // Stable per original token, but NOT registered as a produced fake — a\n // fake number coincides with real numbers too often to skip on round-trip.\n return memoFake(\n \"num\",\n original,\n salt,\n () => {\n const rng = seededRng(`num:${original}`, salt);\n let out = \"\";\n let seenDigit = false;\n for (const ch of numericBody) {\n if (ch >= \"0\" && ch <= \"9\") {\n let d: number;\n if (!seenDigit) {\n // Leading digit: 1-9 so length is preserved.\n d = 1 + Math.floor(rng() * 9);\n seenDigit = true;\n } else {\n d = Math.floor(rng() * 10);\n }\n out += String(d);\n } else {\n out += ch;\n }\n }\n return out;\n },\n false,\n );\n}\n\n/* ------------------------------------------------------------------ *\n * Protect-first tokenizer (ID-safety core)\n * ------------------------------------------------------------------ */\n\n/**\n * Patterns whose matches must be protected from ANY transform. Order matters:\n * the most structural / specific shapes come first so they win the scan.\n */\nconst PROTECT_PATTERNS: RegExp[] = [\n // URLs / URIs with a scheme.\n /\\b[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\/[^\\s]+/g,\n /\\b(?:mailto|data|tel|urn):[^\\s]+/gi,\n // UUID.\n /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/g,\n // JWT — three base64url segments separated by dots.\n /\\b[A-Za-z0-9_-]{4,}\\.[A-Za-z0-9_-]{4,}\\.[A-Za-z0-9_-]{4,}\\b/g,\n // ISO datetime / date.\n /\\b\\d{4}-\\d{2}-\\d{2}(?:[T ]\\d{2}:\\d{2}(?::\\d{2})?(?:\\.\\d+)?Z?)?\\b/g,\n // Bare clock time.\n /\\b\\d{1,2}:\\d{2}(?::\\d{2})?\\b/g,\n // Path-like tokens containing a slash (but not bare prose with slashes —\n // require no spaces and at least one slash with adjacent non-space).\n /(?:\\S*\\/\\S+)+/g,\n // nanoid / hex / base64-ish blobs: an unbroken [A-Za-z0-9_-] run that is\n // either long-with-a-digit, mixes letters AND digits at length >= 10, or\n // contains a `_`/`-` inside the run (real names/numbers never look so).\n /[A-Za-z0-9_-]+/g,\n];\n\nconst PLACEHOLDER_PREFIX = \"\u0001P\";\nconst PLACEHOLDER_SUFFIX = \"\u0001\";\n\nfunction makePlaceholder(index: number): string {\n return `${PLACEHOLDER_PREFIX}${index}${PLACEHOLDER_SUFFIX}`;\n}\n\n/** True if a `[A-Za-z0-9_-]+` run is identifier-shaped (must be protected). */\nfunction looksLikeIdentifierToken(tok: string): boolean {\n if (tok.length < 3) return false;\n const hasLetter = /[A-Za-z]/.test(tok);\n const hasDigit = /[0-9]/.test(tok);\n const hasSep = /[_-]/.test(tok);\n\n // A pure number (optionally with separators handled elsewhere) is NOT an\n // identifier here — the number rule handles those.\n if (!hasLetter && !hasSep) return false;\n\n // Long hex/base64-ish blob with a digit.\n if (tok.length >= 16 && hasDigit) return true;\n // nanoid-ish: length >= 10 mixing letters AND digits.\n if (tok.length >= 10 && hasLetter && hasDigit) return true;\n // Any token that has a `_`/`-` joined inside an unbroken run AND also\n // contains a digit or is long — e.g. `order-2024-abc`, `api_key_v2`.\n if (hasSep && (hasDigit || tok.length >= 10)) return true;\n // Mixed letters+digits adjacency (e.g. `abc123`, `v2`, `step3`) — protect so\n // the number rule never bites an embedded number.\n if (hasLetter && hasDigit) return true;\n\n return false;\n}\n\ninterface Protection {\n text: string;\n restore: Map<string, string>;\n}\n\n/**\n * Walk `text`, replace every protected substring with an opaque placeholder,\n * and return the masked text plus a restore map. Non-overlapping, left-to-right\n * earliest-match-wins so a transform literally cannot see a protected value.\n */\nfunction protect(text: string): Protection {\n const restore = new Map<string, string>();\n let counter = 0;\n\n // Collect all candidate matches across patterns, then resolve overlaps by\n // earliest start (and longest on tie).\n interface Span {\n start: number;\n end: number;\n value: string;\n }\n const spans: Span[] = [];\n\n for (let p = 0; p < PROTECT_PATTERNS.length; p++) {\n const re = new RegExp(\n PROTECT_PATTERNS[p].source,\n PROTECT_PATTERNS[p].flags,\n );\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n const value = m[0];\n if (value.length === 0) {\n re.lastIndex++;\n continue;\n }\n const isTokenPattern = p === PROTECT_PATTERNS.length - 1;\n if (isTokenPattern && !looksLikeIdentifierToken(value)) {\n continue;\n }\n spans.push({ start: m.index, end: m.index + value.length, value });\n }\n }\n\n if (spans.length === 0) return { text, restore };\n\n spans.sort((a, b) =>\n a.start !== b.start ? a.start - b.start : b.end - a.end,\n );\n\n let out = \"\";\n let cursor = 0;\n for (const span of spans) {\n if (span.start < cursor) continue; // overlapped by an earlier protection\n out += text.slice(cursor, span.start);\n const ph = makePlaceholder(counter++);\n restore.set(ph, span.value);\n out += ph;\n cursor = span.end;\n }\n out += text.slice(cursor);\n\n return { text: out, restore };\n}\n\nfunction unprotect(text: string, restore: Map<string, string>): string {\n if (restore.size === 0) return text;\n let out = text;\n for (const [ph, original] of restore) {\n out = out.split(ph).join(original);\n }\n return out;\n}\n\n/* ------------------------------------------------------------------ *\n * Transforms (run only on protected text)\n * ------------------------------------------------------------------ */\n\nconst EMAIL_RE = /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g;\n\n// 2+ capitalized words (each starts uppercase, allows internal lowercase /\n// apostrophes / hyphens). Single-letter middle initials allowed: `Sarah J Connor`.\nconst FULL_NAME_RE = /\\b[A-Z][a-zA-Z'’-]*(?:\\s+[A-Z](?:[a-zA-Z'’-]*)?){1,3}\\b/g;\n\n// The ENTIRE value is a person name: 2–4 consecutive capitalized words. Used\n// to decide whether a short string under a name-ish key (`name`, `from`,\n// `sender`, …) should be coerced wholesale to a fake name. Single tokens\n// (\"Steve\") and mixed-case label phrases (\"Important\", \"Automated\n// notifications\", \"Note to Self\", \"Other\") deliberately fail this so mail\n// folder/tab names and other labels are NOT mangled — we only fake values\n// that genuinely look like a multi-word person name.\nconst LOOKS_LIKE_FULL_NAME_RE =\n /^[A-Z][a-zA-Z'’.-]*(?:\\s+[A-Z][a-zA-Z'’.-]*){1,3}$/;\n\n// A standalone numeric token: optional currency + sign, digits with optional\n// comma grouping and a single optional decimal part. Bounded so it is NOT\n// adjacent to a letter (placeholders already removed letter-mixed tokens, but\n// this keeps the rule self-contained and safe on raw structured values too).\nconst NUMBER_RE =\n /(^|[^A-Za-z0-9_])([$€£]?)([+-]?)(\\d[\\d,]*(?:\\.\\d+)?)(?![A-Za-z0-9_])/g;\n\nfunction transformEmails(text: string, salt: string): string {\n return text.replace(EMAIL_RE, (match) => fakeEmail(match, salt));\n}\n\nfunction transformNames(text: string, salt: string): string {\n return text.replace(FULL_NAME_RE, (match) => {\n // Keep trailing/leading whitespace handling implicit; `match` is the run.\n return fakeName(match, salt);\n });\n}\n\nfunction isProbablyYear(digits: string): boolean {\n if (digits.length !== 4) return false;\n const n = Number(digits);\n return n >= 1900 && n <= 2099;\n}\n\nfunction transformNumbers(text: string, salt: string): string {\n return text.replace(\n NUMBER_RE,\n (_full, pre: string, currency: string, sign: string, body: string) => {\n const hasGrouping = body.includes(\",\");\n const hasDecimal = body.includes(\".\");\n const digitsOnly = body.replace(/[^0-9]/g, \"\");\n\n // Skip bare years like 2026.\n if (\n !currency &&\n !sign &&\n !hasGrouping &&\n !hasDecimal &&\n isProbablyYear(digitsOnly)\n ) {\n return `${pre}${currency}${sign}${body}`;\n }\n\n // Skip standalone integers < 1000 with no currency and no grouping\n // (rewriting \"3 unread\" / \"page 2\" looks broken and isn't sensitive).\n if (!currency && !hasGrouping && !hasDecimal) {\n const n = Number(digitsOnly);\n if (Number.isFinite(n) && n < 1000) {\n return `${pre}${currency}${sign}${body}`;\n }\n }\n\n const fakeBody = fakeNumberBody(body, `${currency}${sign}${body}`, salt);\n return `${pre}${currency}${sign}${fakeBody}`;\n },\n );\n}\n\n/* ------------------------------------------------------------------ *\n * Public: string redactor\n * ------------------------------------------------------------------ */\n\nexport function redactDemoString(text: string, opts?: RedactOptions): string {\n if (typeof text !== \"string\" || text.length === 0) return text;\n const salt = opts?.salt ?? \"\";\n\n const { text: masked, restore } = protect(text);\n let out = masked;\n out = transformEmails(out, salt);\n out = transformNames(out, salt);\n out = transformNumbers(out, salt);\n return unprotect(out, restore);\n}\n\n/* ------------------------------------------------------------------ *\n * Public: structure-aware redactor\n * ------------------------------------------------------------------ */\n\n// Keys whose leaf values must NEVER be transformed (still recurse into nested\n// objects/arrays under them). Besides ids/urls/timestamps this also covers\n// code/query-bearing keys (`sql`, `query`, `expression`, `formula`, `code`):\n// prose-redacting a SQL string injects fake names/numbers into it and rewrites\n// its leading tokens, producing `syntax error at or near \"Henry\"` /\n// `queries must start with SELECT or WITH`. The query must run untouched; its\n// RESULTS are what get redacted so the chart still shows fake names.\nconst PROTECTED_KEY_RE =\n /^id$|(^|_)id$|Id$|Ids$|uuid|guid|slug|token|secret|password|passwd|apikey|api_key|hash|sha\\d*|etag|cursor|nonce|sessionid|messageid|threadid|nodeid|(^|_)key$|keyid|(^|_)ref$|url$|uri$|href$|src$|path$|filename$|mimetype|mime|^sql$|sql$|query|expression|formula|^code$|createdat|updatedat|deletedat|expiresat|timestamp|.+at$|.+_at$/i;\n\n// Keys whose (short) leaf string should be treated as a full name even when it\n// is a single token.\nconst NAME_KEY_RE =\n /name|from$|to$|sender|recipient|author|fullName|displayName|firstName|lastName|contact/i;\n\nconst MAX_DEPTH = 64;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n if (Array.isArray(value)) return false;\n if (value instanceof Date) return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\nfunction redactNameLeaf(value: string, salt: string): string {\n if (value.length === 0 || value.length > 40) {\n // Too long to be a bare name — fall back to prose redaction.\n return redactDemoStringWithSalt(value, salt);\n }\n // If it already contains an email, redact that path instead.\n if (EMAIL_RE.test(value)) {\n EMAIL_RE.lastIndex = 0;\n return redactDemoStringWithSalt(value, salt);\n }\n EMAIL_RE.lastIndex = 0;\n\n // Only coerce the whole value to a fake name when it actually looks like a\n // person's name (2–4 capitalized words). Single tokens (\"Steve\") and\n // label-ish phrases (\"Important\", \"Automated notifications\", \"Note to\n // Self\") are NOT names — fall back to prose redaction, which leaves them\n // intact while still faking any embedded multi-word name / email / number.\n if (!LOOKS_LIKE_FULL_NAME_RE.test(value.trim())) {\n return redactDemoStringWithSalt(value, salt);\n }\n\n const { text: masked, restore } = protect(value);\n // If protection consumed the whole value, it was identifier-shaped — leave.\n if (masked.trim().length === 0 || restore.size > 0) {\n // Be conservative: if any part looked like an ID, prefer prose redaction\n // (which preserves the protected bits) over forcing a name.\n return redactDemoStringWithSalt(value, salt);\n }\n return fakeName(value, salt);\n}\n\nfunction redactDemoStringWithSalt(text: string, salt: string): string {\n return redactDemoString(text, { salt });\n}\n\nfunction redactNumberLeaf(value: number, salt: string): number {\n if (!Number.isFinite(value)) return value;\n const repr = String(value);\n // Re-use the string number transform but only if the representation is a\n // clean numeric token we can round-trip back to a JS number.\n const redacted = transformNumbers(repr, salt);\n if (redacted === repr) return value;\n const n = Number(redacted);\n if (!Number.isFinite(n)) return value;\n return n;\n}\n\nfunction walk(\n value: unknown,\n salt: string,\n depth: number,\n seen: WeakSet<object>,\n underNameKey: boolean,\n): unknown {\n if (depth > MAX_DEPTH) return value;\n\n if (value === null || value === undefined) return value;\n\n const t = typeof value;\n\n if (t === \"string\") {\n const str = value as string;\n if (underNameKey) return redactNameLeaf(str, salt);\n return redactDemoStringWithSalt(str, salt);\n }\n\n if (t === \"number\") {\n return redactNumberLeaf(value as number, salt);\n }\n\n if (t === \"boolean\" || t === \"bigint\" || t === \"function\" || t === \"symbol\") {\n return value;\n }\n\n if (value instanceof Date) return value;\n\n if (Array.isArray(value)) {\n if (seen.has(value)) return value;\n seen.add(value);\n const out = value.map((item) =>\n walk(item, salt, depth + 1, seen, underNameKey),\n );\n seen.delete(value);\n return out;\n }\n\n if (isPlainObject(value)) {\n if (seen.has(value)) return value;\n seen.add(value);\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const keyIsProtected = PROTECTED_KEY_RE.test(key);\n if (keyIsProtected) {\n if (\n entry !== null &&\n typeof entry === \"object\" &&\n !(entry instanceof Date)\n ) {\n // Still recurse into nested structures, but the protected key does\n // not propagate name/transform semantics.\n out[key] = walk(entry, salt, depth + 1, seen, false);\n } else {\n // Leaf under a protected key: pass through completely untouched.\n out[key] = entry;\n }\n continue;\n }\n const keyIsName = NAME_KEY_RE.test(key);\n out[key] = walk(entry, salt, depth + 1, seen, keyIsName);\n }\n seen.delete(value);\n return out;\n }\n\n // Unknown object kind (Map, Set, class instance, etc.) — leave untouched.\n return value;\n}\n\nexport function redactDemoData<T>(value: T, opts?: RedactOptions): T {\n const salt = opts?.salt ?? \"\";\n return walk(value, salt, 0, new WeakSet<object>(), false) as T;\n}\n\n/**\n * Clear the stable-mapping caches. Test-only — the caches are process-global\n * (intentionally, so mappings stay stable for a tab's session), which would\n * otherwise let one test's produced fakes leak into another's assertions.\n */\nexport function __resetDemoRedactCacheForTests(): void {\n forwardCache.clear();\n producedFakes.clear();\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"action-discovery.d.ts","sourceRoot":"","sources":["../../src/server/action-discovery.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAqChE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACnC,IAAI,CAKN;AAyND;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAqC7B;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,mBAAmB,CACvC,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAgGtC;AAED,wBAAsB,uBAAuB,CAC3C,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACpC,OAAO,CAAC,IAAI,CAAC,CAuCf;AAED,oDAAoD;AACpD,eAAO,MAAM,mBAAmB,4BAAsB,CAAC"}
1
+ {"version":3,"file":"action-discovery.d.ts","sourceRoot":"","sources":["../../src/server/action-discovery.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAqChE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACnC,IAAI,CAKN;AAyND;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAqC7B;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,mBAAmB,CACvC,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAgGtC;AAED,wBAAsB,uBAAuB,CAC3C,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACpC,OAAO,CAAC,IAAI,CAAC,CAwCf;AAED,oDAAoD;AACpD,eAAO,MAAM,mBAAmB,4BAAsB,CAAC"}
@@ -424,6 +424,7 @@ export async function mergeCoreSharingActions(registry) {
424
424
  "change-appearance",
425
425
  () => import("../appearance/actions/change-appearance.js"),
426
426
  ],
427
+ ["toggle-demo-mode", () => import("../demo/actions/toggle-demo-mode.js")],
427
428
  ];
428
429
  for (const [name, loader] of entries) {
429
430
  if (registry[name])
@@ -1 +1 @@
1
- {"version":3,"file":"action-discovery.js","sourceRoot":"","sources":["../../src/server/action-discovery.ts"],"names":[],"mappings":"AA6BA,OAAO,QAAQ,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEpD,sDAAsD;AACtD,yFAAyF;AACzF,IAAI,GAAoC,CAAC;AACzC,KAAK,UAAU,KAAK;IAClB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,GAAG,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AACD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,0DAA0D;AAC1D,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,SAAS;IACT,KAAK;IACL,YAAY;IACZ,WAAW;IACX,UAAU;CACX,CAAC,CAAC;AAEH;;;;;;;;;GASG;AACH,MAAM,qBAAqB,GAAgC,EAAE,CAAC;AAE9D;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAoC;IAEpC,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,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Z,GAAG,CAAC,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACrD,GAAG,CAAC,GAAG,CAAC,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACpD,GAAG,CAAC,GAAG,CAAC,YAAY,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBAC7D,CAAC;YACJ,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,gDAAgD;QAClD,CAAC;IACH,CAAC;AACH,CAAC;AAED,oDAAoD;AACpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * Auto-discover actions from a template's actions/ directory.\n *\n * Scans for .ts/.js files and builds an action registry suitable for\n * `createAgentChatPlugin({ actions })`.\n *\n * Supports two action conventions:\n *\n * 1. **Full interface** — exports `tool: ActionTool` and `run(args): Promise<string>`.\n * These are used directly.\n *\n * 2. **CLI-style** — exports only `default async function(args: string[])`.\n * These are wrapped: args are converted from `Record<string, string>` to\n * `[\"--key\", \"value\", ...]`, console output is captured, and a tool\n * definition is synthesized from the action name.\n *\n * 3. **defineAction** — exports `default` from `defineAction()`. Has `tool` and `run`.\n *\n * Usage in agent-chat plugins:\n * ```ts\n * import { autoDiscoverActions } from \"@agent-native/core/server\";\n *\n * export default createAgentChatPlugin({\n * actions: () => autoDiscoverActions(import.meta.url),\n * });\n * ```\n */\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport nodePath from \"node:path\";\nimport { captureCliOutput } from \"./cli-capture.js\";\n\n// Lazy fs — loaded via dynamic import() on first use.\n// Avoids require() which bundlers convert to createRequire() that crashes on CF Workers.\nlet _fs: typeof import(\"fs\") | undefined;\nasync function getFs(): Promise<typeof import(\"fs\")> {\n if (!_fs) {\n _fs = await import(\"node:fs\");\n }\n return _fs;\n}\nimport { fileURLToPath } from \"node:url\";\n\n/** Files to skip during auto-discovery (no extension). */\nconst SKIP_FILES = new Set([\n \"helpers\",\n \"run\",\n \"db-connect\",\n \"db-status\",\n \"registry\",\n]);\n\n/**\n * Global registry of actions contributed by published packages\n * (e.g. `@agent-native/dispatch`). Populated by `registerPackageActions()`\n * which the package calls from import side effects, then merged into\n * `autoDiscoverActions` after the template's local `actions/` directory.\n *\n * Ordering: template `actions/` files always win on name collision so\n * consumers can override a packaged action by dropping a same-named file\n * in their own `actions/` dir.\n */\nconst packageActionRegistry: Record<string, ActionEntry> = {};\n\n/**\n * Register a map of actions contributed by a published package.\n *\n * Called from a package's server entrypoint via import side effects:\n * ```ts\n * // packages/dispatch/src/server/index.ts\n * import { registerPackageActions } from \"@agent-native/core/server\";\n * import { actions } from \"../actions/index.js\";\n * registerPackageActions(actions);\n * ```\n *\n * Idempotent — re-registering the same name from the same import is a no-op\n * so HMR / repeated dynamic imports don't double-warn.\n */\nexport function registerPackageActions(\n actions: Record<string, ActionEntry>,\n): void {\n for (const [name, entry] of Object.entries(actions)) {\n if (packageActionRegistry[name]) continue;\n packageActionRegistry[name] = entry;\n }\n}\n\n/** Internal — used by `autoDiscoverActions`. Returns a shallow copy. */\nfunction getPackageActions(): Record<string, ActionEntry> {\n return { ...packageActionRegistry };\n}\n\n/**\n * Split a string into shell-like tokens, handling double and single quotes.\n * `--title \"My Page\" --content \"\"` → `[\"--title\", \"My Page\", \"--content\", \"\"]`\n */\nfunction splitShellArgs(input: string): string[] {\n const tokens: string[] = [];\n let current = \"\";\n let inDouble = false;\n let inSingle = false;\n let wasQuoted = false;\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i];\n if (ch === '\"' && !inSingle) {\n inDouble = !inDouble;\n wasQuoted = true;\n continue;\n }\n if (ch === \"'\" && !inDouble) {\n inSingle = !inSingle;\n wasQuoted = true;\n continue;\n }\n if ((ch === \" \" || ch === \"\\t\") && !inDouble && !inSingle) {\n if (current.length > 0 || wasQuoted) {\n tokens.push(current);\n }\n current = \"\";\n wasQuoted = false;\n continue;\n }\n current += ch;\n }\n if (current.length > 0 || wasQuoted) {\n tokens.push(current);\n }\n return tokens;\n}\n\n/**\n * Wrap a CLI-style action (that writes to console.log) as an ActionEntry\n * by capturing stdout/stderr and intercepting process.exit. Uses the\n * shared AsyncLocalStorage-backed capture so concurrent invocations do\n * not corrupt the global `console.log` / `process.stdout.write` /\n * `process.exit` pointers (see `cli-capture.ts`).\n */\nfunction wrapDefaultExport(\n name: string,\n defaultFn: (args: string[]) => Promise<void>,\n): ActionEntry {\n const tool: ActionTool = {\n description: `Run the \"${name}\" action. Pass arguments as key-value pairs.`,\n parameters: {\n type: \"object\",\n properties: {\n args: {\n type: \"string\",\n description:\n \"Space-separated CLI arguments (e.g. '--id abc --title Hello')\",\n },\n },\n },\n };\n\n return {\n tool,\n run: async (args: Record<string, string>): Promise<string> => {\n const cliArgs: string[] = [];\n // If only an \"args\" key was provided, split it into CLI tokens\n if (args.args && Object.keys(args).length === 1) {\n cliArgs.push(...splitShellArgs(args.args));\n } else {\n for (const [k, v] of Object.entries(args)) {\n cliArgs.push(`--${k}`, v);\n }\n }\n return captureCliOutput(() => defaultFn(cliArgs));\n },\n };\n}\n\nfunction preserveActionFlags(entry: Record<string, any>): Partial<ActionEntry> {\n const out: Partial<ActionEntry> = {};\n if (typeof entry.readOnly === \"boolean\") out.readOnly = entry.readOnly;\n if (typeof entry.parallelSafe === \"boolean\") {\n out.parallelSafe = entry.parallelSafe;\n }\n if (typeof entry.toolCallable === \"boolean\") {\n out.toolCallable = entry.toolCallable;\n }\n if (\n entry.publicAgent &&\n typeof entry.publicAgent === \"object\" &&\n !Array.isArray(entry.publicAgent)\n ) {\n out.publicAgent = entry.publicAgent;\n }\n return out;\n}\n\n/**\n * Resolve the actions directory from the caller's context.\n *\n * @param from - Either an `import.meta.url` (file:// URL from a plugin file),\n * an absolute directory path, or \"auto\" to use `process.cwd() + \"/actions\"`.\n * When an import.meta.url is provided, the actions directory is resolved as\n * `../../actions/` relative to the caller (typically `server/plugins/agent-chat.ts`).\n * If the resolved directory doesn't exist, falls back to `../../scripts/` for\n * backwards compatibility, then to `process.cwd() + \"/actions\"`.\n */\nasync function resolveActionsDir(from: string): Promise<string> {\n const fs = await getFs();\n const exists = (p: string) => {\n try {\n return fs.existsSync(p);\n } catch {\n return false;\n }\n };\n // On edge runtimes (e.g. Cloudflare Workers), import.meta.url may be\n // undefined after bundling. Fall back to cwd-based discovery.\n if (!from) {\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n if (from.startsWith(\"file://\") || from.startsWith(\"file:///\")) {\n const callerPath = fileURLToPath(from);\n const callerDir = nodePath.dirname(callerPath);\n const actionsResolved = nodePath.resolve(callerDir, \"../../actions\");\n if (exists(actionsResolved)) return actionsResolved;\n const scriptsResolved = nodePath.resolve(callerDir, \"../../scripts\");\n if (exists(scriptsResolved)) return scriptsResolved;\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n if (from === \"auto\") {\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n return nodePath.resolve(from);\n}\n\n/**\n * Load actions from a single directory into the given registry. Shared by\n * both the template-actions discovery path and the workspace-core actions\n * layer. When `skipExisting` is true, an entry with the same name that's\n * already in the registry is left untouched (template-wins on collision).\n */\nasync function loadActionsIntoRegistry(\n actionsDir: string,\n registry: Record<string, ActionEntry>,\n skipExisting: boolean,\n): Promise<void> {\n let files: string[];\n try {\n const fs = await getFs();\n if (!fs.existsSync(actionsDir)) return;\n files = fs.readdirSync(actionsDir);\n } catch {\n return;\n }\n\n const actionFiles = files.filter((f) => {\n if (!f.endsWith(\".ts\") && !f.endsWith(\".js\")) return false;\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (name.startsWith(\"_\")) return false;\n if (SKIP_FILES.has(name)) return false;\n return true;\n });\n\n for (const file of actionFiles) {\n const name = file.replace(/\\.(ts|js)$/, \"\");\n if (skipExisting && registry[name]) continue;\n\n const filePath = nodePath.join(actionsDir, file);\n try {\n const mod = await import(/* @vite-ignore */ filePath);\n\n if (mod.tool && typeof mod.run === \"function\") {\n registry[name] = {\n tool: mod.tool,\n run: mod.run,\n ...(mod.http !== undefined ? { http: mod.http } : {}),\n ...preserveActionFlags(mod),\n };\n } else if (\n mod.default &&\n typeof mod.default === \"object\" &&\n mod.default.tool &&\n typeof mod.default.run === \"function\"\n ) {\n registry[name] = {\n tool: mod.default.tool,\n run: mod.default.run,\n ...(mod.default.http !== undefined ? { http: mod.default.http } : {}),\n ...preserveActionFlags(mod.default),\n };\n } else if (typeof mod.default === \"function\") {\n registry[name] = wrapDefaultExport(name, mod.default);\n }\n } catch {\n // CLI-style scripts (top-level execution) throw on import.\n // Expected — they're available via `pnpm action <name>` / shell instead.\n }\n }\n}\n\n/**\n * Normalize a pre-bundled static action registry (name → raw module) into\n * the `Record<string, ActionEntry>` shape the agent-chat plugin expects.\n *\n * Used by `autoDiscoverActions` when `.generated/actions-registry.ts` is\n * present so that Nitro-bundled serverless functions (Netlify, Vercel,\n * AWS-Lambda) can serve `/_agent-native/actions/*` routes without relying\n * on a filesystem scan that doesn't work in bundled output.\n */\nexport function loadActionsFromStaticRegistry(\n modules: Record<string, unknown>,\n): Record<string, ActionEntry> {\n const registry: Record<string, ActionEntry> = {};\n for (const [name, raw] of Object.entries(modules)) {\n const mod = raw as Record<string, any> | null | undefined;\n if (!mod) continue;\n\n if (mod.tool && typeof mod.run === \"function\") {\n registry[name] = {\n tool: mod.tool,\n run: mod.run,\n ...(mod.http !== undefined ? { http: mod.http } : {}),\n ...preserveActionFlags(mod),\n };\n continue;\n }\n\n const def = mod.default;\n if (\n def &&\n typeof def === \"object\" &&\n def.tool &&\n typeof def.run === \"function\"\n ) {\n registry[name] = {\n tool: def.tool,\n run: def.run,\n ...(def.http !== undefined ? { http: def.http } : {}),\n ...preserveActionFlags(def),\n };\n continue;\n }\n\n if (typeof def === \"function\") {\n registry[name] = wrapDefaultExport(name, def);\n }\n }\n return registry;\n}\n\n/**\n * Auto-discover actions from a directory.\n *\n * Merges in any actions from the enterprise workspace core (if present in\n * the ancestor chain). Template actions take precedence over workspace-core\n * actions on name collision, so an app can override an enterprise-wide\n * action by dropping a same-named file under its own `actions/`.\n *\n * Note: this helper uses a filesystem scan, which works in dev and in\n * non-bundled Node deployments. In bundled serverless functions (Nitro's\n * netlify / vercel / aws-lambda presets) the `actions/` directory is not\n * on disk at runtime; templates should pass the static registry generated\n * by the Vite plugin to `createAgentChatPlugin({ actions })` instead, so\n * the bundler sees static imports and pulls every action into the bundle.\n *\n * @param from - The caller's `import.meta.url` or an absolute path to the\n * actions directory.\n * @returns A record mapping action names to ActionEntry objects, suitable for\n * passing to `createAgentChatPlugin({ actions })`.\n */\nexport async function autoDiscoverActions(\n from: string,\n): Promise<Record<string, ActionEntry>> {\n const actionsDir = await resolveActionsDir(from);\n const registry: Record<string, ActionEntry> = {};\n\n // 1. Template actions first — these are the authoritative layer for the\n // current app and must override any workspace-core entry with the same\n // name.\n try {\n await loadActionsIntoRegistry(actionsDir, registry, false);\n } catch (err: any) {\n console.warn(\n `[autoDiscoverActions] Could not read actions directory: ${actionsDir} — ${err?.message}`,\n );\n }\n\n // 1b. Fallback: if filesystem discovery found no template actions (common\n // in bundled serverless environments like Netlify/Vercel where the\n // actions/ directory doesn't exist on disk), try importing the\n // generated static registry at .generated/actions-registry.\n //\n // This prevents the silent-empty-tools footgun where the agent has no\n // template actions and falls back to generic tools like web-request.\n // Prefer `loadActionsFromStaticRegistry` over `autoDiscoverActions` for\n // production reliability — this fallback is a safety net, not the\n // primary path.\n if (Object.keys(registry).length === 0 && from) {\n try {\n let registryPath: string;\n if (from.startsWith(\"file://\") || from.startsWith(\"file:///\")) {\n const callerDir = nodePath.dirname(fileURLToPath(from));\n registryPath = nodePath.resolve(\n callerDir,\n \"../../.generated/actions-registry.js\",\n );\n } else {\n registryPath = nodePath.resolve(\n from,\n \"../.generated/actions-registry.js\",\n );\n }\n const mod = await import(/* @vite-ignore */ registryPath);\n const staticEntries = loadActionsFromStaticRegistry(mod.default || mod);\n Object.assign(registry, staticEntries);\n if (Object.keys(staticEntries).length > 0) {\n console.log(\n `[autoDiscoverActions] Filesystem scan found 0 actions — loaded ${Object.keys(staticEntries).length} from .generated/actions-registry.ts instead. ` +\n `Consider switching to loadActionsFromStaticRegistry(actionsRegistry) for production reliability.`,\n );\n }\n } catch {\n // No generated registry available — registry stays empty.\n }\n }\n\n // If still empty after all fallbacks, warn loudly.\n if (Object.keys(registry).length === 0) {\n console.warn(\n `[autoDiscoverActions] WARNING: No template actions found! ` +\n `The agent will have no template-specific tools. ` +\n `If in production, switch from autoDiscoverActions to loadActionsFromStaticRegistry. ` +\n `See: https://docs.agent-native.com/actions#static-registry`,\n );\n }\n\n // 1c. Package-registered actions — contributed by published packages\n // (e.g. @agent-native/dispatch) via `registerPackageActions()` from\n // import side effects. Merged with skip-existing so the template's\n // own actions/ files always win on name collision.\n for (const [name, entry] of Object.entries(getPackageActions())) {\n if (registry[name]) continue;\n registry[name] = entry;\n }\n\n // 2. Workspace-core actions — merged in with skipExisting so they can't\n // overwrite template entries.\n try {\n const { getWorkspaceCoreExports } =\n await import(\"../deploy/workspace-core.js\");\n const ws = await getWorkspaceCoreExports(process.cwd());\n if (ws && ws.actionsDir) {\n await loadActionsIntoRegistry(ws.actionsDir, registry, true);\n }\n } catch {\n // workspace-core discovery unavailable (e.g. edge runtime) — skip.\n }\n\n // 3. Framework-level sharing + file-upload actions — always available to any\n // template. Merged with skipExisting so templates can override by\n // providing a same-named file.\n try {\n await mergeCoreSharingActions(registry);\n } catch {\n // Ignore — templates without sharing still work.\n }\n\n return registry;\n}\n\nexport async function mergeCoreSharingActions(\n registry: Record<string, ActionEntry>,\n): Promise<void> {\n const entries: Array<[string, () => Promise<any>]> = [\n [\"share-resource\", () => import(\"../sharing/actions/share-resource.js\")],\n [\n \"unshare-resource\",\n () => import(\"../sharing/actions/unshare-resource.js\"),\n ],\n [\n \"list-resource-shares\",\n () => import(\"../sharing/actions/list-resource-shares.js\"),\n ],\n [\n \"set-resource-visibility\",\n () => import(\"../sharing/actions/set-resource-visibility.js\"),\n ],\n [\"upload-image\", () => import(\"../file-upload/actions/upload-image.js\")],\n [\n \"change-appearance\",\n () => import(\"../appearance/actions/change-appearance.js\"),\n ],\n ];\n for (const [name, loader] of entries) {\n if (registry[name]) continue;\n try {\n const mod = await loader();\n const def = mod.default;\n if (def && def.tool && typeof def.run === \"function\") {\n registry[name] = {\n tool: def.tool,\n run: def.run,\n ...(def.http !== undefined ? { http: def.http } : {}),\n ...(def.readOnly === true ? { readOnly: true } : {}),\n ...(def.parallelSafe === true ? { parallelSafe: true } : {}),\n };\n }\n } catch {\n // Skip any sharing action that fails to import.\n }\n }\n}\n\n/** @deprecated Use `autoDiscoverActions` instead */\nexport const autoDiscoverScripts = autoDiscoverActions;\n"]}
1
+ {"version":3,"file":"action-discovery.js","sourceRoot":"","sources":["../../src/server/action-discovery.ts"],"names":[],"mappings":"AA6BA,OAAO,QAAQ,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEpD,sDAAsD;AACtD,yFAAyF;AACzF,IAAI,GAAoC,CAAC;AACzC,KAAK,UAAU,KAAK;IAClB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,GAAG,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AACD,OAAO,EAAE,aAAa,EAAE,MAAM,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AE,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACrC,IAAI,QAAQ,CAAC,IAAI,CAAC;YAAE,SAAS;QAC7B,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,MAAM,EAAE,CAAC;YAC3B,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC;YACxB,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,IAAI,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU,EAAE,CAAC;gBACrD,QAAQ,CAAC,IAAI,CAAC,GAAG;oBACf,IAAI,EAAE,GAAG,CAAC,IAAI;oBACd,GAAG,EAAE,GAAG,CAAC,GAAG;oBACZ,GAAG,CAAC,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACrD,GAAG,CAAC,GAAG,CAAC,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACpD,GAAG,CAAC,GAAG,CAAC,YAAY,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBAC7D,CAAC;YACJ,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,gDAAgD;QAClD,CAAC;IACH,CAAC;AACH,CAAC;AAED,oDAAoD;AACpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * Auto-discover actions from a template's actions/ directory.\n *\n * Scans for .ts/.js files and builds an action registry suitable for\n * `createAgentChatPlugin({ actions })`.\n *\n * Supports two action conventions:\n *\n * 1. **Full interface** — exports `tool: ActionTool` and `run(args): Promise<string>`.\n * These are used directly.\n *\n * 2. **CLI-style** — exports only `default async function(args: string[])`.\n * These are wrapped: args are converted from `Record<string, string>` to\n * `[\"--key\", \"value\", ...]`, console output is captured, and a tool\n * definition is synthesized from the action name.\n *\n * 3. **defineAction** — exports `default` from `defineAction()`. Has `tool` and `run`.\n *\n * Usage in agent-chat plugins:\n * ```ts\n * import { autoDiscoverActions } from \"@agent-native/core/server\";\n *\n * export default createAgentChatPlugin({\n * actions: () => autoDiscoverActions(import.meta.url),\n * });\n * ```\n */\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport nodePath from \"node:path\";\nimport { captureCliOutput } from \"./cli-capture.js\";\n\n// Lazy fs — loaded via dynamic import() on first use.\n// Avoids require() which bundlers convert to createRequire() that crashes on CF Workers.\nlet _fs: typeof import(\"fs\") | undefined;\nasync function getFs(): Promise<typeof import(\"fs\")> {\n if (!_fs) {\n _fs = await import(\"node:fs\");\n }\n return _fs;\n}\nimport { fileURLToPath } from \"node:url\";\n\n/** Files to skip during auto-discovery (no extension). */\nconst SKIP_FILES = new Set([\n \"helpers\",\n \"run\",\n \"db-connect\",\n \"db-status\",\n \"registry\",\n]);\n\n/**\n * Global registry of actions contributed by published packages\n * (e.g. `@agent-native/dispatch`). Populated by `registerPackageActions()`\n * which the package calls from import side effects, then merged into\n * `autoDiscoverActions` after the template's local `actions/` directory.\n *\n * Ordering: template `actions/` files always win on name collision so\n * consumers can override a packaged action by dropping a same-named file\n * in their own `actions/` dir.\n */\nconst packageActionRegistry: Record<string, ActionEntry> = {};\n\n/**\n * Register a map of actions contributed by a published package.\n *\n * Called from a package's server entrypoint via import side effects:\n * ```ts\n * // packages/dispatch/src/server/index.ts\n * import { registerPackageActions } from \"@agent-native/core/server\";\n * import { actions } from \"../actions/index.js\";\n * registerPackageActions(actions);\n * ```\n *\n * Idempotent — re-registering the same name from the same import is a no-op\n * so HMR / repeated dynamic imports don't double-warn.\n */\nexport function registerPackageActions(\n actions: Record<string, ActionEntry>,\n): void {\n for (const [name, entry] of Object.entries(actions)) {\n if (packageActionRegistry[name]) continue;\n packageActionRegistry[name] = entry;\n }\n}\n\n/** Internal — used by `autoDiscoverActions`. Returns a shallow copy. */\nfunction getPackageActions(): Record<string, ActionEntry> {\n return { ...packageActionRegistry };\n}\n\n/**\n * Split a string into shell-like tokens, handling double and single quotes.\n * `--title \"My Page\" --content \"\"` → `[\"--title\", \"My Page\", \"--content\", \"\"]`\n */\nfunction splitShellArgs(input: string): string[] {\n const tokens: string[] = [];\n let current = \"\";\n let inDouble = false;\n let inSingle = false;\n let wasQuoted = false;\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i];\n if (ch === '\"' && !inSingle) {\n inDouble = !inDouble;\n wasQuoted = true;\n continue;\n }\n if (ch === \"'\" && !inDouble) {\n inSingle = !inSingle;\n wasQuoted = true;\n continue;\n }\n if ((ch === \" \" || ch === \"\\t\") && !inDouble && !inSingle) {\n if (current.length > 0 || wasQuoted) {\n tokens.push(current);\n }\n current = \"\";\n wasQuoted = false;\n continue;\n }\n current += ch;\n }\n if (current.length > 0 || wasQuoted) {\n tokens.push(current);\n }\n return tokens;\n}\n\n/**\n * Wrap a CLI-style action (that writes to console.log) as an ActionEntry\n * by capturing stdout/stderr and intercepting process.exit. Uses the\n * shared AsyncLocalStorage-backed capture so concurrent invocations do\n * not corrupt the global `console.log` / `process.stdout.write` /\n * `process.exit` pointers (see `cli-capture.ts`).\n */\nfunction wrapDefaultExport(\n name: string,\n defaultFn: (args: string[]) => Promise<void>,\n): ActionEntry {\n const tool: ActionTool = {\n description: `Run the \"${name}\" action. Pass arguments as key-value pairs.`,\n parameters: {\n type: \"object\",\n properties: {\n args: {\n type: \"string\",\n description:\n \"Space-separated CLI arguments (e.g. '--id abc --title Hello')\",\n },\n },\n },\n };\n\n return {\n tool,\n run: async (args: Record<string, string>): Promise<string> => {\n const cliArgs: string[] = [];\n // If only an \"args\" key was provided, split it into CLI tokens\n if (args.args && Object.keys(args).length === 1) {\n cliArgs.push(...splitShellArgs(args.args));\n } else {\n for (const [k, v] of Object.entries(args)) {\n cliArgs.push(`--${k}`, v);\n }\n }\n return captureCliOutput(() => defaultFn(cliArgs));\n },\n };\n}\n\nfunction preserveActionFlags(entry: Record<string, any>): Partial<ActionEntry> {\n const out: Partial<ActionEntry> = {};\n if (typeof entry.readOnly === \"boolean\") out.readOnly = entry.readOnly;\n if (typeof entry.parallelSafe === \"boolean\") {\n out.parallelSafe = entry.parallelSafe;\n }\n if (typeof entry.toolCallable === \"boolean\") {\n out.toolCallable = entry.toolCallable;\n }\n if (\n entry.publicAgent &&\n typeof entry.publicAgent === \"object\" &&\n !Array.isArray(entry.publicAgent)\n ) {\n out.publicAgent = entry.publicAgent;\n }\n return out;\n}\n\n/**\n * Resolve the actions directory from the caller's context.\n *\n * @param from - Either an `import.meta.url` (file:// URL from a plugin file),\n * an absolute directory path, or \"auto\" to use `process.cwd() + \"/actions\"`.\n * When an import.meta.url is provided, the actions directory is resolved as\n * `../../actions/` relative to the caller (typically `server/plugins/agent-chat.ts`).\n * If the resolved directory doesn't exist, falls back to `../../scripts/` for\n * backwards compatibility, then to `process.cwd() + \"/actions\"`.\n */\nasync function resolveActionsDir(from: string): Promise<string> {\n const fs = await getFs();\n const exists = (p: string) => {\n try {\n return fs.existsSync(p);\n } catch {\n return false;\n }\n };\n // On edge runtimes (e.g. Cloudflare Workers), import.meta.url may be\n // undefined after bundling. Fall back to cwd-based discovery.\n if (!from) {\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n if (from.startsWith(\"file://\") || from.startsWith(\"file:///\")) {\n const callerPath = fileURLToPath(from);\n const callerDir = nodePath.dirname(callerPath);\n const actionsResolved = nodePath.resolve(callerDir, \"../../actions\");\n if (exists(actionsResolved)) return actionsResolved;\n const scriptsResolved = nodePath.resolve(callerDir, \"../../scripts\");\n if (exists(scriptsResolved)) return scriptsResolved;\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n if (from === \"auto\") {\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n return nodePath.resolve(from);\n}\n\n/**\n * Load actions from a single directory into the given registry. Shared by\n * both the template-actions discovery path and the workspace-core actions\n * layer. When `skipExisting` is true, an entry with the same name that's\n * already in the registry is left untouched (template-wins on collision).\n */\nasync function loadActionsIntoRegistry(\n actionsDir: string,\n registry: Record<string, ActionEntry>,\n skipExisting: boolean,\n): Promise<void> {\n let files: string[];\n try {\n const fs = await getFs();\n if (!fs.existsSync(actionsDir)) return;\n files = fs.readdirSync(actionsDir);\n } catch {\n return;\n }\n\n const actionFiles = files.filter((f) => {\n if (!f.endsWith(\".ts\") && !f.endsWith(\".js\")) return false;\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (name.startsWith(\"_\")) return false;\n if (SKIP_FILES.has(name)) return false;\n return true;\n });\n\n for (const file of actionFiles) {\n const name = file.replace(/\\.(ts|js)$/, \"\");\n if (skipExisting && registry[name]) continue;\n\n const filePath = nodePath.join(actionsDir, file);\n try {\n const mod = await import(/* @vite-ignore */ filePath);\n\n if (mod.tool && typeof mod.run === \"function\") {\n registry[name] = {\n tool: mod.tool,\n run: mod.run,\n ...(mod.http !== undefined ? { http: mod.http } : {}),\n ...preserveActionFlags(mod),\n };\n } else if (\n mod.default &&\n typeof mod.default === \"object\" &&\n mod.default.tool &&\n typeof mod.default.run === \"function\"\n ) {\n registry[name] = {\n tool: mod.default.tool,\n run: mod.default.run,\n ...(mod.default.http !== undefined ? { http: mod.default.http } : {}),\n ...preserveActionFlags(mod.default),\n };\n } else if (typeof mod.default === \"function\") {\n registry[name] = wrapDefaultExport(name, mod.default);\n }\n } catch {\n // CLI-style scripts (top-level execution) throw on import.\n // Expected — they're available via `pnpm action <name>` / shell instead.\n }\n }\n}\n\n/**\n * Normalize a pre-bundled static action registry (name → raw module) into\n * the `Record<string, ActionEntry>` shape the agent-chat plugin expects.\n *\n * Used by `autoDiscoverActions` when `.generated/actions-registry.ts` is\n * present so that Nitro-bundled serverless functions (Netlify, Vercel,\n * AWS-Lambda) can serve `/_agent-native/actions/*` routes without relying\n * on a filesystem scan that doesn't work in bundled output.\n */\nexport function loadActionsFromStaticRegistry(\n modules: Record<string, unknown>,\n): Record<string, ActionEntry> {\n const registry: Record<string, ActionEntry> = {};\n for (const [name, raw] of Object.entries(modules)) {\n const mod = raw as Record<string, any> | null | undefined;\n if (!mod) continue;\n\n if (mod.tool && typeof mod.run === \"function\") {\n registry[name] = {\n tool: mod.tool,\n run: mod.run,\n ...(mod.http !== undefined ? { http: mod.http } : {}),\n ...preserveActionFlags(mod),\n };\n continue;\n }\n\n const def = mod.default;\n if (\n def &&\n typeof def === \"object\" &&\n def.tool &&\n typeof def.run === \"function\"\n ) {\n registry[name] = {\n tool: def.tool,\n run: def.run,\n ...(def.http !== undefined ? { http: def.http } : {}),\n ...preserveActionFlags(def),\n };\n continue;\n }\n\n if (typeof def === \"function\") {\n registry[name] = wrapDefaultExport(name, def);\n }\n }\n return registry;\n}\n\n/**\n * Auto-discover actions from a directory.\n *\n * Merges in any actions from the enterprise workspace core (if present in\n * the ancestor chain). Template actions take precedence over workspace-core\n * actions on name collision, so an app can override an enterprise-wide\n * action by dropping a same-named file under its own `actions/`.\n *\n * Note: this helper uses a filesystem scan, which works in dev and in\n * non-bundled Node deployments. In bundled serverless functions (Nitro's\n * netlify / vercel / aws-lambda presets) the `actions/` directory is not\n * on disk at runtime; templates should pass the static registry generated\n * by the Vite plugin to `createAgentChatPlugin({ actions })` instead, so\n * the bundler sees static imports and pulls every action into the bundle.\n *\n * @param from - The caller's `import.meta.url` or an absolute path to the\n * actions directory.\n * @returns A record mapping action names to ActionEntry objects, suitable for\n * passing to `createAgentChatPlugin({ actions })`.\n */\nexport async function autoDiscoverActions(\n from: string,\n): Promise<Record<string, ActionEntry>> {\n const actionsDir = await resolveActionsDir(from);\n const registry: Record<string, ActionEntry> = {};\n\n // 1. Template actions first — these are the authoritative layer for the\n // current app and must override any workspace-core entry with the same\n // name.\n try {\n await loadActionsIntoRegistry(actionsDir, registry, false);\n } catch (err: any) {\n console.warn(\n `[autoDiscoverActions] Could not read actions directory: ${actionsDir} — ${err?.message}`,\n );\n }\n\n // 1b. Fallback: if filesystem discovery found no template actions (common\n // in bundled serverless environments like Netlify/Vercel where the\n // actions/ directory doesn't exist on disk), try importing the\n // generated static registry at .generated/actions-registry.\n //\n // This prevents the silent-empty-tools footgun where the agent has no\n // template actions and falls back to generic tools like web-request.\n // Prefer `loadActionsFromStaticRegistry` over `autoDiscoverActions` for\n // production reliability — this fallback is a safety net, not the\n // primary path.\n if (Object.keys(registry).length === 0 && from) {\n try {\n let registryPath: string;\n if (from.startsWith(\"file://\") || from.startsWith(\"file:///\")) {\n const callerDir = nodePath.dirname(fileURLToPath(from));\n registryPath = nodePath.resolve(\n callerDir,\n \"../../.generated/actions-registry.js\",\n );\n } else {\n registryPath = nodePath.resolve(\n from,\n \"../.generated/actions-registry.js\",\n );\n }\n const mod = await import(/* @vite-ignore */ registryPath);\n const staticEntries = loadActionsFromStaticRegistry(mod.default || mod);\n Object.assign(registry, staticEntries);\n if (Object.keys(staticEntries).length > 0) {\n console.log(\n `[autoDiscoverActions] Filesystem scan found 0 actions — loaded ${Object.keys(staticEntries).length} from .generated/actions-registry.ts instead. ` +\n `Consider switching to loadActionsFromStaticRegistry(actionsRegistry) for production reliability.`,\n );\n }\n } catch {\n // No generated registry available — registry stays empty.\n }\n }\n\n // If still empty after all fallbacks, warn loudly.\n if (Object.keys(registry).length === 0) {\n console.warn(\n `[autoDiscoverActions] WARNING: No template actions found! ` +\n `The agent will have no template-specific tools. ` +\n `If in production, switch from autoDiscoverActions to loadActionsFromStaticRegistry. ` +\n `See: https://docs.agent-native.com/actions#static-registry`,\n );\n }\n\n // 1c. Package-registered actions — contributed by published packages\n // (e.g. @agent-native/dispatch) via `registerPackageActions()` from\n // import side effects. Merged with skip-existing so the template's\n // own actions/ files always win on name collision.\n for (const [name, entry] of Object.entries(getPackageActions())) {\n if (registry[name]) continue;\n registry[name] = entry;\n }\n\n // 2. Workspace-core actions — merged in with skipExisting so they can't\n // overwrite template entries.\n try {\n const { getWorkspaceCoreExports } =\n await import(\"../deploy/workspace-core.js\");\n const ws = await getWorkspaceCoreExports(process.cwd());\n if (ws && ws.actionsDir) {\n await loadActionsIntoRegistry(ws.actionsDir, registry, true);\n }\n } catch {\n // workspace-core discovery unavailable (e.g. edge runtime) — skip.\n }\n\n // 3. Framework-level sharing + file-upload actions — always available to any\n // template. Merged with skipExisting so templates can override by\n // providing a same-named file.\n try {\n await mergeCoreSharingActions(registry);\n } catch {\n // Ignore — templates without sharing still work.\n }\n\n return registry;\n}\n\nexport async function mergeCoreSharingActions(\n registry: Record<string, ActionEntry>,\n): Promise<void> {\n const entries: Array<[string, () => Promise<any>]> = [\n [\"share-resource\", () => import(\"../sharing/actions/share-resource.js\")],\n [\n \"unshare-resource\",\n () => import(\"../sharing/actions/unshare-resource.js\"),\n ],\n [\n \"list-resource-shares\",\n () => import(\"../sharing/actions/list-resource-shares.js\"),\n ],\n [\n \"set-resource-visibility\",\n () => import(\"../sharing/actions/set-resource-visibility.js\"),\n ],\n [\"upload-image\", () => import(\"../file-upload/actions/upload-image.js\")],\n [\n \"change-appearance\",\n () => import(\"../appearance/actions/change-appearance.js\"),\n ],\n [\"toggle-demo-mode\", () => import(\"../demo/actions/toggle-demo-mode.js\")],\n ];\n for (const [name, loader] of entries) {\n if (registry[name]) continue;\n try {\n const mod = await loader();\n const def = mod.default;\n if (def && def.tool && typeof def.run === \"function\") {\n registry[name] = {\n tool: def.tool,\n run: def.run,\n ...(def.http !== undefined ? { http: def.http } : {}),\n ...(def.readOnly === true ? { readOnly: true } : {}),\n ...(def.parallelSafe === true ? { parallelSafe: true } : {}),\n };\n }\n } catch {\n // Skip any sharing action that fails to import.\n }\n }\n}\n\n/** @deprecated Use `autoDiscoverActions` instead */\nexport const autoDiscoverScripts = autoDiscoverActions;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/server/auth.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gCAAgC,CAAC;AAsChE,KAAK,KAAK,GAAG,SAAS,CAAC;AAQvB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAMlE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAwB5D,OAAO,EAIL,KAAK,oBAAoB,EAC1B,MAAM,qCAAqC,CAAC;AAS7C;;;GAGG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAEzC;AAMD,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,mFAAmF;IACnF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,oEAAoE;IACpE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,kEAAkE;IAClE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,WAAW;IAC1B,mDAAmD;IACnD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IAC7D;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB;;;;;;;;OAQG;IACH,oBAAoB,CAAC,EAAE,oBAAoB,CAAC;IAC5C;;;;OAIG;IACH,uBAAuB,CAAC,EAAE,MAAM,EAAE,CAAC;IACnC;;;OAGG;IACH,0BAA0B,CAAC,EAAE,MAAM,EAAE,CAAC;IACtC;;;;O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uery, getRequestIP, sendRedirect, setResponseHeader, setResponseStatus, getCookie, setCookie, deleteCookie, getHeader, } from "h3";
2
+ import { defineEventHandler, getMethod, getQuery, getRequestIP, setResponseHeader, setResponseStatus, getCookie, setCookie, deleteCookie, getHeader, } from "h3";
3
3
  // In h3 v2, `event.req` IS the web Request — but in Nitro's dev server (srvx
4
4
  // runtime), event.url and event.req share the same underlying URL object.
5
5
  // When registerMiddleware strips the mount prefix from event.url.pathname, it
@@ -1711,7 +1711,18 @@ async function mountBetterAuthRoutes(app, options) {
1711
1711
  });
1712
1712
  const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params}`;
1713
1713
  if (q.redirect === "1") {
1714
- return sendRedirect(event, authUrl, 302);
1714
+ // Return a native web Response — NOT h3 v2's `sendRedirect`. Under
1715
+ // h3 `2.0.1-rc.20`, `sendRedirect = (_, loc, code) => redirect(...)`
1716
+ // ignores the event and returns a non-standard `HTTPResponse` class
1717
+ // instance; the framework request-handler shim doesn't unwrap it and
1718
+ // String()-coerces it to the literal text "[object Object]" with a
1719
+ // 200 status (no Location header), which broke the popup-based
1720
+ // Google sign-in in production. Web `Response` is the proven idiom
1721
+ // here — `oauthCallbackResponse`/`oauthErrorPage` use it and work.
1722
+ return new Response(null, {
1723
+ status: 302,
1724
+ headers: { Location: authUrl },
1725
+ });
1715
1726
  }
1716
1727
  return { url: authUrl };
1717
1728
  }));