@agent-native/core 0.79.7 → 0.79.10

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 (94) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +19 -0
  3. package/corpus/core/package.json +1 -1
  4. package/corpus/core/src/agent/run-manager.ts +9 -1
  5. package/corpus/core/src/client/agent-chat-adapter.ts +24 -16
  6. package/corpus/core/src/client/session-replay.ts +67 -13
  7. package/corpus/core/src/onboarding/default-steps.ts +3 -3
  8. package/corpus/core/src/server/action-routes.ts +6 -2
  9. package/corpus/core/src/server/agent-chat-plugin.ts +82 -162
  10. package/corpus/core/src/server/agent-run-context.ts +204 -0
  11. package/corpus/core/src/server/credential-provider.ts +20 -4
  12. package/corpus/templates/analytics/app/components/dashboard/SqlChart.tsx +14 -4
  13. package/corpus/templates/analytics/changelog/2026-06-26-session-replay-uploads-now-accept-compressed-payloads-so-lar.md +6 -0
  14. package/corpus/templates/analytics/changelog/2026-06-26-sql-chart-tooltips-now-stay-stable-while-moving-across-dense.md +6 -0
  15. package/corpus/templates/analytics/server/handlers/session-replay.ts +56 -8
  16. package/corpus/templates/clips/app/components/player/transcript-panel.tsx +1 -1
  17. package/corpus/templates/clips/app/components/recorder/storage-setup-card.tsx +44 -16
  18. package/corpus/templates/clips/app/i18n/ar-SA.ts +12 -9
  19. package/corpus/templates/clips/app/i18n/de-DE.ts +12 -9
  20. package/corpus/templates/clips/app/i18n/en-US.ts +19 -16
  21. package/corpus/templates/clips/app/i18n/es-ES.ts +12 -9
  22. package/corpus/templates/clips/app/i18n/fr-FR.ts +12 -9
  23. package/corpus/templates/clips/app/i18n/hi-IN.ts +13 -9
  24. package/corpus/templates/clips/app/i18n/ja-JP.ts +12 -9
  25. package/corpus/templates/clips/app/i18n/ko-KR.ts +12 -9
  26. package/corpus/templates/clips/app/i18n/pt-BR.ts +12 -9
  27. package/corpus/templates/clips/app/i18n/zh-CN.ts +19 -14
  28. package/corpus/templates/clips/app/i18n/zh-TW.ts +19 -14
  29. package/corpus/templates/clips/app/routes/r.$recordingId.tsx +7 -0
  30. package/corpus/templates/clips/app/routes/record.tsx +2 -2
  31. package/corpus/templates/clips/changelog/2026-06-26-desktop-recordings-recover-more-reliably-when-macos-reports-.md +6 -0
  32. package/corpus/templates/clips/changelog/2026-06-26-slack-unfurls-now-recognize-recording-dashboard-links-pasted.md +6 -0
  33. package/corpus/templates/clips/changelog/2026-06-26-storage-setup-now-explains-why-clips-needs-connected-storage.md +6 -0
  34. package/corpus/templates/clips/chrome-extension/public/manifest.json +1 -1
  35. package/corpus/templates/clips/chrome-extension/src/background.ts +24 -3
  36. package/corpus/templates/clips/chrome-extension/src/offscreen.ts +28 -2
  37. package/corpus/templates/clips/chrome-extension/src/popup.html +16 -0
  38. package/corpus/templates/clips/chrome-extension/src/popup.ts +59 -7
  39. package/corpus/templates/clips/chrome-extension/src/sentry.ts +28 -1
  40. package/corpus/templates/clips/chrome-extension/src/styles.css +74 -0
  41. package/corpus/templates/clips/desktop/src/app.tsx +85 -18
  42. package/corpus/templates/clips/desktop/src/styles.css +55 -0
  43. package/corpus/templates/clips/desktop/src-tauri/src/native_screen.rs +88 -51
  44. package/corpus/templates/clips/desktop/src-tauri/src/native_speech.rs +12 -3
  45. package/corpus/templates/clips/server/lib/slack-unfurls.ts +5 -2
  46. package/corpus/templates/mail/app/hooks/use-emails.ts +28 -4
  47. package/corpus/templates/mail/app/root.tsx +13 -7
  48. package/corpus/templates/mail/changelog/2026-06-26-mail-avoids-unnecessary-message-list-reloads-after-backgroun.md +6 -0
  49. package/dist/agent/run-manager.d.ts.map +1 -1
  50. package/dist/agent/run-manager.js +12 -1
  51. package/dist/agent/run-manager.js.map +1 -1
  52. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  53. package/dist/client/agent-chat-adapter.js +15 -8
  54. package/dist/client/agent-chat-adapter.js.map +1 -1
  55. package/dist/client/session-replay.d.ts.map +1 -1
  56. package/dist/client/session-replay.js +55 -14
  57. package/dist/client/session-replay.js.map +1 -1
  58. package/dist/collab/awareness.d.ts +2 -2
  59. package/dist/collab/awareness.d.ts.map +1 -1
  60. package/dist/collab/routes.d.ts +2 -2
  61. package/dist/file-upload/actions/upload-image.d.ts +2 -2
  62. package/dist/notifications/routes.d.ts +2 -2
  63. package/dist/observability/routes.d.ts +6 -6
  64. package/dist/onboarding/default-steps.js +3 -3
  65. package/dist/onboarding/default-steps.js.map +1 -1
  66. package/dist/resources/handlers.d.ts +3 -3
  67. package/dist/server/action-routes.d.ts.map +1 -1
  68. package/dist/server/action-routes.js +6 -2
  69. package/dist/server/action-routes.js.map +1 -1
  70. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  71. package/dist/server/agent-chat-plugin.js +69 -154
  72. package/dist/server/agent-chat-plugin.js.map +1 -1
  73. package/dist/server/agent-run-context.d.ts +35 -0
  74. package/dist/server/agent-run-context.d.ts.map +1 -0
  75. package/dist/server/agent-run-context.js +137 -0
  76. package/dist/server/agent-run-context.js.map +1 -0
  77. package/dist/server/credential-provider.d.ts.map +1 -1
  78. package/dist/server/credential-provider.js +15 -4
  79. package/dist/server/credential-provider.js.map +1 -1
  80. package/dist/server/transcribe-voice.d.ts +1 -1
  81. package/package.json +1 -1
  82. package/corpus/templates/.retired/README.md +0 -9
  83. package/corpus/templates/.retired/calls/package.json +0 -8
  84. package/corpus/templates/.retired/code/package.json +0 -8
  85. package/corpus/templates/.retired/contracts/package.json +0 -8
  86. package/corpus/templates/.retired/images/package.json +0 -8
  87. package/corpus/templates/.retired/issues/package.json +0 -8
  88. package/corpus/templates/.retired/meeting-notes/package.json +0 -8
  89. package/corpus/templates/.retired/migration/package.json +0 -8
  90. package/corpus/templates/.retired/recruiting/package.json +0 -8
  91. package/corpus/templates/.retired/scheduling/package.json +0 -8
  92. package/corpus/templates/.retired/visual-plans/package.json +0 -8
  93. package/corpus/templates/.retired/voice/package.json +0 -8
  94. package/corpus/templates/.retired/workbench/package.json +0 -8
