@agent-native/core 0.7.38 → 0.7.40
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.
- package/dist/cli/create.d.ts.map +1 -1
- package/dist/cli/create.js +19 -0
- package/dist/cli/create.js.map +1 -1
- package/dist/deploy/workspace-deploy.d.ts.map +1 -1
- package/dist/deploy/workspace-deploy.js +13 -0
- package/dist/deploy/workspace-deploy.js.map +1 -1
- package/dist/integrations/a2a-continuation-processor.d.ts.map +1 -1
- package/dist/integrations/a2a-continuation-processor.js +18 -2
- package/dist/integrations/a2a-continuation-processor.js.map +1 -1
- package/dist/integrations/adapters/slack.d.ts.map +1 -1
- package/dist/integrations/adapters/slack.js +21 -4
- package/dist/integrations/adapters/slack.js.map +1 -1
- package/dist/server/agent-discovery.d.ts.map +1 -1
- package/dist/server/agent-discovery.js +198 -0
- package/dist/server/agent-discovery.js.map +1 -1
- package/dist/server/framework-request-handler.d.ts.map +1 -1
- package/dist/server/framework-request-handler.js +6 -1
- package/dist/server/framework-request-handler.js.map +1 -1
- package/dist/server/onboarding-html.d.ts.map +1 -1
- package/dist/server/onboarding-html.js +6 -0
- package/dist/server/onboarding-html.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
1
4
|
import { TEMPLATES, visibleTemplates } from "../cli/templates-meta.js";
|
|
2
5
|
/**
|
|
3
6
|
* Built-in agent registry. Derive this from the published CLI metadata so
|
|
@@ -16,6 +19,8 @@ const BUILTIN_AGENTS = visibleTemplates()
|
|
|
16
19
|
color: template.color,
|
|
17
20
|
}));
|
|
18
21
|
const HIDDEN_FIRST_PARTY_AGENT_IDS = new Set(TEMPLATES.filter((template) => template.hidden && template.prodUrl).map((template) => template.name));
|
|
22
|
+
const WORKSPACE_APPS_ENV_KEY = "AGENT_NATIVE_WORKSPACE_APPS_JSON";
|
|
23
|
+
const WORKSPACE_APPS_MANIFEST_FILE = "workspace-apps.json";
|
|
19
24
|
/**
|
|
20
25
|
* Get built-in agents (static, no DB). Used as fallback and for seeding.
|
|
21
26
|
*/
|
|
@@ -91,6 +96,11 @@ export async function discoverAgents(selfAppId) {
|
|
|
91
96
|
catch {
|
|
92
97
|
// Resources not available — use built-ins only
|
|
93
98
|
}
|
|
99
|
+
// Overlay sibling workspace apps last so same-origin workspaces prefer the
|
|
100
|
+
// app mounted in this workspace over the public template with the same id.
|
|
101
|
+
for (const agent of discoverWorkspaceAgents(selfAppId)) {
|
|
102
|
+
agentsById.set(agent.id, agent);
|
|
103
|
+
}
|
|
94
104
|
return Array.from(agentsById.values());
|
|
95
105
|
}
|
|
96
106
|
/**
|
|
@@ -110,6 +120,194 @@ function resolveAgentUrl(app) {
|
|
|
110
120
|
}
|
|
111
121
|
return app.url;
|
|
112
122
|
}
|
|
123
|
+
function readJson(file) {
|
|
124
|
+
try {
|
|
125
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function findWorkspaceRoot(startDir = process.cwd()) {
|
|
132
|
+
let dir = path.resolve(startDir);
|
|
133
|
+
for (let i = 0; i < 20; i++) {
|
|
134
|
+
const pkg = readJson(path.join(dir, "package.json"));
|
|
135
|
+
if (typeof pkg?.["agent-native"]?.workspaceCore === "string") {
|
|
136
|
+
return dir;
|
|
137
|
+
}
|
|
138
|
+
const parent = path.dirname(dir);
|
|
139
|
+
if (parent === dir)
|
|
140
|
+
break;
|
|
141
|
+
dir = parent;
|
|
142
|
+
}
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
function titleCase(value) {
|
|
146
|
+
return value
|
|
147
|
+
.split(/[-_\s]+/)
|
|
148
|
+
.filter(Boolean)
|
|
149
|
+
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
150
|
+
.join(" ");
|
|
151
|
+
}
|
|
152
|
+
function parseWorkspaceAppsManifest(parsed) {
|
|
153
|
+
const rawApps = Array.isArray(parsed?.apps)
|
|
154
|
+
? parsed.apps
|
|
155
|
+
: Array.isArray(parsed)
|
|
156
|
+
? parsed
|
|
157
|
+
: null;
|
|
158
|
+
if (!rawApps)
|
|
159
|
+
return null;
|
|
160
|
+
const apps = rawApps
|
|
161
|
+
.map((entry) => {
|
|
162
|
+
if (!entry || typeof entry !== "object")
|
|
163
|
+
return null;
|
|
164
|
+
const id = typeof entry.id === "string" ? entry.id.trim() : "";
|
|
165
|
+
const pathValue = typeof entry.path === "string" ? entry.path.trim() : "";
|
|
166
|
+
if (!id || !pathValue.startsWith("/"))
|
|
167
|
+
return null;
|
|
168
|
+
return {
|
|
169
|
+
id,
|
|
170
|
+
name: typeof entry.name === "string" && entry.name.trim()
|
|
171
|
+
? entry.name.trim()
|
|
172
|
+
: titleCase(id),
|
|
173
|
+
description: typeof entry.description === "string" ? entry.description : "",
|
|
174
|
+
path: pathValue,
|
|
175
|
+
url: typeof entry.url === "string" && entry.url.trim()
|
|
176
|
+
? entry.url.trim()
|
|
177
|
+
: null,
|
|
178
|
+
isDispatch: typeof entry.isDispatch === "boolean"
|
|
179
|
+
? entry.isDispatch
|
|
180
|
+
: id === "dispatch",
|
|
181
|
+
};
|
|
182
|
+
})
|
|
183
|
+
.filter((app) => !!app)
|
|
184
|
+
.sort((a, b) => {
|
|
185
|
+
if (a.id === "dispatch")
|
|
186
|
+
return -1;
|
|
187
|
+
if (b.id === "dispatch")
|
|
188
|
+
return 1;
|
|
189
|
+
return a.name.localeCompare(b.name);
|
|
190
|
+
});
|
|
191
|
+
return apps.length ? apps : null;
|
|
192
|
+
}
|
|
193
|
+
function readWorkspaceAppsFromEnv() {
|
|
194
|
+
const raw = process.env[WORKSPACE_APPS_ENV_KEY];
|
|
195
|
+
if (!raw)
|
|
196
|
+
return null;
|
|
197
|
+
try {
|
|
198
|
+
return parseWorkspaceAppsManifest(JSON.parse(raw));
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function workspaceAppsManifestCandidates() {
|
|
205
|
+
const candidates = [];
|
|
206
|
+
try {
|
|
207
|
+
candidates.push(path.join(process.cwd(), ".agent-native", WORKSPACE_APPS_MANIFEST_FILE), path.join(process.cwd(), WORKSPACE_APPS_MANIFEST_FILE));
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
// Some edge runtimes do not expose process.cwd().
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
214
|
+
candidates.push(path.join(moduleDir, ".agent-native", WORKSPACE_APPS_MANIFEST_FILE), path.join(moduleDir, WORKSPACE_APPS_MANIFEST_FILE));
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
// Some edge runtimes expose non-file module URLs. The env manifest still
|
|
218
|
+
// works there, so skip file-relative candidates.
|
|
219
|
+
}
|
|
220
|
+
return candidates;
|
|
221
|
+
}
|
|
222
|
+
function readWorkspaceAppsFromManifestFile() {
|
|
223
|
+
for (const file of workspaceAppsManifestCandidates()) {
|
|
224
|
+
if (!fs.existsSync(file))
|
|
225
|
+
continue;
|
|
226
|
+
const apps = parseWorkspaceAppsManifest(readJson(file));
|
|
227
|
+
if (apps)
|
|
228
|
+
return apps;
|
|
229
|
+
}
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
function readWorkspaceAppsFromFilesystem() {
|
|
233
|
+
const workspaceRoot = findWorkspaceRoot();
|
|
234
|
+
if (!workspaceRoot)
|
|
235
|
+
return null;
|
|
236
|
+
const appsDir = path.join(workspaceRoot, "apps");
|
|
237
|
+
if (!fs.existsSync(appsDir))
|
|
238
|
+
return null;
|
|
239
|
+
const apps = fs
|
|
240
|
+
.readdirSync(appsDir, { withFileTypes: true })
|
|
241
|
+
.filter((entry) => entry.isDirectory())
|
|
242
|
+
.map((entry) => {
|
|
243
|
+
const appDir = path.join(appsDir, entry.name);
|
|
244
|
+
const pkg = readJson(path.join(appDir, "package.json"));
|
|
245
|
+
if (!pkg)
|
|
246
|
+
return null;
|
|
247
|
+
return {
|
|
248
|
+
id: entry.name,
|
|
249
|
+
name: pkg.displayName || titleCase(entry.name),
|
|
250
|
+
description: pkg.description || "",
|
|
251
|
+
path: `/${entry.name}`,
|
|
252
|
+
isDispatch: entry.name === "dispatch",
|
|
253
|
+
};
|
|
254
|
+
})
|
|
255
|
+
.filter((app) => !!app)
|
|
256
|
+
.sort((a, b) => {
|
|
257
|
+
if (a.id === "dispatch")
|
|
258
|
+
return -1;
|
|
259
|
+
if (b.id === "dispatch")
|
|
260
|
+
return 1;
|
|
261
|
+
return a.name.localeCompare(b.name);
|
|
262
|
+
});
|
|
263
|
+
return apps.length ? apps : null;
|
|
264
|
+
}
|
|
265
|
+
function workspaceBaseUrl() {
|
|
266
|
+
return (process.env.WORKSPACE_GATEWAY_URL ||
|
|
267
|
+
process.env.APP_URL ||
|
|
268
|
+
process.env.URL ||
|
|
269
|
+
process.env.DEPLOY_URL ||
|
|
270
|
+
process.env.BETTER_AUTH_URL ||
|
|
271
|
+
null);
|
|
272
|
+
}
|
|
273
|
+
function workspaceAppUrl(app) {
|
|
274
|
+
if (app.url)
|
|
275
|
+
return app.url;
|
|
276
|
+
const base = workspaceBaseUrl();
|
|
277
|
+
if (!base)
|
|
278
|
+
return null;
|
|
279
|
+
try {
|
|
280
|
+
return new URL(app.path, `${base.replace(/\/$/, "")}/`).toString();
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
function discoverWorkspaceAgents(selfAppId) {
|
|
287
|
+
const workspaceApps = readWorkspaceAppsFromEnv() ??
|
|
288
|
+
readWorkspaceAppsFromManifestFile() ??
|
|
289
|
+
readWorkspaceAppsFromFilesystem();
|
|
290
|
+
if (!workspaceApps)
|
|
291
|
+
return [];
|
|
292
|
+
return workspaceApps
|
|
293
|
+
.filter((app) => app.id !== selfAppId)
|
|
294
|
+
.map((app) => {
|
|
295
|
+
const url = workspaceAppUrl(app);
|
|
296
|
+
if (!url)
|
|
297
|
+
return null;
|
|
298
|
+
const builtin = BUILTIN_AGENTS.find((agent) => agent.id === app.id);
|
|
299
|
+
return {
|
|
300
|
+
id: app.id,
|
|
301
|
+
name: app.name,
|
|
302
|
+
description: app.description ||
|
|
303
|
+
builtin?.description ||
|
|
304
|
+
`Workspace app mounted at ${app.path}`,
|
|
305
|
+
url,
|
|
306
|
+
color: builtin?.color || "#6B7280",
|
|
307
|
+
};
|
|
308
|
+
})
|
|
309
|
+
.filter((agent) => !!agent);
|
|
310
|
+
}
|
|
113
311
|
/**
|
|
114
312
|
* Like `getBuiltinAgents`, but always returns the production URL — never the
|
|
115
313
|
* env-resolved devUrl. Used by the resource seeder so that a one-time seed
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-discovery.js","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAoBvE;;;;GAIG;AACH,MAAM,cAAc,GAAiB,gBAAgB,EAAE;KACpD,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC;KACxC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAClB,EAAE,EAAE,QAAQ,CAAC,IAAI;IACjB,IAAI,EAAE,QAAQ,CAAC,KAAK;IACpB,WAAW,EAAE,QAAQ,CAAC,WAAW,IAAI,QAAQ,CAAC,IAAI;IAClD,GAAG,EAAE,QAAQ,CAAC,OAAQ;IACtB,MAAM,EAAE,oBAAoB,QAAQ,CAAC,OAAO,EAAE;IAC9C,OAAO,EAAE,QAAQ,CAAC,O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AAE,CAAC;IACzD,CAAC;IACD,OAAO,GAAG,CAAC,GAAG,CAAC;AACjB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,0BAA0B,GACrC,cAAc,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACpD,EAAE,EAAE,GAAG,CAAC,EAAE;IACV,IAAI,EAAE,GAAG,CAAC,IAAI;IACd,WAAW,EAAE,GAAG,CAAC,WAAW;IAC5B,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc;IAC5B,KAAK,EAAE,GAAG,CAAC,KAAK;CACjB,CAAC,CAAC,CAAC","sourcesContent":["import { TEMPLATES, visibleTemplates } from \"../cli/templates-meta.js\";\n\nexport interface DiscoveredAgent {\n id: string;\n name: string;\n description: string;\n url: string;\n color: string;\n}\n\ninterface AgentEntry {\n id: string;\n name: string;\n description: string;\n url: string;\n devUrl?: string;\n devPort: number;\n color: string;\n}\n\n/**\n * Built-in agent registry. Derive this from the published CLI metadata so\n * connected-agent discovery stays aligned with the public template allow-list\n * without depending on @agent-native/shared-app-config at runtime.\n */\nconst BUILTIN_AGENTS: AgentEntry[] = visibleTemplates()\n .filter((template) => !!template.prodUrl)\n .map((template) => ({\n id: template.name,\n name: template.label,\n description: template.description ?? template.hint,\n url: template.prodUrl!,\n devUrl: `http://localhost:${template.devPort}`,\n devPort: template.devPort,\n color: template.color,\n }));\n\nconst HIDDEN_FIRST_PARTY_AGENT_IDS = new Set(\n TEMPLATES.filter((template) => template.hidden && template.prodUrl).map(\n (template) => template.name,\n ),\n);\n\n/**\n * Get built-in agents (static, no DB). Used as fallback and for seeding.\n */\nexport function getBuiltinAgents(selfAppId?: string): DiscoveredAgent[] {\n return BUILTIN_AGENTS.filter((app) => app.id !== selfAppId && app.url).map(\n (app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: resolveAgentUrl(app),\n color: app.color,\n }),\n );\n}\n\n/**\n * Discover all agents: built-in + custom agents stored as resources.\n * Custom agents override built-in agents with the same ID.\n */\nexport async function discoverAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const builtins = getBuiltinAgents(selfAppId);\n const agentsById = new Map<string, DiscoveredAgent>();\n\n // Start with built-ins\n for (const agent of builtins) {\n agentsById.set(agent.id, agent);\n }\n\n // Overlay custom agents from resources\n try {\n const { resourceList, resourceGet, SHARED_OWNER, resourceListAccessible } =\n await import(\"../resources/store.js\");\n const { DEV_MODE_USER_EMAIL } = await import(\"./auth.js\");\n\n const isDevMode =\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\";\n\n const resources = isDevMode\n ? await resourceListAccessible(DEV_MODE_USER_EMAIL, \"remote-agents/\")\n : await resourceList(SHARED_OWNER, \"remote-agents/\");\n const { parseRemoteAgentManifest } =\n await import(\"../resources/metadata.js\");\n\n for (const r of resources) {\n if (!r.path.endsWith(\".json\")) continue;\n try {\n const full = await resourceGet(r.id);\n if (!full) continue;\n const manifest = parseRemoteAgentManifest(full.content, r.path);\n if (!manifest || manifest.id === selfAppId) continue;\n if (HIDDEN_FIRST_PARTY_AGENT_IDS.has(manifest.id)) continue;\n\n // If the resource override carries a localhost URL but we're running\n // in production (e.g. a stale dev-time seed got promoted to the prod\n // DB), fall back to the matching built-in's prod URL instead of\n // letting the override win — otherwise outbound `call-agent` fetches\n // from a serverless function would target localhost and fail with\n // \"fetch failed\" instantly. The override still wins for non-localhost\n // URLs (the supported case for self-hosted custom agents).\n let url = manifest.url;\n if (\n !isDevMode &&\n typeof url === \"string\" &&\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0)(:|\\/|$)/.test(url)\n ) {\n const builtin = agentsById.get(manifest.id);\n if (builtin?.url) url = builtin.url;\n }\n\n agentsById.set(manifest.id, {\n id: manifest.id,\n name: manifest.name,\n description: manifest.description || \"\",\n url,\n color: manifest.color || \"#6B7280\",\n });\n } catch {\n // Skip unreadable resources\n }\n }\n } catch {\n // Resources not available — use built-ins only\n }\n\n return Array.from(agentsById.values());\n}\n\n/**\n * Look up a single agent by ID or name (case-insensitive).\n */\nexport async function findAgent(\n idOrName: string,\n selfAppId?: string,\n): Promise<DiscoveredAgent | undefined> {\n const lower = idOrName.toLowerCase();\n const agents = await discoverAgents(selfAppId);\n return agents.find((a) => a.id === lower || a.name.toLowerCase() === lower);\n}\n\nfunction isDevEnvironment(): boolean {\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n );\n}\n\nfunction resolveAgentUrl(app: AgentEntry): string {\n if (isDevEnvironment()) {\n return app.devUrl || `http://localhost:${app.devPort}`;\n }\n return app.url;\n}\n\n/**\n * Like `getBuiltinAgents`, but always returns the production URL — never the\n * env-resolved devUrl. Used by the resource seeder so that a one-time seed\n * (`ON CONFLICT DO NOTHING`) can't permanently bake a localhost URL into the\n * DB, which would override the built-in's prod URL for every later\n * production deploy.\n */\nexport const BUILTIN_AGENTS_FOR_SEEDING: DiscoveredAgent[] =\n BUILTIN_AGENTS.filter((app) => app.url).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: app.url, // ALWAYS prod\n color: app.color,\n }));\n"]}
|
|
1
|
+
{"version":3,"file":"agent-discovery.js","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAoBvE;;;;GAIG;AACH,MAAM,cAAc,GAAiB,gBAAgB,EAAE;KACpD,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC;KACxC,GAAG,CAAC,CAAC,QAAQ,E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, visibleTemplates } from \"../cli/templates-meta.js\";\n\nexport interface DiscoveredAgent {\n id: string;\n name: string;\n description: string;\n url: string;\n color: string;\n}\n\ninterface AgentEntry {\n id: string;\n name: string;\n description: string;\n url: string;\n devUrl?: string;\n devPort: number;\n color: string;\n}\n\n/**\n * Built-in agent registry. Derive this from the published CLI metadata so\n * connected-agent discovery stays aligned with the public template allow-list\n * without depending on @agent-native/shared-app-config at runtime.\n */\nconst BUILTIN_AGENTS: AgentEntry[] = visibleTemplates()\n .filter((template) => !!template.prodUrl)\n .map((template) => ({\n id: template.name,\n name: template.label,\n description: template.description ?? template.hint,\n url: template.prodUrl!,\n devUrl: `http://localhost:${template.devPort}`,\n devPort: template.devPort,\n color: template.color,\n }));\n\nconst HIDDEN_FIRST_PARTY_AGENT_IDS = new Set(\n TEMPLATES.filter((template) => template.hidden && template.prodUrl).map(\n (template) => template.name,\n ),\n);\n\nconst WORKSPACE_APPS_ENV_KEY = \"AGENT_NATIVE_WORKSPACE_APPS_JSON\";\nconst WORKSPACE_APPS_MANIFEST_FILE = \"workspace-apps.json\";\n\ninterface WorkspaceAppManifestEntry {\n id: string;\n name: string;\n description: string;\n path: string;\n url?: string | null;\n isDispatch?: boolean;\n}\n\n/**\n * Get built-in agents (static, no DB). Used as fallback and for seeding.\n */\nexport function getBuiltinAgents(selfAppId?: string): DiscoveredAgent[] {\n return BUILTIN_AGENTS.filter((app) => app.id !== selfAppId && app.url).map(\n (app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: resolveAgentUrl(app),\n color: app.color,\n }),\n );\n}\n\n/**\n * Discover all agents: built-in + custom agents stored as resources.\n * Custom agents override built-in agents with the same ID.\n */\nexport async function discoverAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const builtins = getBuiltinAgents(selfAppId);\n const agentsById = new Map<string, DiscoveredAgent>();\n\n // Start with built-ins\n for (const agent of builtins) {\n agentsById.set(agent.id, agent);\n }\n\n // Overlay custom agents from resources\n try {\n const { resourceList, resourceGet, SHARED_OWNER, resourceListAccessible } =\n await import(\"../resources/store.js\");\n const { DEV_MODE_USER_EMAIL } = await import(\"./auth.js\");\n\n const isDevMode =\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\";\n\n const resources = isDevMode\n ? await resourceListAccessible(DEV_MODE_USER_EMAIL, \"remote-agents/\")\n : await resourceList(SHARED_OWNER, \"remote-agents/\");\n const { parseRemoteAgentManifest } =\n await import(\"../resources/metadata.js\");\n\n for (const r of resources) {\n if (!r.path.endsWith(\".json\")) continue;\n try {\n const full = await resourceGet(r.id);\n if (!full) continue;\n const manifest = parseRemoteAgentManifest(full.content, r.path);\n if (!manifest || manifest.id === selfAppId) continue;\n if (HIDDEN_FIRST_PARTY_AGENT_IDS.has(manifest.id)) continue;\n\n // If the resource override carries a localhost URL but we're running\n // in production (e.g. a stale dev-time seed got promoted to the prod\n // DB), fall back to the matching built-in's prod URL instead of\n // letting the override win — otherwise outbound `call-agent` fetches\n // from a serverless function would target localhost and fail with\n // \"fetch failed\" instantly. The override still wins for non-localhost\n // URLs (the supported case for self-hosted custom agents).\n let url = manifest.url;\n if (\n !isDevMode &&\n typeof url === \"string\" &&\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0)(:|\\/|$)/.test(url)\n ) {\n const builtin = agentsById.get(manifest.id);\n if (builtin?.url) url = builtin.url;\n }\n\n agentsById.set(manifest.id, {\n id: manifest.id,\n name: manifest.name,\n description: manifest.description || \"\",\n url,\n color: manifest.color || \"#6B7280\",\n });\n } catch {\n // Skip unreadable resources\n }\n }\n } catch {\n // Resources not available — use built-ins only\n }\n\n // Overlay sibling workspace apps last so same-origin workspaces prefer the\n // app mounted in this workspace over the public template with the same id.\n for (const agent of discoverWorkspaceAgents(selfAppId)) {\n agentsById.set(agent.id, agent);\n }\n\n return Array.from(agentsById.values());\n}\n\n/**\n * Look up a single agent by ID or name (case-insensitive).\n */\nexport async function findAgent(\n idOrName: string,\n selfAppId?: string,\n): Promise<DiscoveredAgent | undefined> {\n const lower = idOrName.toLowerCase();\n const agents = await discoverAgents(selfAppId);\n return agents.find((a) => a.id === lower || a.name.toLowerCase() === lower);\n}\n\nfunction isDevEnvironment(): boolean {\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n );\n}\n\nfunction resolveAgentUrl(app: AgentEntry): string {\n if (isDevEnvironment()) {\n return app.devUrl || `http://localhost:${app.devPort}`;\n }\n return app.url;\n}\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction findWorkspaceRoot(startDir = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n for (let i = 0; i < 20; i++) {\n const pkg = readJson(path.join(dir, \"package.json\"));\n if (typeof pkg?.[\"agent-native\"]?.workspaceCore === \"string\") {\n return dir;\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction parseWorkspaceAppsManifest(\n parsed: any,\n): WorkspaceAppManifestEntry[] | null {\n const rawApps = Array.isArray(parsed?.apps)\n ? parsed.apps\n : Array.isArray(parsed)\n ? parsed\n : null;\n if (!rawApps) return null;\n\n const apps = rawApps\n .map((entry) => {\n if (!entry || typeof entry !== \"object\") return null;\n const id = typeof entry.id === \"string\" ? entry.id.trim() : \"\";\n const pathValue = typeof entry.path === \"string\" ? entry.path.trim() : \"\";\n if (!id || !pathValue.startsWith(\"/\")) return null;\n return {\n id,\n name:\n typeof entry.name === \"string\" && entry.name.trim()\n ? entry.name.trim()\n : titleCase(id),\n description:\n typeof entry.description === \"string\" ? entry.description : \"\",\n path: pathValue,\n url:\n typeof entry.url === \"string\" && entry.url.trim()\n ? entry.url.trim()\n : null,\n isDispatch:\n typeof entry.isDispatch === \"boolean\"\n ? entry.isDispatch\n : id === \"dispatch\",\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction readWorkspaceAppsFromEnv(): WorkspaceAppManifestEntry[] | null {\n const raw = process.env[WORKSPACE_APPS_ENV_KEY];\n if (!raw) return null;\n try {\n return parseWorkspaceAppsManifest(JSON.parse(raw));\n } catch {\n return null;\n }\n}\n\nfunction workspaceAppsManifestCandidates(): string[] {\n const candidates: string[] = [];\n try {\n candidates.push(\n path.join(process.cwd(), \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(process.cwd(), WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes do not expose process.cwd().\n }\n try {\n const moduleDir = path.dirname(fileURLToPath(import.meta.url));\n candidates.push(\n path.join(moduleDir, \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(moduleDir, WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes expose non-file module URLs. The env manifest still\n // works there, so skip file-relative candidates.\n }\n return candidates;\n}\n\nfunction readWorkspaceAppsFromManifestFile():\n | WorkspaceAppManifestEntry[]\n | null {\n for (const file of workspaceAppsManifestCandidates()) {\n if (!fs.existsSync(file)) continue;\n const apps = parseWorkspaceAppsManifest(readJson(file));\n if (apps) return apps;\n }\n return null;\n}\n\nfunction readWorkspaceAppsFromFilesystem(): WorkspaceAppManifestEntry[] | null {\n const workspaceRoot = findWorkspaceRoot();\n if (!workspaceRoot) return null;\n const appsDir = path.join(workspaceRoot, \"apps\");\n if (!fs.existsSync(appsDir)) return null;\n\n const apps = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry): WorkspaceAppManifestEntry | null => {\n const appDir = path.join(appsDir, entry.name);\n const pkg = readJson(path.join(appDir, \"package.json\"));\n if (!pkg) return null;\n return {\n id: entry.name,\n name: pkg.displayName || titleCase(entry.name),\n description: pkg.description || \"\",\n path: `/${entry.name}`,\n isDispatch: entry.name === \"dispatch\",\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction workspaceBaseUrl(): string | null {\n return (\n process.env.WORKSPACE_GATEWAY_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL ||\n null\n );\n}\n\nfunction workspaceAppUrl(app: WorkspaceAppManifestEntry): string | null {\n if (app.url) return app.url;\n const base = workspaceBaseUrl();\n if (!base) return null;\n try {\n return new URL(app.path, `${base.replace(/\\/$/, \"\")}/`).toString();\n } catch {\n return null;\n }\n}\n\nfunction discoverWorkspaceAgents(selfAppId?: string): DiscoveredAgent[] {\n const workspaceApps =\n readWorkspaceAppsFromEnv() ??\n readWorkspaceAppsFromManifestFile() ??\n readWorkspaceAppsFromFilesystem();\n if (!workspaceApps) return [];\n\n return workspaceApps\n .filter((app) => app.id !== selfAppId)\n .map((app) => {\n const url = workspaceAppUrl(app);\n if (!url) return null;\n const builtin = BUILTIN_AGENTS.find((agent) => agent.id === app.id);\n return {\n id: app.id,\n name: app.name,\n description:\n app.description ||\n builtin?.description ||\n `Workspace app mounted at ${app.path}`,\n url,\n color: builtin?.color || \"#6B7280\",\n } satisfies DiscoveredAgent;\n })\n .filter((agent): agent is DiscoveredAgent => !!agent);\n}\n\n/**\n * Like `getBuiltinAgents`, but always returns the production URL — never the\n * env-resolved devUrl. Used by the resource seeder so that a one-time seed\n * (`ON CONFLICT DO NOTHING`) can't permanently bake a localhost URL into the\n * DB, which would override the built-in's prod URL for every later\n * production deploy.\n */\nexport const BUILTIN_AGENTS_FOR_SEEDING: DiscoveredAgent[] =\n BUILTIN_AGENTS.filter((app) => app.url).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: app.url, // ALWAYS prod\n color: app.color,\n }));\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"framework-request-handler.d.ts","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,YAAY,EAAW,MAAM,IAAI,CAAC;AAMhD,QAAA,MAAM,gBAAgB,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"framework-request-handler.d.ts","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,YAAY,EAAW,MAAM,IAAI,CAAC;AAMhD,QAAA,MAAM,gBAAgB,mBAAmB,CAAC;AAiD1C;;;GAGG;AACH,MAAM,WAAW,SAAS;IACxB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;IAC/C,GAAG,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;CAClC;AAED;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CAAC,QAAQ,EAAE,GAAG,GAAG,SAAS,CA2CjD;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,QAAQ,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAOjE;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAiB3E;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CAAC,QAAQ,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAMpE;AAgQD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,GAAG,CAAC,CAyBd;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
|
|
@@ -3,6 +3,7 @@ import { getMissingDefaultPlugins } from "../deploy/route-discovery.js";
|
|
|
3
3
|
const BOOTSTRAPPED = new WeakSet();
|
|
4
4
|
const IN_BOOTSTRAP = new WeakSet();
|
|
5
5
|
const FRAMEWORK_PREFIX = "/_agent-native";
|
|
6
|
+
const WELL_KNOWN_PREFIX = "/.well-known";
|
|
6
7
|
const APP_SHIM_KEY = "_agentNativeH3Shim";
|
|
7
8
|
const BOOTSTRAP_PROMISE_KEY = "_agentNativeBootstrapPromise";
|
|
8
9
|
const PLUGIN_READY_KEY = "_agentNativePluginReadyPromise";
|
|
@@ -20,12 +21,16 @@ function getAppBasePath() {
|
|
|
20
21
|
function pathMatchesPrefix(reqPath, prefix) {
|
|
21
22
|
return reqPath === prefix || reqPath.startsWith(prefix + "/");
|
|
22
23
|
}
|
|
24
|
+
function supportsAppBasePathMount(path) {
|
|
25
|
+
return (pathMatchesPrefix(path, FRAMEWORK_PREFIX) ||
|
|
26
|
+
pathMatchesPrefix(path, WELL_KNOWN_PREFIX));
|
|
27
|
+
}
|
|
23
28
|
function resolveMountMatch(reqPath, path) {
|
|
24
29
|
if (pathMatchesPrefix(reqPath, path)) {
|
|
25
30
|
return { mountPath: path, strippedPath: reqPath.slice(path.length) || "/" };
|
|
26
31
|
}
|
|
27
32
|
const appBasePath = getAppBasePath();
|
|
28
|
-
if (!appBasePath || !path
|
|
33
|
+
if (!appBasePath || !supportsAppBasePathMount(path))
|
|
29
34
|
return null;
|
|
30
35
|
const prefixedPath = `${appBasePath}${path}`;
|
|
31
36
|
if (!pathMatchesPrefix(reqPath, prefixedPath))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"framework-request-handler.js","sourceRoot":"","sources":["../../src/server/fram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O,EAAE,gBAAgB,EAAE,CAAC","sourcesContent":["/**\n * Framework request handler — registers framework routes on Nitro's h3 instance.\n *\n * Nitro 3 exposes its h3 app as `nitroApp.h3`. We register framework routes\n * directly on it as middleware (`nitroApp.h3[\"~middleware\"]`), giving each\n * plugin a path-prefix-matched handler that runs before any file-based route.\n *\n * Plugins call `getH3App(nitroApp).use(path, handler)` exactly like h3 v1's\n * `app.use()` — the wrapper translates that into v2 middleware registration.\n *\n * Default plugins that the template doesn't provide are auto-mounted on the\n * first call to `getH3App()` per nitroApp instance.\n */\nimport type { EventHandler, H3Event } from \"h3\";\nimport { setResponseHeader, setResponseStatus } from \"h3\";\nimport { getMissingDefaultPlugins } from \"../deploy/route-discovery.js\";\n\nconst BOOTSTRAPPED = new WeakSet<object>();\nconst IN_BOOTSTRAP = new WeakSet<object>();\nconst FRAMEWORK_PREFIX = \"/_agent-native\";\nconst APP_SHIM_KEY = \"_agentNativeH3Shim\";\nconst BOOTSTRAP_PROMISE_KEY = \"_agentNativeBootstrapPromise\";\nconst PLUGIN_READY_KEY = \"_agentNativePluginReadyPromise\";\n\nfunction normalizeAppBasePath(value: string | undefined): string {\n if (!value || value === \"/\") return \"\";\n const trimmed = value.trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return `/${trimmed.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\")}`;\n}\n\nfunction getAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\nfunction pathMatchesPrefix(reqPath: string, prefix: string): boolean {\n return reqPath === prefix || reqPath.startsWith(prefix + \"/\");\n}\n\nfunction resolveMountMatch(\n reqPath: string,\n path: string,\n): { mountPath: string; strippedPath: string } | null {\n if (pathMatchesPrefix(reqPath, path)) {\n return { mountPath: path, strippedPath: reqPath.slice(path.length) || \"/\" };\n }\n\n const appBasePath = getAppBasePath();\n if (!appBasePath || !path.startsWith(FRAMEWORK_PREFIX)) return null;\n\n const prefixedPath = `${appBasePath}${path}`;\n if (!pathMatchesPrefix(reqPath, prefixedPath)) return null;\n return {\n mountPath: prefixedPath,\n strippedPath: reqPath.slice(prefixedPath.length) || \"/\",\n };\n}\n\n/**\n * Wrapper around Nitro's h3 instance that exposes a v1-style `.use()` API\n * for registering path-prefix middleware.\n */\nexport interface H3AppShim {\n use(path: string, handler: EventHandler): void;\n use(handler: EventHandler): void;\n}\n\n/**\n * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this\n * to register routes via `.use(path, handler)`.\n *\n * On the first call per nitroApp, we kick off auto-mounting any missing\n * default plugins. User-facing plugin factories (createAgentChatPlugin,\n * createAuthPlugin, etc.) await this bootstrap via `awaitBootstrap()` so the\n * default plugins finish registering middleware before requests arrive.\n */\nexport function getH3App(nitroApp: any): H3AppShim {\n if (!nitroApp) throw new Error(\"getH3App: nitroApp is required\");\n\n // Reuse the cached shim if we've wrapped this nitroApp before\n const cached = nitroApp[APP_SHIM_KEY] as H3AppShim | undefined;\n if (cached) return cached;\n\n const shim: H3AppShim = {\n use(arg1: string | EventHandler, arg2?: EventHandler) {\n const path = typeof arg1 === \"string\" ? arg1 : \"\";\n const handler = (typeof arg1 === \"string\" ? arg2 : arg1) as EventHandler;\n if (typeof handler !== \"function\") {\n throw new Error(\"getH3App.use: handler must be a function\");\n }\n registerMiddleware(nitroApp, path, handler);\n },\n };\n\n nitroApp[APP_SHIM_KEY] = shim;\n\n if (!BOOTSTRAPPED.has(nitroApp)) {\n BOOTSTRAPPED.add(nitroApp);\n nitroApp[BOOTSTRAP_PROMISE_KEY] = bootstrapDefaultPlugins(nitroApp).catch(\n (err) => {\n console.warn(\n \"[agent-native] Failed to auto-mount default plugins:\",\n (err as Error).message,\n );\n },\n );\n\n // Readiness gate: Nitro v3 doesn't await async plugins, so routes\n // registered inside an async plugin may not exist when the first\n // request arrives. This middleware holds /_agent-native requests\n // until all tracked plugin inits complete.\n registerMiddleware(nitroApp, FRAMEWORK_PREFIX, (async (event: H3Event) => {\n await awaitPluginsReady(nitroApp);\n // Fall through — the actual route handler runs next.\n return undefined;\n }) as EventHandler);\n }\n\n return shim;\n}\n\n/**\n * Wait for the framework's default-plugin bootstrap to complete.\n *\n * Called by user-facing plugin factories (`createAgentChatPlugin`, etc.) at\n * the top of their plugin function, so that by the time the function returns\n * — and Nitro starts accepting requests — all default plugins have finished\n * registering their middleware.\n *\n * No-op when called from inside the bootstrap itself (avoids deadlock when a\n * default plugin happens to be running as part of bootstrap).\n */\nexport async function awaitBootstrap(nitroApp: any): Promise<void> {\n if (!nitroApp || IN_BOOTSTRAP.has(nitroApp)) return;\n // Trigger bootstrap if it hasn't been already (idempotent — getH3App\n // creates the shim and kicks off bootstrap on first call).\n getH3App(nitroApp);\n const promise = nitroApp[BOOTSTRAP_PROMISE_KEY];\n if (promise) await promise;\n}\n\n/**\n * Track an async plugin's initialization promise. Nitro v3 calls plugins\n * synchronously and doesn't await async return values, so routes registered\n * inside an async plugin may not be ready when the first request arrives.\n *\n * Call this from the TOP of any async plugin so that the readiness gate\n * (installed by getH3App) can hold /_agent-native requests until the plugin\n * finishes mounting its routes.\n */\nexport function trackPluginInit(nitroApp: any, promise: Promise<void>): void {\n if (!nitroApp) return;\n // Attach a no-op catch so the promise doesn't surface as an unhandled\n // rejection when Nitro v3 drops the async return value. The actual error\n // is still observable when awaitPluginsReady() re-awaits the promise.\n const safe = promise.catch((err) => {\n console.error(\n \"[agent-native] Plugin init failed:\",\n (err as Error).message || err,\n );\n });\n const existing = nitroApp[PLUGIN_READY_KEY] as Promise<void>[] | undefined;\n if (existing) {\n existing.push(safe);\n } else {\n nitroApp[PLUGIN_READY_KEY] = [safe];\n }\n}\n\n/**\n * Await all tracked plugin initializations. Called by the readiness gate\n * middleware before dispatching framework routes.\n */\nexport async function awaitPluginsReady(nitroApp: any): Promise<void> {\n const promises = nitroApp[PLUGIN_READY_KEY] as Promise<void>[] | undefined;\n if (promises?.length) {\n await Promise.all(promises);\n nitroApp[PLUGIN_READY_KEY] = [];\n }\n}\n\n/**\n * Register a path-prefix middleware on Nitro's h3 instance.\n *\n * The middleware:\n * - Returns `next()` (continues) if the request path doesn't match.\n * - Otherwise dispatches to the handler. If the handler returns a value,\n * it short-circuits the request. If it returns undefined, next() runs.\n *\n * Path matching emulates h3 v1's `app.use(path, ...)` behavior:\n * - Exact-match prefix: `/foo` matches `/foo`, `/foo/bar`, but not `/foobar`\n * - Empty path: middleware runs on every request\n */\nfunction registerMiddleware(\n nitroApp: any,\n path: string,\n handler: EventHandler,\n) {\n const h3 = nitroApp.h3;\n if (!h3 || !Array.isArray(h3[\"~middleware\"])) {\n throw new Error(\n \"[agent-native] Cannot register route: nitroApp.h3 is not available. \" +\n \"Make sure you're calling getH3App() from inside a Nitro plugin.\",\n );\n }\n\n const middleware = async (event: H3Event, next: () => any) => {\n let originalPathname: string | undefined;\n let originalEventPath: string | undefined;\n let hadEventPath = false;\n const restoreOriginalPath = () => {\n if (originalPathname !== undefined) {\n try {\n event.url.pathname = originalPathname;\n } catch {\n // ignore\n }\n originalPathname = undefined;\n }\n if (hadEventPath) {\n try {\n (event as any).path = originalEventPath;\n } catch {\n // ignore\n }\n } else {\n try {\n delete (event as any).path;\n } catch {\n // ignore\n }\n }\n };\n if (path) {\n const reqPath = event.url?.pathname ?? \"\";\n const match = resolveMountMatch(reqPath, path);\n if (!match) {\n return next();\n }\n // Strip the mount prefix from event.url.pathname so handlers that\n // dispatch sub-routes can read `event.path` (or `event.url.pathname`)\n // and see the path RELATIVE to their mount point — matching h3 v1's\n // `app.use(path, handler)` semantics.\n const eventAny = event as any;\n hadEventPath = \"path\" in eventAny;\n originalEventPath = eventAny.path;\n try {\n originalPathname = event.url.pathname;\n // Save the full path in context so handlers that need the original URL\n // (e.g. Better Auth, which extracts its own basePath prefix) can\n // reconstruct a Request with the un-stripped URL.\n eventAny.context = eventAny.context ?? {};\n eventAny.context._mountedPathname = originalPathname;\n eventAny.context._mountPrefix = match.mountPath;\n event.url.pathname = match.strippedPath;\n eventAny.path = `${match.strippedPath}${event.url.search || \"\"}`;\n } catch {\n // event.url is read-only on some runtimes — fall through. Handlers\n // that don't depend on prefix stripping (most of them) still work.\n }\n }\n try {\n const result = await handler(event);\n if (result === undefined) {\n // Restore the original pathname BEFORE calling next() so downstream\n // middleware sees the full URL — not the stripped mount-relative path.\n // Matches h3 v2's own sub-app middleware pattern where the restore\n // happens inside the next() callback, not after it returns.\n restoreOriginalPath();\n return next();\n }\n return result;\n } catch (err) {\n // Log 500s to the server console so they're debuggable, and respond\n // with JSON instead of the default HTML error page so clients can\n // surface error messages. This only applies to routes mounted under\n // the framework prefix (or middleware mounted at `/`, for which we\n // still want visibility).\n const reqPath = originalPathname ?? event.url?.pathname ?? \"\";\n const e = err as any;\n const status =\n typeof e?.statusCode === \"number\"\n ? e.statusCode\n : typeof e?.status === \"number\"\n ? e.status\n : 500;\n console.error(\n `[agent-native] ${event.method ?? \"\"} ${reqPath} failed (${status}):`,\n e?.stack || e?.message || e,\n );\n try {\n setResponseStatus(event, status);\n setResponseHeader(event, \"content-type\", \"application/json\");\n } catch {\n // Response already sent — best effort.\n }\n return {\n error: e?.message || \"Internal server error\",\n // Only surface the stack to clients when explicitly enabled.\n // `NODE_ENV !== \"production\"` was unsafe — preview deploys and\n // any host that forgets to set NODE_ENV=production leaked stack\n // traces (file paths, dependency versions, internal route\n // topology) to anonymous callers. Operators who want stacks in\n // dev set `AGENT_NATIVE_DEBUG_ERRORS=1` explicitly.\n ...(status >= 500 &&\n process.env.AGENT_NATIVE_DEBUG_ERRORS === \"1\" &&\n e?.stack\n ? { stack: e.stack }\n : {}),\n };\n } finally {\n // Restore the original pathname so downstream middleware sees the\n // full URL.\n restoreOriginalPath();\n }\n };\n\n h3[\"~middleware\"].push(middleware);\n}\n\n/**\n * Auto-mount any default framework plugins that the template doesn't provide.\n *\n * Runs once per nitroApp on the first `getH3App()` call. Uses route-discovery\n * to find which default plugin stems are missing from `server/plugins/`, then\n * dynamically imports and mounts them. If a workspace core is present in the\n * ancestor chain, plugin slots the workspace core exports are mounted from\n * there instead of from @agent-native/core — this is the middle layer of the\n * three-layer inheritance model (app local > workspace core > framework).\n */\nasync function bootstrapDefaultPlugins(nitroApp: any): Promise<void> {\n IN_BOOTSTRAP.add(nitroApp);\n try {\n const cwd = process.cwd();\n const missing = await getMissingDefaultPlugins(cwd);\n if (missing.length === 0) return;\n\n // Lazy import to avoid circular dependency at module load time\n const serverModule = await import(\"./index.js\");\n const terminalModule = await import(\"../terminal/terminal-plugin.js\");\n const integrationsModule = await import(\"../integrations/plugin.js\");\n const orgModule = await import(\"../org/plugin.js\");\n const onboardingModule = await import(\"../onboarding/plugin.js\");\n\n const frameworkImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {\n \"agent-chat\": (serverModule as any).defaultAgentChatPlugin,\n auth: (serverModule as any).defaultAuthPlugin,\n \"core-routes\": (serverModule as any).defaultCoreRoutesPlugin,\n integrations: (integrationsModule as any).defaultIntegrationsPlugin,\n onboarding: (onboardingModule as any).defaultOnboardingPlugin,\n org: (orgModule as any).defaultOrgPlugin,\n resources: (serverModule as any).defaultResourcesPlugin,\n terminal: (terminalModule as any).defaultTerminalPlugin,\n };\n\n // Workspace core layer: if the app is inside an enterprise monorepo with\n // `agent-native.workspaceCore` configured, pull in any plugin slots the\n // workspace core exports from its server entry. We dynamically import the\n // workspace core package at runtime.\n let workspaceImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {};\n try {\n const { getWorkspaceCoreExports } =\n await import(\"../deploy/workspace-core.js\");\n const ws = await getWorkspaceCoreExports(cwd);\n if (ws && Object.keys(ws.plugins).length > 0) {\n try {\n const wsServerModule = await loadWorkspaceCoreServer(\n ws.packageName,\n ws.packageDir,\n );\n for (const [slot, exportName] of Object.entries(ws.plugins)) {\n if (!exportName) continue;\n const impl = (wsServerModule as any)[exportName];\n if (typeof impl === \"function\") {\n workspaceImpls[slot] = impl;\n }\n }\n if (process.env.DEBUG) {\n console.log(\n `[agent-native] Workspace core ${ws.packageName} provides plugin slots: ${Object.keys(workspaceImpls).join(\", \")}`,\n );\n }\n } catch (e) {\n const msg = (e as Error).message ?? \"\";\n // Common cause: workspace-core's package.json points \"./server\"\n // at a TS source file (the scaffold default), but Node can't\n // resolve relative `.js` imports inside it without a TS loader.\n // Tell the user to compile to dist/ rather than just dumping the\n // raw resolution error.\n const tsLoadHint = /\\.js' imported from .*\\.ts/.test(msg)\n ? \" — workspace-core src is TypeScript but isn't being compiled. \" +\n \"Run `pnpm --filter \" +\n ws.packageName +\n \" build` and point its `./server` export at dist/server/index.js.\"\n : \"\";\n console.warn(\n `[agent-native] Failed to load workspace core ${ws.packageName}/server: ${msg}${tsLoadHint}`,\n );\n }\n }\n } catch {\n // Workspace shared package isn't available (e.g. running on an edge\n // runtime without fs). Silently fall through to framework defaults.\n }\n\n if (process.env.DEBUG)\n console.log(\n `[agent-native] Auto-mounting ${missing.length} default plugin(s): ${missing.join(\", \")}`,\n );\n\n for (const stem of missing) {\n // Prefer workspace-core impl over framework default when both exist.\n const impl = workspaceImpls[stem] ?? frameworkImpls[stem];\n if (typeof impl === \"function\") {\n try {\n await impl(nitroApp);\n } catch (e) {\n console.warn(\n `[agent-native] Failed to auto-mount default plugin ${stem}:`,\n (e as Error).message,\n );\n }\n }\n }\n } finally {\n IN_BOOTSTRAP.delete(nitroApp);\n }\n}\n\n/**\n * Load a workspace-core's `/server` entry, transparently handling TS source.\n *\n * The scaffolded workspace-core template ships TS sources without a build\n * step (exports point at `./src/server/index.ts`), so plain `await import()`\n * blows up the moment Node hits a relative `.js` import inside (the standard\n * TS ESM convention) — and even before that, Node may resolve the package\n * relative to the framework's own location rather than the user's monorepo.\n *\n * We try Node's plain `import()` first (fastest path when the user has\n * compiled to dist/) and fall through to jiti on any error. jiti is anchored\n * to a real file inside the workspace-core's directory, so its module\n * resolution starts in the right node_modules tree (handles pnpm hoisting\n * and linked workspaces) AND handles TS source files + `.js` → `.ts` ESM\n * extension remapping.\n *\n * Edge runtimes without `fs` won't be able to load jiti at all; the outer\n * try/catch silently falls through to framework defaults in that case.\n */\nexport async function loadWorkspaceCoreServer(\n packageName: string,\n packageDir: string,\n): Promise<any> {\n let firstErr: unknown;\n try {\n return await import(/* @vite-ignore */ `${packageName}/server`);\n } catch (e) {\n firstErr = e;\n }\n\n try {\n const { createJiti } = await import(\"jiti\");\n const { pathToFileURL } = await import(\"node:url\");\n const path = await import(\"node:path\");\n // Anchor jiti to a real file inside the workspace-core package so its\n // module resolution starts in the right node_modules tree (handles pnpm\n // hoisting and linked workspaces).\n const anchor = pathToFileURL(\n path.join(packageDir, \"package.json\"),\n ).toString();\n const jiti = createJiti(anchor, { interopDefault: true });\n return await jiti.import(`${packageName}/server`);\n } catch (jitiErr) {\n // jiti also failed — rethrow the original Node error since it's usually\n // more informative about *why* the package wasn't resolvable.\n throw firstErr ?? jitiErr;\n }\n}\n\nexport { FRAMEWORK_PREFIX };\n"]}
|
|
1
|
+
{"version":3,"file":"framework-request-handler.js","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AAC1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAExE,MAAM,YAAY,GAAG,IAAI,OAAO,EAAU,CAAC;AAC3C,MAAM,YAAY,GAAG,IAAI,OAAO,EAAU,CAAC;AAC3C,MAAM,gBAAgB,GAAG,gBAAgB,CAAC;AAC1C,MAAM,iBAAiB,GAAG,cAAc,CAAC;AACzC,MAAM,YAAY,GAAG,oBAAoB,CAAC;AAC1C,MAAM,qBAAqB,GAAG,8BAA8B,CAAC;AAC7D,MAAM,gBAAgB,GAAG,gCAAgC,CAAC;AAE1D,SAAS,oBAAoB,CAAC,KAAyB;IACrD,IAAI,CAAC,KAAK,IAAI,KAAK,KAAK,GAAG;QAAE,OAAO,EAAE,CAAC;IACvC,MAAM,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IAAI,CAAC;QACH,OAAO,MAAM,MAAM,CAAC,kBAAkB,CAAC,GAAG,WAAW,SAAS,CAAC,CAAC;IAClE,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,QAAQ,GAAG,CAAC,CAAC;IACf,CAAC;IAED,IAAI,CAAC;QACH,MAAM,EAAE,UAAU,EAAE,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC;QAC5C,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,CAAC;QACnD,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,CAAC;QACvC,sEAAsE;QACtE,wEAAwE;QACxE,mCAAmC;QACnC,MAAM,MAAM,GAAG,aAAa,CAC1B,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,cAAc,CAAC,CACtC,CAAC,QAAQ,EAAE,CAAC;QACb,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1D,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,WAAW,SAAS,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,OAAO,EAAE,CAAC;QACjB,wEAAwE;QACxE,8DAA8D;QAC9D,MAAM,QAAQ,IAAI,OAAO,CAAC;IAC5B,CAAC;AACH,CAAC;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC","sourcesContent":["/**\n * Framework request handler — registers framework routes on Nitro's h3 instance.\n *\n * Nitro 3 exposes its h3 app as `nitroApp.h3`. We register framework routes\n * directly on it as middleware (`nitroApp.h3[\"~middleware\"]`), giving each\n * plugin a path-prefix-matched handler that runs before any file-based route.\n *\n * Plugins call `getH3App(nitroApp).use(path, handler)` exactly like h3 v1's\n * `app.use()` — the wrapper translates that into v2 middleware registration.\n *\n * Default plugins that the template doesn't provide are auto-mounted on the\n * first call to `getH3App()` per nitroApp instance.\n */\nimport type { EventHandler, H3Event } from \"h3\";\nimport { setResponseHeader, setResponseStatus } from \"h3\";\nimport { getMissingDefaultPlugins } from \"../deploy/route-discovery.js\";\n\nconst BOOTSTRAPPED = new WeakSet<object>();\nconst IN_BOOTSTRAP = new WeakSet<object>();\nconst FRAMEWORK_PREFIX = \"/_agent-native\";\nconst WELL_KNOWN_PREFIX = \"/.well-known\";\nconst APP_SHIM_KEY = \"_agentNativeH3Shim\";\nconst BOOTSTRAP_PROMISE_KEY = \"_agentNativeBootstrapPromise\";\nconst PLUGIN_READY_KEY = \"_agentNativePluginReadyPromise\";\n\nfunction normalizeAppBasePath(value: string | undefined): string {\n if (!value || value === \"/\") return \"\";\n const trimmed = value.trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return `/${trimmed.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\")}`;\n}\n\nfunction getAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\nfunction pathMatchesPrefix(reqPath: string, prefix: string): boolean {\n return reqPath === prefix || reqPath.startsWith(prefix + \"/\");\n}\n\nfunction supportsAppBasePathMount(path: string): boolean {\n return (\n pathMatchesPrefix(path, FRAMEWORK_PREFIX) ||\n pathMatchesPrefix(path, WELL_KNOWN_PREFIX)\n );\n}\n\nfunction resolveMountMatch(\n reqPath: string,\n path: string,\n): { mountPath: string; strippedPath: string } | null {\n if (pathMatchesPrefix(reqPath, path)) {\n return { mountPath: path, strippedPath: reqPath.slice(path.length) || \"/\" };\n }\n\n const appBasePath = getAppBasePath();\n if (!appBasePath || !supportsAppBasePathMount(path)) return null;\n\n const prefixedPath = `${appBasePath}${path}`;\n if (!pathMatchesPrefix(reqPath, prefixedPath)) return null;\n return {\n mountPath: prefixedPath,\n strippedPath: reqPath.slice(prefixedPath.length) || \"/\",\n };\n}\n\n/**\n * Wrapper around Nitro's h3 instance that exposes a v1-style `.use()` API\n * for registering path-prefix middleware.\n */\nexport interface H3AppShim {\n use(path: string, handler: EventHandler): void;\n use(handler: EventHandler): void;\n}\n\n/**\n * Get (or create) the shared H3 app wrapper for a nitroApp. Plugins use this\n * to register routes via `.use(path, handler)`.\n *\n * On the first call per nitroApp, we kick off auto-mounting any missing\n * default plugins. User-facing plugin factories (createAgentChatPlugin,\n * createAuthPlugin, etc.) await this bootstrap via `awaitBootstrap()` so the\n * default plugins finish registering middleware before requests arrive.\n */\nexport function getH3App(nitroApp: any): H3AppShim {\n if (!nitroApp) throw new Error(\"getH3App: nitroApp is required\");\n\n // Reuse the cached shim if we've wrapped this nitroApp before\n const cached = nitroApp[APP_SHIM_KEY] as H3AppShim | undefined;\n if (cached) return cached;\n\n const shim: H3AppShim = {\n use(arg1: string | EventHandler, arg2?: EventHandler) {\n const path = typeof arg1 === \"string\" ? arg1 : \"\";\n const handler = (typeof arg1 === \"string\" ? arg2 : arg1) as EventHandler;\n if (typeof handler !== \"function\") {\n throw new Error(\"getH3App.use: handler must be a function\");\n }\n registerMiddleware(nitroApp, path, handler);\n },\n };\n\n nitroApp[APP_SHIM_KEY] = shim;\n\n if (!BOOTSTRAPPED.has(nitroApp)) {\n BOOTSTRAPPED.add(nitroApp);\n nitroApp[BOOTSTRAP_PROMISE_KEY] = bootstrapDefaultPlugins(nitroApp).catch(\n (err) => {\n console.warn(\n \"[agent-native] Failed to auto-mount default plugins:\",\n (err as Error).message,\n );\n },\n );\n\n // Readiness gate: Nitro v3 doesn't await async plugins, so routes\n // registered inside an async plugin may not exist when the first\n // request arrives. This middleware holds /_agent-native requests\n // until all tracked plugin inits complete.\n registerMiddleware(nitroApp, FRAMEWORK_PREFIX, (async (event: H3Event) => {\n await awaitPluginsReady(nitroApp);\n // Fall through — the actual route handler runs next.\n return undefined;\n }) as EventHandler);\n }\n\n return shim;\n}\n\n/**\n * Wait for the framework's default-plugin bootstrap to complete.\n *\n * Called by user-facing plugin factories (`createAgentChatPlugin`, etc.) at\n * the top of their plugin function, so that by the time the function returns\n * — and Nitro starts accepting requests — all default plugins have finished\n * registering their middleware.\n *\n * No-op when called from inside the bootstrap itself (avoids deadlock when a\n * default plugin happens to be running as part of bootstrap).\n */\nexport async function awaitBootstrap(nitroApp: any): Promise<void> {\n if (!nitroApp || IN_BOOTSTRAP.has(nitroApp)) return;\n // Trigger bootstrap if it hasn't been already (idempotent — getH3App\n // creates the shim and kicks off bootstrap on first call).\n getH3App(nitroApp);\n const promise = nitroApp[BOOTSTRAP_PROMISE_KEY];\n if (promise) await promise;\n}\n\n/**\n * Track an async plugin's initialization promise. Nitro v3 calls plugins\n * synchronously and doesn't await async return values, so routes registered\n * inside an async plugin may not be ready when the first request arrives.\n *\n * Call this from the TOP of any async plugin so that the readiness gate\n * (installed by getH3App) can hold /_agent-native requests until the plugin\n * finishes mounting its routes.\n */\nexport function trackPluginInit(nitroApp: any, promise: Promise<void>): void {\n if (!nitroApp) return;\n // Attach a no-op catch so the promise doesn't surface as an unhandled\n // rejection when Nitro v3 drops the async return value. The actual error\n // is still observable when awaitPluginsReady() re-awaits the promise.\n const safe = promise.catch((err) => {\n console.error(\n \"[agent-native] Plugin init failed:\",\n (err as Error).message || err,\n );\n });\n const existing = nitroApp[PLUGIN_READY_KEY] as Promise<void>[] | undefined;\n if (existing) {\n existing.push(safe);\n } else {\n nitroApp[PLUGIN_READY_KEY] = [safe];\n }\n}\n\n/**\n * Await all tracked plugin initializations. Called by the readiness gate\n * middleware before dispatching framework routes.\n */\nexport async function awaitPluginsReady(nitroApp: any): Promise<void> {\n const promises = nitroApp[PLUGIN_READY_KEY] as Promise<void>[] | undefined;\n if (promises?.length) {\n await Promise.all(promises);\n nitroApp[PLUGIN_READY_KEY] = [];\n }\n}\n\n/**\n * Register a path-prefix middleware on Nitro's h3 instance.\n *\n * The middleware:\n * - Returns `next()` (continues) if the request path doesn't match.\n * - Otherwise dispatches to the handler. If the handler returns a value,\n * it short-circuits the request. If it returns undefined, next() runs.\n *\n * Path matching emulates h3 v1's `app.use(path, ...)` behavior:\n * - Exact-match prefix: `/foo` matches `/foo`, `/foo/bar`, but not `/foobar`\n * - Empty path: middleware runs on every request\n */\nfunction registerMiddleware(\n nitroApp: any,\n path: string,\n handler: EventHandler,\n) {\n const h3 = nitroApp.h3;\n if (!h3 || !Array.isArray(h3[\"~middleware\"])) {\n throw new Error(\n \"[agent-native] Cannot register route: nitroApp.h3 is not available. \" +\n \"Make sure you're calling getH3App() from inside a Nitro plugin.\",\n );\n }\n\n const middleware = async (event: H3Event, next: () => any) => {\n let originalPathname: string | undefined;\n let originalEventPath: string | undefined;\n let hadEventPath = false;\n const restoreOriginalPath = () => {\n if (originalPathname !== undefined) {\n try {\n event.url.pathname = originalPathname;\n } catch {\n // ignore\n }\n originalPathname = undefined;\n }\n if (hadEventPath) {\n try {\n (event as any).path = originalEventPath;\n } catch {\n // ignore\n }\n } else {\n try {\n delete (event as any).path;\n } catch {\n // ignore\n }\n }\n };\n if (path) {\n const reqPath = event.url?.pathname ?? \"\";\n const match = resolveMountMatch(reqPath, path);\n if (!match) {\n return next();\n }\n // Strip the mount prefix from event.url.pathname so handlers that\n // dispatch sub-routes can read `event.path` (or `event.url.pathname`)\n // and see the path RELATIVE to their mount point — matching h3 v1's\n // `app.use(path, handler)` semantics.\n const eventAny = event as any;\n hadEventPath = \"path\" in eventAny;\n originalEventPath = eventAny.path;\n try {\n originalPathname = event.url.pathname;\n // Save the full path in context so handlers that need the original URL\n // (e.g. Better Auth, which extracts its own basePath prefix) can\n // reconstruct a Request with the un-stripped URL.\n eventAny.context = eventAny.context ?? {};\n eventAny.context._mountedPathname = originalPathname;\n eventAny.context._mountPrefix = match.mountPath;\n event.url.pathname = match.strippedPath;\n eventAny.path = `${match.strippedPath}${event.url.search || \"\"}`;\n } catch {\n // event.url is read-only on some runtimes — fall through. Handlers\n // that don't depend on prefix stripping (most of them) still work.\n }\n }\n try {\n const result = await handler(event);\n if (result === undefined) {\n // Restore the original pathname BEFORE calling next() so downstream\n // middleware sees the full URL — not the stripped mount-relative path.\n // Matches h3 v2's own sub-app middleware pattern where the restore\n // happens inside the next() callback, not after it returns.\n restoreOriginalPath();\n return next();\n }\n return result;\n } catch (err) {\n // Log 500s to the server console so they're debuggable, and respond\n // with JSON instead of the default HTML error page so clients can\n // surface error messages. This only applies to routes mounted under\n // the framework prefix (or middleware mounted at `/`, for which we\n // still want visibility).\n const reqPath = originalPathname ?? event.url?.pathname ?? \"\";\n const e = err as any;\n const status =\n typeof e?.statusCode === \"number\"\n ? e.statusCode\n : typeof e?.status === \"number\"\n ? e.status\n : 500;\n console.error(\n `[agent-native] ${event.method ?? \"\"} ${reqPath} failed (${status}):`,\n e?.stack || e?.message || e,\n );\n try {\n setResponseStatus(event, status);\n setResponseHeader(event, \"content-type\", \"application/json\");\n } catch {\n // Response already sent — best effort.\n }\n return {\n error: e?.message || \"Internal server error\",\n // Only surface the stack to clients when explicitly enabled.\n // `NODE_ENV !== \"production\"` was unsafe — preview deploys and\n // any host that forgets to set NODE_ENV=production leaked stack\n // traces (file paths, dependency versions, internal route\n // topology) to anonymous callers. Operators who want stacks in\n // dev set `AGENT_NATIVE_DEBUG_ERRORS=1` explicitly.\n ...(status >= 500 &&\n process.env.AGENT_NATIVE_DEBUG_ERRORS === \"1\" &&\n e?.stack\n ? { stack: e.stack }\n : {}),\n };\n } finally {\n // Restore the original pathname so downstream middleware sees the\n // full URL.\n restoreOriginalPath();\n }\n };\n\n h3[\"~middleware\"].push(middleware);\n}\n\n/**\n * Auto-mount any default framework plugins that the template doesn't provide.\n *\n * Runs once per nitroApp on the first `getH3App()` call. Uses route-discovery\n * to find which default plugin stems are missing from `server/plugins/`, then\n * dynamically imports and mounts them. If a workspace core is present in the\n * ancestor chain, plugin slots the workspace core exports are mounted from\n * there instead of from @agent-native/core — this is the middle layer of the\n * three-layer inheritance model (app local > workspace core > framework).\n */\nasync function bootstrapDefaultPlugins(nitroApp: any): Promise<void> {\n IN_BOOTSTRAP.add(nitroApp);\n try {\n const cwd = process.cwd();\n const missing = await getMissingDefaultPlugins(cwd);\n if (missing.length === 0) return;\n\n // Lazy import to avoid circular dependency at module load time\n const serverModule = await import(\"./index.js\");\n const terminalModule = await import(\"../terminal/terminal-plugin.js\");\n const integrationsModule = await import(\"../integrations/plugin.js\");\n const orgModule = await import(\"../org/plugin.js\");\n const onboardingModule = await import(\"../onboarding/plugin.js\");\n\n const frameworkImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {\n \"agent-chat\": (serverModule as any).defaultAgentChatPlugin,\n auth: (serverModule as any).defaultAuthPlugin,\n \"core-routes\": (serverModule as any).defaultCoreRoutesPlugin,\n integrations: (integrationsModule as any).defaultIntegrationsPlugin,\n onboarding: (onboardingModule as any).defaultOnboardingPlugin,\n org: (orgModule as any).defaultOrgPlugin,\n resources: (serverModule as any).defaultResourcesPlugin,\n terminal: (terminalModule as any).defaultTerminalPlugin,\n };\n\n // Workspace core layer: if the app is inside an enterprise monorepo with\n // `agent-native.workspaceCore` configured, pull in any plugin slots the\n // workspace core exports from its server entry. We dynamically import the\n // workspace core package at runtime.\n let workspaceImpls: Record<\n string,\n ((nitroApp: any) => void | Promise<void>) | undefined\n > = {};\n try {\n const { getWorkspaceCoreExports } =\n await import(\"../deploy/workspace-core.js\");\n const ws = await getWorkspaceCoreExports(cwd);\n if (ws && Object.keys(ws.plugins).length > 0) {\n try {\n const wsServerModule = await loadWorkspaceCoreServer(\n ws.packageName,\n ws.packageDir,\n );\n for (const [slot, exportName] of Object.entries(ws.plugins)) {\n if (!exportName) continue;\n const impl = (wsServerModule as any)[exportName];\n if (typeof impl === \"function\") {\n workspaceImpls[slot] = impl;\n }\n }\n if (process.env.DEBUG) {\n console.log(\n `[agent-native] Workspace core ${ws.packageName} provides plugin slots: ${Object.keys(workspaceImpls).join(\", \")}`,\n );\n }\n } catch (e) {\n const msg = (e as Error).message ?? \"\";\n // Common cause: workspace-core's package.json points \"./server\"\n // at a TS source file (the scaffold default), but Node can't\n // resolve relative `.js` imports inside it without a TS loader.\n // Tell the user to compile to dist/ rather than just dumping the\n // raw resolution error.\n const tsLoadHint = /\\.js' imported from .*\\.ts/.test(msg)\n ? \" — workspace-core src is TypeScript but isn't being compiled. \" +\n \"Run `pnpm --filter \" +\n ws.packageName +\n \" build` and point its `./server` export at dist/server/index.js.\"\n : \"\";\n console.warn(\n `[agent-native] Failed to load workspace core ${ws.packageName}/server: ${msg}${tsLoadHint}`,\n );\n }\n }\n } catch {\n // Workspace shared package isn't available (e.g. running on an edge\n // runtime without fs). Silently fall through to framework defaults.\n }\n\n if (process.env.DEBUG)\n console.log(\n `[agent-native] Auto-mounting ${missing.length} default plugin(s): ${missing.join(\", \")}`,\n );\n\n for (const stem of missing) {\n // Prefer workspace-core impl over framework default when both exist.\n const impl = workspaceImpls[stem] ?? frameworkImpls[stem];\n if (typeof impl === \"function\") {\n try {\n await impl(nitroApp);\n } catch (e) {\n console.warn(\n `[agent-native] Failed to auto-mount default plugin ${stem}:`,\n (e as Error).message,\n );\n }\n }\n }\n } finally {\n IN_BOOTSTRAP.delete(nitroApp);\n }\n}\n\n/**\n * Load a workspace-core's `/server` entry, transparently handling TS source.\n *\n * The scaffolded workspace-core template ships TS sources without a build\n * step (exports point at `./src/server/index.ts`), so plain `await import()`\n * blows up the moment Node hits a relative `.js` import inside (the standard\n * TS ESM convention) — and even before that, Node may resolve the package\n * relative to the framework's own location rather than the user's monorepo.\n *\n * We try Node's plain `import()` first (fastest path when the user has\n * compiled to dist/) and fall through to jiti on any error. jiti is anchored\n * to a real file inside the workspace-core's directory, so its module\n * resolution starts in the right node_modules tree (handles pnpm hoisting\n * and linked workspaces) AND handles TS source files + `.js` → `.ts` ESM\n * extension remapping.\n *\n * Edge runtimes without `fs` won't be able to load jiti at all; the outer\n * try/catch silently falls through to framework defaults in that case.\n */\nexport async function loadWorkspaceCoreServer(\n packageName: string,\n packageDir: string,\n): Promise<any> {\n let firstErr: unknown;\n try {\n return await import(/* @vite-ignore */ `${packageName}/server`);\n } catch (e) {\n firstErr = e;\n }\n\n try {\n const { createJiti } = await import(\"jiti\");\n const { pathToFileURL } = await import(\"node:url\");\n const path = await import(\"node:path\");\n // Anchor jiti to a real file inside the workspace-core package so its\n // module resolution starts in the right node_modules tree (handles pnpm\n // hoisting and linked workspaces).\n const anchor = pathToFileURL(\n path.join(packageDir, \"package.json\"),\n ).toString();\n const jiti = createJiti(anchor, { interopDefault: true });\n return await jiti.import(`${packageName}/server`);\n } catch (jitiErr) {\n // jiti also failed — rethrow the original Node error since it's usually\n // more informative about *why* the package wasn't resolvable.\n throw firstErr ?? jitiErr;\n }\n}\n\nexport { FRAMEWORK_PREFIX };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"onboarding-html.d.ts","sourceRoot":"","sources":["../../src/server/onboarding-html.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAkCH,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;OAIG;IACH,SAAS,CAAC,EAAE;QACV,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,EAAE,MAAM,CAAC;QAChB,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;KACrB,CAAC;CACH;AAED,wBAAgB,iBAAiB,CAAC,IAAI,GAAE,qBAA0B,GAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"onboarding-html.d.ts","sourceRoot":"","sources":["../../src/server/onboarding-html.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAkCH,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;OAIG;IACH,SAAS,CAAC,EAAE;QACV,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,EAAE,MAAM,CAAC;QAChB,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;KACrB,CAAC;CACH;AAED,wBAAgB,iBAAiB,CAAC,IAAI,GAAE,qBAA0B,GAAG,MAAM,CAghC1E;AAED,kDAAkD;AAClD,eAAO,MAAM,eAAe,QAAsB,CAAC;AAEnD;;;;GAIG;AACH,wBAAgB,oBAAoB,IAAI,MAAM,CAwG7C"}
|
|
@@ -824,10 +824,16 @@ ${googleOnly
|
|
|
824
824
|
try {
|
|
825
825
|
var params = new URLSearchParams(location.search);
|
|
826
826
|
var qp = params.get('tab');
|
|
827
|
+
var path = location.pathname;
|
|
828
|
+
while (path.length > 1 && path.charAt(path.length - 1) === '/') path = path.slice(0, -1);
|
|
827
829
|
if (qp === 'login' || qp === 'signup') {
|
|
828
830
|
initial = qp;
|
|
829
831
|
} else if (params.has('verified')) {
|
|
830
832
|
initial = 'login';
|
|
833
|
+
} else if (path === '/login' || path.endsWith('/login')) {
|
|
834
|
+
initial = 'login';
|
|
835
|
+
} else if (path === '/signup' || path.endsWith('/signup')) {
|
|
836
|
+
initial = 'signup';
|
|
831
837
|
} else {
|
|
832
838
|
var stored = localStorage.getItem(TAB_STORAGE_KEY);
|
|
833
839
|
if (stored === 'login' || stored === 'signup') initial = stored;
|