@agent-native/core 0.7.65 → 0.7.67

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.
@@ -1 +1 @@
1
- {"version":3,"file":"production-agent.d.ts","sourceRoot":"","sources":["../../src/agent/production-agent.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,YAAY,IAAI,cAAc,EAAE,MAAM,IAAI,CAAC;AACzD,OAAO,KAAK,EACV,UAAU,EACV,mBAAmB,EAEnB,cAAc,EAEf,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,aAAa,EACb,iBAAiB,EAClB,MAAM,mBAAmB,CAAC;AAQ3B,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAEhE,OAAO,EAEL,cAAc,EACd,qBAAqB,EACrB,0BAA0B,EAC1B,MAAM,EACN,QAAQ,EACT,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAgBlD,OAAO,EAGL,KAAK,eAAe,EACrB,MAAM,+BAA+B,CAAC;AAKvC,OAAO,EAAE,eAAe,EAAE,CAAC;AAE3B;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACpC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA+B7B;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE3D;AAuBD;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,oBAAoB,CACxC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACpC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAqB7B;AAED,sEAAsE;AACtE,wBAAsB,uBAAuB,CAC3C,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACpC,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C;IACrB,eAAe,EAAE,MAAM,CAAC;IACxB,gBAAgB,EAAE,MAAM,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACnC,UAAU,EAAE,CAiBd;AAiDD;;;;GAIG;AACH,wBAAsB,YAAY,CAAC,IAAI,EAAE;IACvC,MAAM,EAAE,WAAW,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,UAAU,EAAE,CAAC;IACpB,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IACrC,IAAI,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,CAAC;IACtC,MAAM,EAAE,WAAW,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,eAAe,CAAC,EAAE,GAAG,CAAC;IACtB,aAAa,CAAC,EAAE,kBAAkB,CAAC;IACnC,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,GAAG,OAAO,CAAC,cAAc,CAAC,CA6S1B;AAED,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,sBAAsB,GAC9B,cAAc,CAwxBhB;AAED,OAAO,EACL,qBAAqB,EACrB,0BAA0B,EAC1B,MAAM,EACN,QAAQ,EACR,cAAc,GACf,CAAC"}
1
+ {"version":3,"file":"production-agent.d.ts","sourceRoot":"","sources":["../../src/agent/production-agent.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,YAAY,IAAI,cAAc,EAAE,MAAM,IAAI,CAAC;AACzD,OAAO,KAAK,EACV,UAAU,EACV,mBAAmB,EAEnB,cAAc,EAEf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C;IACd,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,UAAU,EAAE,CAAC;IACpB,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IACrC,IAAI,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,CAAC;IACtC,MAAM,EAAE,WAAW,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,eAAe,CAAC,EAAE,GAAG,CAAC;IACtB,aAAa,CAAC,EAAE,kBAAkB,CAAC;IACnC,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,GAAG,OAAO,CAAC,cAAc,CAAC,CA6S1B;AAED,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,sBAAsB,GAC9B,cAAc,CA4xBhB;AAED,OAAO,EACL,qBAAqB,EACrB,0BAA0B,EAC1B,MAAM,EACN,QAAQ,EACR,cAAc,GACf,CAAC"}
@@ -1280,6 +1280,10 @@ export function createProductionAgentHandler(options) {
1280
1280
  responseText = await callAgent(ref.path, enrichedMessage + screenContext);
1281
1281
  }
1282
1282
  }
1283
+ responseText =
1284
+ userFacingLlmCredentialError(responseText, {
1285
+ agentName: ref.name,
1286
+ }) ?? responseText;
1283
1287
  send({
1284
1288
  type: "agent_call",
1285
1289
  agent: ref.name,
@@ -1 +1 @@
1
- {"version":3,"file":"production-agent.js","sourceRoot":"","sources":["../../src/agent/production-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,GACV,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,E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,CAAC;gBACP,+CAA+C;YACjD,CAAC;QACH,CAAC,EACD,OAAO,CAAC,aAAa;YACnB,CAAC,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,aAAc,CAAC,GAAG,EAAE,QAAQ,CAAC;YAChD,CAAC,CAAC,SAAS,CACd,CAAC;QAEF,uDAAuD;QACvD,MAAM,MAAM,GAAG,cAAc,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QACxC,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;YAC9B,OAAO,EAAE,KAAK,EAAE,2BAA2B,EAAE,CAAC;QAChD,CAAC;QAED,iBAAiB,CAAC,KAAK,EAAE,cAAc,EAAE,mBAAmB,CAAC,CAAC;QAC9D,iBAAiB,CAAC,KAAK,EAAE,eAAe,EAAE,UAAU,CAAC,CAAC;QACtD,iBAAiB,CAAC,KAAK,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;QACrD,iBAAiB,CAAC,KAAK,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;QAE5C,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,OAAO,EACL,qBAAqB,EACrB,0BAA0B,EAC1B,MAAM,EACN,QAAQ,EACR,cAAc,GACf,CAAC","sourcesContent":["import {\n defineEventHandler,\n setResponseHeader,\n setResponseStatus,\n getMethod,\n} from \"h3\";\nimport { DEV_MODE_USER_EMAIL } from \"../server/auth.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\nimport { readDeployCredentialEnv } from \"../server/credential-provider.js\";\nimport type { EventHandler as H3EventHandler } from \"h3\";\nimport type {\n ActionTool,\n AgentChatAttachment,\n AgentChatRequest,\n AgentChatEvent,\n AgentChatReference,\n} from \"./types.js\";\nimport type {\n AgentEngine,\n EngineTool,\n EngineMessage,\n EngineContentPart,\n} from \"./engine/types.js\";\nimport { EngineError } from \"./engine/types.js\";\nimport {\n resolveEngine,\n registerBuiltinEngines,\n getStoredModelForEngine,\n} from \"./engine/index.js\";\nimport { userFacingLlmCredentialError } from \"./engine/credential-errors.js\";\nimport { PROVIDER_TO_ENV } from \"./engine/provider-env-vars.js\";\nimport { readAppState } from \"../application-state/script-helpers.js\";\nimport {\n startRun,\n subscribeToRun,\n getActiveRunForThread,\n getActiveRunForThreadAsync,\n getRun,\n abortRun,\n} from \"./run-manager.js\";\nimport type { ActiveRun } from \"./run-manager.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport {\n getRequestOrgId,\n getRequestUserEmail,\n} from \"../server/request-context.js\";\nimport { isMcpToolAllowedForRequest } from \"../mcp-client/visibility.js\";\nimport {\n createToolSearchEntry,\n TOOL_SEARCH_ACTION_NAME,\n} from \"./tool-search.js\";\nimport {\n getDefaultMaxIterations,\n normalizeMaxIterations,\n readAgentLoopSettings,\n} from \"./loop-settings.js\";\nimport {\n isReasoningEffort,\n normalizeReasoningEffortForModel,\n type ReasoningEffort,\n} from \"../shared/reasoning-effort.js\";\n\n// Register built-in engines on first import\nregisterBuiltinEngines();\n\nexport { PROVIDER_TO_ENV };\n\n/**\n * Look up a user's persisted API key for the given provider. Returns\n * `undefined` for unauthenticated/local callers so the shared platform key\n * is never keyed off `local@localhost` in multi-tenant deployments.\n *\n * Read order:\n * 1. `app_secrets` — encrypted, scope=user, current source of truth.\n * 2. Legacy `user-api-key:<provider>:<email>` settings row — pre-migration\n * data that hasn't been backfilled yet. Surfaced for compat only;\n * writes always go to app_secrets now.\n */\nexport async function getOwnerApiKey(\n provider: string,\n ownerEmail: string | null | undefined,\n): Promise<string | undefined> {\n if (!ownerEmail || ownerEmail === DEV_MODE_USER_EMAIL) return undefined;\n const secretKey =\n PROVIDER_TO_ENV[provider] ?? `${provider.toUpperCase()}_API_KEY`;\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n const fromSecrets = await readAppSecret({\n key: secretKey,\n scope: \"user\",\n scopeId: ownerEmail,\n });\n if (fromSecrets?.value) return fromSecrets.value;\n } catch {\n // app_secrets table not ready — fall through to legacy lookup.\n }\n try {\n const { getSetting } = await import(\"../settings/store.js\");\n const stored = await getSetting(`user-api-key:${provider}:${ownerEmail}`);\n const key =\n stored && typeof stored.key === \"string\" ? stored.key.trim() : \"\";\n if (key) return key;\n if (provider === \"anthropic\") {\n const legacy = await getSetting(`user-anthropic-api-key:${ownerEmail}`);\n const legacyKey =\n legacy && typeof legacy.key === \"string\" ? legacy.key.trim() : \"\";\n return legacyKey || undefined;\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Derive the provider name from the active engine setting.\n * \"ai-sdk:openai\" → \"openai\", \"anthropic\" → \"anthropic\"\n */\nexport function engineToProvider(engineName: string): string {\n return engineName.startsWith(\"ai-sdk:\") ? engineName.slice(7) : engineName;\n}\n\n/**\n * Returns true when this process is acting as a multi-tenant deployment —\n * i.e. a hosted shared-DB environment where one user's identity must NOT be\n * silently substituted with the deploy-level API key.\n *\n * Mirrors the gate in `resolveBuilderCredential` (server/credential-provider.ts).\n *\n * Heuristic:\n * - `NODE_ENV === \"production\"`, AND\n * - The DB is not a local file (i.e. it's Neon/Postgres/Turso/D1 — any\n * backend that could be shared across multiple users).\n *\n * Self-hosted single-tenant deployments (a local sqlite file, or NODE_ENV\n * unset/development) keep the env-var fallback so the original BYO-server\n * UX continues to work without a per-user key.\n */\nfunction isMultiTenantDeploy(): boolean {\n if (process.env.NODE_ENV !== \"production\") return false;\n return !isLocalDatabase();\n}\n\n/**\n * Resolve the active engine's provider and look up the user's API key for it.\n *\n * In multi-tenant deploys we deliberately refuse the deploy-level\n * deploy-level fallback for authenticated users. Without that gate any\n * signed-in user who hasn't configured their own provider key would silently\n * inherit the deployment's key (uncapped billing on the owner's account,\n * prompt logging tied to the deployment owner) — exactly the prior-incident\n * pattern we hit on 2026-04-29.\n *\n * Single-tenant (local-dev, self-hosted SQLite) keeps the env fallback.\n *\n * Callers in `agent-chat-plugin.ts`, `triggers/dispatcher.ts`,\n * `jobs/scheduler.ts`, and `integrations/plugin.ts` historically layer\n * another deployment-key fallback after this must keep the same gate.\n */\nexport async function getOwnerActiveApiKey(\n ownerEmail: string | null | undefined,\n): Promise<string | undefined> {\n try {\n const { getSetting } = await import(\"../settings/store.js\");\n const engineSetting = await getSetting(\"agent-engine\");\n const activeEngine =\n (engineSetting?.engine as string | undefined) ?? \"anthropic\";\n const provider = engineToProvider(activeEngine);\n const userKey = await getOwnerApiKey(provider, ownerEmail);\n if (userKey) return userKey;\n if (isMultiTenantDeploy()) {\n // Multi-tenant: refuse the env fallback. A null user (unauthenticated /\n // background context with no owner) gets undefined here too — there's\n // no user to bill, and the call site must surface a \"configure a key\"\n // error to the requester rather than silently using the deploy key.\n return undefined;\n }\n const envVar = PROVIDER_TO_ENV[provider];\n return envVar ? readDeployCredentialEnv(envVar) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** @deprecated Use getOwnerApiKey(\"anthropic\", ownerEmail) instead */\nexport async function getOwnerAnthropicApiKey(\n ownerEmail: string | null | undefined,\n): Promise<string | undefined> {\n return getOwnerApiKey(\"anthropic\", ownerEmail);\n}\n\n/** Context passed to action run() for emitting intermediate events */\nexport interface ActionRunContext {\n /** Emit an SSE event to the client (e.g., agent_call_text for streaming) */\n send: (event: AgentChatEvent) => void;\n}\n\nexport interface ActionEntry {\n tool: ActionTool;\n run: (\n args: Record<string, string>,\n context?: ActionRunContext,\n ) => Promise<any>;\n /** HTTP exposure config. `false` = agent-only. Omitted = auto-inferred from name. */\n http?: import(\"../action.js\").ActionHttpConfig | false;\n /** If true, completion does NOT trigger a screen-refresh poll event.\n * Set automatically by `defineAction` when `http.method === \"GET\"`. */\n readOnly?: boolean;\n /** Whether this action may be invoked from the tools-iframe bridge.\n * **Default-allow opt-out**: only an explicit `false` returns 403.\n * - `true` / `undefined` — allow.\n * - `false` — explicit deny; the tools bridge returns 403.\n * See `defineAction` (`packages/core/src/action.ts`) and audit H5 in\n * `security-audit/05-tools-sandbox.md`. */\n toolCallable?: boolean;\n}\n\n/** @deprecated Use `ActionEntry` instead */\nexport type ScriptEntry = ActionEntry;\n\nexport type AgentExecutionMode = \"act\" | \"plan\";\n\nexport const PLAN_MODE_SYSTEM_PROMPT = `## Plan Mode Active\n\nYou are in Plan mode. This turn is for research, clarification, and a proposed approach only.\n\nHard rules:\n- Use only read-only tools. Do not edit files, write resources, run shell commands, mutate SQL rows, navigate the UI, send notifications, create jobs, create tools, call external agents, or change external systems.\n- If a needed detail is unclear, ask a concise clarifying question before proposing a plan.\n- When ready, present a concrete plan with the files/tools you expect to touch, the intended changes, validation steps, and notable risks.\n- Do not treat approval as implicit while Plan mode is still active. Tell the user to switch to Act mode with the mode selector, Shift+Tab, or /act before implementation.`;\n\nconst PLAN_MODE_BLOCKED_READONLY_TOOLS = new Set([\n \"refresh-screen\",\n \"set-search-params\",\n \"set-url-path\",\n]);\n\nconst PLAN_MODE_ALLOWED_ACTIONS: Record<string, readonly string[]> = {\n resources: [\"list\", \"read\"],\n \"chat-history\": [\"search\"],\n \"agent-teams\": [\"status\", \"read-result\", \"list\"],\n \"manage-jobs\": [\"list\"],\n \"manage-automations\": [\"list-events\", \"list\"],\n \"manage-notifications\": [\"list\"],\n \"manage-progress\": [\"list\"],\n \"manage-agent-engine\": [\"list\"],\n};\n\nconst PLAN_MODE_WEB_REQUEST_METHODS = new Set([\"GET\", \"HEAD\"]);\n\nfunction getToolAction(name: string, args: unknown): string {\n const raw =\n args && typeof args === \"object\" && \"action\" in args\n ? (args as Record<string, unknown>).action\n : undefined;\n if (raw == null && name === \"chat-history\") return \"search\";\n return String(raw ?? \"\").toLowerCase();\n}\n\nfunction getWebRequestMethod(args: unknown): string {\n const raw =\n args && typeof args === \"object\" && \"method\" in args\n ? (args as Record<string, unknown>).method\n : undefined;\n return String(raw ?? \"GET\").toUpperCase();\n}\n\nfunction restrictActionEnum(\n parameters: ActionTool[\"parameters\"] | undefined,\n allowedActions: readonly string[],\n): ActionTool[\"parameters\"] | undefined {\n if (!parameters) return parameters;\n const actionParam = parameters.properties.action;\n if (!actionParam) return parameters;\n return {\n ...parameters,\n properties: {\n ...parameters.properties,\n action: {\n ...actionParam,\n enum: [...allowedActions],\n },\n },\n };\n}\n\nfunction restrictWebRequestMethods(\n parameters: ActionTool[\"parameters\"] | undefined,\n): ActionTool[\"parameters\"] | undefined {\n if (!parameters) return parameters;\n const methodParam = parameters.properties.method;\n if (!methodParam) return parameters;\n return {\n ...parameters,\n properties: {\n ...parameters.properties,\n method: {\n ...methodParam,\n enum: [...PLAN_MODE_WEB_REQUEST_METHODS],\n },\n },\n };\n}\n\nfunction planModeBlockedMessage(toolName: string, reason?: string): string {\n return (\n `Plan mode blocked \\`${toolName}\\`` +\n (reason ? ` (${reason})` : \"\") +\n \". Switch to Act mode after the user approves the plan, then retry the action.\"\n );\n}\n\nexport function isPlanModeToolCallAllowed(\n name: string,\n input: unknown,\n entry: ActionEntry,\n): boolean {\n if (PLAN_MODE_BLOCKED_READONLY_TOOLS.has(name)) return false;\n\n if (name === \"web-request\") {\n return PLAN_MODE_WEB_REQUEST_METHODS.has(getWebRequestMethod(input));\n }\n\n const allowedActions = PLAN_MODE_ALLOWED_ACTIONS[name];\n if (allowedActions) {\n return allowedActions.includes(getToolAction(name, input));\n }\n\n return entry.readOnly === true;\n}\n\nfunction createPlanModeGuardedAction(\n name: string,\n entry: ActionEntry,\n allowedActions: readonly string[],\n): ActionEntry {\n return {\n ...entry,\n readOnly: true,\n tool: {\n ...entry.tool,\n description:\n `${entry.tool.description}\\n\\nPlan mode: only these read-only actions are available: ` +\n allowedActions.map((action) => `\"${action}\"`).join(\", \") +\n \".\",\n parameters: restrictActionEnum(entry.tool.parameters, allowedActions),\n },\n run: async (args, context) => {\n const action = getToolAction(name, args);\n if (!allowedActions.includes(action)) {\n return planModeBlockedMessage(\n name,\n `action=\"${action || \"(missing)\"}\"`,\n );\n }\n return entry.run(args, context);\n },\n };\n}\n\nfunction createPlanModeWebRequestAction(entry: ActionEntry): ActionEntry {\n return {\n ...entry,\n readOnly: true,\n tool: {\n ...entry.tool,\n description: `${entry.tool.description}\\n\\nPlan mode: only GET and HEAD requests are allowed.`,\n parameters: restrictWebRequestMethods(entry.tool.parameters),\n },\n run: async (args, context) => {\n const method = getWebRequestMethod(args);\n if (!PLAN_MODE_WEB_REQUEST_METHODS.has(method)) {\n return planModeBlockedMessage(\"web-request\", `method=\"${method}\"`);\n }\n return entry.run(args, context);\n },\n };\n}\n\nexport function createPlanModeActionRegistry(\n actions: Record<string, ActionEntry>,\n): Record<string, ActionEntry> {\n const filtered: Record<string, ActionEntry> = {};\n\n for (const [name, entry] of Object.entries(actions)) {\n if (name === TOOL_SEARCH_ACTION_NAME) continue;\n if (PLAN_MODE_BLOCKED_READONLY_TOOLS.has(name)) continue;\n\n const allowedActions = PLAN_MODE_ALLOWED_ACTIONS[name];\n if (allowedActions) {\n filtered[name] = createPlanModeGuardedAction(name, entry, allowedActions);\n continue;\n }\n\n if (name === \"web-request\") {\n filtered[name] = createPlanModeWebRequestAction(entry);\n continue;\n }\n\n if (entry.readOnly === true) {\n filtered[name] = entry;\n }\n }\n\n if (actions[TOOL_SEARCH_ACTION_NAME]) {\n filtered[TOOL_SEARCH_ACTION_NAME] = createToolSearchEntry(() => filtered);\n }\n\n return filtered;\n}\n\nexport interface ProductionAgentOptions {\n /** Action entries for the agent. Use `actions` (preferred) or `scripts` (deprecated alias). */\n actions?: Record<string, ActionEntry>;\n /** @deprecated Use `actions` instead */\n scripts?: Record<string, ActionEntry>;\n /** Static system prompt string, or async function called per-request with the H3 event */\n systemPrompt: string | ((event: any) => string | Promise<string>);\n /** Falls back to ANTHROPIC_API_KEY env var. Ignored when `engine` is provided. */\n apiKey?: string;\n /** Agent engine to use. Defaults to the \"anthropic\" engine. */\n engine?:\n | AgentEngine\n | string\n | { name: string; config: Record<string, unknown> };\n /** Model to use. Default: claude-sonnet-4-6 */\n model?: string;\n /** Default reasoning effort for requests that do not supply an override. */\n reasoningEffort?: ReasoningEffort;\n /** Provider-specific options passed through to the engine */\n providerOptions?: EngineMessage extends never ? never : any;\n /** Called when a run completes (for server-side thread persistence) */\n onRunComplete?: (run: ActiveRun, threadId: string | undefined) => void;\n /** Called when a run starts, with the send function for emitting events and the threadId */\n onRunStart?: (\n send: (event: AgentChatEvent) => void,\n threadId: string,\n ) => void;\n /**\n * Called after the engine + model are resolved for this request. Used by\n * the plugin layer to thread the parent's choices into sub-agents so\n * delegated tasks don't default back to Anthropic + Claude.\n */\n onEngineResolved?: (engine: AgentEngine, model: string) => void;\n /** Resolve the owner email from the H3 event (for usage tracking) */\n resolveOwnerEmail?: (event: any) => string | Promise<string>;\n /**\n * Skip auto-injecting the workspace files/skills/agents inventory on the\n * first message of a conversation. Useful for minimal/voice apps where\n * the ~2KB inventory of unrelated resources is noise, not signal.\n * Default: false (inventory is injected).\n */\n skipFilesContext?: boolean;\n}\n\nconst MAX_RETRIES = 3;\nconst RETRY_BASE_DELAY_MS = 2000;\n\nfunction generateRunId(): string {\n return `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\n/** Check if an error is transient and should be retried */\nfunction isContextTooLongError(err: unknown): boolean {\n if (!(err instanceof Error)) return false;\n const msg = err.message.toLowerCase();\n if (\n msg.includes(\"context_length_exceeded\") ||\n msg.includes(\"input_too_long\") ||\n msg.includes(\"too many tokens\") ||\n msg.includes(\"prompt is too long\") ||\n msg.includes(\"reduce the length\")\n )\n return true;\n if (err instanceof EngineError) {\n const code = (err.errorCode ?? \"\").toLowerCase();\n if (code.includes(\"context_length\") || code.includes(\"input_too_long\"))\n return true;\n }\n return false;\n}\n\nfunction isRetryableError(err: unknown): boolean {\n if (!(err instanceof Error)) return false;\n const msg = err.message.toLowerCase();\n const code =\n err instanceof EngineError ? (err.errorCode ?? \"\").toLowerCase() : \"\";\n if (code === \"builder_gateway_timeout\") return false;\n return (\n code === \"http_502\" ||\n code === \"http_503\" ||\n code === \"http_504\" ||\n code === \"timeout\" ||\n msg.includes(\"overloaded\") ||\n msg.includes(\"rate_limit\") ||\n msg.includes(\"529\") ||\n msg.includes(\"502\") ||\n msg.includes(\"503\") ||\n msg.includes(\"504\") ||\n msg.includes(\"too many requests\") ||\n msg.includes(\"timeout\") ||\n msg.includes(\"gateway timeout\") ||\n msg.includes(\"inactivity timeout\") ||\n msg.includes(\"too much time has passed without sending any data\")\n );\n}\n\n/** Wait with exponential backoff, respecting abort signal */\nfunction retryDelay(attempt: number, signal: AbortSignal): Promise<void> {\n const ms = RETRY_BASE_DELAY_MS * Math.pow(2, attempt);\n return new Promise((resolve, reject) => {\n if (signal.aborted) return reject(new Error(\"aborted\"));\n const timer = setTimeout(resolve, ms);\n signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(new Error(\"aborted\"));\n },\n { once: true },\n );\n });\n}\n\ntype SupportedImageMediaType =\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\";\n\nfunction isSupportedImageMediaType(\n mediaType: string,\n): mediaType is SupportedImageMediaType {\n return (\n mediaType === \"image/jpeg\" ||\n mediaType === \"image/png\" ||\n mediaType === \"image/gif\" ||\n mediaType === \"image/webp\"\n );\n}\n\nfunction escapeAttachmentAttribute(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n}\n\nfunction formatTextAttachment(att: AgentChatAttachment): string | null {\n if (typeof att.text !== \"string\" || att.text.length === 0) return null;\n\n const attrs = [\n `name=\"${escapeAttachmentAttribute(att.name || \"attachment\")}\"`,\n att.contentType\n ? `contentType=\"${escapeAttachmentAttribute(att.contentType)}\"`\n : null,\n att.type ? `type=\"${escapeAttachmentAttribute(att.type)}\"` : null,\n ].filter(Boolean);\n\n return `<attachment ${attrs.join(\" \")}>\\n${att.text}\\n</attachment>`;\n}\n\nfunction dataUrlToFilePart(\n att: AgentChatAttachment,\n): { type: \"file\"; data: string; mediaType: string; filename?: string } | null {\n if (att.type !== \"file\" || typeof att.data !== \"string\") return null;\n const match = att.data.match(/^data:([^;]+);base64,(.+)$/);\n if (!match) return null;\n return {\n type: \"file\",\n data: match[2],\n mediaType: att.contentType || match[1],\n filename: att.name || undefined,\n };\n}\n\nexport function buildUserContentWithAttachments(opts: {\n text: string;\n attachments?: AgentChatAttachment[];\n}): EngineContentPart[] {\n const userContent: EngineContentPart[] = [];\n const textAttachments: string[] = [];\n\n for (const att of opts.attachments ?? []) {\n if (att.type === \"image\" && att.data) {\n const match = att.data.match(/^data:(image\\/[^;]+);base64,(.+)$/);\n if (match && isSupportedImageMediaType(match[1])) {\n userContent.push({\n type: \"image\",\n data: match[2],\n mediaType: match[1],\n });\n }\n continue;\n }\n\n const filePart = dataUrlToFilePart(att);\n if (filePart) {\n userContent.push(filePart);\n continue;\n }\n\n const textAttachment = formatTextAttachment(att);\n if (textAttachment) {\n textAttachments.push(textAttachment);\n }\n }\n\n userContent.push({\n type: \"text\",\n text:\n textAttachments.length > 0\n ? `${textAttachments.join(\"\\n\\n\")}\\n\\n${opts.text}`\n : opts.text,\n });\n\n return userContent;\n}\n\n/** Build enriched message with file/skill/mention references */\nfunction enrichMessage(\n message: string,\n references: AgentChatReference[],\n): string {\n if (references.length === 0) return message;\n\n const fileRefs = references.filter((r) => r.type === \"file\");\n const skillRefs = references.filter((r) => r.type === \"skill\");\n const customAgentRefs = references.filter((r) => r.type === \"custom-agent\");\n const mentionRefs = references.filter((r) => r.type === \"mention\");\n\n const parts: string[] = [];\n if (fileRefs.length > 0) {\n parts.push(\n \"Referenced files:\\n\" +\n fileRefs\n .map(\n (r) => `- ${r.path}${r.source === \"resource\" ? \" (resource)\" : \"\"}`,\n )\n .join(\"\\n\"),\n );\n }\n if (skillRefs.length > 0) {\n parts.push(\n \"Applied skills:\\n\" +\n skillRefs\n .map(\n (r) =>\n `- ${r.name} (${r.path})${r.source === \"resource\" ? \" — read with resource-read\" : \" — read with read-file\"}`,\n )\n .join(\"\\n\"),\n );\n }\n if (customAgentRefs.length > 0) {\n parts.push(\n \"Requested custom agents:\\n\" +\n customAgentRefs\n .map(\n (r) =>\n `- ${r.name}${r.refId ? ` (id: ${r.refId})` : \"\"}${r.path ? ` (path: ${r.path})` : \"\"}`,\n )\n .join(\"\\n\"),\n );\n }\n if (mentionRefs.length > 0) {\n parts.push(\n \"Referenced items:\\n\" +\n mentionRefs\n .map(\n (r) =>\n `- [${r.refType || \"item\"}] ${r.name}${r.refId ? ` (id: ${r.refId})` : \"\"}${r.path ? ` (path: ${r.path})` : \"\"}`,\n )\n .join(\"\\n\"),\n );\n }\n\n return `${parts.join(\"\\n\\n\")}\\n\\n${message}`;\n}\n\n/** Accumulated token usage from an agent loop run */\nexport interface AgentLoopUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n model: string;\n}\n\n/**\n * Convert ActionEntry registry to EngineTool array.\n */\nexport function actionsToEngineTools(\n actions: Record<string, ActionEntry>,\n): EngineTool[] {\n const tools: EngineTool[] = [];\n for (const [name, entry] of Object.entries(actions)) {\n const inputSchema = normalizeToolInputSchema(entry.tool.parameters);\n if (!inputSchema) {\n console.warn(\n `[agent] Skipping tool \"${name}\" because its input schema is not an object.`,\n );\n continue;\n }\n tools.push({\n name,\n description: entry.tool.description,\n inputSchema,\n });\n }\n return tools;\n}\n\nfunction normalizeToolInputSchema(\n schema: ActionTool[\"parameters\"] | undefined,\n): EngineTool[\"inputSchema\"] | null {\n if (!schema) return { type: \"object\", properties: {} };\n if (schema.type !== \"object\") return null;\n return {\n ...schema,\n type: \"object\",\n properties:\n schema.properties && typeof schema.properties === \"object\"\n ? schema.properties\n : {},\n required: Array.isArray(schema.required) ? schema.required : [],\n };\n}\n\nfunction stringifyToolInput(input: unknown): string {\n try {\n const str = JSON.stringify(input);\n if (!str) return String(input);\n return str.length > 500 ? `${str.slice(0, 500)}…` : str;\n } catch {\n return String(input);\n }\n}\n\nfunction normalizeToolCallInputForHistory(\n input: unknown,\n): Record<string, unknown> {\n if (input && typeof input === \"object\" && !Array.isArray(input)) {\n return input as Record<string, unknown>;\n }\n return { rawInput: input };\n}\n\nfunction toolInputSchemaErrorResult(\n toolName: string,\n input: unknown,\n error: string,\n): string {\n return (\n `Invalid action parameters for ${toolName}: ${error}. ` +\n `Received: ${stringifyToolInput(input)}. ` +\n \"The tool was not executed; retry with arguments that match the tool schema.\"\n );\n}\n\n/**\n * The core agent loop — calls the engine iteratively until no more tool calls.\n * Decoupled from HTTP transport so it can run in the background.\n * Returns accumulated token usage for cost tracking.\n */\nexport async function runAgentLoop(opts: {\n engine: AgentEngine;\n model: string;\n systemPrompt: string;\n tools: EngineTool[];\n messages: EngineMessage[];\n actions: Record<string, ActionEntry>;\n send: (event: AgentChatEvent) => void;\n signal: AbortSignal;\n ownerEmail?: string | null;\n orgId?: string | null;\n reasoningEffort?: ReasoningEffort;\n providerOptions?: any;\n executionMode?: AgentExecutionMode;\n maxIterations?: number;\n}): Promise<AgentLoopUsage> {\n const {\n engine,\n model,\n systemPrompt,\n tools,\n messages,\n actions,\n send,\n signal,\n } = opts;\n\n const usage: AgentLoopUsage = {\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n model,\n };\n\n const maxIterations = normalizeMaxIterations(\n opts.maxIterations,\n getDefaultMaxIterations(),\n );\n let iterations = 0;\n while (true) {\n if (signal.aborted) break;\n if (++iterations > maxIterations) {\n send({ type: \"loop_limit\", maxIterations });\n break;\n }\n\n let assistantContent: EngineContentPart[] | undefined;\n const toolCallErrors = new Map<\n string,\n { name: string; input: unknown; error: string }\n >();\n\n for (let retry = 0; ; retry++) {\n assistantContent = undefined;\n toolCallErrors.clear();\n try {\n const streamOpts = {\n model,\n systemPrompt,\n messages,\n tools,\n abortSignal: signal,\n reasoningEffort: opts.reasoningEffort,\n providerOptions: opts.providerOptions,\n };\n\n const eventStream = engine.stream(streamOpts);\n let thinkingBuffer = \"\";\n\n for await (const event of eventStream) {\n if (event.type === \"text-delta\") {\n send({ type: \"text\", text: event.text });\n } else if (event.type === \"thinking-delta\") {\n thinkingBuffer += event.text;\n // Thinking deltas are not forwarded to the SSE client yet —\n // we accumulate them. In a future iteration, we can surface\n // them as a collapsible \"reasoning\" section in the UI.\n } else if (event.type === \"tool-call\") {\n // The authoritative tool-call blocks arrive in assistant-content.\n } else if (event.type === \"tool-call-error\") {\n toolCallErrors.set(event.id, {\n name: event.name,\n input: event.input,\n error: event.error,\n });\n } else if (event.type === \"assistant-content\") {\n assistantContent = event.parts;\n } else if (event.type === \"usage\") {\n usage.inputTokens += event.inputTokens;\n usage.outputTokens += event.outputTokens;\n usage.cacheReadTokens += event.cacheReadTokens ?? 0;\n usage.cacheWriteTokens += event.cacheWriteTokens ?? 0;\n } else if (event.type === \"stop\" && event.reason === \"error\") {\n throw new EngineError(event.error ?? \"Engine stream error\", {\n errorCode: event.errorCode,\n upgradeUrl: event.upgradeUrl,\n });\n }\n }\n\n break;\n } catch (err: unknown) {\n if (signal.aborted) throw err;\n if (isContextTooLongError(err)) {\n throw new EngineError(\n \"Conversation has grown too long. Start a new conversation to continue.\",\n { errorCode: \"context_length_exceeded\" },\n );\n }\n if (retry < MAX_RETRIES && isRetryableError(err)) {\n // Clear partial text from the failed attempt so the retry\n // doesn't produce garbled duplicate output\n send({ type: \"clear\" });\n send({\n type: \"text\",\n text: `*Retrying in ${(RETRY_BASE_DELAY_MS * Math.pow(2, retry)) / 1000}s...*\\n\\n`,\n });\n await retryDelay(retry, signal);\n continue;\n }\n throw err;\n }\n }\n\n if (!assistantContent && toolCallErrors.size > 0) {\n assistantContent = [];\n }\n\n if (!assistantContent) {\n // No content — done\n break;\n }\n\n if (toolCallErrors.size > 0) {\n const existingToolCallIds = new Set(\n assistantContent\n .filter(\n (part): part is import(\"./engine/types.js\").EngineToolCallPart =>\n part.type === \"tool-call\",\n )\n .map((part) => part.id),\n );\n for (const [id, info] of toolCallErrors) {\n if (!existingToolCallIds.has(id)) {\n assistantContent.push({\n type: \"tool-call\",\n id,\n name: info.name,\n input: info.input,\n });\n }\n }\n }\n\n const assistantContentForHistory = assistantContent.map((part) =>\n part.type === \"tool-call\"\n ? {\n ...part,\n input: normalizeToolCallInputForHistory(part.input),\n }\n : part,\n );\n\n messages.push({ role: \"assistant\", content: assistantContentForHistory });\n\n const toolCallParts = assistantContent.filter(\n (p): p is import(\"./engine/types.js\").EngineToolCallPart =>\n p.type === \"tool-call\",\n );\n\n if (toolCallParts.length === 0) break;\n\n const runToolCall = async (\n toolCall: import(\"./engine/types.js\").EngineToolCallPart,\n ): Promise<EngineContentPart> => {\n const actionEntry = actions[toolCall.name];\n if (!actionEntry) {\n const result = `Error: Unknown tool \"${toolCall.name}\"`;\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n send({ type: \"tool_done\", tool: toolCall.name, result });\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n content: result,\n isError: true,\n };\n }\n\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n\n const toolCallSchemaError = toolCallErrors.get(toolCall.id);\n if (toolCallSchemaError) {\n const result = toolInputSchemaErrorResult(\n toolCall.name,\n toolCallSchemaError.input,\n toolCallSchemaError.error,\n );\n send({ type: \"tool_done\", tool: toolCall.name, result });\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n content: result,\n isError: true,\n };\n }\n\n if (\n opts.executionMode === \"plan\" &&\n !isPlanModeToolCallAllowed(toolCall.name, toolCall.input, actionEntry)\n ) {\n const result = planModeBlockedMessage(toolCall.name);\n send({ type: \"tool_done\", tool: toolCall.name, result });\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n content: result,\n isError: true,\n };\n }\n\n const MAX_TOOL_RESULT_CHARS = 50_000;\n const TOOL_TIMEOUT_MS = 60_000;\n let result: string;\n let isError = false;\n try {\n const timeoutSignal = AbortSignal.timeout(TOOL_TIMEOUT_MS);\n const raw = await Promise.race([\n actionEntry.run(toolCall.input as Record<string, string>, { send }),\n new Promise<never>((_, reject) => {\n timeoutSignal.addEventListener(\"abort\", () =>\n reject(new Error(\"Tool call timed out after 60 seconds\")),\n );\n }),\n ]);\n let resultStr =\n typeof raw === \"string\" ? raw : JSON.stringify(raw, null, 2);\n if (resultStr.length > MAX_TOOL_RESULT_CHARS) {\n const truncated = resultStr.slice(0, MAX_TOOL_RESULT_CHARS);\n resultStr = `${truncated}\\n\\n...[truncated — full result was ${resultStr.length.toLocaleString()} chars; only first ${MAX_TOOL_RESULT_CHARS.toLocaleString()} shown]`;\n }\n result = resultStr;\n } catch (err: any) {\n result = `Error running ${toolCall.name}: ${err?.message ?? String(err)}`;\n isError = true;\n }\n\n // Auto-refresh the UI after a successful mutating tool call. Any action\n // that isn't explicitly read-only is assumed to mutate. The client's\n // useDbSync listener sees a poll event with source:\"action\" and\n // invalidates [\"action\"] queries so list-* / get-* refetch. This makes\n // refresh after agent writes reliable without the model needing to\n // remember to call `refresh-screen` itself.\n if (!isError && actionEntry.readOnly !== true) {\n try {\n const { recordChange } = await import(\"../server/poll.js\");\n const owner = opts.ownerEmail ?? getRequestUserEmail() ?? undefined;\n const orgId = opts.orgId ?? getRequestOrgId() ?? undefined;\n recordChange({\n source: \"action\",\n type: \"change\",\n key: toolCall.name,\n ...(owner ? { owner } : {}),\n ...(orgId ? { orgId } : {}),\n });\n } catch {\n // poll module may be unavailable in non-server contexts — ignore\n }\n }\n\n send({ type: \"tool_done\", tool: toolCall.name, result });\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n content: result,\n ...(isError ? { isError } : {}),\n };\n };\n\n const hasMutatingToolCall = toolCallParts.some((toolCall) => {\n const entry = actions[toolCall.name];\n return entry && entry.readOnly !== true;\n });\n\n // Engines can emit several tool-call blocks in one turn. Keep read-only\n // calls parallel for latency, but serialize any batch containing a mutating\n // call so DB writes and UI refresh events preserve model order and do not\n // interleave or partially race.\n const toolResultParts: EngineContentPart[] = [];\n if (hasMutatingToolCall) {\n for (const toolCall of toolCallParts) {\n toolResultParts.push(await runToolCall(toolCall));\n }\n } else {\n toolResultParts.push(\n ...(await Promise.all(toolCallParts.map(runToolCall))),\n );\n }\n\n messages.push({ role: \"user\", content: toolResultParts });\n }\n\n send({ type: \"done\" });\n return usage;\n}\n\nexport function createProductionAgentHandler(\n options: ProductionAgentOptions,\n): H3EventHandler {\n // Undefined = let each engine pick its own defaultModel at request time.\n const configuredModel = options.model;\n\n // Resolve actions — prefer `actions`, fall back to deprecated `scripts`\n const resolvedActions = options.actions ?? options.scripts ?? {};\n\n // Engine tools are derived from the action registry at request time so that\n // registries which mutate after handler creation (e.g. MCP servers added via\n // the settings UI) show up to the LLM without a process restart. MCP tools\n // are also scope-filtered per request — a user-scope server added by Alice\n // must not appear in Bob's tool list in a shared-process deployment.\n const getEngineTools = (\n actions: Record<string, ActionEntry> = resolvedActions,\n ) => {\n const filtered: Record<string, ActionEntry> = {};\n for (const [name, entry] of Object.entries(actions)) {\n if (name.startsWith(\"mcp__\") && !isMcpToolAllowedForRequest(name)) {\n continue;\n }\n filtered[name] = entry;\n }\n return actionsToEngineTools(filtered);\n };\n\n return defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n let body: AgentChatRequest;\n try {\n body = await readBody(event);\n } catch {\n setResponseStatus(event, 400);\n return { error: \"Invalid request body\" };\n }\n\n const {\n message,\n history = [],\n references = [],\n threadId,\n attachments,\n model: requestModel,\n engine: requestEngine,\n effort: requestEffort,\n } = body;\n const requestMode: AgentExecutionMode =\n body.mode === \"plan\" ? \"plan\" : \"act\";\n if (!message) {\n setResponseStatus(event, 400);\n return { error: \"message is required\" };\n }\n\n // Resolve owner first so we can look up a per-owner API key. Users\n // who bring their own key use their key for this request (durable\n // across serverless cold starts via the settings table).\n let ownerEmail: string | null = null;\n if (options.resolveOwnerEmail) {\n try {\n ownerEmail = await options.resolveOwnerEmail(event);\n } catch {\n ownerEmail = null;\n }\n }\n\n // When a per-request engine override is specified, resolve the API key\n // for that provider instead of the global active engine's provider.\n let userApiKey: string | undefined;\n if (requestEngine) {\n const provider = engineToProvider(requestEngine);\n userApiKey = await getOwnerApiKey(provider, ownerEmail);\n if (!userApiKey && !isMultiTenantDeploy()) {\n // Single-tenant only: env fallback for the requested provider.\n // Multi-tenant deploys never silently substitute the deploy-level\n // key for an authenticated user (see getOwnerActiveApiKey for the\n // full rationale).\n const envVar = PROVIDER_TO_ENV[provider];\n userApiKey = envVar ? readDeployCredentialEnv(envVar) : undefined;\n }\n } else {\n userApiKey = await getOwnerActiveApiKey(ownerEmail);\n }\n\n // `options.apiKey` is the value the template constructed the plugin with\n // (e.g. wired from a deployment env var). On a multi-tenant deploy this\n // is the same cross-tenant hazard as any deploy-level provider key:\n // accepting it as the final fallback would silently bill every key-less\n // user to the deployment's account. Only honour it in single-tenant mode.\n const effectiveApiKey = isMultiTenantDeploy()\n ? userApiKey\n : (userApiKey ??\n options.apiKey ??\n readDeployCredentialEnv(\"ANTHROPIC_API_KEY\"));\n\n // Resolve engine — per-request engine override takes priority\n let engine: AgentEngine;\n try {\n engine = await resolveEngine({\n engineOption: requestEngine ?? options.engine,\n apiKey: effectiveApiKey,\n model: configuredModel,\n });\n } catch {\n engine = await resolveEngine({\n apiKey: effectiveApiKey,\n });\n }\n\n // Honor the model the user picked in the settings UI (written via\n // `manage-agent-engine` action=\"set\"), but only when the caller hasn't overridden it for\n // this request or at plugin construction time. Read per-request so a\n // dropdown change in the UI takes effect without a server restart. Skip\n // the DB read entirely when a higher-precedence value is set.\n const model =\n requestModel ??\n configuredModel ??\n (await getStoredModelForEngine(engine)) ??\n engine.defaultModel;\n const reasoningEffort = normalizeReasoningEffortForModel(\n model,\n isReasoningEffort(requestEffort)\n ? requestEffort\n : options.reasoningEffort,\n );\n\n options.onEngineResolved?.(engine, model);\n\n // One-line per-turn resolution log so it's obvious in dev which engine\n // is actually handling the request. `requestEngine` is what the client\n // sent from the model picker; `engine.name` is what resolveEngine picked.\n // Divergence between them is the usual cause of \"status says builder but\n // no [builder-engine] log lines appear\" confusion.\n console.log(\n `[agent-chat] resolved engine=${engine.name} model=${model} requestEngine=${requestEngine ?? \"(none)\"}`,\n );\n\n // Check for API key before starting a run (only for anthropic engine)\n if (engine.name === \"anthropic\" && !effectiveApiKey) {\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n setResponseHeader(event, \"Connection\", \"keep-alive\");\n const encoder = new TextEncoder();\n return new ReadableStream({\n start(controller) {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ type: \"missing_api_key\" })}\\n\\n`,\n ),\n );\n controller.close();\n },\n });\n }\n\n // Run all independent pre-send steps in parallel. Each of these hits\n // the DB or invokes an action; running them sequentially was the\n // single biggest contributor to pre-LLM latency.\n const enrichedMessage = enrichMessage(message, references);\n const loopSettingsPromise = readAgentLoopSettings({\n userEmail: ownerEmail ?? getRequestUserEmail() ?? null,\n orgId: getRequestOrgId() ?? null,\n }).catch(() => readAgentLoopSettings({}));\n\n let systemPromptError: any = null;\n const systemPromptPromise = (async (): Promise<string> => {\n try {\n return typeof options.systemPrompt === \"function\"\n ? await options.systemPrompt(event)\n : options.systemPrompt;\n } catch (error) {\n systemPromptError = error;\n return \"\";\n }\n })();\n\n const screenContextPromise = (async (): Promise<string> => {\n try {\n const viewScreenAction = resolvedActions[\"view-screen\"];\n if (viewScreenAction) {\n const result = await viewScreenAction.run({});\n if (result && result !== \"(no output)\") {\n return `\\n\\n<current-screen>\\n${result}\\n</current-screen>`;\n }\n } else {\n const navigation = await readAppState(\"navigation\");\n if (navigation) {\n return `\\n\\n<current-screen>\\n${JSON.stringify(navigation, null, 2)}\\n</current-screen>`;\n }\n }\n } catch {\n // DB not ready or no navigation state — skip silently\n }\n return \"\";\n })();\n\n const urlContextPromise = (async (): Promise<string> => {\n try {\n const url = (await readAppState(\"__url__\")) as {\n pathname?: string;\n search?: string;\n hash?: string;\n searchParams?: Record<string, string>;\n } | null;\n if (url && (url.pathname || url.search || url.hash)) {\n const lines: string[] = [];\n if (url.pathname) lines.push(`pathname: ${url.pathname}`);\n if (url.search) lines.push(`search: ${url.search}`);\n if (url.hash) lines.push(`hash: ${url.hash}`);\n if (url.searchParams && Object.keys(url.searchParams).length > 0) {\n lines.push(\"searchParams:\");\n for (const [k, v] of Object.entries(url.searchParams)) {\n lines.push(` ${k}: ${v}`);\n }\n }\n return `\\n\\n<current-url>\\n${lines.join(\"\\n\")}\\n</current-url>`;\n }\n } catch {\n // DB not ready — skip silently\n }\n return \"\";\n })();\n\n // Selection context: written by the client when the user presses Cmd+I\n // with text selected on the page. Treat anything older than 5 minutes\n // as stale and ignore it.\n const SELECTION_TTL_MS = 5 * 60 * 1000;\n const selectionContextPromise = (async (): Promise<string> => {\n try {\n const sel = (await readAppState(\"pending-selection-context\")) as {\n text?: string;\n capturedAt?: number;\n } | null;\n if (!sel?.text) return \"\";\n const capturedAt =\n typeof sel.capturedAt === \"number\" ? sel.capturedAt : 0;\n if (Date.now() - capturedAt > SELECTION_TTL_MS) return \"\";\n return (\n `\\n\\nThe user has selected the following text and pressed Cmd+I to focus the agent. ` +\n `Treat this as the immediate context to act on:\\n` +\n `<selection>\\n${sel.text}\\n</selection>`\n );\n } catch {\n // DB not ready — skip silently\n }\n return \"\";\n })();\n\n // On the first message of a conversation, inject workspace inventory\n // so the agent knows what files, skills, jobs, and custom agents exist.\n // Templates can opt out via `skipFilesContext: true` when the inventory\n // is unrelated to the app's job (e.g. a voice-first macro tracker).\n const filesContextPromise = (async (): Promise<string> => {\n let filesContext = \"\";\n if (options.skipFilesContext) return filesContext;\n if (history.length === 0) {\n try {\n const { resourceListAccessible, SHARED_OWNER, resourceGet } =\n await import(\"../resources/store.js\");\n const {\n getResourceKind,\n parseCustomAgentProfile,\n parseRemoteAgentManifest,\n parseSkillMetadata,\n } = await import(\"../resources/metadata.js\");\n const ownerEmail = getRequestUserEmail();\n if (!ownerEmail) throw new Error(\"no authenticated user\");\n const allResources = await resourceListAccessible(ownerEmail);\n\n if (allResources.length > 0) {\n const fileLines: string[] = [];\n const skillLines: string[] = [];\n const agentLines: string[] = [];\n const jobLines: string[] = [];\n for (const r of allResources) {\n const scope = r.owner === SHARED_OWNER ? \"shared\" : \"personal\";\n const kind = getResourceKind(r.path);\n if (kind === \"file\") {\n fileLines.push(` ${r.path} (${scope})`);\n continue;\n }\n\n if (kind === \"job\") {\n jobLines.push(` ${r.path} (${scope})`);\n continue;\n }\n\n if (\n kind === \"skill\" ||\n kind === \"agent\" ||\n kind === \"remote-agent\"\n ) {\n const full = await resourceGet(r.id);\n if (!full) continue;\n if (kind === \"skill\") {\n const skill = parseSkillMetadata(full.content, r.path);\n skillLines.push(\n ` ${skill?.name || r.path} — ${skill?.description || r.path} (${scope}, ${r.path})`,\n );\n } else if (kind === \"agent\") {\n const agent = parseCustomAgentProfile(full.content, r.path);\n agentLines.push(\n ` ${agent?.name || r.path} — ${agent?.description || \"Custom workspace agent\"} (${scope}, ${r.path}${agent?.model ? `, model: ${agent.model}` : \"\"})`,\n );\n } else {\n const agent = parseRemoteAgentManifest(full.content, r.path);\n agentLines.push(\n ` ${agent?.name || r.path} — ${agent?.description || \"Connected A2A agent\"} (${scope}, remote via ${r.path})`,\n );\n }\n }\n }\n const blocks: string[] = [];\n if (fileLines.length > 0) {\n blocks.push(\n `<available-files>\\nFiles in the workspace:\\n${fileLines.join(\"\\n\")}\\n\\nTo read a file's contents, use the resource-read action with the file path.\\n</available-files>`,\n );\n }\n if (skillLines.length > 0) {\n blocks.push(\n `<available-skills>\\nSkills in the workspace:\\n${skillLines.join(\"\\n\")}\\n</available-skills>`,\n );\n }\n if (agentLines.length > 0) {\n blocks.push(\n `<available-agents>\\nCustom and connected agents in the workspace:\\n${agentLines.join(\"\\n\")}\\n\\nCustom agents under agents/*.md can be mentioned or used via agent-teams (action: \"spawn\") with the agent parameter.\\n</available-agents>`,\n );\n }\n if (jobLines.length > 0) {\n blocks.push(\n `<available-jobs>\\nScheduled tasks in the workspace:\\n${jobLines.join(\"\\n\")}\\n</available-jobs>`,\n );\n }\n filesContext =\n blocks.length > 0 ? `\\n\\n${blocks.join(\"\\n\\n\")}` : \"\";\n }\n } catch {\n // Resources not available — skip silently\n }\n }\n return filesContext;\n })();\n\n const [\n systemPrompt,\n screenBlock,\n urlBlock,\n selectionBlock,\n filesContext,\n loopSettings,\n ] = await Promise.all([\n systemPromptPromise,\n screenContextPromise,\n urlContextPromise,\n selectionContextPromise,\n filesContextPromise,\n loopSettingsPromise,\n ]);\n\n if (systemPromptError) {\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n const encoder = new TextEncoder();\n const err = systemPromptError;\n return new ReadableStream({\n start(controller) {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ type: \"error\", error: `Failed to load system prompt: ${err?.message ?? String(err)}` })}\\n\\n`,\n ),\n );\n controller.close();\n },\n });\n }\n const screenContext = screenBlock + urlBlock + selectionBlock;\n const requestActions =\n requestMode === \"plan\"\n ? createPlanModeActionRegistry(resolvedActions)\n : resolvedActions;\n const requestTools = getEngineTools(requestActions);\n const requestSystemPrompt =\n requestMode === \"plan\"\n ? `${systemPrompt}\\n\\n${PLAN_MODE_SYSTEM_PROMPT}`\n : systemPrompt;\n\n // Pre-compute agent references for A2A resolution inside the run\n const agentRefs = references.filter((r) => r.type === \"agent\");\n const customAgentRefs = references.filter((r) => r.type === \"custom-agent\");\n const planModeAgentNote =\n requestMode === \"plan\" && agentRefs.length > 0\n ? \"\\n\\n<plan-mode-note>Connected external agent mentions were not called because Plan mode is read-only. Mention that they can be called after the user switches to Act mode if the plan needs them.</plan-mode-note>\"\n : \"\";\n\n const userContent = buildUserContentWithAttachments({\n text: enrichedMessage + screenContext + filesContext + planModeAgentNote,\n attachments,\n });\n\n const messages: EngineMessage[] = [\n ...history\n .filter((m) => m.content.trim())\n .map((m) => ({\n role: m.role as \"user\" | \"assistant\",\n content: [{ type: \"text\" as const, text: m.content }],\n })),\n { role: \"user\" as const, content: userContent },\n ];\n\n // If there's already an active run for this thread, reject with 409 so\n // the client can queue or wait rather than silently aborting the existing run.\n if (threadId) {\n const existingRun = getActiveRunForThread(threadId);\n if (existingRun && existingRun.status === \"running\") {\n setResponseStatus(event, 409);\n return {\n error: \"Run already in progress for this thread\",\n activeRunId: existingRun.runId,\n };\n }\n }\n\n // Start agent loop in background via run-manager\n const runId = generateRunId();\n startRun(\n runId,\n threadId ?? runId,\n async (send, signal) => {\n // Notify listeners that a run has started (used by agent teams)\n if (options.onRunStart) {\n options.onRunStart(send, threadId ?? runId);\n }\n\n // Resolve custom workspace agent mentions first.\n if (customAgentRefs.length > 0) {\n const ownerEmail = getRequestUserEmail();\n if (!ownerEmail) throw new Error(\"no authenticated user\");\n const { findAccessibleCustomAgent } =\n await import(\"../resources/agents.js\");\n const customResults = await Promise.allSettled(\n customAgentRefs.map(async (ref) => {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"start\",\n });\n try {\n const profile = await findAccessibleCustomAgent(\n ownerEmail,\n ref.refId || ref.path || ref.name,\n );\n if (!profile) {\n throw new Error(\"Profile not found\");\n }\n\n const profilePrompt =\n `${requestSystemPrompt}\\n\\n<custom-agent-profile name=\"${profile.name}\" path=\"${profile.path}\">\\n` +\n (profile.description ? `${profile.description}\\n\\n` : \"\") +\n `${profile.instructions}\\n</custom-agent-profile>`;\n\n let responseText = \"\";\n const subUsage = await runAgentLoop({\n engine,\n model: profile.model ?? model,\n systemPrompt: profilePrompt,\n tools: requestTools,\n messages: [\n {\n role: \"user\",\n content: [\n { type: \"text\", text: enrichedMessage + screenContext },\n ],\n },\n ],\n actions: requestActions,\n send: (event) => {\n if (event.type === \"text\") {\n responseText += event.text;\n send({\n type: \"agent_call_text\",\n agent: ref.name,\n text: event.text,\n });\n }\n },\n signal,\n reasoningEffort,\n providerOptions: options.providerOptions,\n executionMode: requestMode,\n maxIterations: loopSettings.maxIterations,\n });\n\n // Attribute custom-agent sub-calls under their own label\n // so the Usage panel separates them from the main chat.\n try {\n const ownerEmail = options.resolveOwnerEmail\n ? await options.resolveOwnerEmail(event)\n : getRequestUserEmail();\n if (!ownerEmail) {\n // Skip usage recording for unauthenticated runs.\n return;\n }\n const { recordUsage } = await import(\"../usage/store.js\");\n await recordUsage({\n ownerEmail,\n inputTokens: subUsage.inputTokens,\n outputTokens: subUsage.outputTokens,\n cacheReadTokens: subUsage.cacheReadTokens,\n cacheWriteTokens: subUsage.cacheWriteTokens,\n model: subUsage.model,\n label: `custom-agent:${ref.name}`,\n });\n } catch {}\n\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"done\",\n });\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" type=\"custom-agent\">\\n${responseText}\\n</agent-response>`;\n } catch (err: any) {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"error\",\n });\n const message =\n userFacingLlmCredentialError(err, {\n agentName: ref.name,\n }) ?? `Failed to run ${ref.name}: ${err?.message}`;\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" type=\"custom-agent\" error=\"true\">\\n${message}\\n</agent-response>`;\n }\n }),\n );\n\n const customResponses = customResults\n .filter(\n (result): result is PromiseFulfilledResult<string> =>\n result.status === \"fulfilled\",\n )\n .map((result) => result.value);\n\n if (customResponses.length > 0) {\n const agentContext =\n \"Responses from custom workspace agents:\\n\\n\" +\n customResponses.join(\"\\n\\n\");\n const lastMsg = messages[messages.length - 1];\n if (lastMsg?.role === \"user\" && Array.isArray(lastMsg.content)) {\n const textPart = lastMsg.content.find(\n (p): p is import(\"./engine/types.js\").EngineTextPart =>\n p.type === \"text\",\n );\n if (textPart) {\n textPart.text = agentContext + \"\\n\\n\" + textPart.text;\n }\n }\n }\n }\n\n // Resolve connected agent @-mentions via A2A calls.\n if (agentRefs.length > 0 && requestMode !== \"plan\") {\n const { A2AClient, callAgent } = await import(\"../a2a/client.js\");\n const results = await Promise.allSettled(\n agentRefs.map(async (ref) => {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"start\",\n });\n try {\n const a2aClient = new A2AClient(ref.path);\n const callerEmail = getRequestUserEmail();\n\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n\n try {\n for await (const task of a2aClient.stream(\n {\n role: \"user\",\n parts: [\n {\n type: \"text\",\n text: enrichedMessage + screenContext,\n },\n ],\n },\n Object.keys(a2aMetadata).length > 0\n ? { metadata: a2aMetadata }\n : undefined,\n )) {\n const newText =\n task.status?.message?.parts\n ?.filter(\n (p): p is { type: \"text\"; text: string } =>\n p.type === \"text\",\n )\n ?.map((p) => p.text)\n ?.join(\"\") ?? \"\";\n\n if (newText.length > lastSentLength) {\n send({\n type: \"agent_call_text\",\n agent: ref.name,\n text: newText.slice(lastSentLength),\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n }\n } catch {\n if (!responseText) {\n responseText = await callAgent(\n ref.path,\n enrichedMessage + screenContext,\n );\n }\n }\n\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"done\",\n });\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\">\\n${responseText}\\n</agent-response>`;\n } catch (err: any) {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"error\",\n });\n const message =\n userFacingLlmCredentialError(err, {\n agentName: ref.name,\n }) ?? `Failed to reach ${ref.name}: ${err?.message}`;\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" error=\"true\">\\n${message}\\n</agent-response>`;\n }\n }),\n );\n\n const agentResponses_local: string[] = [];\n for (const result of results) {\n if (result.status === \"fulfilled\") {\n agentResponses_local.push(result.value);\n }\n }\n\n if (agentResponses_local.length > 0) {\n const agentContext =\n \"Responses from other agents:\\n\\n\" +\n agentResponses_local.join(\"\\n\\n\");\n const lastMsg = messages[messages.length - 1];\n if (lastMsg?.role === \"user\" && Array.isArray(lastMsg.content)) {\n const textPart = lastMsg.content.find(\n (p): p is import(\"./engine/types.js\").EngineTextPart =>\n p.type === \"text\",\n );\n if (textPart) {\n textPart.text = agentContext + \"\\n\\n\" + textPart.text;\n }\n }\n }\n }\n\n // Apply experiment variant overrides (A/B testing)\n let effectiveModel = model;\n try {\n const { resolveActiveExperimentConfig } =\n await import(\"../observability/experiments.js\");\n if (!ownerEmail) {\n // Without an authenticated owner we can't resolve user-scoped experiments.\n throw new Error(\"no authenticated user\");\n }\n const expConfig = await resolveActiveExperimentConfig(ownerEmail);\n if (expConfig) {\n if (typeof expConfig.configs.model === \"string\") {\n effectiveModel = expConfig.configs.model;\n }\n }\n } catch {\n // Experiments module unavailable — use default model\n }\n\n const agentLoopOpts = {\n engine,\n model: effectiveModel,\n systemPrompt: requestSystemPrompt,\n tools: requestTools,\n messages,\n actions: requestActions,\n send,\n signal,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n reasoningEffort,\n providerOptions: options.providerOptions,\n executionMode: requestMode,\n maxIterations: loopSettings.maxIterations,\n };\n\n let loopUsage: AgentLoopUsage;\n let instrumented = false;\n try {\n const { getObservabilityConfig, instrumentAgentLoop } =\n await import(\"../observability/traces.js\");\n const obsConfig = await getObservabilityConfig();\n if (obsConfig.enabled) {\n instrumented = true;\n loopUsage = await instrumentAgentLoop({\n runAgentLoop,\n loopOpts: agentLoopOpts,\n runId,\n threadId: threadId ?? null,\n userId: ownerEmail,\n config: obsConfig,\n });\n }\n } catch (err) {\n // If instrumentation setup failed, fall through to uninstrumented.\n // If the agent loop itself failed (via instrumentAgentLoop), re-throw.\n if (instrumented) throw err;\n }\n if (!instrumented) {\n loopUsage = await runAgentLoop(agentLoopOpts);\n }\n\n // Record token usage for cost monitoring so the Usage panel in\n // settings works in every mode, including local dev.\n try {\n const ownerEmail = options.resolveOwnerEmail\n ? await options.resolveOwnerEmail(event)\n : getRequestUserEmail();\n if (\n ownerEmail &&\n (loopUsage.inputTokens > 0 ||\n loopUsage.outputTokens > 0 ||\n loopUsage.cacheReadTokens > 0 ||\n loopUsage.cacheWriteTokens > 0)\n ) {\n const { recordUsage } = await import(\"../usage/store.js\");\n await recordUsage({\n ownerEmail,\n inputTokens: loopUsage.inputTokens,\n outputTokens: loopUsage.outputTokens,\n cacheReadTokens: loopUsage.cacheReadTokens,\n cacheWriteTokens: loopUsage.cacheWriteTokens,\n model: loopUsage.model,\n label: body.usageLabel || \"chat\",\n });\n }\n } catch {\n // Usage recording failed — don't break the run\n }\n },\n options.onRunComplete\n ? (run) => options.onRunComplete!(run, threadId)\n : undefined,\n );\n\n // Subscribe to the run and stream events to the client\n const stream = subscribeToRun(runId, 0);\n if (!stream) {\n setResponseStatus(event, 500);\n return { error: \"Failed to start agent run\" };\n }\n\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n setResponseHeader(event, \"Connection\", \"keep-alive\");\n setResponseHeader(event, \"X-Run-Id\", runId);\n\n return stream;\n });\n}\n\nexport {\n getActiveRunForThread,\n getActiveRunForThreadAsync,\n getRun,\n abortRun,\n subscribeToRun,\n};\n"]}
1
+ {"version":3,"file":"production-agent.js","sourceRoot":"","sources":["../../src/agent/production-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,GACV,MAAM,IAA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SAAS,CAAC,YAAY;wBACpC,eAAe,EAAE,SAAS,CAAC,eAAe;wBAC1C,gBAAgB,EAAE,SAAS,CAAC,gBAAgB;wBAC5C,KAAK,EAAE,SAAS,CAAC,KAAK;wBACtB,KAAK,EAAE,IAAI,CAAC,UAAU,IAAI,MAAM;qBACjC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAAC,MAAM,CAAC;gBACP,+CAA+C;YACjD,CAAC;QACH,CAAC,EACD,OAAO,CAAC,aAAa;YACnB,CAAC,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,aAAc,CAAC,GAAG,EAAE,QAAQ,CAAC;YAChD,CAAC,CAAC,SAAS,CACd,CAAC;QAEF,uDAAuD;QACvD,MAAM,MAAM,GAAG,cAAc,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QACxC,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;YAC9B,OAAO,EAAE,KAAK,EAAE,2BAA2B,EAAE,CAAC;QAChD,CAAC;QAED,iBAAiB,CAAC,KAAK,EAAE,cAAc,EAAE,mBAAmB,CAAC,CAAC;QAC9D,iBAAiB,CAAC,KAAK,EAAE,eAAe,EAAE,UAAU,CAAC,CAAC;QACtD,iBAAiB,CAAC,KAAK,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;QACrD,iBAAiB,CAAC,KAAK,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;QAE5C,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,OAAO,EACL,qBAAqB,EACrB,0BAA0B,EAC1B,MAAM,EACN,QAAQ,EACR,cAAc,GACf,CAAC","sourcesContent":["import {\n defineEventHandler,\n setResponseHeader,\n setResponseStatus,\n getMethod,\n} from \"h3\";\nimport { DEV_MODE_USER_EMAIL } from \"../server/auth.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\nimport { readDeployCredentialEnv } from \"../server/credential-provider.js\";\nimport type { EventHandler as H3EventHandler } from \"h3\";\nimport type {\n ActionTool,\n AgentChatAttachment,\n AgentChatRequest,\n AgentChatEvent,\n AgentChatReference,\n} from \"./types.js\";\nimport type {\n AgentEngine,\n EngineTool,\n EngineMessage,\n EngineContentPart,\n} from \"./engine/types.js\";\nimport { EngineError } from \"./engine/types.js\";\nimport {\n resolveEngine,\n registerBuiltinEngines,\n getStoredModelForEngine,\n} from \"./engine/index.js\";\nimport { userFacingLlmCredentialError } from \"./engine/credential-errors.js\";\nimport { PROVIDER_TO_ENV } from \"./engine/provider-env-vars.js\";\nimport { readAppState } from \"../application-state/script-helpers.js\";\nimport {\n startRun,\n subscribeToRun,\n getActiveRunForThread,\n getActiveRunForThreadAsync,\n getRun,\n abortRun,\n} from \"./run-manager.js\";\nimport type { ActiveRun } from \"./run-manager.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport {\n getRequestOrgId,\n getRequestUserEmail,\n} from \"../server/request-context.js\";\nimport { isMcpToolAllowedForRequest } from \"../mcp-client/visibility.js\";\nimport {\n createToolSearchEntry,\n TOOL_SEARCH_ACTION_NAME,\n} from \"./tool-search.js\";\nimport {\n getDefaultMaxIterations,\n normalizeMaxIterations,\n readAgentLoopSettings,\n} from \"./loop-settings.js\";\nimport {\n isReasoningEffort,\n normalizeReasoningEffortForModel,\n type ReasoningEffort,\n} from \"../shared/reasoning-effort.js\";\n\n// Register built-in engines on first import\nregisterBuiltinEngines();\n\nexport { PROVIDER_TO_ENV };\n\n/**\n * Look up a user's persisted API key for the given provider. Returns\n * `undefined` for unauthenticated/local callers so the shared platform key\n * is never keyed off `local@localhost` in multi-tenant deployments.\n *\n * Read order:\n * 1. `app_secrets` — encrypted, scope=user, current source of truth.\n * 2. Legacy `user-api-key:<provider>:<email>` settings row — pre-migration\n * data that hasn't been backfilled yet. Surfaced for compat only;\n * writes always go to app_secrets now.\n */\nexport async function getOwnerApiKey(\n provider: string,\n ownerEmail: string | null | undefined,\n): Promise<string | undefined> {\n if (!ownerEmail || ownerEmail === DEV_MODE_USER_EMAIL) return undefined;\n const secretKey =\n PROVIDER_TO_ENV[provider] ?? `${provider.toUpperCase()}_API_KEY`;\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n const fromSecrets = await readAppSecret({\n key: secretKey,\n scope: \"user\",\n scopeId: ownerEmail,\n });\n if (fromSecrets?.value) return fromSecrets.value;\n } catch {\n // app_secrets table not ready — fall through to legacy lookup.\n }\n try {\n const { getSetting } = await import(\"../settings/store.js\");\n const stored = await getSetting(`user-api-key:${provider}:${ownerEmail}`);\n const key =\n stored && typeof stored.key === \"string\" ? stored.key.trim() : \"\";\n if (key) return key;\n if (provider === \"anthropic\") {\n const legacy = await getSetting(`user-anthropic-api-key:${ownerEmail}`);\n const legacyKey =\n legacy && typeof legacy.key === \"string\" ? legacy.key.trim() : \"\";\n return legacyKey || undefined;\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Derive the provider name from the active engine setting.\n * \"ai-sdk:openai\" → \"openai\", \"anthropic\" → \"anthropic\"\n */\nexport function engineToProvider(engineName: string): string {\n return engineName.startsWith(\"ai-sdk:\") ? engineName.slice(7) : engineName;\n}\n\n/**\n * Returns true when this process is acting as a multi-tenant deployment —\n * i.e. a hosted shared-DB environment where one user's identity must NOT be\n * silently substituted with the deploy-level API key.\n *\n * Mirrors the gate in `resolveBuilderCredential` (server/credential-provider.ts).\n *\n * Heuristic:\n * - `NODE_ENV === \"production\"`, AND\n * - The DB is not a local file (i.e. it's Neon/Postgres/Turso/D1 — any\n * backend that could be shared across multiple users).\n *\n * Self-hosted single-tenant deployments (a local sqlite file, or NODE_ENV\n * unset/development) keep the env-var fallback so the original BYO-server\n * UX continues to work without a per-user key.\n */\nfunction isMultiTenantDeploy(): boolean {\n if (process.env.NODE_ENV !== \"production\") return false;\n return !isLocalDatabase();\n}\n\n/**\n * Resolve the active engine's provider and look up the user's API key for it.\n *\n * In multi-tenant deploys we deliberately refuse the deploy-level\n * deploy-level fallback for authenticated users. Without that gate any\n * signed-in user who hasn't configured their own provider key would silently\n * inherit the deployment's key (uncapped billing on the owner's account,\n * prompt logging tied to the deployment owner) — exactly the prior-incident\n * pattern we hit on 2026-04-29.\n *\n * Single-tenant (local-dev, self-hosted SQLite) keeps the env fallback.\n *\n * Callers in `agent-chat-plugin.ts`, `triggers/dispatcher.ts`,\n * `jobs/scheduler.ts`, and `integrations/plugin.ts` historically layer\n * another deployment-key fallback after this must keep the same gate.\n */\nexport async function getOwnerActiveApiKey(\n ownerEmail: string | null | undefined,\n): Promise<string | undefined> {\n try {\n const { getSetting } = await import(\"../settings/store.js\");\n const engineSetting = await getSetting(\"agent-engine\");\n const activeEngine =\n (engineSetting?.engine as string | undefined) ?? \"anthropic\";\n const provider = engineToProvider(activeEngine);\n const userKey = await getOwnerApiKey(provider, ownerEmail);\n if (userKey) return userKey;\n if (isMultiTenantDeploy()) {\n // Multi-tenant: refuse the env fallback. A null user (unauthenticated /\n // background context with no owner) gets undefined here too — there's\n // no user to bill, and the call site must surface a \"configure a key\"\n // error to the requester rather than silently using the deploy key.\n return undefined;\n }\n const envVar = PROVIDER_TO_ENV[provider];\n return envVar ? readDeployCredentialEnv(envVar) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** @deprecated Use getOwnerApiKey(\"anthropic\", ownerEmail) instead */\nexport async function getOwnerAnthropicApiKey(\n ownerEmail: string | null | undefined,\n): Promise<string | undefined> {\n return getOwnerApiKey(\"anthropic\", ownerEmail);\n}\n\n/** Context passed to action run() for emitting intermediate events */\nexport interface ActionRunContext {\n /** Emit an SSE event to the client (e.g., agent_call_text for streaming) */\n send: (event: AgentChatEvent) => void;\n}\n\nexport interface ActionEntry {\n tool: ActionTool;\n run: (\n args: Record<string, string>,\n context?: ActionRunContext,\n ) => Promise<any>;\n /** HTTP exposure config. `false` = agent-only. Omitted = auto-inferred from name. */\n http?: import(\"../action.js\").ActionHttpConfig | false;\n /** If true, completion does NOT trigger a screen-refresh poll event.\n * Set automatically by `defineAction` when `http.method === \"GET\"`. */\n readOnly?: boolean;\n /** Whether this action may be invoked from the tools-iframe bridge.\n * **Default-allow opt-out**: only an explicit `false` returns 403.\n * - `true` / `undefined` — allow.\n * - `false` — explicit deny; the tools bridge returns 403.\n * See `defineAction` (`packages/core/src/action.ts`) and audit H5 in\n * `security-audit/05-tools-sandbox.md`. */\n toolCallable?: boolean;\n}\n\n/** @deprecated Use `ActionEntry` instead */\nexport type ScriptEntry = ActionEntry;\n\nexport type AgentExecutionMode = \"act\" | \"plan\";\n\nexport const PLAN_MODE_SYSTEM_PROMPT = `## Plan Mode Active\n\nYou are in Plan mode. This turn is for research, clarification, and a proposed approach only.\n\nHard rules:\n- Use only read-only tools. Do not edit files, write resources, run shell commands, mutate SQL rows, navigate the UI, send notifications, create jobs, create tools, call external agents, or change external systems.\n- If a needed detail is unclear, ask a concise clarifying question before proposing a plan.\n- When ready, present a concrete plan with the files/tools you expect to touch, the intended changes, validation steps, and notable risks.\n- Do not treat approval as implicit while Plan mode is still active. Tell the user to switch to Act mode with the mode selector, Shift+Tab, or /act before implementation.`;\n\nconst PLAN_MODE_BLOCKED_READONLY_TOOLS = new Set([\n \"refresh-screen\",\n \"set-search-params\",\n \"set-url-path\",\n]);\n\nconst PLAN_MODE_ALLOWED_ACTIONS: Record<string, readonly string[]> = {\n resources: [\"list\", \"read\"],\n \"chat-history\": [\"search\"],\n \"agent-teams\": [\"status\", \"read-result\", \"list\"],\n \"manage-jobs\": [\"list\"],\n \"manage-automations\": [\"list-events\", \"list\"],\n \"manage-notifications\": [\"list\"],\n \"manage-progress\": [\"list\"],\n \"manage-agent-engine\": [\"list\"],\n};\n\nconst PLAN_MODE_WEB_REQUEST_METHODS = new Set([\"GET\", \"HEAD\"]);\n\nfunction getToolAction(name: string, args: unknown): string {\n const raw =\n args && typeof args === \"object\" && \"action\" in args\n ? (args as Record<string, unknown>).action\n : undefined;\n if (raw == null && name === \"chat-history\") return \"search\";\n return String(raw ?? \"\").toLowerCase();\n}\n\nfunction getWebRequestMethod(args: unknown): string {\n const raw =\n args && typeof args === \"object\" && \"method\" in args\n ? (args as Record<string, unknown>).method\n : undefined;\n return String(raw ?? \"GET\").toUpperCase();\n}\n\nfunction restrictActionEnum(\n parameters: ActionTool[\"parameters\"] | undefined,\n allowedActions: readonly string[],\n): ActionTool[\"parameters\"] | undefined {\n if (!parameters) return parameters;\n const actionParam = parameters.properties.action;\n if (!actionParam) return parameters;\n return {\n ...parameters,\n properties: {\n ...parameters.properties,\n action: {\n ...actionParam,\n enum: [...allowedActions],\n },\n },\n };\n}\n\nfunction restrictWebRequestMethods(\n parameters: ActionTool[\"parameters\"] | undefined,\n): ActionTool[\"parameters\"] | undefined {\n if (!parameters) return parameters;\n const methodParam = parameters.properties.method;\n if (!methodParam) return parameters;\n return {\n ...parameters,\n properties: {\n ...parameters.properties,\n method: {\n ...methodParam,\n enum: [...PLAN_MODE_WEB_REQUEST_METHODS],\n },\n },\n };\n}\n\nfunction planModeBlockedMessage(toolName: string, reason?: string): string {\n return (\n `Plan mode blocked \\`${toolName}\\`` +\n (reason ? ` (${reason})` : \"\") +\n \". Switch to Act mode after the user approves the plan, then retry the action.\"\n );\n}\n\nexport function isPlanModeToolCallAllowed(\n name: string,\n input: unknown,\n entry: ActionEntry,\n): boolean {\n if (PLAN_MODE_BLOCKED_READONLY_TOOLS.has(name)) return false;\n\n if (name === \"web-request\") {\n return PLAN_MODE_WEB_REQUEST_METHODS.has(getWebRequestMethod(input));\n }\n\n const allowedActions = PLAN_MODE_ALLOWED_ACTIONS[name];\n if (allowedActions) {\n return allowedActions.includes(getToolAction(name, input));\n }\n\n return entry.readOnly === true;\n}\n\nfunction createPlanModeGuardedAction(\n name: string,\n entry: ActionEntry,\n allowedActions: readonly string[],\n): ActionEntry {\n return {\n ...entry,\n readOnly: true,\n tool: {\n ...entry.tool,\n description:\n `${entry.tool.description}\\n\\nPlan mode: only these read-only actions are available: ` +\n allowedActions.map((action) => `\"${action}\"`).join(\", \") +\n \".\",\n parameters: restrictActionEnum(entry.tool.parameters, allowedActions),\n },\n run: async (args, context) => {\n const action = getToolAction(name, args);\n if (!allowedActions.includes(action)) {\n return planModeBlockedMessage(\n name,\n `action=\"${action || \"(missing)\"}\"`,\n );\n }\n return entry.run(args, context);\n },\n };\n}\n\nfunction createPlanModeWebRequestAction(entry: ActionEntry): ActionEntry {\n return {\n ...entry,\n readOnly: true,\n tool: {\n ...entry.tool,\n description: `${entry.tool.description}\\n\\nPlan mode: only GET and HEAD requests are allowed.`,\n parameters: restrictWebRequestMethods(entry.tool.parameters),\n },\n run: async (args, context) => {\n const method = getWebRequestMethod(args);\n if (!PLAN_MODE_WEB_REQUEST_METHODS.has(method)) {\n return planModeBlockedMessage(\"web-request\", `method=\"${method}\"`);\n }\n return entry.run(args, context);\n },\n };\n}\n\nexport function createPlanModeActionRegistry(\n actions: Record<string, ActionEntry>,\n): Record<string, ActionEntry> {\n const filtered: Record<string, ActionEntry> = {};\n\n for (const [name, entry] of Object.entries(actions)) {\n if (name === TOOL_SEARCH_ACTION_NAME) continue;\n if (PLAN_MODE_BLOCKED_READONLY_TOOLS.has(name)) continue;\n\n const allowedActions = PLAN_MODE_ALLOWED_ACTIONS[name];\n if (allowedActions) {\n filtered[name] = createPlanModeGuardedAction(name, entry, allowedActions);\n continue;\n }\n\n if (name === \"web-request\") {\n filtered[name] = createPlanModeWebRequestAction(entry);\n continue;\n }\n\n if (entry.readOnly === true) {\n filtered[name] = entry;\n }\n }\n\n if (actions[TOOL_SEARCH_ACTION_NAME]) {\n filtered[TOOL_SEARCH_ACTION_NAME] = createToolSearchEntry(() => filtered);\n }\n\n return filtered;\n}\n\nexport interface ProductionAgentOptions {\n /** Action entries for the agent. Use `actions` (preferred) or `scripts` (deprecated alias). */\n actions?: Record<string, ActionEntry>;\n /** @deprecated Use `actions` instead */\n scripts?: Record<string, ActionEntry>;\n /** Static system prompt string, or async function called per-request with the H3 event */\n systemPrompt: string | ((event: any) => string | Promise<string>);\n /** Falls back to ANTHROPIC_API_KEY env var. Ignored when `engine` is provided. */\n apiKey?: string;\n /** Agent engine to use. Defaults to the \"anthropic\" engine. */\n engine?:\n | AgentEngine\n | string\n | { name: string; config: Record<string, unknown> };\n /** Model to use. Default: claude-sonnet-4-6 */\n model?: string;\n /** Default reasoning effort for requests that do not supply an override. */\n reasoningEffort?: ReasoningEffort;\n /** Provider-specific options passed through to the engine */\n providerOptions?: EngineMessage extends never ? never : any;\n /** Called when a run completes (for server-side thread persistence) */\n onRunComplete?: (run: ActiveRun, threadId: string | undefined) => void;\n /** Called when a run starts, with the send function for emitting events and the threadId */\n onRunStart?: (\n send: (event: AgentChatEvent) => void,\n threadId: string,\n ) => void;\n /**\n * Called after the engine + model are resolved for this request. Used by\n * the plugin layer to thread the parent's choices into sub-agents so\n * delegated tasks don't default back to Anthropic + Claude.\n */\n onEngineResolved?: (engine: AgentEngine, model: string) => void;\n /** Resolve the owner email from the H3 event (for usage tracking) */\n resolveOwnerEmail?: (event: any) => string | Promise<string>;\n /**\n * Skip auto-injecting the workspace files/skills/agents inventory on the\n * first message of a conversation. Useful for minimal/voice apps where\n * the ~2KB inventory of unrelated resources is noise, not signal.\n * Default: false (inventory is injected).\n */\n skipFilesContext?: boolean;\n}\n\nconst MAX_RETRIES = 3;\nconst RETRY_BASE_DELAY_MS = 2000;\n\nfunction generateRunId(): string {\n return `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\n/** Check if an error is transient and should be retried */\nfunction isContextTooLongError(err: unknown): boolean {\n if (!(err instanceof Error)) return false;\n const msg = err.message.toLowerCase();\n if (\n msg.includes(\"context_length_exceeded\") ||\n msg.includes(\"input_too_long\") ||\n msg.includes(\"too many tokens\") ||\n msg.includes(\"prompt is too long\") ||\n msg.includes(\"reduce the length\")\n )\n return true;\n if (err instanceof EngineError) {\n const code = (err.errorCode ?? \"\").toLowerCase();\n if (code.includes(\"context_length\") || code.includes(\"input_too_long\"))\n return true;\n }\n return false;\n}\n\nfunction isRetryableError(err: unknown): boolean {\n if (!(err instanceof Error)) return false;\n const msg = err.message.toLowerCase();\n const code =\n err instanceof EngineError ? (err.errorCode ?? \"\").toLowerCase() : \"\";\n if (code === \"builder_gateway_timeout\") return false;\n return (\n code === \"http_502\" ||\n code === \"http_503\" ||\n code === \"http_504\" ||\n code === \"timeout\" ||\n msg.includes(\"overloaded\") ||\n msg.includes(\"rate_limit\") ||\n msg.includes(\"529\") ||\n msg.includes(\"502\") ||\n msg.includes(\"503\") ||\n msg.includes(\"504\") ||\n msg.includes(\"too many requests\") ||\n msg.includes(\"timeout\") ||\n msg.includes(\"gateway timeout\") ||\n msg.includes(\"inactivity timeout\") ||\n msg.includes(\"too much time has passed without sending any data\")\n );\n}\n\n/** Wait with exponential backoff, respecting abort signal */\nfunction retryDelay(attempt: number, signal: AbortSignal): Promise<void> {\n const ms = RETRY_BASE_DELAY_MS * Math.pow(2, attempt);\n return new Promise((resolve, reject) => {\n if (signal.aborted) return reject(new Error(\"aborted\"));\n const timer = setTimeout(resolve, ms);\n signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(new Error(\"aborted\"));\n },\n { once: true },\n );\n });\n}\n\ntype SupportedImageMediaType =\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\";\n\nfunction isSupportedImageMediaType(\n mediaType: string,\n): mediaType is SupportedImageMediaType {\n return (\n mediaType === \"image/jpeg\" ||\n mediaType === \"image/png\" ||\n mediaType === \"image/gif\" ||\n mediaType === \"image/webp\"\n );\n}\n\nfunction escapeAttachmentAttribute(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n}\n\nfunction formatTextAttachment(att: AgentChatAttachment): string | null {\n if (typeof att.text !== \"string\" || att.text.length === 0) return null;\n\n const attrs = [\n `name=\"${escapeAttachmentAttribute(att.name || \"attachment\")}\"`,\n att.contentType\n ? `contentType=\"${escapeAttachmentAttribute(att.contentType)}\"`\n : null,\n att.type ? `type=\"${escapeAttachmentAttribute(att.type)}\"` : null,\n ].filter(Boolean);\n\n return `<attachment ${attrs.join(\" \")}>\\n${att.text}\\n</attachment>`;\n}\n\nfunction dataUrlToFilePart(\n att: AgentChatAttachment,\n): { type: \"file\"; data: string; mediaType: string; filename?: string } | null {\n if (att.type !== \"file\" || typeof att.data !== \"string\") return null;\n const match = att.data.match(/^data:([^;]+);base64,(.+)$/);\n if (!match) return null;\n return {\n type: \"file\",\n data: match[2],\n mediaType: att.contentType || match[1],\n filename: att.name || undefined,\n };\n}\n\nexport function buildUserContentWithAttachments(opts: {\n text: string;\n attachments?: AgentChatAttachment[];\n}): EngineContentPart[] {\n const userContent: EngineContentPart[] = [];\n const textAttachments: string[] = [];\n\n for (const att of opts.attachments ?? []) {\n if (att.type === \"image\" && att.data) {\n const match = att.data.match(/^data:(image\\/[^;]+);base64,(.+)$/);\n if (match && isSupportedImageMediaType(match[1])) {\n userContent.push({\n type: \"image\",\n data: match[2],\n mediaType: match[1],\n });\n }\n continue;\n }\n\n const filePart = dataUrlToFilePart(att);\n if (filePart) {\n userContent.push(filePart);\n continue;\n }\n\n const textAttachment = formatTextAttachment(att);\n if (textAttachment) {\n textAttachments.push(textAttachment);\n }\n }\n\n userContent.push({\n type: \"text\",\n text:\n textAttachments.length > 0\n ? `${textAttachments.join(\"\\n\\n\")}\\n\\n${opts.text}`\n : opts.text,\n });\n\n return userContent;\n}\n\n/** Build enriched message with file/skill/mention references */\nfunction enrichMessage(\n message: string,\n references: AgentChatReference[],\n): string {\n if (references.length === 0) return message;\n\n const fileRefs = references.filter((r) => r.type === \"file\");\n const skillRefs = references.filter((r) => r.type === \"skill\");\n const customAgentRefs = references.filter((r) => r.type === \"custom-agent\");\n const mentionRefs = references.filter((r) => r.type === \"mention\");\n\n const parts: string[] = [];\n if (fileRefs.length > 0) {\n parts.push(\n \"Referenced files:\\n\" +\n fileRefs\n .map(\n (r) => `- ${r.path}${r.source === \"resource\" ? \" (resource)\" : \"\"}`,\n )\n .join(\"\\n\"),\n );\n }\n if (skillRefs.length > 0) {\n parts.push(\n \"Applied skills:\\n\" +\n skillRefs\n .map(\n (r) =>\n `- ${r.name} (${r.path})${r.source === \"resource\" ? \" — read with resource-read\" : \" — read with read-file\"}`,\n )\n .join(\"\\n\"),\n );\n }\n if (customAgentRefs.length > 0) {\n parts.push(\n \"Requested custom agents:\\n\" +\n customAgentRefs\n .map(\n (r) =>\n `- ${r.name}${r.refId ? ` (id: ${r.refId})` : \"\"}${r.path ? ` (path: ${r.path})` : \"\"}`,\n )\n .join(\"\\n\"),\n );\n }\n if (mentionRefs.length > 0) {\n parts.push(\n \"Referenced items:\\n\" +\n mentionRefs\n .map(\n (r) =>\n `- [${r.refType || \"item\"}] ${r.name}${r.refId ? ` (id: ${r.refId})` : \"\"}${r.path ? ` (path: ${r.path})` : \"\"}`,\n )\n .join(\"\\n\"),\n );\n }\n\n return `${parts.join(\"\\n\\n\")}\\n\\n${message}`;\n}\n\n/** Accumulated token usage from an agent loop run */\nexport interface AgentLoopUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n model: string;\n}\n\n/**\n * Convert ActionEntry registry to EngineTool array.\n */\nexport function actionsToEngineTools(\n actions: Record<string, ActionEntry>,\n): EngineTool[] {\n const tools: EngineTool[] = [];\n for (const [name, entry] of Object.entries(actions)) {\n const inputSchema = normalizeToolInputSchema(entry.tool.parameters);\n if (!inputSchema) {\n console.warn(\n `[agent] Skipping tool \"${name}\" because its input schema is not an object.`,\n );\n continue;\n }\n tools.push({\n name,\n description: entry.tool.description,\n inputSchema,\n });\n }\n return tools;\n}\n\nfunction normalizeToolInputSchema(\n schema: ActionTool[\"parameters\"] | undefined,\n): EngineTool[\"inputSchema\"] | null {\n if (!schema) return { type: \"object\", properties: {} };\n if (schema.type !== \"object\") return null;\n return {\n ...schema,\n type: \"object\",\n properties:\n schema.properties && typeof schema.properties === \"object\"\n ? schema.properties\n : {},\n required: Array.isArray(schema.required) ? schema.required : [],\n };\n}\n\nfunction stringifyToolInput(input: unknown): string {\n try {\n const str = JSON.stringify(input);\n if (!str) return String(input);\n return str.length > 500 ? `${str.slice(0, 500)}…` : str;\n } catch {\n return String(input);\n }\n}\n\nfunction normalizeToolCallInputForHistory(\n input: unknown,\n): Record<string, unknown> {\n if (input && typeof input === \"object\" && !Array.isArray(input)) {\n return input as Record<string, unknown>;\n }\n return { rawInput: input };\n}\n\nfunction toolInputSchemaErrorResult(\n toolName: string,\n input: unknown,\n error: string,\n): string {\n return (\n `Invalid action parameters for ${toolName}: ${error}. ` +\n `Received: ${stringifyToolInput(input)}. ` +\n \"The tool was not executed; retry with arguments that match the tool schema.\"\n );\n}\n\n/**\n * The core agent loop — calls the engine iteratively until no more tool calls.\n * Decoupled from HTTP transport so it can run in the background.\n * Returns accumulated token usage for cost tracking.\n */\nexport async function runAgentLoop(opts: {\n engine: AgentEngine;\n model: string;\n systemPrompt: string;\n tools: EngineTool[];\n messages: EngineMessage[];\n actions: Record<string, ActionEntry>;\n send: (event: AgentChatEvent) => void;\n signal: AbortSignal;\n ownerEmail?: string | null;\n orgId?: string | null;\n reasoningEffort?: ReasoningEffort;\n providerOptions?: any;\n executionMode?: AgentExecutionMode;\n maxIterations?: number;\n}): Promise<AgentLoopUsage> {\n const {\n engine,\n model,\n systemPrompt,\n tools,\n messages,\n actions,\n send,\n signal,\n } = opts;\n\n const usage: AgentLoopUsage = {\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n model,\n };\n\n const maxIterations = normalizeMaxIterations(\n opts.maxIterations,\n getDefaultMaxIterations(),\n );\n let iterations = 0;\n while (true) {\n if (signal.aborted) break;\n if (++iterations > maxIterations) {\n send({ type: \"loop_limit\", maxIterations });\n break;\n }\n\n let assistantContent: EngineContentPart[] | undefined;\n const toolCallErrors = new Map<\n string,\n { name: string; input: unknown; error: string }\n >();\n\n for (let retry = 0; ; retry++) {\n assistantContent = undefined;\n toolCallErrors.clear();\n try {\n const streamOpts = {\n model,\n systemPrompt,\n messages,\n tools,\n abortSignal: signal,\n reasoningEffort: opts.reasoningEffort,\n providerOptions: opts.providerOptions,\n };\n\n const eventStream = engine.stream(streamOpts);\n let thinkingBuffer = \"\";\n\n for await (const event of eventStream) {\n if (event.type === \"text-delta\") {\n send({ type: \"text\", text: event.text });\n } else if (event.type === \"thinking-delta\") {\n thinkingBuffer += event.text;\n // Thinking deltas are not forwarded to the SSE client yet —\n // we accumulate them. In a future iteration, we can surface\n // them as a collapsible \"reasoning\" section in the UI.\n } else if (event.type === \"tool-call\") {\n // The authoritative tool-call blocks arrive in assistant-content.\n } else if (event.type === \"tool-call-error\") {\n toolCallErrors.set(event.id, {\n name: event.name,\n input: event.input,\n error: event.error,\n });\n } else if (event.type === \"assistant-content\") {\n assistantContent = event.parts;\n } else if (event.type === \"usage\") {\n usage.inputTokens += event.inputTokens;\n usage.outputTokens += event.outputTokens;\n usage.cacheReadTokens += event.cacheReadTokens ?? 0;\n usage.cacheWriteTokens += event.cacheWriteTokens ?? 0;\n } else if (event.type === \"stop\" && event.reason === \"error\") {\n throw new EngineError(event.error ?? \"Engine stream error\", {\n errorCode: event.errorCode,\n upgradeUrl: event.upgradeUrl,\n });\n }\n }\n\n break;\n } catch (err: unknown) {\n if (signal.aborted) throw err;\n if (isContextTooLongError(err)) {\n throw new EngineError(\n \"Conversation has grown too long. Start a new conversation to continue.\",\n { errorCode: \"context_length_exceeded\" },\n );\n }\n if (retry < MAX_RETRIES && isRetryableError(err)) {\n // Clear partial text from the failed attempt so the retry\n // doesn't produce garbled duplicate output\n send({ type: \"clear\" });\n send({\n type: \"text\",\n text: `*Retrying in ${(RETRY_BASE_DELAY_MS * Math.pow(2, retry)) / 1000}s...*\\n\\n`,\n });\n await retryDelay(retry, signal);\n continue;\n }\n throw err;\n }\n }\n\n if (!assistantContent && toolCallErrors.size > 0) {\n assistantContent = [];\n }\n\n if (!assistantContent) {\n // No content — done\n break;\n }\n\n if (toolCallErrors.size > 0) {\n const existingToolCallIds = new Set(\n assistantContent\n .filter(\n (part): part is import(\"./engine/types.js\").EngineToolCallPart =>\n part.type === \"tool-call\",\n )\n .map((part) => part.id),\n );\n for (const [id, info] of toolCallErrors) {\n if (!existingToolCallIds.has(id)) {\n assistantContent.push({\n type: \"tool-call\",\n id,\n name: info.name,\n input: info.input,\n });\n }\n }\n }\n\n const assistantContentForHistory = assistantContent.map((part) =>\n part.type === \"tool-call\"\n ? {\n ...part,\n input: normalizeToolCallInputForHistory(part.input),\n }\n : part,\n );\n\n messages.push({ role: \"assistant\", content: assistantContentForHistory });\n\n const toolCallParts = assistantContent.filter(\n (p): p is import(\"./engine/types.js\").EngineToolCallPart =>\n p.type === \"tool-call\",\n );\n\n if (toolCallParts.length === 0) break;\n\n const runToolCall = async (\n toolCall: import(\"./engine/types.js\").EngineToolCallPart,\n ): Promise<EngineContentPart> => {\n const actionEntry = actions[toolCall.name];\n if (!actionEntry) {\n const result = `Error: Unknown tool \"${toolCall.name}\"`;\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n send({ type: \"tool_done\", tool: toolCall.name, result });\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n content: result,\n isError: true,\n };\n }\n\n send({\n type: \"tool_start\",\n tool: toolCall.name,\n input: toolCall.input as Record<string, string>,\n });\n\n const toolCallSchemaError = toolCallErrors.get(toolCall.id);\n if (toolCallSchemaError) {\n const result = toolInputSchemaErrorResult(\n toolCall.name,\n toolCallSchemaError.input,\n toolCallSchemaError.error,\n );\n send({ type: \"tool_done\", tool: toolCall.name, result });\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n content: result,\n isError: true,\n };\n }\n\n if (\n opts.executionMode === \"plan\" &&\n !isPlanModeToolCallAllowed(toolCall.name, toolCall.input, actionEntry)\n ) {\n const result = planModeBlockedMessage(toolCall.name);\n send({ type: \"tool_done\", tool: toolCall.name, result });\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n content: result,\n isError: true,\n };\n }\n\n const MAX_TOOL_RESULT_CHARS = 50_000;\n const TOOL_TIMEOUT_MS = 60_000;\n let result: string;\n let isError = false;\n try {\n const timeoutSignal = AbortSignal.timeout(TOOL_TIMEOUT_MS);\n const raw = await Promise.race([\n actionEntry.run(toolCall.input as Record<string, string>, { send }),\n new Promise<never>((_, reject) => {\n timeoutSignal.addEventListener(\"abort\", () =>\n reject(new Error(\"Tool call timed out after 60 seconds\")),\n );\n }),\n ]);\n let resultStr =\n typeof raw === \"string\" ? raw : JSON.stringify(raw, null, 2);\n if (resultStr.length > MAX_TOOL_RESULT_CHARS) {\n const truncated = resultStr.slice(0, MAX_TOOL_RESULT_CHARS);\n resultStr = `${truncated}\\n\\n...[truncated — full result was ${resultStr.length.toLocaleString()} chars; only first ${MAX_TOOL_RESULT_CHARS.toLocaleString()} shown]`;\n }\n result = resultStr;\n } catch (err: any) {\n result = `Error running ${toolCall.name}: ${err?.message ?? String(err)}`;\n isError = true;\n }\n\n // Auto-refresh the UI after a successful mutating tool call. Any action\n // that isn't explicitly read-only is assumed to mutate. The client's\n // useDbSync listener sees a poll event with source:\"action\" and\n // invalidates [\"action\"] queries so list-* / get-* refetch. This makes\n // refresh after agent writes reliable without the model needing to\n // remember to call `refresh-screen` itself.\n if (!isError && actionEntry.readOnly !== true) {\n try {\n const { recordChange } = await import(\"../server/poll.js\");\n const owner = opts.ownerEmail ?? getRequestUserEmail() ?? undefined;\n const orgId = opts.orgId ?? getRequestOrgId() ?? undefined;\n recordChange({\n source: \"action\",\n type: \"change\",\n key: toolCall.name,\n ...(owner ? { owner } : {}),\n ...(orgId ? { orgId } : {}),\n });\n } catch {\n // poll module may be unavailable in non-server contexts — ignore\n }\n }\n\n send({ type: \"tool_done\", tool: toolCall.name, result });\n return {\n type: \"tool-result\" as const,\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n content: result,\n ...(isError ? { isError } : {}),\n };\n };\n\n const hasMutatingToolCall = toolCallParts.some((toolCall) => {\n const entry = actions[toolCall.name];\n return entry && entry.readOnly !== true;\n });\n\n // Engines can emit several tool-call blocks in one turn. Keep read-only\n // calls parallel for latency, but serialize any batch containing a mutating\n // call so DB writes and UI refresh events preserve model order and do not\n // interleave or partially race.\n const toolResultParts: EngineContentPart[] = [];\n if (hasMutatingToolCall) {\n for (const toolCall of toolCallParts) {\n toolResultParts.push(await runToolCall(toolCall));\n }\n } else {\n toolResultParts.push(\n ...(await Promise.all(toolCallParts.map(runToolCall))),\n );\n }\n\n messages.push({ role: \"user\", content: toolResultParts });\n }\n\n send({ type: \"done\" });\n return usage;\n}\n\nexport function createProductionAgentHandler(\n options: ProductionAgentOptions,\n): H3EventHandler {\n // Undefined = let each engine pick its own defaultModel at request time.\n const configuredModel = options.model;\n\n // Resolve actions — prefer `actions`, fall back to deprecated `scripts`\n const resolvedActions = options.actions ?? options.scripts ?? {};\n\n // Engine tools are derived from the action registry at request time so that\n // registries which mutate after handler creation (e.g. MCP servers added via\n // the settings UI) show up to the LLM without a process restart. MCP tools\n // are also scope-filtered per request — a user-scope server added by Alice\n // must not appear in Bob's tool list in a shared-process deployment.\n const getEngineTools = (\n actions: Record<string, ActionEntry> = resolvedActions,\n ) => {\n const filtered: Record<string, ActionEntry> = {};\n for (const [name, entry] of Object.entries(actions)) {\n if (name.startsWith(\"mcp__\") && !isMcpToolAllowedForRequest(name)) {\n continue;\n }\n filtered[name] = entry;\n }\n return actionsToEngineTools(filtered);\n };\n\n return defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n let body: AgentChatRequest;\n try {\n body = await readBody(event);\n } catch {\n setResponseStatus(event, 400);\n return { error: \"Invalid request body\" };\n }\n\n const {\n message,\n history = [],\n references = [],\n threadId,\n attachments,\n model: requestModel,\n engine: requestEngine,\n effort: requestEffort,\n } = body;\n const requestMode: AgentExecutionMode =\n body.mode === \"plan\" ? \"plan\" : \"act\";\n if (!message) {\n setResponseStatus(event, 400);\n return { error: \"message is required\" };\n }\n\n // Resolve owner first so we can look up a per-owner API key. Users\n // who bring their own key use their key for this request (durable\n // across serverless cold starts via the settings table).\n let ownerEmail: string | null = null;\n if (options.resolveOwnerEmail) {\n try {\n ownerEmail = await options.resolveOwnerEmail(event);\n } catch {\n ownerEmail = null;\n }\n }\n\n // When a per-request engine override is specified, resolve the API key\n // for that provider instead of the global active engine's provider.\n let userApiKey: string | undefined;\n if (requestEngine) {\n const provider = engineToProvider(requestEngine);\n userApiKey = await getOwnerApiKey(provider, ownerEmail);\n if (!userApiKey && !isMultiTenantDeploy()) {\n // Single-tenant only: env fallback for the requested provider.\n // Multi-tenant deploys never silently substitute the deploy-level\n // key for an authenticated user (see getOwnerActiveApiKey for the\n // full rationale).\n const envVar = PROVIDER_TO_ENV[provider];\n userApiKey = envVar ? readDeployCredentialEnv(envVar) : undefined;\n }\n } else {\n userApiKey = await getOwnerActiveApiKey(ownerEmail);\n }\n\n // `options.apiKey` is the value the template constructed the plugin with\n // (e.g. wired from a deployment env var). On a multi-tenant deploy this\n // is the same cross-tenant hazard as any deploy-level provider key:\n // accepting it as the final fallback would silently bill every key-less\n // user to the deployment's account. Only honour it in single-tenant mode.\n const effectiveApiKey = isMultiTenantDeploy()\n ? userApiKey\n : (userApiKey ??\n options.apiKey ??\n readDeployCredentialEnv(\"ANTHROPIC_API_KEY\"));\n\n // Resolve engine — per-request engine override takes priority\n let engine: AgentEngine;\n try {\n engine = await resolveEngine({\n engineOption: requestEngine ?? options.engine,\n apiKey: effectiveApiKey,\n model: configuredModel,\n });\n } catch {\n engine = await resolveEngine({\n apiKey: effectiveApiKey,\n });\n }\n\n // Honor the model the user picked in the settings UI (written via\n // `manage-agent-engine` action=\"set\"), but only when the caller hasn't overridden it for\n // this request or at plugin construction time. Read per-request so a\n // dropdown change in the UI takes effect without a server restart. Skip\n // the DB read entirely when a higher-precedence value is set.\n const model =\n requestModel ??\n configuredModel ??\n (await getStoredModelForEngine(engine)) ??\n engine.defaultModel;\n const reasoningEffort = normalizeReasoningEffortForModel(\n model,\n isReasoningEffort(requestEffort)\n ? requestEffort\n : options.reasoningEffort,\n );\n\n options.onEngineResolved?.(engine, model);\n\n // One-line per-turn resolution log so it's obvious in dev which engine\n // is actually handling the request. `requestEngine` is what the client\n // sent from the model picker; `engine.name` is what resolveEngine picked.\n // Divergence between them is the usual cause of \"status says builder but\n // no [builder-engine] log lines appear\" confusion.\n console.log(\n `[agent-chat] resolved engine=${engine.name} model=${model} requestEngine=${requestEngine ?? \"(none)\"}`,\n );\n\n // Check for API key before starting a run (only for anthropic engine)\n if (engine.name === \"anthropic\" && !effectiveApiKey) {\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n setResponseHeader(event, \"Connection\", \"keep-alive\");\n const encoder = new TextEncoder();\n return new ReadableStream({\n start(controller) {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ type: \"missing_api_key\" })}\\n\\n`,\n ),\n );\n controller.close();\n },\n });\n }\n\n // Run all independent pre-send steps in parallel. Each of these hits\n // the DB or invokes an action; running them sequentially was the\n // single biggest contributor to pre-LLM latency.\n const enrichedMessage = enrichMessage(message, references);\n const loopSettingsPromise = readAgentLoopSettings({\n userEmail: ownerEmail ?? getRequestUserEmail() ?? null,\n orgId: getRequestOrgId() ?? null,\n }).catch(() => readAgentLoopSettings({}));\n\n let systemPromptError: any = null;\n const systemPromptPromise = (async (): Promise<string> => {\n try {\n return typeof options.systemPrompt === \"function\"\n ? await options.systemPrompt(event)\n : options.systemPrompt;\n } catch (error) {\n systemPromptError = error;\n return \"\";\n }\n })();\n\n const screenContextPromise = (async (): Promise<string> => {\n try {\n const viewScreenAction = resolvedActions[\"view-screen\"];\n if (viewScreenAction) {\n const result = await viewScreenAction.run({});\n if (result && result !== \"(no output)\") {\n return `\\n\\n<current-screen>\\n${result}\\n</current-screen>`;\n }\n } else {\n const navigation = await readAppState(\"navigation\");\n if (navigation) {\n return `\\n\\n<current-screen>\\n${JSON.stringify(navigation, null, 2)}\\n</current-screen>`;\n }\n }\n } catch {\n // DB not ready or no navigation state — skip silently\n }\n return \"\";\n })();\n\n const urlContextPromise = (async (): Promise<string> => {\n try {\n const url = (await readAppState(\"__url__\")) as {\n pathname?: string;\n search?: string;\n hash?: string;\n searchParams?: Record<string, string>;\n } | null;\n if (url && (url.pathname || url.search || url.hash)) {\n const lines: string[] = [];\n if (url.pathname) lines.push(`pathname: ${url.pathname}`);\n if (url.search) lines.push(`search: ${url.search}`);\n if (url.hash) lines.push(`hash: ${url.hash}`);\n if (url.searchParams && Object.keys(url.searchParams).length > 0) {\n lines.push(\"searchParams:\");\n for (const [k, v] of Object.entries(url.searchParams)) {\n lines.push(` ${k}: ${v}`);\n }\n }\n return `\\n\\n<current-url>\\n${lines.join(\"\\n\")}\\n</current-url>`;\n }\n } catch {\n // DB not ready — skip silently\n }\n return \"\";\n })();\n\n // Selection context: written by the client when the user presses Cmd+I\n // with text selected on the page. Treat anything older than 5 minutes\n // as stale and ignore it.\n const SELECTION_TTL_MS = 5 * 60 * 1000;\n const selectionContextPromise = (async (): Promise<string> => {\n try {\n const sel = (await readAppState(\"pending-selection-context\")) as {\n text?: string;\n capturedAt?: number;\n } | null;\n if (!sel?.text) return \"\";\n const capturedAt =\n typeof sel.capturedAt === \"number\" ? sel.capturedAt : 0;\n if (Date.now() - capturedAt > SELECTION_TTL_MS) return \"\";\n return (\n `\\n\\nThe user has selected the following text and pressed Cmd+I to focus the agent. ` +\n `Treat this as the immediate context to act on:\\n` +\n `<selection>\\n${sel.text}\\n</selection>`\n );\n } catch {\n // DB not ready — skip silently\n }\n return \"\";\n })();\n\n // On the first message of a conversation, inject workspace inventory\n // so the agent knows what files, skills, jobs, and custom agents exist.\n // Templates can opt out via `skipFilesContext: true` when the inventory\n // is unrelated to the app's job (e.g. a voice-first macro tracker).\n const filesContextPromise = (async (): Promise<string> => {\n let filesContext = \"\";\n if (options.skipFilesContext) return filesContext;\n if (history.length === 0) {\n try {\n const { resourceListAccessible, SHARED_OWNER, resourceGet } =\n await import(\"../resources/store.js\");\n const {\n getResourceKind,\n parseCustomAgentProfile,\n parseRemoteAgentManifest,\n parseSkillMetadata,\n } = await import(\"../resources/metadata.js\");\n const ownerEmail = getRequestUserEmail();\n if (!ownerEmail) throw new Error(\"no authenticated user\");\n const allResources = await resourceListAccessible(ownerEmail);\n\n if (allResources.length > 0) {\n const fileLines: string[] = [];\n const skillLines: string[] = [];\n const agentLines: string[] = [];\n const jobLines: string[] = [];\n for (const r of allResources) {\n const scope = r.owner === SHARED_OWNER ? \"shared\" : \"personal\";\n const kind = getResourceKind(r.path);\n if (kind === \"file\") {\n fileLines.push(` ${r.path} (${scope})`);\n continue;\n }\n\n if (kind === \"job\") {\n jobLines.push(` ${r.path} (${scope})`);\n continue;\n }\n\n if (\n kind === \"skill\" ||\n kind === \"agent\" ||\n kind === \"remote-agent\"\n ) {\n const full = await resourceGet(r.id);\n if (!full) continue;\n if (kind === \"skill\") {\n const skill = parseSkillMetadata(full.content, r.path);\n skillLines.push(\n ` ${skill?.name || r.path} — ${skill?.description || r.path} (${scope}, ${r.path})`,\n );\n } else if (kind === \"agent\") {\n const agent = parseCustomAgentProfile(full.content, r.path);\n agentLines.push(\n ` ${agent?.name || r.path} — ${agent?.description || \"Custom workspace agent\"} (${scope}, ${r.path}${agent?.model ? `, model: ${agent.model}` : \"\"})`,\n );\n } else {\n const agent = parseRemoteAgentManifest(full.content, r.path);\n agentLines.push(\n ` ${agent?.name || r.path} — ${agent?.description || \"Connected A2A agent\"} (${scope}, remote via ${r.path})`,\n );\n }\n }\n }\n const blocks: string[] = [];\n if (fileLines.length > 0) {\n blocks.push(\n `<available-files>\\nFiles in the workspace:\\n${fileLines.join(\"\\n\")}\\n\\nTo read a file's contents, use the resource-read action with the file path.\\n</available-files>`,\n );\n }\n if (skillLines.length > 0) {\n blocks.push(\n `<available-skills>\\nSkills in the workspace:\\n${skillLines.join(\"\\n\")}\\n</available-skills>`,\n );\n }\n if (agentLines.length > 0) {\n blocks.push(\n `<available-agents>\\nCustom and connected agents in the workspace:\\n${agentLines.join(\"\\n\")}\\n\\nCustom agents under agents/*.md can be mentioned or used via agent-teams (action: \"spawn\") with the agent parameter.\\n</available-agents>`,\n );\n }\n if (jobLines.length > 0) {\n blocks.push(\n `<available-jobs>\\nScheduled tasks in the workspace:\\n${jobLines.join(\"\\n\")}\\n</available-jobs>`,\n );\n }\n filesContext =\n blocks.length > 0 ? `\\n\\n${blocks.join(\"\\n\\n\")}` : \"\";\n }\n } catch {\n // Resources not available — skip silently\n }\n }\n return filesContext;\n })();\n\n const [\n systemPrompt,\n screenBlock,\n urlBlock,\n selectionBlock,\n filesContext,\n loopSettings,\n ] = await Promise.all([\n systemPromptPromise,\n screenContextPromise,\n urlContextPromise,\n selectionContextPromise,\n filesContextPromise,\n loopSettingsPromise,\n ]);\n\n if (systemPromptError) {\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n const encoder = new TextEncoder();\n const err = systemPromptError;\n return new ReadableStream({\n start(controller) {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ type: \"error\", error: `Failed to load system prompt: ${err?.message ?? String(err)}` })}\\n\\n`,\n ),\n );\n controller.close();\n },\n });\n }\n const screenContext = screenBlock + urlBlock + selectionBlock;\n const requestActions =\n requestMode === \"plan\"\n ? createPlanModeActionRegistry(resolvedActions)\n : resolvedActions;\n const requestTools = getEngineTools(requestActions);\n const requestSystemPrompt =\n requestMode === \"plan\"\n ? `${systemPrompt}\\n\\n${PLAN_MODE_SYSTEM_PROMPT}`\n : systemPrompt;\n\n // Pre-compute agent references for A2A resolution inside the run\n const agentRefs = references.filter((r) => r.type === \"agent\");\n const customAgentRefs = references.filter((r) => r.type === \"custom-agent\");\n const planModeAgentNote =\n requestMode === \"plan\" && agentRefs.length > 0\n ? \"\\n\\n<plan-mode-note>Connected external agent mentions were not called because Plan mode is read-only. Mention that they can be called after the user switches to Act mode if the plan needs them.</plan-mode-note>\"\n : \"\";\n\n const userContent = buildUserContentWithAttachments({\n text: enrichedMessage + screenContext + filesContext + planModeAgentNote,\n attachments,\n });\n\n const messages: EngineMessage[] = [\n ...history\n .filter((m) => m.content.trim())\n .map((m) => ({\n role: m.role as \"user\" | \"assistant\",\n content: [{ type: \"text\" as const, text: m.content }],\n })),\n { role: \"user\" as const, content: userContent },\n ];\n\n // If there's already an active run for this thread, reject with 409 so\n // the client can queue or wait rather than silently aborting the existing run.\n if (threadId) {\n const existingRun = getActiveRunForThread(threadId);\n if (existingRun && existingRun.status === \"running\") {\n setResponseStatus(event, 409);\n return {\n error: \"Run already in progress for this thread\",\n activeRunId: existingRun.runId,\n };\n }\n }\n\n // Start agent loop in background via run-manager\n const runId = generateRunId();\n startRun(\n runId,\n threadId ?? runId,\n async (send, signal) => {\n // Notify listeners that a run has started (used by agent teams)\n if (options.onRunStart) {\n options.onRunStart(send, threadId ?? runId);\n }\n\n // Resolve custom workspace agent mentions first.\n if (customAgentRefs.length > 0) {\n const ownerEmail = getRequestUserEmail();\n if (!ownerEmail) throw new Error(\"no authenticated user\");\n const { findAccessibleCustomAgent } =\n await import(\"../resources/agents.js\");\n const customResults = await Promise.allSettled(\n customAgentRefs.map(async (ref) => {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"start\",\n });\n try {\n const profile = await findAccessibleCustomAgent(\n ownerEmail,\n ref.refId || ref.path || ref.name,\n );\n if (!profile) {\n throw new Error(\"Profile not found\");\n }\n\n const profilePrompt =\n `${requestSystemPrompt}\\n\\n<custom-agent-profile name=\"${profile.name}\" path=\"${profile.path}\">\\n` +\n (profile.description ? `${profile.description}\\n\\n` : \"\") +\n `${profile.instructions}\\n</custom-agent-profile>`;\n\n let responseText = \"\";\n const subUsage = await runAgentLoop({\n engine,\n model: profile.model ?? model,\n systemPrompt: profilePrompt,\n tools: requestTools,\n messages: [\n {\n role: \"user\",\n content: [\n { type: \"text\", text: enrichedMessage + screenContext },\n ],\n },\n ],\n actions: requestActions,\n send: (event) => {\n if (event.type === \"text\") {\n responseText += event.text;\n send({\n type: \"agent_call_text\",\n agent: ref.name,\n text: event.text,\n });\n }\n },\n signal,\n reasoningEffort,\n providerOptions: options.providerOptions,\n executionMode: requestMode,\n maxIterations: loopSettings.maxIterations,\n });\n\n // Attribute custom-agent sub-calls under their own label\n // so the Usage panel separates them from the main chat.\n try {\n const ownerEmail = options.resolveOwnerEmail\n ? await options.resolveOwnerEmail(event)\n : getRequestUserEmail();\n if (!ownerEmail) {\n // Skip usage recording for unauthenticated runs.\n return;\n }\n const { recordUsage } = await import(\"../usage/store.js\");\n await recordUsage({\n ownerEmail,\n inputTokens: subUsage.inputTokens,\n outputTokens: subUsage.outputTokens,\n cacheReadTokens: subUsage.cacheReadTokens,\n cacheWriteTokens: subUsage.cacheWriteTokens,\n model: subUsage.model,\n label: `custom-agent:${ref.name}`,\n });\n } catch {}\n\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"done\",\n });\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" type=\"custom-agent\">\\n${responseText}\\n</agent-response>`;\n } catch (err: any) {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"error\",\n });\n const message =\n userFacingLlmCredentialError(err, {\n agentName: ref.name,\n }) ?? `Failed to run ${ref.name}: ${err?.message}`;\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" type=\"custom-agent\" error=\"true\">\\n${message}\\n</agent-response>`;\n }\n }),\n );\n\n const customResponses = customResults\n .filter(\n (result): result is PromiseFulfilledResult<string> =>\n result.status === \"fulfilled\",\n )\n .map((result) => result.value);\n\n if (customResponses.length > 0) {\n const agentContext =\n \"Responses from custom workspace agents:\\n\\n\" +\n customResponses.join(\"\\n\\n\");\n const lastMsg = messages[messages.length - 1];\n if (lastMsg?.role === \"user\" && Array.isArray(lastMsg.content)) {\n const textPart = lastMsg.content.find(\n (p): p is import(\"./engine/types.js\").EngineTextPart =>\n p.type === \"text\",\n );\n if (textPart) {\n textPart.text = agentContext + \"\\n\\n\" + textPart.text;\n }\n }\n }\n }\n\n // Resolve connected agent @-mentions via A2A calls.\n if (agentRefs.length > 0 && requestMode !== \"plan\") {\n const { A2AClient, callAgent } = await import(\"../a2a/client.js\");\n const results = await Promise.allSettled(\n agentRefs.map(async (ref) => {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"start\",\n });\n try {\n const a2aClient = new A2AClient(ref.path);\n const callerEmail = getRequestUserEmail();\n\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n\n try {\n for await (const task of a2aClient.stream(\n {\n role: \"user\",\n parts: [\n {\n type: \"text\",\n text: enrichedMessage + screenContext,\n },\n ],\n },\n Object.keys(a2aMetadata).length > 0\n ? { metadata: a2aMetadata }\n : undefined,\n )) {\n const newText =\n task.status?.message?.parts\n ?.filter(\n (p): p is { type: \"text\"; text: string } =>\n p.type === \"text\",\n )\n ?.map((p) => p.text)\n ?.join(\"\") ?? \"\";\n\n if (newText.length > lastSentLength) {\n send({\n type: \"agent_call_text\",\n agent: ref.name,\n text: newText.slice(lastSentLength),\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n }\n } catch {\n if (!responseText) {\n responseText = await callAgent(\n ref.path,\n enrichedMessage + screenContext,\n );\n }\n }\n responseText =\n userFacingLlmCredentialError(responseText, {\n agentName: ref.name,\n }) ?? responseText;\n\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"done\",\n });\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\">\\n${responseText}\\n</agent-response>`;\n } catch (err: any) {\n send({\n type: \"agent_call\",\n agent: ref.name,\n status: \"error\",\n });\n const message =\n userFacingLlmCredentialError(err, {\n agentName: ref.name,\n }) ?? `Failed to reach ${ref.name}: ${err?.message}`;\n return `<agent-response name=\"${ref.name}\" id=\"${ref.refId}\" error=\"true\">\\n${message}\\n</agent-response>`;\n }\n }),\n );\n\n const agentResponses_local: string[] = [];\n for (const result of results) {\n if (result.status === \"fulfilled\") {\n agentResponses_local.push(result.value);\n }\n }\n\n if (agentResponses_local.length > 0) {\n const agentContext =\n \"Responses from other agents:\\n\\n\" +\n agentResponses_local.join(\"\\n\\n\");\n const lastMsg = messages[messages.length - 1];\n if (lastMsg?.role === \"user\" && Array.isArray(lastMsg.content)) {\n const textPart = lastMsg.content.find(\n (p): p is import(\"./engine/types.js\").EngineTextPart =>\n p.type === \"text\",\n );\n if (textPart) {\n textPart.text = agentContext + \"\\n\\n\" + textPart.text;\n }\n }\n }\n }\n\n // Apply experiment variant overrides (A/B testing)\n let effectiveModel = model;\n try {\n const { resolveActiveExperimentConfig } =\n await import(\"../observability/experiments.js\");\n if (!ownerEmail) {\n // Without an authenticated owner we can't resolve user-scoped experiments.\n throw new Error(\"no authenticated user\");\n }\n const expConfig = await resolveActiveExperimentConfig(ownerEmail);\n if (expConfig) {\n if (typeof expConfig.configs.model === \"string\") {\n effectiveModel = expConfig.configs.model;\n }\n }\n } catch {\n // Experiments module unavailable — use default model\n }\n\n const agentLoopOpts = {\n engine,\n model: effectiveModel,\n systemPrompt: requestSystemPrompt,\n tools: requestTools,\n messages,\n actions: requestActions,\n send,\n signal,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n reasoningEffort,\n providerOptions: options.providerOptions,\n executionMode: requestMode,\n maxIterations: loopSettings.maxIterations,\n };\n\n let loopUsage: AgentLoopUsage;\n let instrumented = false;\n try {\n const { getObservabilityConfig, instrumentAgentLoop } =\n await import(\"../observability/traces.js\");\n const obsConfig = await getObservabilityConfig();\n if (obsConfig.enabled) {\n instrumented = true;\n loopUsage = await instrumentAgentLoop({\n runAgentLoop,\n loopOpts: agentLoopOpts,\n runId,\n threadId: threadId ?? null,\n userId: ownerEmail,\n config: obsConfig,\n });\n }\n } catch (err) {\n // If instrumentation setup failed, fall through to uninstrumented.\n // If the agent loop itself failed (via instrumentAgentLoop), re-throw.\n if (instrumented) throw err;\n }\n if (!instrumented) {\n loopUsage = await runAgentLoop(agentLoopOpts);\n }\n\n // Record token usage for cost monitoring so the Usage panel in\n // settings works in every mode, including local dev.\n try {\n const ownerEmail = options.resolveOwnerEmail\n ? await options.resolveOwnerEmail(event)\n : getRequestUserEmail();\n if (\n ownerEmail &&\n (loopUsage.inputTokens > 0 ||\n loopUsage.outputTokens > 0 ||\n loopUsage.cacheReadTokens > 0 ||\n loopUsage.cacheWriteTokens > 0)\n ) {\n const { recordUsage } = await import(\"../usage/store.js\");\n await recordUsage({\n ownerEmail,\n inputTokens: loopUsage.inputTokens,\n outputTokens: loopUsage.outputTokens,\n cacheReadTokens: loopUsage.cacheReadTokens,\n cacheWriteTokens: loopUsage.cacheWriteTokens,\n model: loopUsage.model,\n label: body.usageLabel || \"chat\",\n });\n }\n } catch {\n // Usage recording failed — don't break the run\n }\n },\n options.onRunComplete\n ? (run) => options.onRunComplete!(run, threadId)\n : undefined,\n );\n\n // Subscribe to the run and stream events to the client\n const stream = subscribeToRun(runId, 0);\n if (!stream) {\n setResponseStatus(event, 500);\n return { error: \"Failed to start agent run\" };\n }\n\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n setResponseHeader(event, \"Connection\", \"keep-alive\");\n setResponseHeader(event, \"X-Run-Id\", runId);\n\n return stream;\n });\n}\n\nexport {\n getActiveRunForThread,\n getActiveRunForThreadAsync,\n getRun,\n abortRun,\n subscribeToRun,\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAuDrE,eAAO,MAAM,IAAI,EAAE,UAqBlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC5B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAwMjB;AAkDD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CASzE"}
1
+ {"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAoErE,eAAO,MAAM,IAAI,EAAE,UAqBlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC5B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAoNjB;AAkDD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CASzE"}
@@ -1,6 +1,7 @@
1
1
  import { findAgent, discoverAgents } from "../server/agent-discovery.js";
2
2
  import { A2AClient, A2ATaskTimeoutError, callAgent, signA2AToken, } from "../a2a/client.js";
3
3
  import { A2A_CONTINUATION_QUEUED_MARKER } from "../integrations/a2a-continuation-marker.js";
4
+ import { formatLlmCredentialErrorMessage, isLlmCredentialError, } from "../agent/engine/credential-errors.js";
4
5
  import { getRequestUserEmail, getRequestOrgId, isIntegrationCallerRequest, getIntegrationRequestContext, } from "../server/request-context.js";
5
6
  import { getOrgDomain, getOrgA2ASecret } from "../org/context.js";
6
7
  const DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;
@@ -35,6 +36,11 @@ function getIntegrationCallTimeoutMs() {
35
36
  return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;
36
37
  return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;
37
38
  }
39
+ function formatDownstreamLlmCredentialFailure(agentName, value) {
40
+ return isLlmCredentialError(value)
41
+ ? formatLlmCredentialErrorMessage({ agentName })
42
+ : null;
43
+ }
38
44
  export const tool = {
39
45
  description: "Call a DIFFERENT, separately-deployed agent app to ask a question or delegate a task. This is strictly for cross-app A2A communication — for example, asking the mail agent to send an email while you are the calendar agent. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. " +
40
46
  "IMPORTANT — handling the response: " +
@@ -175,6 +181,9 @@ export async function run(args, context, selfAppId) {
175
181
  orgSecret: callerOrgSecret,
176
182
  ...(callTimeoutMs ? { timeoutMs: callTimeoutMs } : {}),
177
183
  });
184
+ responseText =
185
+ formatDownstreamLlmCredentialFailure(agent.name, responseText) ??
186
+ responseText;
178
187
  // Some agents reply with relative paths (e.g. slides emits
179
188
  // "/deck/abc"). Those resolve against the caller's host, not the
180
189
  // receiver's, so they're broken for the user. Expand any leading-slash
@@ -197,7 +206,9 @@ export async function run(args, context, selfAppId) {
197
206
  }
198
207
  else {
199
208
  const reason = pollErr?.message ?? "unknown error";
200
- responseText = `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;
209
+ responseText =
210
+ formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??
211
+ `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;
201
212
  }
202
213
  }
203
214
  context.send({
@@ -228,10 +239,14 @@ export async function run(args, context, selfAppId) {
228
239
  orgDomain: domain,
229
240
  orgSecret,
230
241
  });
231
- return expandRelativeUrls(response, agent.url) || "(empty response)";
242
+ const sanitized = formatDownstreamLlmCredentialFailure(agent.name, response) ?? response;
243
+ return expandRelativeUrls(sanitized, agent.url) || "(empty response)";
232
244
  }
233
245
  catch (err) {
234
246
  const msg = err?.message ?? String(err);
247
+ const credentialMessage = formatDownstreamLlmCredentialFailure(agent.name, err);
248
+ if (credentialMessage)
249
+ return credentialMessage;
235
250
  // Friendlier message for the common timeout case so the calling agent can
236
251
  // decide whether to give up or retry.
237
252
  if (/timeout|did not complete|Inactivity|504/i.test(msg)) {
@@ -1 +1 @@
1
- {"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EACL,SAAS,EACT,mBAAmB,EACnB,SAAS,EACT,YAAY,GACb,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAC5F,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAElE,MAAM,6CAA6C,GAAG,MAAM,CAAC;AAC7D,MAAM,kCAAkC,GAAG,MAAM,CAAC;AAClD,MAAM,yBAAyB,GAAG,KAAK,CAAC;AAExC,SAAS,cAAc,CAAC,KAAyB;IAC/C,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,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BAAkB,CAAC,IAAY,EAAE,QAAgB;IAC/D,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACzC,4EAA4E;IAC5E,8EAA8E;IAC9E,OAAO,IAAI,CAAC,OAAO,CACjB,qDAAqD,EACrD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import type { ActionTool } from \"../agent/types.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n A2AClient,\n A2ATaskTimeoutError,\n callAgent,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 50_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction isServerlessHost(): boolean {\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env` global injected by workerd.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s, but leave room for\n // cold start, polling overhead, and the caller's final platform response.\n if (process.env.NETLIFY) return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Call a DIFFERENT, separately-deployed agent app to ask a question or delegate a task. This is strictly for cross-app A2A communication — for example, asking the mail agent to send an email while you are the calendar agent. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real.',\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description: \"The message/question to send to the other agent\",\n },\n },\n required: [\"agent\", \"message\"],\n },\n};\n\nexport async function run(\n args: Record<string, string>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const { agent: agentIdOrName, message } = args;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message) return \"Error: --message is required\";\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const messageWithHint =\n `${message}\\n\\n` +\n `[Note: this request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/design/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only artifact IDs and URL paths returned by successful actions — never invent slugs, IDs, or hosts.]`;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n {\n expiresIn: INTEGRATION_A2A_TOKEN_TTL,\n preferGlobalSecret: true,\n },\n );\n } catch {}\n }\n\n const client = new A2AClient(agent.url, apiKey);\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is we lose progressive in-UI text streaming for cross-app\n // A2A calls, but the receiving agent's full response still surfaces via\n // the tool_result event below.\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n ...(callTimeoutMs ? { timeoutMs: callTimeoutMs } : {}),\n });\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n if (pollErr instanceof A2ATaskTimeoutError) {\n const queued = await enqueueIntegrationContinuationIfPossible(\n pollErr,\n agent,\n callerEmail,\n );\n if (queued) {\n responseText = `${A2A_CONTINUATION_QUEUED_MARKER}\\nThe ${agent.name} agent is still working. Do not send an interim reply to the user; the final result will be posted to the originating integration thread automatically.`;\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText = `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText = `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\n });\n\n return responseText || \"(empty response)\";\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n });\n return expandRelativeUrls(response, agent.url) || \"(empty response)\";\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n return `The ${agent.name} agent is taking longer than expected. Please try again, ask a simpler question, or open the ${agent.name} app directly.`;\n }\n return `Error calling ${agent.name}: ${msg}`;\n }\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n error: A2ATaskTimeoutError,\n agent: { name: string; url: string },\n ownerEmail: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n a2aTaskId: error.taskId,\n // Do not persist the short-lived JWT used for the initial send. The\n // continuation processor can mint a fresh token for each poll.\n a2aAuthToken: null,\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s(\\[<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}
1
+ {"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B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,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACzC,4EAA4E;IAC5E,8EAA8E;IAC9E,OAAO,IAAI,CAAC,OAAO,CACjB,qDAAqD,EACrD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import type { ActionTool } from \"../agent/types.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n A2AClient,\n A2ATaskTimeoutError,\n callAgent,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 50_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction isServerlessHost(): boolean {\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env` global injected by workerd.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s, but leave room for\n // cold start, polling overhead, and the caller's final platform response.\n if (process.env.NETLIFY) return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\nfunction formatDownstreamLlmCredentialFailure(\n agentName: string,\n value: unknown,\n): string | null {\n return isLlmCredentialError(value)\n ? formatLlmCredentialErrorMessage({ agentName })\n : null;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Call a DIFFERENT, separately-deployed agent app to ask a question or delegate a task. This is strictly for cross-app A2A communication — for example, asking the mail agent to send an email while you are the calendar agent. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real.',\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description: \"The message/question to send to the other agent\",\n },\n },\n required: [\"agent\", \"message\"],\n },\n};\n\nexport async function run(\n args: Record<string, string>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const { agent: agentIdOrName, message } = args;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message) return \"Error: --message is required\";\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const messageWithHint =\n `${message}\\n\\n` +\n `[Note: this request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/design/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only artifact IDs and URL paths returned by successful actions — never invent slugs, IDs, or hosts.]`;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n {\n expiresIn: INTEGRATION_A2A_TOKEN_TTL,\n preferGlobalSecret: true,\n },\n );\n } catch {}\n }\n\n const client = new A2AClient(agent.url, apiKey);\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is we lose progressive in-UI text streaming for cross-app\n // A2A calls, but the receiving agent's full response still surfaces via\n // the tool_result event below.\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n ...(callTimeoutMs ? { timeoutMs: callTimeoutMs } : {}),\n });\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, responseText) ??\n responseText;\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n if (pollErr instanceof A2ATaskTimeoutError) {\n const queued = await enqueueIntegrationContinuationIfPossible(\n pollErr,\n agent,\n callerEmail,\n );\n if (queued) {\n responseText = `${A2A_CONTINUATION_QUEUED_MARKER}\\nThe ${agent.name} agent is still working. Do not send an interim reply to the user; the final result will be posted to the originating integration thread automatically.`;\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText = `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??\n `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\n });\n\n return responseText || \"(empty response)\";\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n });\n const sanitized =\n formatDownstreamLlmCredentialFailure(agent.name, response) ?? response;\n return expandRelativeUrls(sanitized, agent.url) || \"(empty response)\";\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const credentialMessage = formatDownstreamLlmCredentialFailure(\n agent.name,\n err,\n );\n if (credentialMessage) return credentialMessage;\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n return `The ${agent.name} agent is taking longer than expected. Please try again, ask a simpler question, or open the ${agent.name} app directly.`;\n }\n return `Error calling ${agent.name}: ${msg}`;\n }\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n error: A2ATaskTimeoutError,\n agent: { name: string; url: string },\n ownerEmail: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n a2aTaskId: error.taskId,\n // Do not persist the short-lived JWT used for the initial send. The\n // continuation processor can mint a fresh token for each poll.\n a2aAuthToken: null,\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s(\\[<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}
@@ -560,8 +560,8 @@ ${marketingStyles}
560
560
  <body${hasMarketing ? ' class="has-marketing"' : ""}>
561
561
  ${marketingPanelHtml}
562
562
  <div class="card">
563
- <h1 id="heading">Welcome</h1>
564
- <p class="subtitle" id="subtitle">Create an account to get started</p>
563
+ <h1 id="heading">${googleOnly ? "Sign in" : "Welcome"}</h1>
564
+ <p class="subtitle" id="subtitle">${googleOnly ? "Use your workspace Google account to continue" : "Create an account to get started"}</p>
565
565
  <p
566
566
  class="upgrade-note"
567
567
  id="upgrade-note"
@@ -1 +1 @@
1
- {"version":3,"file":"onboarding-html.js","sourceRoot":"","sources":["../../src/server/onboarding-html.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,SAAS,cAAc;IACrB,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,IAAI,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,kBAAkB;IACzB,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,EAAE,CAAC;IAC3C,IAAI,CAAC,GAAG;QAAE,OAAO,qBAAqB,CAAC;IACvC,IAAI,GAAG,CAAC,UAAU,CAAC,aAAa,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,eAAe,CAAC,EAAE,CAAC;QACrE,IAAI,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC;YAAE,OAAO,eAAe,CAAC;QACtD,IAAI,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC;YAAE,OAAO,mBAAmB,CAAC;QACzD,OAAO,UAAU,CAAC;IACpB,CAAC;IACD,IAAI,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC;QAA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IAAI,CAAC,SAAS,CAAC,WAAW,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuChD,UAAU;QACR,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuVN;EAEE,UAAU;QACR,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;IAwBF;QACA,CAAC,CAAC,EACN;EACE,eAAe;;;QAGT,CAAC;AACT,CAAC;AAED,kDAAkD;AAClD,MAAM,CAAC,MAAM,eAAe,GAAG,iBAAiB,EAAE,CAAC;AAEnD;;;;GAIG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAsGD,CAAC;AACT,CAAC","sourcesContent":["/**\n * First-run onboarding page for agent-native apps.\n *\n * Shown when Better Auth is active and the user isn't signed in.\n * Provides a path to create or sign into an account from day one.\n *\n * After first account exists, this page acts as a normal login page.\n */\n\nfunction hasGoogleOAuth(): boolean {\n return !!(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET);\n}\n\nfunction getConnectionLabel(): string {\n const url = process.env.DATABASE_URL || \"\";\n if (!url) return \"SQLite (local file)\";\n if (url.startsWith(\"postgres://\") || url.startsWith(\"postgresql://\")) {\n if (url.includes(\"neon.tech\")) return \"Neon Postgres\";\n if (url.includes(\"supabase\")) return \"Supabase Postgres\";\n return \"Postgres\";\n }\n if (url.startsWith(\"file:\")) return \"SQLite (local file)\";\n if (url.startsWith(\"libsql://\") || url.includes(\"turso.io\")) return \"Turso\";\n return \"SQL database\";\n}\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 withAppBasePath(path: string): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n const basePath = normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n return `${basePath}${cleanPath}`;\n}\n\nexport interface OnboardingHtmlOptions {\n /**\n * Hide email/password forms and show ONLY the Google sign-in button.\n * Useful for templates (mail, calendar) where Google is required anyway.\n * If Google OAuth env vars are not configured, an error message is shown.\n */\n googleOnly?: boolean;\n /**\n * Product marketing content shown alongside the sign-in form.\n * When provided, the page uses a split layout: marketing on the left,\n * sign-in form on the right (stacked on mobile).\n */\n marketing?: {\n appName: string;\n tagline: string;\n description?: string;\n features?: string[];\n };\n}\n\nexport function getOnboardingHtml(opts: OnboardingHtmlOptions = {}): string {\n const showGoogle = hasGoogleOAuth();\n const googleOnly = !!opts.googleOnly;\n const appBasePath = normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n\n const marketing = opts.marketing;\n const hasMarketing = !!marketing;\n const brandMarkSrc = withAppBasePath(\"/agent-native-icon-dark.svg\");\n const esc = (s: string) =>\n s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n\n const marketingStyles = hasMarketing\n ? `\n body.has-marketing { padding: 0; position: relative; overflow-x: hidden; }\n #starfield {\n position: fixed;\n inset: 0;\n width: 100%;\n height: 100%;\n opacity: 0.35;\n pointer-events: none;\n z-index: 0;\n }\n .split {\n position: relative;\n z-index: 1;\n display: flex;\n min-height: 100vh;\n width: 100%;\n max-width: 1100px;\n margin: 0 auto;\n }\n .marketing-panel {\n flex: 1;\n display: flex;\n flex-direction: column;\n justify-content: center;\n padding: 3rem 3.5rem;\n }\n .marketing-content { max-width: 480px; }\n .app-name {\n display: flex;\n align-items: center;\n gap: 0.625rem;\n font-size: 2rem;\n font-weight: 700;\n color: #fff;\n margin-bottom: 0.625rem;\n letter-spacing: -0.02em;\n }\n .app-name img.brand-mark {\n height: 2.21375rem;\n width: auto;\n display: block;\n flex-shrink: 0;\n }\n .app-tagline {\n font-size: 1.25rem;\n color: #a1a1aa;\n line-height: 1.6;\n margin-bottom: 2rem;\n }\n .app-desc {\n font-size: 1rem;\n color: #71717a;\n line-height: 1.6;\n margin-bottom: 2rem;\n }\n .feature-list {\n list-style: none;\n display: flex;\n flex-direction: column;\n gap: 0.875rem;\n }\n .feature-list li {\n display: flex;\n align-items: flex-start;\n gap: 0.625rem;\n font-size: 1rem;\n color: #a1a1aa;\n line-height: 1.5;\n }\n .feature-list li::before {\n content: '';\n flex-shrink: 0;\n width: 8px;\n height: 8px;\n margin-top: 6px;\n border-radius: 50%;\n background: #3f3f46;\n border: 1px solid #52525b;\n }\n .oss-link {\n display: inline-flex;\n align-items: center;\n gap: 0.375rem;\n margin-top: 2rem;\n font-size: 0.8125rem;\n color: #71717a;\n text-decoration: none;\n }\n .oss-link:hover { color: #a1a1aa; }\n .oss-link svg { width: 15px; height: 15px; flex-shrink: 0; }\n .form-panel {\n flex: 0 0 440px;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 2rem;\n }\n .form-panel .card { max-width: 400px; }\n .form-panel .local-note { max-width: 400px; }\n @media (max-width: 900px) {\n .split { flex-direction: column; min-height: auto; }\n .marketing-panel { padding: 2rem 1.5rem 1.5rem; }\n .app-name { font-size: 1.375rem; }\n .app-name img.brand-mark { height: 1.58125rem; }\n .app-tagline { font-size: 1rem; margin-bottom: 1rem; }\n .app-desc { margin-bottom: 1rem; }\n .feature-list { gap: 0.5rem; }\n .form-panel { flex: none; padding: 1.5rem 1rem; }\n }\n`\n : \"\";\n\n const marketingPanelHtml = hasMarketing\n ? `<canvas id=\"starfield\"></canvas>\n<div class=\"split\">\n <div class=\"marketing-panel\">\n <div class=\"marketing-content\">\n <h2 class=\"app-name\">\n <img class=\"brand-mark\" src=\"${esc(brandMarkSrc)}\" alt=\"\" aria-hidden=\"true\" />\n <span>${esc(marketing!.appName)}</span>\n </h2>\n <p class=\"app-tagline\">${esc(marketing!.tagline)}</p>\n${marketing!.description ? ` <p class=\"app-desc\">${esc(marketing!.description)}</p>\\n` : \"\"}${\n marketing!.features?.length\n ? ` <ul class=\"feature-list\">\\n${marketing!.features.map((f) => ` <li>${esc(f)}</li>`).join(\"\\n\")}\\n </ul>\\n`\n : \"\"\n } <a class=\"oss-link\" href=\"https://github.com/BuilderIO/agent-native\" target=\"_blank\" rel=\"noreferrer\">\n <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 19c-4.3 1.4-4.3-2.5-6-3m12 5v-3.5c0-1 .1-1.4-.5-2 2.8-.3 5.5-1.4 5.5-6a4.6 4.6 0 00-1.3-3.2 4.2 4.2 0 00-.1-3.2s-1.1-.3-3.5 1.3a12.3 12.3 0 00-6.2 0C6.5 2.8 5.4 3.1 5.4 3.1a4.2 4.2 0 00-.1 3.2A4.6 4.6 0 004 9.5c0 4.6 2.7 5.7 5.5 6-.6.6-.6 1.2-.5 2V21\"/></svg>\n Open source\n </a>\n </div>\n </div>\n <div class=\"form-panel\">`\n : \"\";\n\n const marketingCloseHtml = hasMarketing ? `\\n </div>\\n</div>` : \"\";\n\n const starfieldScript = hasMarketing\n ? `\n (function initStarfield() {\n var canvas = document.getElementById('starfield');\n if (!canvas) return;\n var gl = canvas.getContext('webgl', { alpha: false, antialias: false });\n if (!gl) return;\n\n var vs = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vs, 'attribute vec2 position;void main(){gl_Position=vec4(position,0.0,1.0);}');\n gl.compileShader(vs);\n\n var fs = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fs, [\n 'precision highp float;',\n 'uniform float iTime;uniform vec2 iResolution;',\n '#define S(a,b,t) smoothstep(a,b,t)',\n '#define NUM_LAYERS 4.',\n 'float N21(vec2 p){vec3 a=fract(vec3(p.xyx)*vec3(213.897,653.453,253.098));a+=dot(a,a.yzx+79.76);return fract((a.x+a.y)*a.z);}',\n 'vec2 GetPos(vec2 id,vec2 offs,float t){float n=N21(id+offs);float n1=fract(n*10.);float n2=fract(n*100.);float a=t+n;return offs+vec2(sin(a*n1),cos(a*n2))*.4;}',\n 'float df_line(vec2 a,vec2 b,vec2 p){vec2 pa=p-a,ba=b-a;float h=clamp(dot(pa,ba)/dot(ba,ba),0.,1.);return length(pa-ba*h);}',\n 'float line(vec2 a,vec2 b,vec2 uv){float r1=.025;float r2=.006;float d=df_line(a,b,uv);float d2=length(a-b);float fade=S(1.5,.5,d2);fade+=S(.05,.02,abs(d2-.75));return S(r1,r2,d)*fade;}',\n 'float NetLayer(vec2 st,float n,float t){',\n ' vec2 id=floor(st)+n;st=fract(st)-.5;',\n ' vec2 p0=GetPos(id,vec2(-1,-1),t);vec2 p1=GetPos(id,vec2(0,-1),t);vec2 p2=GetPos(id,vec2(1,-1),t);',\n ' vec2 p3=GetPos(id,vec2(-1,0),t);vec2 p4=GetPos(id,vec2(0,0),t);vec2 p5=GetPos(id,vec2(1,0),t);',\n ' vec2 p6=GetPos(id,vec2(-1,1),t);vec2 p7=GetPos(id,vec2(0,1),t);vec2 p8=GetPos(id,vec2(1,1),t);',\n ' float m=0.;float sparkle=0.;float d;float s;float pulse;',\n ' m+=line(p4,p0,st);d=length(st-p0);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p0.x)+fract(p0.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p1,st);d=length(st-p1);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p1.x)+fract(p1.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p2,st);d=length(st-p2);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p2.x)+fract(p2.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p3,st);d=length(st-p3);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p3.x)+fract(p3.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p4,st);d=length(st-p4);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p4.x)+fract(p4.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p5,st);d=length(st-p5);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p5.x)+fract(p5.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p6,st);d=length(st-p6);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p6.x)+fract(p6.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p7,st);d=length(st-p7);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p7.x)+fract(p7.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p8,st);d=length(st-p8);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p8.x)+fract(p8.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p1,p3,st);m+=line(p1,p5,st);m+=line(p7,p5,st);m+=line(p7,p3,st);',\n ' float sPhase=(sin(t+n)+sin(t*.1))*.25+.5;sPhase+=pow(sin(t*.1)*.5+.5,50.)*5.;m+=sparkle*sPhase;',\n ' return m;',\n '}',\n 'void mainImage(out vec4 fragColor,in vec2 fragCoord){',\n ' vec2 uv=(fragCoord-iResolution.xy*.5)/iResolution.y;',\n ' float t=iTime*.03;float s=sin(t);float c=cos(t);mat2 rot=mat2(c,-s,s,c);vec2 st=uv*rot;',\n ' float m=0.;',\n ' for(float i=0.;i<1.;i+=1./NUM_LAYERS){float z=fract(t+i);float size=mix(15.,1.,z);float fade=S(0.,.6,z)*S(1.,.8,z);m+=fade*NetLayer(st*size,i,iTime*0.3);}',\n ' vec3 col=vec3(0.35)*m;col*=1.-dot(uv,uv);',\n ' float tt=min(iTime,5.0);col*=S(0.,20.,tt);',\n ' col=clamp(col,0.,1.);fragColor=vec4(col,1.);',\n '}',\n 'void main(){mainImage(gl_FragColor,gl_FragCoord.xy);}'\n ].join('\\\\n'));\n gl.compileShader(fs);\n\n var prog = gl.createProgram();\n gl.attachShader(prog, vs);\n gl.attachShader(prog, fs);\n gl.linkProgram(prog);\n gl.useProgram(prog);\n\n var buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]), gl.STATIC_DRAW);\n var pos = gl.getAttribLocation(prog, 'position');\n gl.enableVertexAttribArray(pos);\n gl.vertexAttribPointer(pos, 2, gl.FLOAT, false, 0, 0);\n\n var uTime = gl.getUniformLocation(prog, 'iTime');\n var uRes = gl.getUniformLocation(prog, 'iResolution');\n\n function resize() {\n var w = window.innerWidth, h = window.innerHeight;\n var dpr = Math.min(window.devicePixelRatio, 1.5);\n canvas.width = w * dpr; canvas.height = h * dpr;\n gl.viewport(0, 0, canvas.width, canvas.height);\n }\n resize();\n window.addEventListener('resize', resize);\n\n var start = performance.now(), last = 0;\n function render(now) {\n requestAnimationFrame(render);\n if (now - last < 33) return;\n last = now;\n gl.uniform1f(uTime, (now - start) * 0.001);\n gl.uniform2f(uRes, canvas.width, canvas.height);\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n }\n requestAnimationFrame(render);\n })();`\n : \"\";\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\">\n<title>${hasMarketing ? esc(marketing!.appName) + \" — Sign in\" : \"Welcome\"}</title>\n${\n hasMarketing\n ? `<meta name=\"description\" content=\"${esc(marketing!.tagline)}\">\n<meta property=\"og:title\" content=\"${esc(marketing!.appName)}\">\n<meta property=\"og:description\" content=\"${esc(marketing!.tagline)}\">`\n : \"\"\n}\n<style>\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n background: #0a0a0a;\n color: #e5e5e5;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n padding: 1rem;\n }\n .card {\n width: 100%;\n max-width: 400px;\n padding: 2rem;\n background: #141414;\n border: 1px solid rgba(255,255,255,0.08);\n border-radius: 12px;\n }\n h1 { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.25rem; color: #fff; }\n .subtitle { font-size: 0.8125rem; color: #888; margin-bottom: 1.5rem; }\n .tabs {\n display: inline-flex;\n width: 100%;\n padding: 4px;\n margin-bottom: 1.5rem;\n background: rgba(255,255,255,0.06);\n border-radius: 8px;\n }\n .tab {\n flex: 1;\n padding: 0.5rem 0.75rem;\n background: none;\n border: none;\n color: #888;\n font-size: 0.8125rem;\n font-weight: 500;\n cursor: pointer;\n border-radius: 6px;\n }\n .tab.active {\n background: #1e1e1e;\n color: #fff;\n box-shadow: 0 1px 2px rgba(0,0,0,0.3);\n }\n .tab:hover:not(.active) { color: #bbb; }\n .form { display: none; }\n .form.active { display: block; }\n .card.verifying .tabs,\n .card.verifying #google-btn,\n .card.verifying #google-err,\n .card.verifying #auth-divider,\n .card.verifying #upgrade-note {\n display: none;\n }\n label { display: block; font-size: 0.8125rem; color: #888; margin-bottom: 0.375rem; }\n input {\n width: 100%;\n padding: 0.5rem 0.75rem;\n background: transparent;\n border: 1px solid rgba(255,255,255,0.12);\n border-radius: 6px;\n color: #e5e5e5;\n font-size: 0.875rem;\n outline: none;\n margin-bottom: 0.875rem;\n }\n input:focus { border-color: rgba(255,255,255,0.3); box-shadow: 0 0 0 1px rgba(255,255,255,0.1); }\n input::placeholder { color: #555; }\n button[type=\"submit\"], .btn-primary {\n width: 100%;\n margin-top: 0.25rem;\n padding: 0.5rem;\n background: #fff;\n color: #000;\n border: none;\n border-radius: 6px;\n font-size: 0.875rem;\n font-weight: 500;\n cursor: pointer;\n }\n button[type=\"submit\"]:hover, .btn-primary:hover { background: #e5e5e5; }\n button[type=\"submit\"]:disabled { opacity: 0.5; cursor: not-allowed; }\n .btn-secondary {\n width: 100%;\n margin-top: 0.75rem;\n padding: 0.5rem;\n background: transparent;\n color: #888;\n border: 1px solid rgba(255,255,255,0.1);\n border-radius: 6px;\n font-size: 0.8125rem;\n cursor: pointer;\n }\n .btn-secondary:hover { color: #bbb; border-color: rgba(255,255,255,0.2); }\n .msg { margin-top: 0.75rem; font-size: 0.8125rem; display: none; }\n .msg.error { color: #f87171; }\n .msg.success { color: #4ade80; }\n .msg.show { display: block; }\n .step-progress {\n display: grid;\n grid-template-columns: repeat(3, minmax(0, 1fr));\n gap: 0.5rem;\n margin-bottom: 1.25rem;\n }\n .progress-step {\n position: relative;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 0.375rem;\n color: #666;\n font-size: 0.6875rem;\n line-height: 1.2;\n text-align: center;\n }\n .progress-step::before {\n content: '';\n position: absolute;\n top: 11px;\n left: calc(-50% + 16px);\n width: calc(100% - 32px);\n height: 1px;\n background: rgba(255,255,255,0.1);\n }\n .progress-step:first-child::before { display: none; }\n .progress-step span {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 22px;\n height: 22px;\n border-radius: 999px;\n border: 1px solid rgba(255,255,255,0.14);\n background: #151515;\n color: #777;\n font-size: 0.6875rem;\n font-weight: 600;\n }\n .progress-step strong { font-weight: 500; }\n .progress-step.complete,\n .progress-step.current { color: #e5e5e5; }\n .progress-step.complete span {\n background: #d9f99d;\n border-color: #d9f99d;\n color: #111;\n }\n .progress-step.current span {\n background: #fff;\n border-color: #fff;\n color: #000;\n box-shadow: 0 0 0 4px rgba(255,255,255,0.08);\n }\n .verification-panel {\n padding: 1rem;\n margin-bottom: 0.875rem;\n background: rgba(255,255,255,0.04);\n border: 1px solid rgba(255,255,255,0.08);\n border-radius: 8px;\n }\n .verification-kicker {\n margin-bottom: 0.5rem;\n color: #bef264;\n font-size: 0.75rem;\n font-weight: 500;\n }\n .verification-copy {\n color: #d4d4d8;\n font-size: 0.875rem;\n line-height: 1.55;\n }\n .verification-copy strong {\n color: #fff;\n font-weight: 600;\n word-break: break-word;\n }\n .verification-note {\n margin-top: 0.75rem;\n color: #71717a;\n font-size: 0.75rem;\n line-height: 1.45;\n }\n .inline-actions {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 0.75rem;\n margin-top: 0.75rem;\n }\n .link-button {\n padding: 0.25rem 0;\n background: none;\n border: none;\n color: #888;\n cursor: pointer;\n font-size: 0.75rem;\n text-decoration: underline;\n text-underline-offset: 2px;\n }\n .link-button:hover { color: #bbb; }\n .link-button:disabled { cursor: wait; opacity: 0.5; }\n .divider {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n margin: 1.25rem 0;\n font-size: 0.75rem;\n color: #555;\n }\n .divider::before, .divider::after {\n content: '';\n flex: 1;\n height: 1px;\n background: rgba(255,255,255,0.08);\n }\n .upgrade-note {\n margin-bottom: 1rem;\n padding: 0.75rem;\n border: 1px solid rgba(255,255,255,0.08);\n border-radius: 8px;\n background: rgba(255,255,255,0.03);\n font-size: 0.75rem;\n line-height: 1.5;\n color: #a1a1aa;\n display: none;\n }\n .upgrade-note.show { display: block; }\n .btn-google {\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 0.625rem;\n padding: 0.5rem;\n background: #fff;\n color: #000;\n border: none;\n border-radius: 6px;\n font-size: 0.875rem;\n font-weight: 500;\n cursor: pointer;\n }\n .btn-google:hover { background: #e5e5e5; }\n .btn-google:disabled { opacity: 0.5; cursor: wait; }\n .btn-google svg { width: 18px; height: 18px; flex-shrink: 0; }\n .google-error { margin-top: 0.5rem; font-size: 0.8125rem; color: #f87171; display: none; }\n .google-error.show { display: block; }\n .local-note {\n display: none;\n max-width: 400px;\n width: 100%;\n margin-top: 1rem;\n padding: 0.625rem 0.875rem;\n font-size: 0.6875rem;\n line-height: 1.5;\n color: #666;\n border: 1px dashed rgba(255,255,255,0.08);\n border-radius: 8px;\n text-align: center;\n }\n .local-note.show { display: block; }\n .local-note strong { color: #999; font-weight: 500; }\n .local-note a { color: #888; text-decoration: none; }\n .local-note a:hover { color: #bbb; }\n${marketingStyles}\n</style>\n</head>\n<body${hasMarketing ? ' class=\"has-marketing\"' : \"\"}>\n${marketingPanelHtml}\n<div class=\"card\">\n <h1 id=\"heading\">Welcome</h1>\n <p class=\"subtitle\" id=\"subtitle\">Create an account to get started</p>\n <p\n class=\"upgrade-note\"\n id=\"upgrade-note\"\n data-upgrade-copy=\"Continue signing in to attach this app to your account and migrate local data.\"\n ></p>\n\n${\n showGoogle\n ? `\n <button class=\"btn-google\" id=\"google-btn\" onclick=\"signInWithGoogle()\">\n <svg viewBox=\"0 0 24 24\"><path fill=\"#4285F4\" d=\"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z\"/><path fill=\"#34A853\" d=\"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z\"/><path fill=\"#FBBC05\" d=\"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z\"/><path fill=\"#EA4335\" d=\"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z\"/></svg>\n Sign in with Google\n </button>\n <p class=\"google-error\" id=\"google-err\"></p>\n${googleOnly ? \"\" : `\\n <div class=\"divider\" id=\"auth-divider\">or</div>\\n`}\n`\n : googleOnly\n ? `\n <p style=\"color:#f87171;font-size:0.875rem;text-align:center;padding:1rem 0\">\n Google sign-in is not configured. Set <code>GOOGLE_CLIENT_ID</code> and\n <code>GOOGLE_CLIENT_SECRET</code> environment variables to enable login.\n </p>\n`\n : \"\"\n}\n${\n googleOnly\n ? \"\"\n : ` <div class=\"tabs\">\n <button class=\"tab\" data-tab=\"signup\">Create account</button>\n <button class=\"tab\" data-tab=\"login\">Sign in</button>\n </div>\n\n <form id=\"signup-form\" class=\"form\">\n <label for=\"s-email\">Email</label>\n <input id=\"s-email\" type=\"email\" autocomplete=\"email\" autofocus placeholder=\"you@example.com\" required />\n <label for=\"s-pass\">Password</label>\n <input id=\"s-pass\" type=\"password\" autocomplete=\"new-password\" placeholder=\"At least 8 characters\" required minlength=\"8\" />\n <label for=\"s-pass2\">Confirm password</label>\n <input id=\"s-pass2\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Confirm password\" required minlength=\"8\" />\n <button type=\"submit\">Create account</button>\n <p class=\"msg\" id=\"s-msg\"></p>\n </form>\n\n <div id=\"verification-step\" class=\"form verification-step\" aria-live=\"polite\">\n <div class=\"step-progress\" aria-label=\"Signup progress\">\n <div class=\"progress-step complete\"><span>1</span><strong>Account</strong></div>\n <div class=\"progress-step current\"><span>2</span><strong>Verify</strong></div>\n <div class=\"progress-step\"><span>3</span><strong>Start</strong></div>\n </div>\n <div class=\"verification-panel\">\n <p class=\"verification-kicker\">Verification email sent</p>\n <p class=\"verification-copy\">We sent a secure link to <strong id=\"verify-email\"></strong>. When you click it, this app will finish signing you in automatically.</p>\n <p class=\"verification-note\">You can keep this tab open. After verifying, use Continue if the app has not refreshed yet.</p>\n </div>\n <button type=\"button\" class=\"btn-primary\" id=\"verify-continue\">Continue</button>\n <div class=\"inline-actions\">\n <button type=\"button\" class=\"link-button\" id=\"resend-verification\">Resend email</button>\n <button type=\"button\" class=\"link-button\" id=\"back-to-signup\">Back</button>\n </div>\n <p class=\"msg\" id=\"verify-msg\"></p>\n </div>\n\n <form id=\"login-form\" class=\"form\">\n <label for=\"l-email\">Email</label>\n <input id=\"l-email\" type=\"email\" autocomplete=\"email\" placeholder=\"you@example.com\" required />\n <label for=\"l-pass\">Password</label>\n <input id=\"l-pass\" type=\"password\" autocomplete=\"current-password\" placeholder=\"Enter password\" required />\n <button type=\"submit\">Sign in</button>\n <p class=\"msg error\" id=\"l-msg\"></p>\n <p style=\"margin-top:0.75rem;font-size:0.75rem;text-align:right\">\n <a href=\"#\" id=\"forgot-link\" style=\"color:#888;text-decoration:underline;text-underline-offset:2px\">Forgot password?</a>\n </p>\n </form>\n\n <form id=\"forgot-form\" class=\"form\">\n <label for=\"f-email\">Email</label>\n <input id=\"f-email\" type=\"email\" autocomplete=\"email\" placeholder=\"you@example.com\" required />\n <button type=\"submit\">Send reset link</button>\n <p class=\"msg\" id=\"f-msg\"></p>\n <p style=\"margin-top:0.75rem;font-size:0.75rem;text-align:center\">\n <a href=\"#\" id=\"back-to-login\" style=\"color:#888;text-decoration:underline;text-underline-offset:2px\">Back to sign in</a>\n </p>\n </form>`\n}\n</div>\n<p class=\"local-note\" id=\"local-note\">\n Your account is stored in this app's own DB (<strong>${getConnectionLabel()}</strong>), not a third-party service.\n</p>${marketingCloseHtml}\n<script>\n function __anBasePath() {\n var configured = ${JSON.stringify(appBasePath)};\n if (configured) return configured;\n var marker = '/_agent-native';\n var idx = window.location.pathname.indexOf(marker);\n return idx > 0 ? window.location.pathname.slice(0, idx) : '';\n }\n function __anPath(path) {\n return __anBasePath() + path;\n }\n function __anGetReturnPath() {\n try {\n var inner = new URLSearchParams(window.location.search).get('return');\n if (inner) return inner;\n } catch(e) {}\n return window.location.pathname + window.location.search;\n }\n (function revealLocalNote() {\n var h = location.hostname;\n if (h === 'localhost' || h === '127.0.0.1' || h === '::1' || h.endsWith('.local')) {\n var n = document.getElementById('local-note');\n if (n) n.classList.add('show');\n }\n })();\n (function revealUpgradeNote() {\n var shouldShow = false;\n try {\n var params = new URLSearchParams(location.search);\n shouldShow = params.get('signin') === '1' || params.get('upgrade-from-local') === '1';\n } catch(e) {}\n if (!shouldShow) {\n try { shouldShow = localStorage.getItem('an_migrate_from_local') === '1'; } catch(e) {}\n }\n if (!shouldShow) return;\n var n = document.getElementById('upgrade-note');\n if (!n) return;\n n.textContent = n.getAttribute('data-upgrade-copy') || 'Continue signing in to migrate local data.';\n n.classList.add('show');\n })();\n${\n googleOnly\n ? \"\"\n : ` var TAB_STORAGE_KEY = 'an.onboarding.tab';\n var tabs = document.querySelectorAll('.tab');\n var forms = document.querySelectorAll('.form');\n var subtitles = { signup: 'Create an account to get started', login: 'Sign in to your account' };\n var headings = { signup: 'Welcome', login: 'Welcome back' };\n var pendingSignupEmail = '';\n function setActiveTab(name, opts) {\n if (name !== 'signup' && name !== 'login') return;\n var form = document.getElementById(name + '-form');\n if (!form) return;\n var card = document.querySelector('.card');\n if (card) card.classList.remove('verifying');\n tabs.forEach(function(x) { x.classList.remove('active'); });\n forms.forEach(function(x) { x.classList.remove('active'); });\n var btn = document.querySelector('.tab[data-tab=\"' + name + '\"]');\n if (btn) btn.classList.add('active');\n form.classList.add('active');\n var sub = document.getElementById('subtitle');\n if (sub && subtitles[name]) sub.textContent = subtitles[name];\n var heading = document.getElementById('heading');\n if (heading && headings[name]) heading.textContent = headings[name];\n if (opts && opts.persist) {\n try { localStorage.setItem(TAB_STORAGE_KEY, name); } catch (e) {}\n }\n }\n function showVerificationStep(email) {\n pendingSignupEmail = email || '';\n tabs.forEach(function(x) { x.classList.remove('active'); });\n forms.forEach(function(x) { x.classList.remove('active'); });\n var card = document.querySelector('.card');\n if (card) card.classList.add('verifying');\n var step = document.getElementById('verification-step');\n if (step) step.classList.add('active');\n var emailNode = document.getElementById('verify-email');\n if (emailNode) emailNode.textContent = pendingSignupEmail;\n var heading = document.getElementById('heading');\n if (heading) heading.textContent = 'Check your email';\n var sub = document.getElementById('subtitle');\n if (sub) sub.textContent = 'Finish creating your account';\n var msg = document.getElementById('verify-msg');\n if (msg) {\n msg.classList.remove('show', 'error', 'success');\n msg.textContent = '';\n }\n try { localStorage.setItem(TAB_STORAGE_KEY, 'signup'); } catch (e) {}\n }\n function getVerificationMessageNode() {\n var verifyStep = document.getElementById('verification-step');\n if (verifyStep && verifyStep.classList.contains('active')) {\n return document.getElementById('verify-msg');\n }\n return document.getElementById('l-msg') || document.getElementById('verify-msg');\n }\n async function checkVerificationSession(fallbackText) {\n var msg = getVerificationMessageNode();\n if (msg) {\n msg.textContent = 'Checking your verification...';\n msg.classList.remove('error');\n msg.classList.add('show', 'success');\n }\n try {\n var res = await fetch(__anPath('/_agent-native/auth/session'), {\n headers: { 'Accept': 'application/json' },\n });\n var data = await res.json().catch(function() { return {}; });\n if (res.ok && data && data.email && !data.error) {\n window.location.reload();\n return;\n }\n if (msg) {\n msg.textContent = fallbackText || 'Still waiting on verification. Click the link in your email, then try Continue again.';\n msg.classList.remove('success');\n msg.classList.add('show', 'error');\n }\n } catch (err) {\n if (msg) {\n msg.textContent = 'Could not check verification. Please try again.';\n msg.classList.remove('success');\n msg.classList.add('show', 'error');\n }\n }\n }\n async function resendVerificationEmail() {\n var btn = document.getElementById('resend-verification');\n var msg = document.getElementById('verify-msg');\n var email = pendingSignupEmail || document.getElementById('s-email').value;\n if (!email) return;\n var original = btn ? btn.textContent : '';\n if (btn) {\n btn.disabled = true;\n btn.textContent = 'Sending...';\n }\n if (msg) msg.classList.remove('show', 'error', 'success');\n try {\n var res = await fetch(__anPath('/_agent-native/auth/ba/send-verification-email'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: email, callbackURL: __anGetReturnPath() }),\n });\n if (res.ok) {\n if (msg) {\n msg.textContent = 'Sent a fresh verification link.';\n msg.classList.add('show', 'success');\n }\n if (btn) btn.textContent = 'Sent';\n setTimeout(function() {\n if (btn) {\n btn.disabled = false;\n btn.textContent = original;\n }\n }, 1600);\n return;\n }\n var data = await res.json().catch(function() { return {}; });\n if (msg) {\n msg.textContent = (data && (data.message || data.error)) || 'Could not resend the verification email.';\n msg.classList.add('show', 'error');\n }\n if (btn) {\n btn.disabled = false;\n btn.textContent = original;\n }\n } catch (err) {\n if (msg) {\n msg.textContent = 'Network error. Please try again.';\n msg.classList.add('show', 'error');\n }\n if (btn) {\n btn.disabled = false;\n btn.textContent = original;\n }\n }\n }\n (function initActiveTab() {\n var initial = 'signup';\n try {\n var params = new URLSearchParams(location.search);\n var qp = params.get('tab');\n var path = location.pathname;\n while (path.length > 1 && path.charAt(path.length - 1) === '/') path = path.slice(0, -1);\n if (qp === 'login' || qp === 'signup') {\n initial = qp;\n } else if (params.has('verified')) {\n initial = 'login';\n } else if (path === '/login' || path.endsWith('/login')) {\n initial = 'login';\n } else if (path === '/signup' || path.endsWith('/signup')) {\n initial = 'signup';\n } else {\n var stored = localStorage.getItem(TAB_STORAGE_KEY);\n if (stored === 'login' || stored === 'signup') initial = stored;\n }\n } catch (e) {}\n setActiveTab(initial, { persist: false });\n try {\n if (new URLSearchParams(location.search).has('verified')) {\n var msg = document.getElementById('l-msg');\n if (msg) {\n msg.textContent = 'Email verified. Finishing sign-in...';\n msg.classList.remove('error');\n msg.classList.add('show', 'success');\n }\n checkVerificationSession('Email verified. Sign in to continue.');\n }\n } catch (e) {}\n })();\n tabs.forEach(function(t) { t.addEventListener('click', function() {\n setActiveTab(t.dataset.tab, { persist: true });\n }); });\n\n document.getElementById('signup-form').addEventListener('submit', async function(e) {\n e.preventDefault();\n var form = e.currentTarget;\n var btn = form.querySelector('button[type=\"submit\"]');\n var msg = document.getElementById('s-msg');\n msg.classList.remove('show', 'error', 'success');\n var pass = document.getElementById('s-pass').value;\n var pass2 = document.getElementById('s-pass2').value;\n if (pass !== pass2) {\n msg.textContent = 'Passwords do not match';\n msg.classList.add('show', 'error');\n return;\n }\n var originalLabel = btn.textContent;\n btn.disabled = true;\n btn.textContent = 'Creating account…';\n try {\n var email = document.getElementById('s-email').value;\n var res = await fetch(__anPath('/_agent-native/auth/register'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n email: email,\n password: pass,\n callbackURL: __anGetReturnPath(),\n }),\n });\n var data = await res.json().catch(function() { return {}; });\n if (res.ok) {\n // If email verification is required, the server won't return a session.\n // Try logging in — if it fails (unverified), show a \"check your email\" message.\n var loginRes = await fetch(__anPath('/_agent-native/auth/login'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: email, password: pass }),\n });\n if (loginRes.ok) {\n msg.textContent = 'Account created — signing you in…';\n msg.classList.add('show', 'success');\n window.location.reload();\n return;\n }\n btn.disabled = false;\n btn.textContent = originalLabel;\n showVerificationStep(email);\n return;\n }\n msg.textContent = data.error || 'Registration failed';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = originalLabel;\n } catch (err) {\n msg.textContent = 'Network error — please try again';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = originalLabel;\n }\n });\n\n var verifyContinue = document.getElementById('verify-continue');\n if (verifyContinue) verifyContinue.addEventListener('click', function(e) {\n e.preventDefault();\n checkVerificationSession();\n });\n var resendBtn = document.getElementById('resend-verification');\n if (resendBtn) resendBtn.addEventListener('click', function(e) {\n e.preventDefault();\n resendVerificationEmail();\n });\n var backToSignup = document.getElementById('back-to-signup');\n if (backToSignup) backToSignup.addEventListener('click', function(e) {\n e.preventDefault();\n setActiveTab('signup', { persist: true });\n var email = document.getElementById('s-email');\n setTimeout(function() { if (email) email.focus(); }, 0);\n });\n\n var forgotLink = document.getElementById('forgot-link');\n var backToLogin = document.getElementById('back-to-login');\n if (forgotLink) forgotLink.addEventListener('click', function(e) {\n e.preventDefault();\n document.getElementById('login-form').classList.remove('active');\n document.getElementById('forgot-form').classList.add('active');\n var sub = document.getElementById('subtitle');\n if (sub) sub.textContent = 'Reset your password';\n var heading = document.getElementById('heading');\n if (heading) heading.textContent = 'Reset password';\n var fEmail = document.getElementById('f-email');\n var lEmail = document.getElementById('l-email');\n if (lEmail && lEmail.value) fEmail.value = lEmail.value;\n setTimeout(function() { fEmail.focus(); }, 0);\n });\n if (backToLogin) backToLogin.addEventListener('click', function(e) {\n e.preventDefault();\n document.getElementById('forgot-form').classList.remove('active');\n document.getElementById('login-form').classList.add('active');\n var sub = document.getElementById('subtitle');\n if (sub) sub.textContent = subtitles.login;\n var heading = document.getElementById('heading');\n if (heading) heading.textContent = headings.login;\n });\n\n var forgotForm = document.getElementById('forgot-form');\n if (forgotForm) forgotForm.addEventListener('submit', async function(e) {\n e.preventDefault();\n var btn = e.currentTarget.querySelector('button[type=\"submit\"]');\n var msg = document.getElementById('f-msg');\n msg.classList.remove('show', 'error', 'success');\n var original = btn.textContent;\n btn.disabled = true;\n btn.textContent = 'Sending…';\n try {\n var email = document.getElementById('f-email').value;\n var res = await fetch(__anPath('/_agent-native/auth/ba/request-password-reset'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: email }),\n });\n if (res.ok) {\n msg.textContent = 'If that email exists, a reset link is on its way.';\n msg.classList.add('show', 'success');\n btn.textContent = 'Sent';\n return;\n }\n var data = await res.json().catch(function() { return {}; });\n msg.textContent = (data && (data.message || data.error)) || 'Could not send reset email.';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = original;\n } catch (err) {\n msg.textContent = 'Network error — please try again';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = original;\n }\n });\n\n document.getElementById('login-form').addEventListener('submit', async function(e) {\n e.preventDefault();\n var form = e.currentTarget;\n var btn = form.querySelector('button[type=\"submit\"]');\n var msg = document.getElementById('l-msg');\n msg.classList.remove('show', 'success');\n msg.classList.add('error');\n var originalLabel = btn.textContent;\n btn.disabled = true;\n btn.textContent = 'Signing in…';\n try {\n var res = await fetch(__anPath('/_agent-native/auth/login'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n email: document.getElementById('l-email').value,\n password: document.getElementById('l-pass').value,\n }),\n });\n if (res.ok) {\n window.location.reload();\n return;\n }\n var data = await res.json().catch(function() { return {}; });\n msg.textContent = data.error || 'Invalid email or password';\n msg.classList.add('show');\n btn.disabled = false;\n btn.textContent = originalLabel;\n } catch (err) {\n msg.textContent = 'Network error — please try again';\n msg.classList.add('show');\n btn.disabled = false;\n btn.textContent = originalLabel;\n }\n });\n`\n}\n${\n showGoogle\n ? `\n async function signInWithGoogle() {\n var btn = document.getElementById('google-btn');\n var err = document.getElementById('google-err');\n btn.disabled = true;\n err.classList.remove('show');\n try {\n var ret = __anGetReturnPath();\n var authUrl = __anPath('/_agent-native/google/auth-url') + '?return=' + encodeURIComponent(ret);\n var res = await fetch(authUrl);\n var data = await res.json();\n if (data.url) {\n try { sessionStorage.setItem('__an_signin', '1'); } catch(e) {}\n window.location.href = data.url;\n } else {\n err.textContent = data.message || 'Google OAuth is not configured.';\n err.classList.add('show');\n btn.disabled = false;\n }\n } catch (e) {\n err.textContent = 'Failed to connect. Please try again.';\n err.classList.add('show');\n btn.disabled = false;\n }\n }`\n : \"\"\n}\n${starfieldScript}\n</script>\n</body>\n</html>`;\n}\n\n/** @deprecated Use getOnboardingHtml() instead */\nexport const ONBOARDING_HTML = getOnboardingHtml();\n\n/**\n * HTML for the password reset page — shown when the user clicks the link in\n * their reset email. Posts `{ newPassword, token }` to Better Auth's\n * `/reset-password` endpoint, then redirects to the login page.\n */\nexport function getResetPasswordHtml(): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\">\n<title>Reset password</title>\n<style>\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n body { font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; background: #0a0a0a; color: #e5e5e5; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 1rem; }\n .card { width: 100%; max-width: 400px; padding: 2rem; background: #141414; border: 1px solid rgba(255,255,255,0.08); border-radius: 12px; }\n h1 { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.25rem; color: #fff; }\n .subtitle { font-size: 0.8125rem; color: #888; margin-bottom: 1.5rem; }\n label { display: block; font-size: 0.8125rem; color: #888; margin-bottom: 0.375rem; }\n input { width: 100%; padding: 0.5rem 0.75rem; background: transparent; border: 1px solid rgba(255,255,255,0.12); border-radius: 6px; color: #e5e5e5; font-size: 0.875rem; outline: none; margin-bottom: 0.875rem; }\n input:focus { border-color: rgba(255,255,255,0.3); box-shadow: 0 0 0 1px rgba(255,255,255,0.1); }\n input::placeholder { color: #555; }\n button[type=\"submit\"] { width: 100%; margin-top: 0.25rem; padding: 0.5rem; background: #fff; color: #000; border: none; border-radius: 6px; font-size: 0.875rem; font-weight: 500; cursor: pointer; }\n button[type=\"submit\"]:hover { background: #e5e5e5; }\n button[type=\"submit\"]:disabled { opacity: 0.5; cursor: not-allowed; }\n .msg { margin-top: 0.75rem; font-size: 0.8125rem; display: none; }\n .msg.error { color: #f87171; }\n .msg.success { color: #4ade80; }\n .msg.show { display: block; }\n .back { display: inline-block; margin-top: 1rem; font-size: 0.75rem; color: #888; text-decoration: none; }\n .back:hover { color: #bbb; }\n</style>\n</head>\n<body>\n<div class=\"card\">\n <h1>Choose a new password</h1>\n <p class=\"subtitle\">Set a new password for your account.</p>\n <form id=\"reset-form\">\n <label for=\"p1\">New password</label>\n <input id=\"p1\" type=\"password\" autocomplete=\"new-password\" autofocus placeholder=\"At least 8 characters\" required minlength=\"8\" />\n <label for=\"p2\">Confirm password</label>\n <input id=\"p2\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Confirm password\" required minlength=\"8\" />\n <button type=\"submit\">Save new password</button>\n <p class=\"msg\" id=\"msg\"></p>\n </form>\n <a class=\"back\" id=\"back-link\" href=\"/\">Back to sign in</a>\n</div>\n<script>\n (function() {\n // Derive the app's base path so apps mounted under a prefix\n // (e.g. /mail, /calendar) get sent home instead of to the root domain.\n var RESET_PATH = '/_agent-native/auth/reset';\n var pathname = window.location.pathname;\n var idx = pathname.indexOf(RESET_PATH);\n var basePath = (idx >= 0 ? pathname.slice(0, idx) : '') || '';\n var homeHref = basePath + '/';\n var backLink = document.getElementById('back-link');\n if (backLink) backLink.setAttribute('href', homeHref);\n var params = new URLSearchParams(location.search);\n var token = params.get('token') || '';\n var msg = document.getElementById('msg');\n if (!token) {\n msg.textContent = 'Missing or invalid reset token. Request a new reset link.';\n msg.classList.add('show', 'error');\n document.getElementById('reset-form').style.display = 'none';\n return;\n }\n document.getElementById('reset-form').addEventListener('submit', async function(e) {\n e.preventDefault();\n var btn = e.currentTarget.querySelector('button[type=\"submit\"]');\n var p1 = document.getElementById('p1').value;\n var p2 = document.getElementById('p2').value;\n msg.classList.remove('show', 'error', 'success');\n if (p1 !== p2) {\n msg.textContent = 'Passwords do not match';\n msg.classList.add('show', 'error');\n return;\n }\n var original = btn.textContent;\n btn.disabled = true;\n btn.textContent = 'Saving…';\n try {\n var res = await fetch(basePath + '/_agent-native/auth/ba/reset-password', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ newPassword: p1, token: token }),\n });\n if (res.ok) {\n msg.textContent = 'Password updated — redirecting to sign in…';\n msg.classList.add('show', 'success');\n setTimeout(function() { window.location.href = homeHref; }, 1200);\n return;\n }\n var data = await res.json().catch(function() { return {}; });\n msg.textContent = (data && (data.message || data.error)) || 'Reset failed. The link may have expired — request a new one.';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = original;\n } catch (err) {\n msg.textContent = 'Network error — please try again';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = original;\n }\n });\n })();\n</script>\n</body>\n</html>`;\n}\n"]}
1
+ {"version":3,"file":"onboarding-html.js","sourceRoot":"","sources":["../../src/server/onboarding-html.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,SAAS,cAAc;IACrB,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,IAAI,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,kBAAkB;IACzB,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,EAAE,CAAC;IAC3C,IAAI,CAAC,GAAG;QAAE,OAAO,qBAAqB,CAAC;IACvC,IAAI,GAAG,CAAC,UAAU,CAAC,aAAa,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,eAAe,CAAC,EAAE,CAAC;QACrE,IAAI,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC;YAAE,OAAO,eAAe,CAAC;QACtD,IAAI,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC;YAAE,OAAO,mBAAmB,CAAC;QACzD,OAAO,UAAU,CAAC;IACpB,CAAC;IACD,IAAI,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC;QAAE,OAAO,qBAAqB,CAAC;IAC1D,IAAI,GAAG,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,GAAG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yD,kBAAkB,EAAE;MACvE,kBAAkB;;;uBAGD,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuChD,UAAU;QACR,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuVN;EAEE,UAAU;QACR,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;IAwBF;QACA,CAAC,CAAC,EACN;EACE,eAAe;;;QAGT,CAAC;AACT,CAAC;AAED,kDAAkD;AAClD,MAAM,CAAC,MAAM,eAAe,GAAG,iBAAiB,EAAE,CAAC;AAEnD;;;;GAIG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAsGD,CAAC;AACT,CAAC","sourcesContent":["/**\n * First-run onboarding page for agent-native apps.\n *\n * Shown when Better Auth is active and the user isn't signed in.\n * Provides a path to create or sign into an account from day one.\n *\n * After first account exists, this page acts as a normal login page.\n */\n\nfunction hasGoogleOAuth(): boolean {\n return !!(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET);\n}\n\nfunction getConnectionLabel(): string {\n const url = process.env.DATABASE_URL || \"\";\n if (!url) return \"SQLite (local file)\";\n if (url.startsWith(\"postgres://\") || url.startsWith(\"postgresql://\")) {\n if (url.includes(\"neon.tech\")) return \"Neon Postgres\";\n if (url.includes(\"supabase\")) return \"Supabase Postgres\";\n return \"Postgres\";\n }\n if (url.startsWith(\"file:\")) return \"SQLite (local file)\";\n if (url.startsWith(\"libsql://\") || url.includes(\"turso.io\")) return \"Turso\";\n return \"SQL database\";\n}\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 withAppBasePath(path: string): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n const basePath = normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n return `${basePath}${cleanPath}`;\n}\n\nexport interface OnboardingHtmlOptions {\n /**\n * Hide email/password forms and show ONLY the Google sign-in button.\n * Useful for templates (mail, calendar) where Google is required anyway.\n * If Google OAuth env vars are not configured, an error message is shown.\n */\n googleOnly?: boolean;\n /**\n * Product marketing content shown alongside the sign-in form.\n * When provided, the page uses a split layout: marketing on the left,\n * sign-in form on the right (stacked on mobile).\n */\n marketing?: {\n appName: string;\n tagline: string;\n description?: string;\n features?: string[];\n };\n}\n\nexport function getOnboardingHtml(opts: OnboardingHtmlOptions = {}): string {\n const showGoogle = hasGoogleOAuth();\n const googleOnly = !!opts.googleOnly;\n const appBasePath = normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n\n const marketing = opts.marketing;\n const hasMarketing = !!marketing;\n const brandMarkSrc = withAppBasePath(\"/agent-native-icon-dark.svg\");\n const esc = (s: string) =>\n s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n\n const marketingStyles = hasMarketing\n ? `\n body.has-marketing { padding: 0; position: relative; overflow-x: hidden; }\n #starfield {\n position: fixed;\n inset: 0;\n width: 100%;\n height: 100%;\n opacity: 0.35;\n pointer-events: none;\n z-index: 0;\n }\n .split {\n position: relative;\n z-index: 1;\n display: flex;\n min-height: 100vh;\n width: 100%;\n max-width: 1100px;\n margin: 0 auto;\n }\n .marketing-panel {\n flex: 1;\n display: flex;\n flex-direction: column;\n justify-content: center;\n padding: 3rem 3.5rem;\n }\n .marketing-content { max-width: 480px; }\n .app-name {\n display: flex;\n align-items: center;\n gap: 0.625rem;\n font-size: 2rem;\n font-weight: 700;\n color: #fff;\n margin-bottom: 0.625rem;\n letter-spacing: -0.02em;\n }\n .app-name img.brand-mark {\n height: 2.21375rem;\n width: auto;\n display: block;\n flex-shrink: 0;\n }\n .app-tagline {\n font-size: 1.25rem;\n color: #a1a1aa;\n line-height: 1.6;\n margin-bottom: 2rem;\n }\n .app-desc {\n font-size: 1rem;\n color: #71717a;\n line-height: 1.6;\n margin-bottom: 2rem;\n }\n .feature-list {\n list-style: none;\n display: flex;\n flex-direction: column;\n gap: 0.875rem;\n }\n .feature-list li {\n display: flex;\n align-items: flex-start;\n gap: 0.625rem;\n font-size: 1rem;\n color: #a1a1aa;\n line-height: 1.5;\n }\n .feature-list li::before {\n content: '';\n flex-shrink: 0;\n width: 8px;\n height: 8px;\n margin-top: 6px;\n border-radius: 50%;\n background: #3f3f46;\n border: 1px solid #52525b;\n }\n .oss-link {\n display: inline-flex;\n align-items: center;\n gap: 0.375rem;\n margin-top: 2rem;\n font-size: 0.8125rem;\n color: #71717a;\n text-decoration: none;\n }\n .oss-link:hover { color: #a1a1aa; }\n .oss-link svg { width: 15px; height: 15px; flex-shrink: 0; }\n .form-panel {\n flex: 0 0 440px;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 2rem;\n }\n .form-panel .card { max-width: 400px; }\n .form-panel .local-note { max-width: 400px; }\n @media (max-width: 900px) {\n .split { flex-direction: column; min-height: auto; }\n .marketing-panel { padding: 2rem 1.5rem 1.5rem; }\n .app-name { font-size: 1.375rem; }\n .app-name img.brand-mark { height: 1.58125rem; }\n .app-tagline { font-size: 1rem; margin-bottom: 1rem; }\n .app-desc { margin-bottom: 1rem; }\n .feature-list { gap: 0.5rem; }\n .form-panel { flex: none; padding: 1.5rem 1rem; }\n }\n`\n : \"\";\n\n const marketingPanelHtml = hasMarketing\n ? `<canvas id=\"starfield\"></canvas>\n<div class=\"split\">\n <div class=\"marketing-panel\">\n <div class=\"marketing-content\">\n <h2 class=\"app-name\">\n <img class=\"brand-mark\" src=\"${esc(brandMarkSrc)}\" alt=\"\" aria-hidden=\"true\" />\n <span>${esc(marketing!.appName)}</span>\n </h2>\n <p class=\"app-tagline\">${esc(marketing!.tagline)}</p>\n${marketing!.description ? ` <p class=\"app-desc\">${esc(marketing!.description)}</p>\\n` : \"\"}${\n marketing!.features?.length\n ? ` <ul class=\"feature-list\">\\n${marketing!.features.map((f) => ` <li>${esc(f)}</li>`).join(\"\\n\")}\\n </ul>\\n`\n : \"\"\n } <a class=\"oss-link\" href=\"https://github.com/BuilderIO/agent-native\" target=\"_blank\" rel=\"noreferrer\">\n <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 19c-4.3 1.4-4.3-2.5-6-3m12 5v-3.5c0-1 .1-1.4-.5-2 2.8-.3 5.5-1.4 5.5-6a4.6 4.6 0 00-1.3-3.2 4.2 4.2 0 00-.1-3.2s-1.1-.3-3.5 1.3a12.3 12.3 0 00-6.2 0C6.5 2.8 5.4 3.1 5.4 3.1a4.2 4.2 0 00-.1 3.2A4.6 4.6 0 004 9.5c0 4.6 2.7 5.7 5.5 6-.6.6-.6 1.2-.5 2V21\"/></svg>\n Open source\n </a>\n </div>\n </div>\n <div class=\"form-panel\">`\n : \"\";\n\n const marketingCloseHtml = hasMarketing ? `\\n </div>\\n</div>` : \"\";\n\n const starfieldScript = hasMarketing\n ? `\n (function initStarfield() {\n var canvas = document.getElementById('starfield');\n if (!canvas) return;\n var gl = canvas.getContext('webgl', { alpha: false, antialias: false });\n if (!gl) return;\n\n var vs = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vs, 'attribute vec2 position;void main(){gl_Position=vec4(position,0.0,1.0);}');\n gl.compileShader(vs);\n\n var fs = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fs, [\n 'precision highp float;',\n 'uniform float iTime;uniform vec2 iResolution;',\n '#define S(a,b,t) smoothstep(a,b,t)',\n '#define NUM_LAYERS 4.',\n 'float N21(vec2 p){vec3 a=fract(vec3(p.xyx)*vec3(213.897,653.453,253.098));a+=dot(a,a.yzx+79.76);return fract((a.x+a.y)*a.z);}',\n 'vec2 GetPos(vec2 id,vec2 offs,float t){float n=N21(id+offs);float n1=fract(n*10.);float n2=fract(n*100.);float a=t+n;return offs+vec2(sin(a*n1),cos(a*n2))*.4;}',\n 'float df_line(vec2 a,vec2 b,vec2 p){vec2 pa=p-a,ba=b-a;float h=clamp(dot(pa,ba)/dot(ba,ba),0.,1.);return length(pa-ba*h);}',\n 'float line(vec2 a,vec2 b,vec2 uv){float r1=.025;float r2=.006;float d=df_line(a,b,uv);float d2=length(a-b);float fade=S(1.5,.5,d2);fade+=S(.05,.02,abs(d2-.75));return S(r1,r2,d)*fade;}',\n 'float NetLayer(vec2 st,float n,float t){',\n ' vec2 id=floor(st)+n;st=fract(st)-.5;',\n ' vec2 p0=GetPos(id,vec2(-1,-1),t);vec2 p1=GetPos(id,vec2(0,-1),t);vec2 p2=GetPos(id,vec2(1,-1),t);',\n ' vec2 p3=GetPos(id,vec2(-1,0),t);vec2 p4=GetPos(id,vec2(0,0),t);vec2 p5=GetPos(id,vec2(1,0),t);',\n ' vec2 p6=GetPos(id,vec2(-1,1),t);vec2 p7=GetPos(id,vec2(0,1),t);vec2 p8=GetPos(id,vec2(1,1),t);',\n ' float m=0.;float sparkle=0.;float d;float s;float pulse;',\n ' m+=line(p4,p0,st);d=length(st-p0);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p0.x)+fract(p0.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p1,st);d=length(st-p1);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p1.x)+fract(p1.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p2,st);d=length(st-p2);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p2.x)+fract(p2.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p3,st);d=length(st-p3);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p3.x)+fract(p3.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p4,st);d=length(st-p4);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p4.x)+fract(p4.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p5,st);d=length(st-p5);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p5.x)+fract(p5.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p6,st);d=length(st-p6);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p6.x)+fract(p6.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p7,st);d=length(st-p7);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p7.x)+fract(p7.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p4,p8,st);d=length(st-p8);s=(.005/(d*d));s*=S(1.,.7,d);pulse=sin((fract(p8.x)+fract(p8.y)+t)*5.)*.4+.6;pulse=pow(pulse,20.);sparkle+=s*pulse;',\n ' m+=line(p1,p3,st);m+=line(p1,p5,st);m+=line(p7,p5,st);m+=line(p7,p3,st);',\n ' float sPhase=(sin(t+n)+sin(t*.1))*.25+.5;sPhase+=pow(sin(t*.1)*.5+.5,50.)*5.;m+=sparkle*sPhase;',\n ' return m;',\n '}',\n 'void mainImage(out vec4 fragColor,in vec2 fragCoord){',\n ' vec2 uv=(fragCoord-iResolution.xy*.5)/iResolution.y;',\n ' float t=iTime*.03;float s=sin(t);float c=cos(t);mat2 rot=mat2(c,-s,s,c);vec2 st=uv*rot;',\n ' float m=0.;',\n ' for(float i=0.;i<1.;i+=1./NUM_LAYERS){float z=fract(t+i);float size=mix(15.,1.,z);float fade=S(0.,.6,z)*S(1.,.8,z);m+=fade*NetLayer(st*size,i,iTime*0.3);}',\n ' vec3 col=vec3(0.35)*m;col*=1.-dot(uv,uv);',\n ' float tt=min(iTime,5.0);col*=S(0.,20.,tt);',\n ' col=clamp(col,0.,1.);fragColor=vec4(col,1.);',\n '}',\n 'void main(){mainImage(gl_FragColor,gl_FragCoord.xy);}'\n ].join('\\\\n'));\n gl.compileShader(fs);\n\n var prog = gl.createProgram();\n gl.attachShader(prog, vs);\n gl.attachShader(prog, fs);\n gl.linkProgram(prog);\n gl.useProgram(prog);\n\n var buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]), gl.STATIC_DRAW);\n var pos = gl.getAttribLocation(prog, 'position');\n gl.enableVertexAttribArray(pos);\n gl.vertexAttribPointer(pos, 2, gl.FLOAT, false, 0, 0);\n\n var uTime = gl.getUniformLocation(prog, 'iTime');\n var uRes = gl.getUniformLocation(prog, 'iResolution');\n\n function resize() {\n var w = window.innerWidth, h = window.innerHeight;\n var dpr = Math.min(window.devicePixelRatio, 1.5);\n canvas.width = w * dpr; canvas.height = h * dpr;\n gl.viewport(0, 0, canvas.width, canvas.height);\n }\n resize();\n window.addEventListener('resize', resize);\n\n var start = performance.now(), last = 0;\n function render(now) {\n requestAnimationFrame(render);\n if (now - last < 33) return;\n last = now;\n gl.uniform1f(uTime, (now - start) * 0.001);\n gl.uniform2f(uRes, canvas.width, canvas.height);\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n }\n requestAnimationFrame(render);\n })();`\n : \"\";\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\">\n<title>${hasMarketing ? esc(marketing!.appName) + \" — Sign in\" : \"Welcome\"}</title>\n${\n hasMarketing\n ? `<meta name=\"description\" content=\"${esc(marketing!.tagline)}\">\n<meta property=\"og:title\" content=\"${esc(marketing!.appName)}\">\n<meta property=\"og:description\" content=\"${esc(marketing!.tagline)}\">`\n : \"\"\n}\n<style>\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n background: #0a0a0a;\n color: #e5e5e5;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n padding: 1rem;\n }\n .card {\n width: 100%;\n max-width: 400px;\n padding: 2rem;\n background: #141414;\n border: 1px solid rgba(255,255,255,0.08);\n border-radius: 12px;\n }\n h1 { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.25rem; color: #fff; }\n .subtitle { font-size: 0.8125rem; color: #888; margin-bottom: 1.5rem; }\n .tabs {\n display: inline-flex;\n width: 100%;\n padding: 4px;\n margin-bottom: 1.5rem;\n background: rgba(255,255,255,0.06);\n border-radius: 8px;\n }\n .tab {\n flex: 1;\n padding: 0.5rem 0.75rem;\n background: none;\n border: none;\n color: #888;\n font-size: 0.8125rem;\n font-weight: 500;\n cursor: pointer;\n border-radius: 6px;\n }\n .tab.active {\n background: #1e1e1e;\n color: #fff;\n box-shadow: 0 1px 2px rgba(0,0,0,0.3);\n }\n .tab:hover:not(.active) { color: #bbb; }\n .form { display: none; }\n .form.active { display: block; }\n .card.verifying .tabs,\n .card.verifying #google-btn,\n .card.verifying #google-err,\n .card.verifying #auth-divider,\n .card.verifying #upgrade-note {\n display: none;\n }\n label { display: block; font-size: 0.8125rem; color: #888; margin-bottom: 0.375rem; }\n input {\n width: 100%;\n padding: 0.5rem 0.75rem;\n background: transparent;\n border: 1px solid rgba(255,255,255,0.12);\n border-radius: 6px;\n color: #e5e5e5;\n font-size: 0.875rem;\n outline: none;\n margin-bottom: 0.875rem;\n }\n input:focus { border-color: rgba(255,255,255,0.3); box-shadow: 0 0 0 1px rgba(255,255,255,0.1); }\n input::placeholder { color: #555; }\n button[type=\"submit\"], .btn-primary {\n width: 100%;\n margin-top: 0.25rem;\n padding: 0.5rem;\n background: #fff;\n color: #000;\n border: none;\n border-radius: 6px;\n font-size: 0.875rem;\n font-weight: 500;\n cursor: pointer;\n }\n button[type=\"submit\"]:hover, .btn-primary:hover { background: #e5e5e5; }\n button[type=\"submit\"]:disabled { opacity: 0.5; cursor: not-allowed; }\n .btn-secondary {\n width: 100%;\n margin-top: 0.75rem;\n padding: 0.5rem;\n background: transparent;\n color: #888;\n border: 1px solid rgba(255,255,255,0.1);\n border-radius: 6px;\n font-size: 0.8125rem;\n cursor: pointer;\n }\n .btn-secondary:hover { color: #bbb; border-color: rgba(255,255,255,0.2); }\n .msg { margin-top: 0.75rem; font-size: 0.8125rem; display: none; }\n .msg.error { color: #f87171; }\n .msg.success { color: #4ade80; }\n .msg.show { display: block; }\n .step-progress {\n display: grid;\n grid-template-columns: repeat(3, minmax(0, 1fr));\n gap: 0.5rem;\n margin-bottom: 1.25rem;\n }\n .progress-step {\n position: relative;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 0.375rem;\n color: #666;\n font-size: 0.6875rem;\n line-height: 1.2;\n text-align: center;\n }\n .progress-step::before {\n content: '';\n position: absolute;\n top: 11px;\n left: calc(-50% + 16px);\n width: calc(100% - 32px);\n height: 1px;\n background: rgba(255,255,255,0.1);\n }\n .progress-step:first-child::before { display: none; }\n .progress-step span {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 22px;\n height: 22px;\n border-radius: 999px;\n border: 1px solid rgba(255,255,255,0.14);\n background: #151515;\n color: #777;\n font-size: 0.6875rem;\n font-weight: 600;\n }\n .progress-step strong { font-weight: 500; }\n .progress-step.complete,\n .progress-step.current { color: #e5e5e5; }\n .progress-step.complete span {\n background: #d9f99d;\n border-color: #d9f99d;\n color: #111;\n }\n .progress-step.current span {\n background: #fff;\n border-color: #fff;\n color: #000;\n box-shadow: 0 0 0 4px rgba(255,255,255,0.08);\n }\n .verification-panel {\n padding: 1rem;\n margin-bottom: 0.875rem;\n background: rgba(255,255,255,0.04);\n border: 1px solid rgba(255,255,255,0.08);\n border-radius: 8px;\n }\n .verification-kicker {\n margin-bottom: 0.5rem;\n color: #bef264;\n font-size: 0.75rem;\n font-weight: 500;\n }\n .verification-copy {\n color: #d4d4d8;\n font-size: 0.875rem;\n line-height: 1.55;\n }\n .verification-copy strong {\n color: #fff;\n font-weight: 600;\n word-break: break-word;\n }\n .verification-note {\n margin-top: 0.75rem;\n color: #71717a;\n font-size: 0.75rem;\n line-height: 1.45;\n }\n .inline-actions {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 0.75rem;\n margin-top: 0.75rem;\n }\n .link-button {\n padding: 0.25rem 0;\n background: none;\n border: none;\n color: #888;\n cursor: pointer;\n font-size: 0.75rem;\n text-decoration: underline;\n text-underline-offset: 2px;\n }\n .link-button:hover { color: #bbb; }\n .link-button:disabled { cursor: wait; opacity: 0.5; }\n .divider {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n margin: 1.25rem 0;\n font-size: 0.75rem;\n color: #555;\n }\n .divider::before, .divider::after {\n content: '';\n flex: 1;\n height: 1px;\n background: rgba(255,255,255,0.08);\n }\n .upgrade-note {\n margin-bottom: 1rem;\n padding: 0.75rem;\n border: 1px solid rgba(255,255,255,0.08);\n border-radius: 8px;\n background: rgba(255,255,255,0.03);\n font-size: 0.75rem;\n line-height: 1.5;\n color: #a1a1aa;\n display: none;\n }\n .upgrade-note.show { display: block; }\n .btn-google {\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 0.625rem;\n padding: 0.5rem;\n background: #fff;\n color: #000;\n border: none;\n border-radius: 6px;\n font-size: 0.875rem;\n font-weight: 500;\n cursor: pointer;\n }\n .btn-google:hover { background: #e5e5e5; }\n .btn-google:disabled { opacity: 0.5; cursor: wait; }\n .btn-google svg { width: 18px; height: 18px; flex-shrink: 0; }\n .google-error { margin-top: 0.5rem; font-size: 0.8125rem; color: #f87171; display: none; }\n .google-error.show { display: block; }\n .local-note {\n display: none;\n max-width: 400px;\n width: 100%;\n margin-top: 1rem;\n padding: 0.625rem 0.875rem;\n font-size: 0.6875rem;\n line-height: 1.5;\n color: #666;\n border: 1px dashed rgba(255,255,255,0.08);\n border-radius: 8px;\n text-align: center;\n }\n .local-note.show { display: block; }\n .local-note strong { color: #999; font-weight: 500; }\n .local-note a { color: #888; text-decoration: none; }\n .local-note a:hover { color: #bbb; }\n${marketingStyles}\n</style>\n</head>\n<body${hasMarketing ? ' class=\"has-marketing\"' : \"\"}>\n${marketingPanelHtml}\n<div class=\"card\">\n <h1 id=\"heading\">${googleOnly ? \"Sign in\" : \"Welcome\"}</h1>\n <p class=\"subtitle\" id=\"subtitle\">${googleOnly ? \"Use your workspace Google account to continue\" : \"Create an account to get started\"}</p>\n <p\n class=\"upgrade-note\"\n id=\"upgrade-note\"\n data-upgrade-copy=\"Continue signing in to attach this app to your account and migrate local data.\"\n ></p>\n\n${\n showGoogle\n ? `\n <button class=\"btn-google\" id=\"google-btn\" onclick=\"signInWithGoogle()\">\n <svg viewBox=\"0 0 24 24\"><path fill=\"#4285F4\" d=\"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z\"/><path fill=\"#34A853\" d=\"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z\"/><path fill=\"#FBBC05\" d=\"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z\"/><path fill=\"#EA4335\" d=\"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z\"/></svg>\n Sign in with Google\n </button>\n <p class=\"google-error\" id=\"google-err\"></p>\n${googleOnly ? \"\" : `\\n <div class=\"divider\" id=\"auth-divider\">or</div>\\n`}\n`\n : googleOnly\n ? `\n <p style=\"color:#f87171;font-size:0.875rem;text-align:center;padding:1rem 0\">\n Google sign-in is not configured. Set <code>GOOGLE_CLIENT_ID</code> and\n <code>GOOGLE_CLIENT_SECRET</code> environment variables to enable login.\n </p>\n`\n : \"\"\n}\n${\n googleOnly\n ? \"\"\n : ` <div class=\"tabs\">\n <button class=\"tab\" data-tab=\"signup\">Create account</button>\n <button class=\"tab\" data-tab=\"login\">Sign in</button>\n </div>\n\n <form id=\"signup-form\" class=\"form\">\n <label for=\"s-email\">Email</label>\n <input id=\"s-email\" type=\"email\" autocomplete=\"email\" autofocus placeholder=\"you@example.com\" required />\n <label for=\"s-pass\">Password</label>\n <input id=\"s-pass\" type=\"password\" autocomplete=\"new-password\" placeholder=\"At least 8 characters\" required minlength=\"8\" />\n <label for=\"s-pass2\">Confirm password</label>\n <input id=\"s-pass2\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Confirm password\" required minlength=\"8\" />\n <button type=\"submit\">Create account</button>\n <p class=\"msg\" id=\"s-msg\"></p>\n </form>\n\n <div id=\"verification-step\" class=\"form verification-step\" aria-live=\"polite\">\n <div class=\"step-progress\" aria-label=\"Signup progress\">\n <div class=\"progress-step complete\"><span>1</span><strong>Account</strong></div>\n <div class=\"progress-step current\"><span>2</span><strong>Verify</strong></div>\n <div class=\"progress-step\"><span>3</span><strong>Start</strong></div>\n </div>\n <div class=\"verification-panel\">\n <p class=\"verification-kicker\">Verification email sent</p>\n <p class=\"verification-copy\">We sent a secure link to <strong id=\"verify-email\"></strong>. When you click it, this app will finish signing you in automatically.</p>\n <p class=\"verification-note\">You can keep this tab open. After verifying, use Continue if the app has not refreshed yet.</p>\n </div>\n <button type=\"button\" class=\"btn-primary\" id=\"verify-continue\">Continue</button>\n <div class=\"inline-actions\">\n <button type=\"button\" class=\"link-button\" id=\"resend-verification\">Resend email</button>\n <button type=\"button\" class=\"link-button\" id=\"back-to-signup\">Back</button>\n </div>\n <p class=\"msg\" id=\"verify-msg\"></p>\n </div>\n\n <form id=\"login-form\" class=\"form\">\n <label for=\"l-email\">Email</label>\n <input id=\"l-email\" type=\"email\" autocomplete=\"email\" placeholder=\"you@example.com\" required />\n <label for=\"l-pass\">Password</label>\n <input id=\"l-pass\" type=\"password\" autocomplete=\"current-password\" placeholder=\"Enter password\" required />\n <button type=\"submit\">Sign in</button>\n <p class=\"msg error\" id=\"l-msg\"></p>\n <p style=\"margin-top:0.75rem;font-size:0.75rem;text-align:right\">\n <a href=\"#\" id=\"forgot-link\" style=\"color:#888;text-decoration:underline;text-underline-offset:2px\">Forgot password?</a>\n </p>\n </form>\n\n <form id=\"forgot-form\" class=\"form\">\n <label for=\"f-email\">Email</label>\n <input id=\"f-email\" type=\"email\" autocomplete=\"email\" placeholder=\"you@example.com\" required />\n <button type=\"submit\">Send reset link</button>\n <p class=\"msg\" id=\"f-msg\"></p>\n <p style=\"margin-top:0.75rem;font-size:0.75rem;text-align:center\">\n <a href=\"#\" id=\"back-to-login\" style=\"color:#888;text-decoration:underline;text-underline-offset:2px\">Back to sign in</a>\n </p>\n </form>`\n}\n</div>\n<p class=\"local-note\" id=\"local-note\">\n Your account is stored in this app's own DB (<strong>${getConnectionLabel()}</strong>), not a third-party service.\n</p>${marketingCloseHtml}\n<script>\n function __anBasePath() {\n var configured = ${JSON.stringify(appBasePath)};\n if (configured) return configured;\n var marker = '/_agent-native';\n var idx = window.location.pathname.indexOf(marker);\n return idx > 0 ? window.location.pathname.slice(0, idx) : '';\n }\n function __anPath(path) {\n return __anBasePath() + path;\n }\n function __anGetReturnPath() {\n try {\n var inner = new URLSearchParams(window.location.search).get('return');\n if (inner) return inner;\n } catch(e) {}\n return window.location.pathname + window.location.search;\n }\n (function revealLocalNote() {\n var h = location.hostname;\n if (h === 'localhost' || h === '127.0.0.1' || h === '::1' || h.endsWith('.local')) {\n var n = document.getElementById('local-note');\n if (n) n.classList.add('show');\n }\n })();\n (function revealUpgradeNote() {\n var shouldShow = false;\n try {\n var params = new URLSearchParams(location.search);\n shouldShow = params.get('signin') === '1' || params.get('upgrade-from-local') === '1';\n } catch(e) {}\n if (!shouldShow) {\n try { shouldShow = localStorage.getItem('an_migrate_from_local') === '1'; } catch(e) {}\n }\n if (!shouldShow) return;\n var n = document.getElementById('upgrade-note');\n if (!n) return;\n n.textContent = n.getAttribute('data-upgrade-copy') || 'Continue signing in to migrate local data.';\n n.classList.add('show');\n })();\n${\n googleOnly\n ? \"\"\n : ` var TAB_STORAGE_KEY = 'an.onboarding.tab';\n var tabs = document.querySelectorAll('.tab');\n var forms = document.querySelectorAll('.form');\n var subtitles = { signup: 'Create an account to get started', login: 'Sign in to your account' };\n var headings = { signup: 'Welcome', login: 'Welcome back' };\n var pendingSignupEmail = '';\n function setActiveTab(name, opts) {\n if (name !== 'signup' && name !== 'login') return;\n var form = document.getElementById(name + '-form');\n if (!form) return;\n var card = document.querySelector('.card');\n if (card) card.classList.remove('verifying');\n tabs.forEach(function(x) { x.classList.remove('active'); });\n forms.forEach(function(x) { x.classList.remove('active'); });\n var btn = document.querySelector('.tab[data-tab=\"' + name + '\"]');\n if (btn) btn.classList.add('active');\n form.classList.add('active');\n var sub = document.getElementById('subtitle');\n if (sub && subtitles[name]) sub.textContent = subtitles[name];\n var heading = document.getElementById('heading');\n if (heading && headings[name]) heading.textContent = headings[name];\n if (opts && opts.persist) {\n try { localStorage.setItem(TAB_STORAGE_KEY, name); } catch (e) {}\n }\n }\n function showVerificationStep(email) {\n pendingSignupEmail = email || '';\n tabs.forEach(function(x) { x.classList.remove('active'); });\n forms.forEach(function(x) { x.classList.remove('active'); });\n var card = document.querySelector('.card');\n if (card) card.classList.add('verifying');\n var step = document.getElementById('verification-step');\n if (step) step.classList.add('active');\n var emailNode = document.getElementById('verify-email');\n if (emailNode) emailNode.textContent = pendingSignupEmail;\n var heading = document.getElementById('heading');\n if (heading) heading.textContent = 'Check your email';\n var sub = document.getElementById('subtitle');\n if (sub) sub.textContent = 'Finish creating your account';\n var msg = document.getElementById('verify-msg');\n if (msg) {\n msg.classList.remove('show', 'error', 'success');\n msg.textContent = '';\n }\n try { localStorage.setItem(TAB_STORAGE_KEY, 'signup'); } catch (e) {}\n }\n function getVerificationMessageNode() {\n var verifyStep = document.getElementById('verification-step');\n if (verifyStep && verifyStep.classList.contains('active')) {\n return document.getElementById('verify-msg');\n }\n return document.getElementById('l-msg') || document.getElementById('verify-msg');\n }\n async function checkVerificationSession(fallbackText) {\n var msg = getVerificationMessageNode();\n if (msg) {\n msg.textContent = 'Checking your verification...';\n msg.classList.remove('error');\n msg.classList.add('show', 'success');\n }\n try {\n var res = await fetch(__anPath('/_agent-native/auth/session'), {\n headers: { 'Accept': 'application/json' },\n });\n var data = await res.json().catch(function() { return {}; });\n if (res.ok && data && data.email && !data.error) {\n window.location.reload();\n return;\n }\n if (msg) {\n msg.textContent = fallbackText || 'Still waiting on verification. Click the link in your email, then try Continue again.';\n msg.classList.remove('success');\n msg.classList.add('show', 'error');\n }\n } catch (err) {\n if (msg) {\n msg.textContent = 'Could not check verification. Please try again.';\n msg.classList.remove('success');\n msg.classList.add('show', 'error');\n }\n }\n }\n async function resendVerificationEmail() {\n var btn = document.getElementById('resend-verification');\n var msg = document.getElementById('verify-msg');\n var email = pendingSignupEmail || document.getElementById('s-email').value;\n if (!email) return;\n var original = btn ? btn.textContent : '';\n if (btn) {\n btn.disabled = true;\n btn.textContent = 'Sending...';\n }\n if (msg) msg.classList.remove('show', 'error', 'success');\n try {\n var res = await fetch(__anPath('/_agent-native/auth/ba/send-verification-email'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: email, callbackURL: __anGetReturnPath() }),\n });\n if (res.ok) {\n if (msg) {\n msg.textContent = 'Sent a fresh verification link.';\n msg.classList.add('show', 'success');\n }\n if (btn) btn.textContent = 'Sent';\n setTimeout(function() {\n if (btn) {\n btn.disabled = false;\n btn.textContent = original;\n }\n }, 1600);\n return;\n }\n var data = await res.json().catch(function() { return {}; });\n if (msg) {\n msg.textContent = (data && (data.message || data.error)) || 'Could not resend the verification email.';\n msg.classList.add('show', 'error');\n }\n if (btn) {\n btn.disabled = false;\n btn.textContent = original;\n }\n } catch (err) {\n if (msg) {\n msg.textContent = 'Network error. Please try again.';\n msg.classList.add('show', 'error');\n }\n if (btn) {\n btn.disabled = false;\n btn.textContent = original;\n }\n }\n }\n (function initActiveTab() {\n var initial = 'signup';\n try {\n var params = new URLSearchParams(location.search);\n var qp = params.get('tab');\n var path = location.pathname;\n while (path.length > 1 && path.charAt(path.length - 1) === '/') path = path.slice(0, -1);\n if (qp === 'login' || qp === 'signup') {\n initial = qp;\n } else if (params.has('verified')) {\n initial = 'login';\n } else if (path === '/login' || path.endsWith('/login')) {\n initial = 'login';\n } else if (path === '/signup' || path.endsWith('/signup')) {\n initial = 'signup';\n } else {\n var stored = localStorage.getItem(TAB_STORAGE_KEY);\n if (stored === 'login' || stored === 'signup') initial = stored;\n }\n } catch (e) {}\n setActiveTab(initial, { persist: false });\n try {\n if (new URLSearchParams(location.search).has('verified')) {\n var msg = document.getElementById('l-msg');\n if (msg) {\n msg.textContent = 'Email verified. Finishing sign-in...';\n msg.classList.remove('error');\n msg.classList.add('show', 'success');\n }\n checkVerificationSession('Email verified. Sign in to continue.');\n }\n } catch (e) {}\n })();\n tabs.forEach(function(t) { t.addEventListener('click', function() {\n setActiveTab(t.dataset.tab, { persist: true });\n }); });\n\n document.getElementById('signup-form').addEventListener('submit', async function(e) {\n e.preventDefault();\n var form = e.currentTarget;\n var btn = form.querySelector('button[type=\"submit\"]');\n var msg = document.getElementById('s-msg');\n msg.classList.remove('show', 'error', 'success');\n var pass = document.getElementById('s-pass').value;\n var pass2 = document.getElementById('s-pass2').value;\n if (pass !== pass2) {\n msg.textContent = 'Passwords do not match';\n msg.classList.add('show', 'error');\n return;\n }\n var originalLabel = btn.textContent;\n btn.disabled = true;\n btn.textContent = 'Creating account…';\n try {\n var email = document.getElementById('s-email').value;\n var res = await fetch(__anPath('/_agent-native/auth/register'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n email: email,\n password: pass,\n callbackURL: __anGetReturnPath(),\n }),\n });\n var data = await res.json().catch(function() { return {}; });\n if (res.ok) {\n // If email verification is required, the server won't return a session.\n // Try logging in — if it fails (unverified), show a \"check your email\" message.\n var loginRes = await fetch(__anPath('/_agent-native/auth/login'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: email, password: pass }),\n });\n if (loginRes.ok) {\n msg.textContent = 'Account created — signing you in…';\n msg.classList.add('show', 'success');\n window.location.reload();\n return;\n }\n btn.disabled = false;\n btn.textContent = originalLabel;\n showVerificationStep(email);\n return;\n }\n msg.textContent = data.error || 'Registration failed';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = originalLabel;\n } catch (err) {\n msg.textContent = 'Network error — please try again';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = originalLabel;\n }\n });\n\n var verifyContinue = document.getElementById('verify-continue');\n if (verifyContinue) verifyContinue.addEventListener('click', function(e) {\n e.preventDefault();\n checkVerificationSession();\n });\n var resendBtn = document.getElementById('resend-verification');\n if (resendBtn) resendBtn.addEventListener('click', function(e) {\n e.preventDefault();\n resendVerificationEmail();\n });\n var backToSignup = document.getElementById('back-to-signup');\n if (backToSignup) backToSignup.addEventListener('click', function(e) {\n e.preventDefault();\n setActiveTab('signup', { persist: true });\n var email = document.getElementById('s-email');\n setTimeout(function() { if (email) email.focus(); }, 0);\n });\n\n var forgotLink = document.getElementById('forgot-link');\n var backToLogin = document.getElementById('back-to-login');\n if (forgotLink) forgotLink.addEventListener('click', function(e) {\n e.preventDefault();\n document.getElementById('login-form').classList.remove('active');\n document.getElementById('forgot-form').classList.add('active');\n var sub = document.getElementById('subtitle');\n if (sub) sub.textContent = 'Reset your password';\n var heading = document.getElementById('heading');\n if (heading) heading.textContent = 'Reset password';\n var fEmail = document.getElementById('f-email');\n var lEmail = document.getElementById('l-email');\n if (lEmail && lEmail.value) fEmail.value = lEmail.value;\n setTimeout(function() { fEmail.focus(); }, 0);\n });\n if (backToLogin) backToLogin.addEventListener('click', function(e) {\n e.preventDefault();\n document.getElementById('forgot-form').classList.remove('active');\n document.getElementById('login-form').classList.add('active');\n var sub = document.getElementById('subtitle');\n if (sub) sub.textContent = subtitles.login;\n var heading = document.getElementById('heading');\n if (heading) heading.textContent = headings.login;\n });\n\n var forgotForm = document.getElementById('forgot-form');\n if (forgotForm) forgotForm.addEventListener('submit', async function(e) {\n e.preventDefault();\n var btn = e.currentTarget.querySelector('button[type=\"submit\"]');\n var msg = document.getElementById('f-msg');\n msg.classList.remove('show', 'error', 'success');\n var original = btn.textContent;\n btn.disabled = true;\n btn.textContent = 'Sending…';\n try {\n var email = document.getElementById('f-email').value;\n var res = await fetch(__anPath('/_agent-native/auth/ba/request-password-reset'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: email }),\n });\n if (res.ok) {\n msg.textContent = 'If that email exists, a reset link is on its way.';\n msg.classList.add('show', 'success');\n btn.textContent = 'Sent';\n return;\n }\n var data = await res.json().catch(function() { return {}; });\n msg.textContent = (data && (data.message || data.error)) || 'Could not send reset email.';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = original;\n } catch (err) {\n msg.textContent = 'Network error — please try again';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = original;\n }\n });\n\n document.getElementById('login-form').addEventListener('submit', async function(e) {\n e.preventDefault();\n var form = e.currentTarget;\n var btn = form.querySelector('button[type=\"submit\"]');\n var msg = document.getElementById('l-msg');\n msg.classList.remove('show', 'success');\n msg.classList.add('error');\n var originalLabel = btn.textContent;\n btn.disabled = true;\n btn.textContent = 'Signing in…';\n try {\n var res = await fetch(__anPath('/_agent-native/auth/login'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n email: document.getElementById('l-email').value,\n password: document.getElementById('l-pass').value,\n }),\n });\n if (res.ok) {\n window.location.reload();\n return;\n }\n var data = await res.json().catch(function() { return {}; });\n msg.textContent = data.error || 'Invalid email or password';\n msg.classList.add('show');\n btn.disabled = false;\n btn.textContent = originalLabel;\n } catch (err) {\n msg.textContent = 'Network error — please try again';\n msg.classList.add('show');\n btn.disabled = false;\n btn.textContent = originalLabel;\n }\n });\n`\n}\n${\n showGoogle\n ? `\n async function signInWithGoogle() {\n var btn = document.getElementById('google-btn');\n var err = document.getElementById('google-err');\n btn.disabled = true;\n err.classList.remove('show');\n try {\n var ret = __anGetReturnPath();\n var authUrl = __anPath('/_agent-native/google/auth-url') + '?return=' + encodeURIComponent(ret);\n var res = await fetch(authUrl);\n var data = await res.json();\n if (data.url) {\n try { sessionStorage.setItem('__an_signin', '1'); } catch(e) {}\n window.location.href = data.url;\n } else {\n err.textContent = data.message || 'Google OAuth is not configured.';\n err.classList.add('show');\n btn.disabled = false;\n }\n } catch (e) {\n err.textContent = 'Failed to connect. Please try again.';\n err.classList.add('show');\n btn.disabled = false;\n }\n }`\n : \"\"\n}\n${starfieldScript}\n</script>\n</body>\n</html>`;\n}\n\n/** @deprecated Use getOnboardingHtml() instead */\nexport const ONBOARDING_HTML = getOnboardingHtml();\n\n/**\n * HTML for the password reset page — shown when the user clicks the link in\n * their reset email. Posts `{ newPassword, token }` to Better Auth's\n * `/reset-password` endpoint, then redirects to the login page.\n */\nexport function getResetPasswordHtml(): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\">\n<title>Reset password</title>\n<style>\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n body { font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; background: #0a0a0a; color: #e5e5e5; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 1rem; }\n .card { width: 100%; max-width: 400px; padding: 2rem; background: #141414; border: 1px solid rgba(255,255,255,0.08); border-radius: 12px; }\n h1 { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.25rem; color: #fff; }\n .subtitle { font-size: 0.8125rem; color: #888; margin-bottom: 1.5rem; }\n label { display: block; font-size: 0.8125rem; color: #888; margin-bottom: 0.375rem; }\n input { width: 100%; padding: 0.5rem 0.75rem; background: transparent; border: 1px solid rgba(255,255,255,0.12); border-radius: 6px; color: #e5e5e5; font-size: 0.875rem; outline: none; margin-bottom: 0.875rem; }\n input:focus { border-color: rgba(255,255,255,0.3); box-shadow: 0 0 0 1px rgba(255,255,255,0.1); }\n input::placeholder { color: #555; }\n button[type=\"submit\"] { width: 100%; margin-top: 0.25rem; padding: 0.5rem; background: #fff; color: #000; border: none; border-radius: 6px; font-size: 0.875rem; font-weight: 500; cursor: pointer; }\n button[type=\"submit\"]:hover { background: #e5e5e5; }\n button[type=\"submit\"]:disabled { opacity: 0.5; cursor: not-allowed; }\n .msg { margin-top: 0.75rem; font-size: 0.8125rem; display: none; }\n .msg.error { color: #f87171; }\n .msg.success { color: #4ade80; }\n .msg.show { display: block; }\n .back { display: inline-block; margin-top: 1rem; font-size: 0.75rem; color: #888; text-decoration: none; }\n .back:hover { color: #bbb; }\n</style>\n</head>\n<body>\n<div class=\"card\">\n <h1>Choose a new password</h1>\n <p class=\"subtitle\">Set a new password for your account.</p>\n <form id=\"reset-form\">\n <label for=\"p1\">New password</label>\n <input id=\"p1\" type=\"password\" autocomplete=\"new-password\" autofocus placeholder=\"At least 8 characters\" required minlength=\"8\" />\n <label for=\"p2\">Confirm password</label>\n <input id=\"p2\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Confirm password\" required minlength=\"8\" />\n <button type=\"submit\">Save new password</button>\n <p class=\"msg\" id=\"msg\"></p>\n </form>\n <a class=\"back\" id=\"back-link\" href=\"/\">Back to sign in</a>\n</div>\n<script>\n (function() {\n // Derive the app's base path so apps mounted under a prefix\n // (e.g. /mail, /calendar) get sent home instead of to the root domain.\n var RESET_PATH = '/_agent-native/auth/reset';\n var pathname = window.location.pathname;\n var idx = pathname.indexOf(RESET_PATH);\n var basePath = (idx >= 0 ? pathname.slice(0, idx) : '') || '';\n var homeHref = basePath + '/';\n var backLink = document.getElementById('back-link');\n if (backLink) backLink.setAttribute('href', homeHref);\n var params = new URLSearchParams(location.search);\n var token = params.get('token') || '';\n var msg = document.getElementById('msg');\n if (!token) {\n msg.textContent = 'Missing or invalid reset token. Request a new reset link.';\n msg.classList.add('show', 'error');\n document.getElementById('reset-form').style.display = 'none';\n return;\n }\n document.getElementById('reset-form').addEventListener('submit', async function(e) {\n e.preventDefault();\n var btn = e.currentTarget.querySelector('button[type=\"submit\"]');\n var p1 = document.getElementById('p1').value;\n var p2 = document.getElementById('p2').value;\n msg.classList.remove('show', 'error', 'success');\n if (p1 !== p2) {\n msg.textContent = 'Passwords do not match';\n msg.classList.add('show', 'error');\n return;\n }\n var original = btn.textContent;\n btn.disabled = true;\n btn.textContent = 'Saving…';\n try {\n var res = await fetch(basePath + '/_agent-native/auth/ba/reset-password', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ newPassword: p1, token: token }),\n });\n if (res.ok) {\n msg.textContent = 'Password updated — redirecting to sign in…';\n msg.classList.add('show', 'success');\n setTimeout(function() { window.location.href = homeHref; }, 1200);\n return;\n }\n var data = await res.json().catch(function() { return {}; });\n msg.textContent = (data && (data.message || data.error)) || 'Reset failed. The link may have expired — request a new one.';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = original;\n } catch (err) {\n msg.textContent = 'Network error — please try again';\n msg.classList.add('show', 'error');\n btn.disabled = false;\n btn.textContent = original;\n }\n });\n })();\n</script>\n</body>\n</html>`;\n}\n"]}
@@ -1,3 +1,7 @@
1
1
  // Export workspace-wide server plugin overrides here when you need them.
2
- // Anything not exported falls through to @agent-native/core defaults.
3
- export {};
2
+ // Starter apps inherit these exports, so provide explicit framework defaults
3
+ // to keep generated workspaces warning-free until a workspace customizes them.
4
+ export {
5
+ defaultAgentChatPlugin,
6
+ defaultAuthPlugin,
7
+ } from "@agent-native/core/server";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.7.65",
3
+ "version": "0.7.67",
4
4
  "type": "module",
5
5
  "description": "Framework for agent-native application development — where AI agents and UI share state via files",
6
6
  "license": "MIT",
@@ -1,3 +1,7 @@
1
1
  // Export workspace-wide server plugin overrides here when you need them.
2
- // Anything not exported falls through to @agent-native/core defaults.
3
- export {};
2
+ // Starter apps inherit these exports, so provide explicit framework defaults
3
+ // to keep generated workspaces warning-free until a workspace customizes them.
4
+ export {
5
+ defaultAgentChatPlugin,
6
+ defaultAuthPlugin,
7
+ } from "@agent-native/core/server";