@@ -275,13 +275,17 @@ export function mountActionRoutes(nitroApp, actions, options) {
275
275
  // ignore
276
276
  }
277
277
  }
278
- // If the action returned a string, try to parse as JSON for a clean response
278
+ // If the action returned a string, try to parse as JSON for a
279
+ // clean response. Plain strings still need to go over the HTTP
280
+ // action transport as JSON, otherwise H3 sends text/plain and the
281
+ // browser action client rejects the successful 2xx response.
279
282
  if (typeof result === "string") {
280
283
  try {
281
284
  return JSON.parse(result);
282
285
  }
283
286
  catch {
284
- return result;
287
+ setResponseHeader(event, "Content-Type", "application/json");
288
+ return JSON.stringify(result);
285
289
  }
286
290
  }
287
291
  return result;
@@ -1 +1 @@
1
- {"version":3,"file":"action-routes.js","sourceRoot":"","sources":["../../src/server/action-routes.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,QAAQ,EACR,SAAS,GACV,MAAM,IAAI,CAAC;AAEZ,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAEtD,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EACL,oBAAoB,EACpB,4BAA4B,EAC5B,8BAA8B,GAC/B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EACL,oBAAoB,IAAI,wBAAwB,EAChD,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAC3B;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,MAAM,YAAY,GAAG,wBAAwB,CAAC;AAE9C,MAAM,UAAU,uBAAuB,CACrC,YAA6B;IAE7B,MAAM,MAAM,GAAwB,EAAE,CAAC;IACvC,KAAK,MAAM,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AC,CAAC;oBAC9D,OAAO,EAAE,KAAK,EAAE,uBAAuB,EAAE,CAAC;gBAC5C,CAAC;YACH,CAAC,CACF,CAAC,CAAC,4BAA4B;QACjC,CAAC,CAAC,CACH,CAAC;QAEF,OAAO,CAAC,IAAI,CAAC,GAAG,MAAM,IAAI,SAAS,EAAE,CAAC,CAAC;IACzC,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK;QACzC,OAAO,CAAC,GAAG,CACT,2BAA2B,OAAO,CAAC,MAAM,qBAAqB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACnF,CAAC;AACN,CAAC","sourcesContent":["import {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getQuery,\n getHeader,\n} from \"h3\";\n\nimport { isAgentActionStopError } from \"../action.js\";\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { EMBED_TARGET_HEADER } from \"../shared/embed-auth.js\";\nimport {\n isMcpEmbedCorsOrigin,\n MCP_EMBED_CORS_ALLOW_HEADERS,\n shouldAllowMcpEmbedCredentials,\n} from \"../shared/mcp-embed-headers.js\";\nimport { notifyActionChange } from \"./action-change.js\";\nimport {\n getAllowedCorsOrigin as resolveAllowedCorsOrigin,\n readCorsAllowedOrigins,\n} from \"./cors-origins.js\";\n/**\n * Auto-mount actions as HTTP endpoints under /_agent-native/actions/:name.\n *\n * Actions are exposed as POST by default. Use `http: { method: \"GET\" }` in\n * defineAction to expose as GET. Use `http: false` to mark as agent-only.\n */\nimport { getH3App } from \"./framework-request-handler.js\";\nimport { runWithRequestContext } from \"./request-context.js\";\n\nconst ROUTE_PREFIX = \"/_agent-native/actions\";\n\nexport function parseActionSearchParams(\n searchParams: URLSearchParams,\n): Record<string, any> {\n const params: Record<string, any> = {};\n for (const [rawKey, value] of searchParams.entries()) {\n appendActionParam(params, rawKey, value);\n }\n return params;\n}\n\nfunction parseActionQueryObject(\n query: Record<string, unknown>,\n): Record<string, any> {\n const params: Record<string, any> = {};\n for (const [rawKey, rawValue] of Object.entries(query)) {\n const values = Array.isArray(rawValue) ? rawValue : [rawValue];\n for (const value of values) {\n if (value != null) appendActionParam(params, rawKey, String(value));\n }\n }\n return params;\n}\n\nfunction appendActionParam(\n params: Record<string, any>,\n rawKey: string,\n value: any,\n) {\n const isArrayKey = rawKey.endsWith(\"[]\");\n // The core client serializes arrays as `key[]=value` so even a single\n // value can validate against z.array() action schemas.\n const key = isArrayKey ? rawKey.slice(0, -2) : rawKey;\n const current = params[key];\n if (current === undefined) {\n params[key] = isArrayKey ? [value] : value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n params[key] = [current, value];\n }\n}\n\n/**\n * Read the caller's IANA timezone from the `x-user-timezone` header. The core\n * client sends this on every action request so server-side \"today\" fallbacks\n * can honor the user's local day.\n */\nfunction readTimezoneHeader(event: any): string | undefined {\n try {\n const raw = getHeader(event, \"x-user-timezone\");\n if (!raw || typeof raw !== \"string\") return undefined;\n const trimmed = raw.trim();\n return trimmed.length > 0 && trimmed.length < 64 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * True when the request originated from the browser action client\n * (`useActionQuery` / `useActionMutation` / `callAction`), which tags every\n * call with `X-Agent-Native-Frontend: 1`. Used to set `ctx.caller` to\n * `\"frontend\"` vs a bare programmatic `\"http\"` POST. The header carries no\n * auth weight — it only narrows the caller tag for tracking/branching.\n */\nfunction isFrontendActionRequest(event: any): boolean {\n try {\n return getHeader(event, \"x-agent-native-frontend\") === \"1\";\n } catch {\n return false;\n }\n}\n\ntype CorsOrigin = {\n origin: string;\n credentials: boolean;\n};\n\nfunction getAllowedCorsOrigin(origin: string | undefined): CorsOrigin | null {\n const allowedOrigin = resolveAllowedCorsOrigin(origin, {\n allowedOrigins: readCorsAllowedOrigins(),\n // Let the cors-origins default apply (dev-only). Omitting this option\n // keeps production from trusting arbitrary localhost callers.\n });\n if (allowedOrigin) {\n return { origin: allowedOrigin, credentials: true };\n }\n if (origin && isMcpEmbedCorsOrigin(origin)) {\n return {\n origin,\n credentials: shouldAllowMcpEmbedCredentials(origin),\n };\n }\n return null;\n}\n\nfunction handleOptionsRequest(event: any): string {\n const origin = getHeader(event, \"origin\");\n const cors = getAllowedCorsOrigin(\n typeof origin === \"string\" ? origin : undefined,\n );\n\n if (origin && !cors) {\n setResponseStatus(event, 403);\n return \"\";\n }\n\n if (cors) {\n setResponseHeader(event, \"Access-Control-Allow-Origin\", cors.origin);\n setResponseHeader(event, \"Vary\", \"Origin\");\n if (cors.credentials) {\n setResponseHeader(event, \"Access-Control-Allow-Credentials\", \"true\");\n }\n setResponseHeader(\n event,\n \"Access-Control-Allow-Methods\",\n \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n );\n setResponseHeader(\n event,\n \"Access-Control-Allow-Headers\",\n cors.credentials\n ? `Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend,${EMBED_TARGET_HEADER}`\n : `${MCP_EMBED_CORS_ALLOW_HEADERS},X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend`,\n );\n }\n\n setResponseStatus(event, 204);\n return \"\";\n}\n\nexport interface MountActionRoutesOptions {\n /** Resolve owner email from the H3 event (for data scoping). */\n getOwnerFromEvent?: (event: any) => string | Promise<string>;\n /** Resolve display name from the H3 event, when available. */\n getUserNameFromEvent?: (\n event: any,\n ) => string | undefined | Promise<string | undefined>;\n /** Resolve org ID from the H3 event (for org scoping). */\n resolveOrgId?: (event: any) => string | null | Promise<string | null>;\n}\n\nfunction isAuthResolutionFailure(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const maybeStatus = error as {\n status?: unknown;\n statusCode?: unknown;\n statusMessage?: unknown;\n };\n const status =\n typeof maybeStatus.statusCode === \"number\"\n ? maybeStatus.statusCode\n : typeof maybeStatus.status === \"number\"\n ? maybeStatus.status\n : undefined;\n if (status === 401 || status === 403) return true;\n return (\n typeof maybeStatus.statusMessage === \"string\" &&\n /unauthenticated|forbidden/i.test(maybeStatus.statusMessage)\n );\n}\n\n/**\n * Mount discovered actions as HTTP endpoints.\n *\n * Only actions from `autoDiscoverActions` (template actions) are mounted.\n * Built-in actions (resource-*, chat-*, shell, etc.) are NOT passed here.\n */\nexport function mountActionRoutes(\n nitroApp: any,\n actions: Record<string, ActionEntry>,\n options?: MountActionRoutesOptions,\n) {\n const mounted: string[] = [];\n\n for (const [name, entry] of Object.entries(actions)) {\n // Skip agent-only actions\n if (entry.http === false) continue;\n\n const method = entry.http?.method ?? \"POST\";\n const path = entry.http?.path ?? name;\n const routePath = `${ROUTE_PREFIX}/${path}`;\n\n getH3App(nitroApp).use(\n routePath,\n defineEventHandler(async (event) => {\n const reqMethod = getMethod(event);\n const effectiveMethod =\n reqMethod === \"HEAD\" && method === \"GET\" ? \"GET\" : reqMethod;\n\n if (reqMethod === \"OPTIONS\") {\n return handleOptionsRequest(event);\n }\n\n setResponseHeader(event, \"Cache-Control\", \"no-store\");\n\n // Allow the declared method\n if (effectiveMethod !== method) {\n setResponseStatus(event, 405);\n return { error: `Method not allowed. Use ${method}.` };\n }\n\n // (audit H5) Per-action `toolCallable` opt-out for the tools-iframe\n // bridge. The bridge tags every outbound action call with\n // X-Agent-Native-Tool-Bridge: 1. When that header is present and the\n // action declares `toolCallable: false`, we 403 — used by the\n // framework's share-resource / unshare-resource /\n // set-resource-visibility for defense-in-depth on auth-adjacent\n // operations. Undefined defaults to allow: tools are intra-org and\n // typically authored by trusted teammates, so the default is to\n // trust the org-level access controls.\n // The header is set by the parent (the React host), not by the\n // iframe's user-authored content; sanitizeToolRequestOptions strips\n // iframe attempts to spoof it.\n const fromToolBridge =\n getHeader(event, \"x-agent-native-tool-bridge\") === \"1\";\n if (fromToolBridge && entry.toolCallable === false) {\n setResponseStatus(event, 403);\n return {\n error: `Action '${name}' is not callable from tools.`,\n };\n }\n\n // Resolve auth context for per-request scoping\n let userEmail: string | undefined;\n let userName: string | undefined;\n if (options?.getOwnerFromEvent) {\n try {\n userEmail = await options.getOwnerFromEvent(event);\n userName = options?.getUserNameFromEvent\n ? await options.getUserNameFromEvent(event)\n : undefined;\n } catch (error) {\n if (\n entry.requiresAuth === false &&\n isAuthResolutionFailure(error)\n ) {\n userEmail = undefined;\n userName = undefined;\n } else {\n throw error;\n }\n }\n }\n const orgId = options?.resolveOrgId\n ? ((await options.resolveOrgId(event)) ?? undefined)\n : undefined;\n const timezone = readTimezoneHeader(event);\n\n return runWithRequestContext(\n { userEmail, userName, orgId, timezone },\n async () => {\n // Parse params based on method. On web-standard runtimes (Netlify\n // Functions, CF Workers), event.req IS the web Request — use .json()\n // directly. H3's readBody fails on those runtimes because it expects\n // a Node.js stream on event.node.req.\n let params: Record<string, any>;\n try {\n if (method === \"GET\") {\n // H3 v2: prefer web Request URL, fallback to getQuery\n const webReq = (event as any).req;\n if (webReq?.url) {\n const url = new URL(webReq.url);\n params = parseActionSearchParams(url.searchParams);\n } else {\n params = parseActionQueryObject(\n getQuery(event) as Record<string, any>,\n );\n }\n } else {\n const webReq = (event as any).req;\n if (webReq && typeof webReq.json === \"function\") {\n // H3 v2: event.req is the web Request — use .json() directly\n params = (await webReq.json().catch(() => null)) ?? {};\n } else {\n // Fallback: H3's readBody (Node.js dev)\n params = (await readBody(event)) ?? {};\n }\n }\n } catch {\n params = {};\n }\n\n // Run the action. Tag the caller: browser calls (useActionQuery /\n // useActionMutation / callAction) send X-Agent-Native-Frontend: 1,\n // so they become \"frontend\"; bare programmatic POSTs are \"http\".\n // userEmail / orgId mirror the request context resolved above (do\n // NOT inject a dev identity — leave undefined when unauthenticated).\n try {\n const caller = isFrontendActionRequest(event)\n ? \"frontend\"\n : \"http\";\n const result = await entry.run(params, {\n userEmail,\n orgId: orgId ?? null,\n caller,\n actionName: name,\n });\n\n // Auto-refresh the UI after a successful mutating action. GET\n // actions and actions explicitly flagged readOnly are skipped.\n // Other tabs' useDbSync will see source:\"action\" and invalidate\n // their action queries. The calling tab already refetches via\n // useActionMutation's onSuccess, so this is mainly cross-tab\n // sync (and parity with the agent's tool-call path).\n // Explicit entry.readOnly (true OR false) wins over the method\n // heuristic. defineAction already auto-infers GET → readOnly=true,\n // so for actions registered through that path entry.readOnly is\n // always set and the fallback just guards legacy wrap paths.\n const isReadOnly =\n typeof entry.readOnly === \"boolean\"\n ? entry.readOnly\n : method === \"GET\";\n if (!isReadOnly) {\n try {\n await notifyActionChange({\n actionName: name,\n ...(userEmail ? { owner: userEmail } : {}),\n });\n } catch {\n // ignore\n }\n }\n\n // If the action returned a string, try to parse as JSON for a clean response\n if (typeof result === \"string\") {\n try {\n return JSON.parse(result);\n } catch {\n return result;\n }\n }\n\n return result;\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const isValidationError = msg.startsWith(\n \"Invalid action parameters\",\n );\n const explicitStatus =\n typeof err?.statusCode === \"number\"\n ? err.statusCode\n : undefined;\n // Return 400 for validation errors, the explicit statusCode if\n // set, otherwise 500.\n const status = isValidationError ? 400 : (explicitStatus ?? 500);\n setResponseStatus(event, status);\n\n // Only echo the raw message for known-safe cases:\n // - validation errors (deterministic, parameter-shape only)\n // - explicit user-facing errors (AgentActionStopError / fail())\n // - errors with an explicit statusCode < 500 (client errors)\n // For uncategorized 500s, return a generic message and keep the\n // real detail server-side only — it can contain DB/driver/\n // upstream text we must not leak to HTTP callers.\n const isUserFacing =\n isValidationError ||\n isAgentActionStopError(err) ||\n (explicitStatus !== undefined && explicitStatus < 500);\n if (isUserFacing) {\n return { error: msg };\n }\n console.error(`[agent-native] action '${name}' failed:`, err);\n return { error: \"Internal server error\" };\n }\n },\n ); // end runWithRequestContext\n }),\n );\n\n mounted.push(`${method} ${routePath}`);\n }\n\n if (mounted.length > 0 && process.env.DEBUG)\n console.log(\n `[action-routes] Mounted ${mounted.length} action route(s): ${mounted.join(\", \")}`,\n );\n}\n"]}
1
+ {"version":3,"file":"action-routes.js","sourceRoot":"","sources":["../../src/server/action-routes.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,QAAQ,EACR,SAAS,GACV,MAAM,IAAI,CAAC;AAEZ,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAEtD,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EACL,oBAAoB,EACpB,4BAA4B,EAC5B,8BAA8B,GAC/B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EACL,oBAAoB,IAAI,wBAAwB,EAChD,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAC3B;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,MAAM,YAAY,GAAG,wBAAwB,CAAC;AAE9C,MAAM,UAAU,uBAAuB,CACrC,YAA6B;IAE7B,MAAM,MAAM,GAAwB,EAAE,CAAC;IACvC,KAAK,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,YAAY,CAAC,OAAO,EAAE,EAAE,CAAC;QACrD,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IAC3C,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,sBAAsB,CAC7B,KAA8B;IAE9B,MAAM,MAAM,GAAwB,EAAE,CAAC;IACvC,KAAK,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACvD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zC,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK;QACzC,OAAO,CAAC,GAAG,CACT,2BAA2B,OAAO,CAAC,MAAM,qBAAqB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACnF,CAAC;AACN,CAAC","sourcesContent":["import {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getQuery,\n getHeader,\n} from \"h3\";\n\nimport { isAgentActionStopError } from \"../action.js\";\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { EMBED_TARGET_HEADER } from \"../shared/embed-auth.js\";\nimport {\n isMcpEmbedCorsOrigin,\n MCP_EMBED_CORS_ALLOW_HEADERS,\n shouldAllowMcpEmbedCredentials,\n} from \"../shared/mcp-embed-headers.js\";\nimport { notifyActionChange } from \"./action-change.js\";\nimport {\n getAllowedCorsOrigin as resolveAllowedCorsOrigin,\n readCorsAllowedOrigins,\n} from \"./cors-origins.js\";\n/**\n * Auto-mount actions as HTTP endpoints under /_agent-native/actions/:name.\n *\n * Actions are exposed as POST by default. Use `http: { method: \"GET\" }` in\n * defineAction to expose as GET. Use `http: false` to mark as agent-only.\n */\nimport { getH3App } from \"./framework-request-handler.js\";\nimport { runWithRequestContext } from \"./request-context.js\";\n\nconst ROUTE_PREFIX = \"/_agent-native/actions\";\n\nexport function parseActionSearchParams(\n searchParams: URLSearchParams,\n): Record<string, any> {\n const params: Record<string, any> = {};\n for (const [rawKey, value] of searchParams.entries()) {\n appendActionParam(params, rawKey, value);\n }\n return params;\n}\n\nfunction parseActionQueryObject(\n query: Record<string, unknown>,\n): Record<string, any> {\n const params: Record<string, any> = {};\n for (const [rawKey, rawValue] of Object.entries(query)) {\n const values = Array.isArray(rawValue) ? rawValue : [rawValue];\n for (const value of values) {\n if (value != null) appendActionParam(params, rawKey, String(value));\n }\n }\n return params;\n}\n\nfunction appendActionParam(\n params: Record<string, any>,\n rawKey: string,\n value: any,\n) {\n const isArrayKey = rawKey.endsWith(\"[]\");\n // The core client serializes arrays as `key[]=value` so even a single\n // value can validate against z.array() action schemas.\n const key = isArrayKey ? rawKey.slice(0, -2) : rawKey;\n const current = params[key];\n if (current === undefined) {\n params[key] = isArrayKey ? [value] : value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n params[key] = [current, value];\n }\n}\n\n/**\n * Read the caller's IANA timezone from the `x-user-timezone` header. The core\n * client sends this on every action request so server-side \"today\" fallbacks\n * can honor the user's local day.\n */\nfunction readTimezoneHeader(event: any): string | undefined {\n try {\n const raw = getHeader(event, \"x-user-timezone\");\n if (!raw || typeof raw !== \"string\") return undefined;\n const trimmed = raw.trim();\n return trimmed.length > 0 && trimmed.length < 64 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * True when the request originated from the browser action client\n * (`useActionQuery` / `useActionMutation` / `callAction`), which tags every\n * call with `X-Agent-Native-Frontend: 1`. Used to set `ctx.caller` to\n * `\"frontend\"` vs a bare programmatic `\"http\"` POST. The header carries no\n * auth weight — it only narrows the caller tag for tracking/branching.\n */\nfunction isFrontendActionRequest(event: any): boolean {\n try {\n return getHeader(event, \"x-agent-native-frontend\") === \"1\";\n } catch {\n return false;\n }\n}\n\ntype CorsOrigin = {\n origin: string;\n credentials: boolean;\n};\n\nfunction getAllowedCorsOrigin(origin: string | undefined): CorsOrigin | null {\n const allowedOrigin = resolveAllowedCorsOrigin(origin, {\n allowedOrigins: readCorsAllowedOrigins(),\n // Let the cors-origins default apply (dev-only). Omitting this option\n // keeps production from trusting arbitrary localhost callers.\n });\n if (allowedOrigin) {\n return { origin: allowedOrigin, credentials: true };\n }\n if (origin && isMcpEmbedCorsOrigin(origin)) {\n return {\n origin,\n credentials: shouldAllowMcpEmbedCredentials(origin),\n };\n }\n return null;\n}\n\nfunction handleOptionsRequest(event: any): string {\n const origin = getHeader(event, \"origin\");\n const cors = getAllowedCorsOrigin(\n typeof origin === \"string\" ? origin : undefined,\n );\n\n if (origin && !cors) {\n setResponseStatus(event, 403);\n return \"\";\n }\n\n if (cors) {\n setResponseHeader(event, \"Access-Control-Allow-Origin\", cors.origin);\n setResponseHeader(event, \"Vary\", \"Origin\");\n if (cors.credentials) {\n setResponseHeader(event, \"Access-Control-Allow-Credentials\", \"true\");\n }\n setResponseHeader(\n event,\n \"Access-Control-Allow-Methods\",\n \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n );\n setResponseHeader(\n event,\n \"Access-Control-Allow-Headers\",\n cors.credentials\n ? `Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend,${EMBED_TARGET_HEADER}`\n : `${MCP_EMBED_CORS_ALLOW_HEADERS},X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend`,\n );\n }\n\n setResponseStatus(event, 204);\n return \"\";\n}\n\nexport interface MountActionRoutesOptions {\n /** Resolve owner email from the H3 event (for data scoping). */\n getOwnerFromEvent?: (event: any) => string | Promise<string>;\n /** Resolve display name from the H3 event, when available. */\n getUserNameFromEvent?: (\n event: any,\n ) => string | undefined | Promise<string | undefined>;\n /** Resolve org ID from the H3 event (for org scoping). */\n resolveOrgId?: (event: any) => string | null | Promise<string | null>;\n}\n\nfunction isAuthResolutionFailure(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const maybeStatus = error as {\n status?: unknown;\n statusCode?: unknown;\n statusMessage?: unknown;\n };\n const status =\n typeof maybeStatus.statusCode === \"number\"\n ? maybeStatus.statusCode\n : typeof maybeStatus.status === \"number\"\n ? maybeStatus.status\n : undefined;\n if (status === 401 || status === 403) return true;\n return (\n typeof maybeStatus.statusMessage === \"string\" &&\n /unauthenticated|forbidden/i.test(maybeStatus.statusMessage)\n );\n}\n\n/**\n * Mount discovered actions as HTTP endpoints.\n *\n * Only actions from `autoDiscoverActions` (template actions) are mounted.\n * Built-in actions (resource-*, chat-*, shell, etc.) are NOT passed here.\n */\nexport function mountActionRoutes(\n nitroApp: any,\n actions: Record<string, ActionEntry>,\n options?: MountActionRoutesOptions,\n) {\n const mounted: string[] = [];\n\n for (const [name, entry] of Object.entries(actions)) {\n // Skip agent-only actions\n if (entry.http === false) continue;\n\n const method = entry.http?.method ?? \"POST\";\n const path = entry.http?.path ?? name;\n const routePath = `${ROUTE_PREFIX}/${path}`;\n\n getH3App(nitroApp).use(\n routePath,\n defineEventHandler(async (event) => {\n const reqMethod = getMethod(event);\n const effectiveMethod =\n reqMethod === \"HEAD\" && method === \"GET\" ? \"GET\" : reqMethod;\n\n if (reqMethod === \"OPTIONS\") {\n return handleOptionsRequest(event);\n }\n\n setResponseHeader(event, \"Cache-Control\", \"no-store\");\n\n // Allow the declared method\n if (effectiveMethod !== method) {\n setResponseStatus(event, 405);\n return { error: `Method not allowed. Use ${method}.` };\n }\n\n // (audit H5) Per-action `toolCallable` opt-out for the tools-iframe\n // bridge. The bridge tags every outbound action call with\n // X-Agent-Native-Tool-Bridge: 1. When that header is present and the\n // action declares `toolCallable: false`, we 403 — used by the\n // framework's share-resource / unshare-resource /\n // set-resource-visibility for defense-in-depth on auth-adjacent\n // operations. Undefined defaults to allow: tools are intra-org and\n // typically authored by trusted teammates, so the default is to\n // trust the org-level access controls.\n // The header is set by the parent (the React host), not by the\n // iframe's user-authored content; sanitizeToolRequestOptions strips\n // iframe attempts to spoof it.\n const fromToolBridge =\n getHeader(event, \"x-agent-native-tool-bridge\") === \"1\";\n if (fromToolBridge && entry.toolCallable === false) {\n setResponseStatus(event, 403);\n return {\n error: `Action '${name}' is not callable from tools.`,\n };\n }\n\n // Resolve auth context for per-request scoping\n let userEmail: string | undefined;\n let userName: string | undefined;\n if (options?.getOwnerFromEvent) {\n try {\n userEmail = await options.getOwnerFromEvent(event);\n userName = options?.getUserNameFromEvent\n ? await options.getUserNameFromEvent(event)\n : undefined;\n } catch (error) {\n if (\n entry.requiresAuth === false &&\n isAuthResolutionFailure(error)\n ) {\n userEmail = undefined;\n userName = undefined;\n } else {\n throw error;\n }\n }\n }\n const orgId = options?.resolveOrgId\n ? ((await options.resolveOrgId(event)) ?? undefined)\n : undefined;\n const timezone = readTimezoneHeader(event);\n\n return runWithRequestContext(\n { userEmail, userName, orgId, timezone },\n async () => {\n // Parse params based on method. On web-standard runtimes (Netlify\n // Functions, CF Workers), event.req IS the web Request — use .json()\n // directly. H3's readBody fails on those runtimes because it expects\n // a Node.js stream on event.node.req.\n let params: Record<string, any>;\n try {\n if (method === \"GET\") {\n // H3 v2: prefer web Request URL, fallback to getQuery\n const webReq = (event as any).req;\n if (webReq?.url) {\n const url = new URL(webReq.url);\n params = parseActionSearchParams(url.searchParams);\n } else {\n params = parseActionQueryObject(\n getQuery(event) as Record<string, any>,\n );\n }\n } else {\n const webReq = (event as any).req;\n if (webReq && typeof webReq.json === \"function\") {\n // H3 v2: event.req is the web Request — use .json() directly\n params = (await webReq.json().catch(() => null)) ?? {};\n } else {\n // Fallback: H3's readBody (Node.js dev)\n params = (await readBody(event)) ?? {};\n }\n }\n } catch {\n params = {};\n }\n\n // Run the action. Tag the caller: browser calls (useActionQuery /\n // useActionMutation / callAction) send X-Agent-Native-Frontend: 1,\n // so they become \"frontend\"; bare programmatic POSTs are \"http\".\n // userEmail / orgId mirror the request context resolved above (do\n // NOT inject a dev identity — leave undefined when unauthenticated).\n try {\n const caller = isFrontendActionRequest(event)\n ? \"frontend\"\n : \"http\";\n const result = await entry.run(params, {\n userEmail,\n orgId: orgId ?? null,\n caller,\n actionName: name,\n });\n\n // Auto-refresh the UI after a successful mutating action. GET\n // actions and actions explicitly flagged readOnly are skipped.\n // Other tabs' useDbSync will see source:\"action\" and invalidate\n // their action queries. The calling tab already refetches via\n // useActionMutation's onSuccess, so this is mainly cross-tab\n // sync (and parity with the agent's tool-call path).\n // Explicit entry.readOnly (true OR false) wins over the method\n // heuristic. defineAction already auto-infers GET → readOnly=true,\n // so for actions registered through that path entry.readOnly is\n // always set and the fallback just guards legacy wrap paths.\n const isReadOnly =\n typeof entry.readOnly === \"boolean\"\n ? entry.readOnly\n : method === \"GET\";\n if (!isReadOnly) {\n try {\n await notifyActionChange({\n actionName: name,\n ...(userEmail ? { owner: userEmail } : {}),\n });\n } catch {\n // ignore\n }\n }\n\n // If the action returned a string, try to parse as JSON for a\n // clean response. Plain strings still need to go over the HTTP\n // action transport as JSON, otherwise H3 sends text/plain and the\n // browser action client rejects the successful 2xx response.\n if (typeof result === \"string\") {\n try {\n return JSON.parse(result);\n } catch {\n setResponseHeader(event, \"Content-Type\", \"application/json\");\n return JSON.stringify(result);\n }\n }\n\n return result;\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const isValidationError = msg.startsWith(\n \"Invalid action parameters\",\n );\n const explicitStatus =\n typeof err?.statusCode === \"number\"\n ? err.statusCode\n : undefined;\n // Return 400 for validation errors, the explicit statusCode if\n // set, otherwise 500.\n const status = isValidationError ? 400 : (explicitStatus ?? 500);\n setResponseStatus(event, status);\n\n // Only echo the raw message for known-safe cases:\n // - validation errors (deterministic, parameter-shape only)\n // - explicit user-facing errors (AgentActionStopError / fail())\n // - errors with an explicit statusCode < 500 (client errors)\n // For uncategorized 500s, return a generic message and keep the\n // real detail server-side only — it can contain DB/driver/\n // upstream text we must not leak to HTTP callers.\n const isUserFacing =\n isValidationError ||\n isAgentActionStopError(err) ||\n (explicitStatus !== undefined && explicitStatus < 500);\n if (isUserFacing) {\n return { error: msg };\n }\n console.error(`[agent-native] action '${name}' failed:`, err);\n return { error: \"Internal server error\" };\n }\n },\n ); // end runWithRequestContext\n }),\n );\n\n mounted.push(`${method} ${routePath}`);\n }\n\n if (mounted.length > 0 && process.env.DEBUG)\n console.log(\n `[action-routes] Mounted ${mounted.length} action route(s): ${mounted.join(\", \")}`,\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-chat-plugin.d.ts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GAAG,OAAO,CA2BV;AAED,wBAAgB,qBAAqB,CACnC,OAAO,CAAC,EAAE,sBAAsB,GAC/B,cAAc,CAivIhB;AAED;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,EAAE,cAAwC,CAAC;AAa9E,yEAAyE;AACzE,wBAAgB,mBAAmB,IAAI,gBAAgB,GAAG,IAAI,CAE7D;AAED,yFAAyF;AACzF,wBAAsB,uBAAuB,IAAI,OAAO,CAAC,OAAO,CAAC,CAKhE"}
@@ -28,10 +28,12 @@ import { normalizeDatabaseToolsMode, } from "../scripts/db/tool-mode.js";
28
28
  import { dbExecToolParameters } from "../scripts/db/tool-schemas.js";
29
29
  import { getSetting, putSetting } from "../settings/store.js";
30
30
  import { discoverAgents } from "./agent-discovery.js";
31
+ import { resolveAgentRunOwnerContext, runWithAgentRunContext, seedBackgroundAgentRunOwnerContext, } from "./agent-run-context.js";
31
32
  import { AGENT_TEAM_PROCESS_RUN_PATH, getCurrentDelegationDepth, processAgentTeamRun, reconcileAgentTeamRunsForOwner, } from "./agent-teams.js";
32
33
  import { withConfiguredAppBasePath } from "./app-base-path.js";
33
34
  import { getSession } from "./auth.js";
34
35
  import { getBuilderBrowserConnectUrlForOwner, resolveBuilderBranchProjectId, } from "./builder-browser.js";
36
+ import { captureError } from "./capture-error.js";
35
37
  import { captureCliOutput } from "./cli-capture.js";
36
38
  import { getH3App, markDefaultPluginProvided, trackPluginInit, } from "./framework-request-handler.js";
37
39
  import { getOrigin } from "./google-oauth.js";
@@ -581,13 +583,47 @@ function resolveArtifactBaseUrl(event) {
581
583
  return undefined;
582
584
  }
583
585
  export function assembleA2AFinalResponse(events, toolResults, options = {}) {
584
- const responseText = collectFinalResponseTextFromAgentEvents(events);
586
+ const terminalError = getA2ATerminalErrorEvent(events);
587
+ const responseText = collectFinalResponseTextFromAgentEvents(events, {
588
+ fallbackToPreToolText: !terminalError,
589
+ });
585
590
  const finalText = appendA2AArtifactLinks(responseText, [...toolResults], {
586
591
  baseUrl: options.baseUrl ?? resolveArtifactBaseUrl(options.event),
587
592
  includeReferencedArtifacts: true,
588
593
  });
594
+ if (terminalError && !finalText.trim()) {
595
+ throw new Error(formatA2ATerminalError(terminalError));
596
+ }
589
597
  return { responseText, finalText };
590
598
  }
599
+ function getA2ATerminalErrorEvent(events) {
600
+ for (let i = events.length - 1; i >= 0; i--) {
601
+ const event = events[i];
602
+ if (event.type === "clear")
603
+ continue;
604
+ if (event.type === "done")
605
+ return null;
606
+ if (event.type === "error")
607
+ return event;
608
+ if (event.type === "auto_continue") {
609
+ return {
610
+ type: "error",
611
+ error: `Agent stopped before finishing (${event.reason}).`,
612
+ errorCode: event.reason,
613
+ recoverable: true,
614
+ };
615
+ }
616
+ }
617
+ return null;
618
+ }
619
+ function formatA2ATerminalError(event) {
620
+ const parts = [
621
+ event.error || "Agent failed before producing a final response.",
622
+ event.errorCode ? `code: ${event.errorCode}` : "",
623
+ event.details ? `details: ${event.details}` : "",
624
+ ].filter(Boolean);
625
+ return parts.join("\n");
626
+ }
591
627
  /**
592
628
  * Creates the `get-framework-context` tool. Returns detailed instructions
593
629
  * for framework capabilities that are summarized in the compact prompt.
@@ -2149,6 +2185,8 @@ In Act mode, if the user asks for generated interactive UI in chat, choose the s
2149
2185
 
2150
2186
  These are **NOT** source-code changes and do **NOT** go through \`connect-builder\`. Extensions are sandboxed mini-apps — no source files are touched, no PR is opened, no build is required. Saved extensions can be edited later via \`update-extension\`.
2151
2187
 
2188
+ If the app exposes native actions or instructions for dashboards, reports, analyses, charts, documents, decks, or other domain artifacts, use those app-native actions first. Choose an extension only when the user explicitly asks for an extension/custom mini-app, or when the app's native artifact format cannot faithfully express the requested interaction.
2189
+
2152
2190
  Keep \`create-extension\` payloads compact enough to finish quickly. For complex extensions, create a useful working v1 first, then call \`update-extension\` with focused edits for refinements instead of trying to assemble one enormous initial tool input.
2153
2191
 
2154
2192
  Generated UI content can use appAction(), appFetch(), dbQuery(), dbExec(), extensionFetch(), extensionData, agentNative.ui.output(value, opts?), and agentNative.chat.send(...)/sendToAgentChat(...). It can receive chat inputs through slotContext/window.onSlotContext. Use agentNative.ui.output for passive current values from knobs, sliders, selections, and controls; it writes application state at \`inline-ui:<extensionId>:output\` scoped to the inline extension id returned by \`render-inline-extension\` or \`show-extension-inline\`. When the user later says "use that value", "apply the current setting", or similar, read it with \`readAppState("inline-ui:<id>:output")\` instead of asking them to send it again. Use agentNative.chat.send for visible submit/apply actions that should put a message into chat. Transient extensionData is browser-local and not agent-readable, synced, promoted, or garbage-collected; use application_state/appFetch, appAction, ui.output, or chat.send for anything the agent or app must observe. Use semantic Tailwind classes like bg-background, text-foreground, bg-primary, border-border, and text-muted-foreground so the UI inherits the parent app theme.
@@ -2176,7 +2214,7 @@ Route by what the request changes, not how it is phrased. Extensions render in t
2176
2214
  | Ambiguous, satisfiable either way (e.g. "give me an unread view") | \`render-inline-extension\` for chat-only, \`create-extension\` for reusable |
2177
2215
  </routing>
2178
2216
 
2179
- Worked examples: "a widget showing unread emails grouped by sender", "a dashboard summarizing my pipeline", "a tracker for my newsletter subscriptions" → \`create-extension\`. "Add an Unread tab to the left navigation", "make the subject lines wrap", "change the inbox grouping logic", "add a field to the compose form" → \`connect-builder\`.`
2217
+ Worked examples: "a widget showing unread emails grouped by sender", "a tracker for my newsletter subscriptions", "a custom kanban board with drag-and-drop rules the app does not have" → \`create-extension\`. "Add an Unread tab to the left navigation", "make the subject lines wrap", "change the inbox grouping logic", "add a field to the compose form" → \`connect-builder\`.`
2180
2218
  : `### Extensions Disabled
2181
2219
 
2182
2220
  Extension creation and management tools are disabled for this app. Do not claim you can create, edit, hide, or delete Agent-Native extensions unless the template exposes its own typed action for that workflow. For requests that would otherwise be handled as an extension/widget/dashboard/calculator mini-app, explain that this app has disabled extension tools and use the app's available actions instead.`;
@@ -2185,6 +2223,8 @@ Extension creation and management tools are disabled for this app. Do not claim
2185
2223
 
2186
2224
  In Act mode, if the user asks for generated interactive UI in chat, call \`render-inline-extension\` for one-time inline controls/knobs/calculators/visualizers that do not need saving. If the user asks for an **extension**, **widget**, **dashboard**, **calculator**, or **mini-app** that should be reusable or saved, call \`create-extension\` with a self-contained Alpine.js HTML body. To load a saved extension inline, call \`show-extension-inline\`. These are NOT code changes — extensions are sandboxed mini-apps. Do not preface with "let me build…" — just call the right extension action.
2187
2225
 
2226
+ Use app-native artifact actions first when they exist for dashboards, reports, analyses, charts, documents, decks, or similar domain artifacts. Pick \`create-extension\` only for explicit extension/custom mini-app requests or for behavior the native artifact format cannot support.
2227
+
2188
2228
  Keep the first \`create-extension\` call compact and working. If the request is complex, create the v1 first and then refine with focused \`update-extension\` edits.
2189
2229
 
2190
2230
  Generated UI can read chat inputs from slotContext/window.onSlotContext, see/update app state through appFetch/appAction, use extensionData, record passive current values through agentNative.ui.output(value, opts?), and send visible results through agentNative.chat.send(...) or sendToAgentChat(...). ui.output writes \`inline-ui:<extensionId>:output\` in application state; when the user asks to use the current slider/selection/value, read \`readAppState("inline-ui:<id>:output")\`. Transient extensionData is browser-local only, so do not rely on it for values the agent or app must observe. Use semantic Tailwind theme classes.
@@ -3798,36 +3838,11 @@ export function createAgentChatPlugin(options) {
3798
3838
  },
3799
3839
  });
3800
3840
  }
3801
- const OWNER_CONTEXT_KEY = "__agentNativeOwnerContext";
3802
3841
  // Resolve owner from the H3 event's session, with an optional
3803
3842
  // template-provided anonymous owner for public read-only surfaces.
3804
3843
  const resolveOwnerContext = async (event) => {
3805
- const eventContext = event?.context;
3806
- if (eventContext?.[OWNER_CONTEXT_KEY]) {
3807
- return eventContext[OWNER_CONTEXT_KEY];
3808
- }
3809
- const session = await getSession(event);
3810
- if (session?.email) {
3811
- const resolved = {
3812
- owner: session.email,
3813
- anonymous: false,
3814
- name: session.name,
3815
- };
3816
- if (eventContext)
3817
- eventContext[OWNER_CONTEXT_KEY] = resolved;
3818
- return resolved;
3819
- }
3820
- const anonymousOwner = await options?.anonymousOwner?.(event);
3821
- if (anonymousOwner) {
3822
- const resolved = { owner: anonymousOwner, anonymous: true };
3823
- if (eventContext)
3824
- eventContext[OWNER_CONTEXT_KEY] = resolved;
3825
- return resolved;
3826
- }
3827
- const { createError } = await import("h3");
3828
- throw createError({
3829
- statusCode: 401,
3830
- statusMessage: "Unauthenticated",
3844
+ return resolveAgentRunOwnerContext(event, {
3845
+ anonymousOwner: options?.anonymousOwner,
3831
3846
  });
3832
3847
  };
3833
3848
  const getOwnerFromEvent = async (event) => {
@@ -6078,91 +6093,13 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
6078
6093
  // the background worker), so both go through identical context + handler
6079
6094
  // selection.
6080
6095
  const invokeAgentChatHandler = async (event) => {
6081
- // Resolve per-request auth context
6096
+ // Resolve per-request auth context.
6082
6097
  const ownerContext = await resolveOwnerContext(event);
6083
- const owner = ownerContext.owner;
6084
- // Resolve org ID: explicit callback > session.orgId from Better Auth
6085
- // > implicit org membership. Better Auth leaves session.orgId null
6086
- // until the user explicitly switches orgs, so a fresh signup with
6087
- // implicit membership (e.g. domain-matched org) would otherwise see
6088
- // no org-scoped credentials. getOrgContext() does the same DB lookup
6089
- // the /builder/status endpoint uses to decide "Connected".
6090
- let resolvedOrgId;
6091
- if (options?.resolveOrgId) {
6092
- resolvedOrgId = (await options.resolveOrgId(event)) ?? undefined;
6093
- }
6094
- else {
6095
- try {
6096
- const session = await getSession(event);
6097
- resolvedOrgId = session?.orgId ?? undefined;
6098
- }
6099
- catch {
6100
- // Session not available
6101
- }
6102
- if (!resolvedOrgId) {
6103
- try {
6104
- const { getOrgContext } = await import("../org/context.js");
6105
- const ctx = await getOrgContext(event);
6106
- resolvedOrgId = ctx.orgId ?? undefined;
6107
- }
6108
- catch {
6109
- // org_members table may not exist yet on first boot
6110
- }
6111
- }
6112
- }
6113
- // Cookieless durable background worker: getSession()/getOrgContext()
6114
- // resolve from the (absent) session, so org-scoped credential resolution
6115
- // (the Builder engine) would miss the owner's org and resolveEngine would
6116
- // fall back to the anthropic default — bailing on a missing key before
6117
- // the worker claims its run. The owner IS known here (seeded via
6118
- // OWNER_CONTEXT_KEY from the run's thread), so resolve the org directly
6119
- // from the owner email, the same active-org logic the foreground session
6120
- // would yield.
6121
- if (!resolvedOrgId && owner) {
6122
- try {
6123
- const { resolveOrgIdForEmail } = await import("../org/context.js");
6124
- resolvedOrgId = (await resolveOrgIdForEmail(owner)) ?? undefined;
6125
- }
6126
- catch {
6127
- // org tables unavailable — proceed without org (foreground-equivalent)
6128
- }
6129
- }
6130
- // DURABLE OWNER CONTEXT, PART 2: ORG.
6131
- // The cookieless `_process-run` self-dispatch (and any other background
6132
- // re-entry) resolves the owner from the run row, but has NO session —
6133
- // every org resolver above ultimately derives identity from
6134
- // getSession(event), so they all come back null here. That silently
6135
- // scopes the agent to `org_id IS NULL` rows only: it sees and writes
6136
- // resources outside the user's org, while the foreground UI — which
6137
- // carries the session cookie — resolves the real org. The result is the
6138
- // observed split where the agent can't list/read the same resources the
6139
- // UI shows and writes new rows with a null org. Resolve the org from the
6140
- // now-known owner email (the same active-org / membership logic
6141
- // getOrgContext uses, minus the session) so the agent and the UI operate
6142
- // over the same org-scoped data.
6143
- if (!resolvedOrgId && owner && !ownerContext.anonymous) {
6144
- try {
6145
- const { resolveOrgIdForEmail } = await import("../org/context.js");
6146
- resolvedOrgId = (await resolveOrgIdForEmail(owner)) ?? undefined;
6147
- }
6148
- catch {
6149
- // org tables unavailable (first boot) — leave org unscoped
6150
- }
6151
- }
6152
- // Propagate the caller's IANA timezone from `x-user-timezone` so that
6153
- // tool calls made by the agent (e.g. log-meal with no explicit date)
6154
- // resolve "today" in the user's local timezone instead of server UTC.
6155
- const tzRaw = getHeader(event, "x-user-timezone");
6156
- const timezone = typeof tzRaw === "string" &&
6157
- tzRaw.trim().length > 0 &&
6158
- tzRaw.trim().length < 64
6159
- ? tzRaw.trim()
6160
- : undefined;
6161
- return runWithRequestContext({
6162
- userEmail: owner,
6163
- userName: ownerContext.name,
6164
- orgId: resolvedOrgId,
6165
- timezone,
6098
+ return runWithAgentRunContext({
6099
+ event,
6100
+ ownerContext,
6101
+ resolveOrgId: options?.resolveOrgId,
6102
+ isBackgroundWorker: Boolean(event.context?.__agentChatBackgroundBody),
6166
6103
  }, () => {
6167
6104
  // App-rendered chat can't host direct code edits — HMR/full
6168
6105
  // reloads would kill the same chat surface mid-run. Force the
@@ -6256,51 +6193,29 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
6256
6193
  // is already consumed, so the handler reads this instead.
6257
6194
  event.context = event.context ?? {};
6258
6195
  event.context.__agentChatBackgroundBody = prepared.body;
6259
- // DURABLE OWNER CONTEXT: this self-dispatch is cookieless (HMAC-only
6260
- // the foreground POST carried the user's session, but this background-
6261
- // function invocation does not). Without a session, resolveOwnerContext()
6262
- // falls through to its 401 "Unauthenticated" throw and the worker dies
6263
- // before it can even claim the run (observed in prod as the `route_threw`
6264
- // diag stage — every durable run only completed via the foreground
6265
- // circuit-breaker's inline recovery). The run's chat thread already
6266
- // records the authenticated owner (written by the foreground under the
6267
- // signed-in user), so resolve the owner from the run row — NOT from the
6268
- // request body, which the HMAC does not cover and a caller could forge —
6269
- // and pre-seed the owner context the handler reads (resolveOwnerContext
6270
- // returns it before attempting any session lookup).
6271
- let backgroundOwner = null;
6272
- try {
6273
- const { getRunOwnerEmail } = await import("../agent/run-store.js");
6274
- backgroundOwner = await getRunOwnerEmail(prepared.runId);
6275
- if (backgroundOwner) {
6276
- event.context[OWNER_CONTEXT_KEY] = {
6277
- owner: backgroundOwner,
6278
- anonymous: false,
6279
- };
6280
- }
6281
- }
6282
- catch {
6283
- // Best-effort: if the lookup fails, resolveOwnerContext runs as before
6284
- // and throws its normal 401, surfaced via the route_threw diagnostic.
6285
- }
6196
+ // Durable owner context: this self-dispatch is cookieless (HMAC-only).
6197
+ // Resolve the owner from the persisted run row, never the request body,
6198
+ // then invoke the normal handler. The shared agent-run context helper
6199
+ // expands that owner into the same user/org AsyncLocalStorage context the
6200
+ // foreground request uses, so credential and data scoping stay aligned.
6201
+ await seedBackgroundAgentRunOwnerContext(event, prepared.runId);
6286
6202
  try {
6287
- // Run the worker INSIDE the owner's AsyncLocalStorage request context.
6288
- // Seeding OWNER_CONTEXT_KEY (above) only feeds getOwnerFromEvent; the
6289
- // engine-resolution path (detectEngineFromUserSecrets) and other
6290
- // owner-scoped reads use getRequestUserEmail()/getRequestOrgId(),
6291
- // which a cookieless background worker otherwise leaves empty. Without
6292
- // this, resolveEngine can't see the owner's Builder credential, falls
6293
- // back to the anthropic default, and — when the owner has no stored
6294
- // anthropic key and deploy-credential fallback is blocked — bails at
6295
- // the API-key check BEFORE claiming its run (the analytics durable
6296
- // worker's "stalls at post_model, never claims" bug).
6297
- const invoke = () => invokeAgentChatHandler(event);
6298
- return await (backgroundOwner
6299
- ? runWithRequestContext({ userEmail: backgroundOwner }, invoke)
6300
- : invoke());
6203
+ return await invokeAgentChatHandler(event);
6301
6204
  }
6302
6205
  catch (err) {
6303
6206
  console.error("[agent-chat] _process-run failed:", err);
6207
+ captureError(err, {
6208
+ route: AGENT_CHAT_PROCESS_RUN_PATH,
6209
+ method: getMethod(event),
6210
+ userAgent: getHeader(event, "user-agent"),
6211
+ tags: {
6212
+ source: "agent-chat-bg-worker",
6213
+ phase: "process-run",
6214
+ },
6215
+ extra: {
6216
+ runId: prepared.runId,
6217
+ },
6218
+ });
6304
6219
  // DIAGNOSTIC: the worker invocation threw at the route boundary —
6305
6220
  // record the message so the failure cause is readable client-side.
6306
6221
  if (diag) {