@agent-native/core 0.7.66 → 0.7.68

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.
@@ -45,7 +45,8 @@ export const tool = {
45
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. " +
46
46
  "IMPORTANT — handling the response: " +
47
47
  "(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. " +
48
- '(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.',
48
+ '(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. ' +
49
+ "(c) If the downstream response reports missing credentials, never repeat raw env var names, Vault key names, token names, secret names, or other credential identifiers. Tell the user the target app needs its LLM/provider connection configured.",
49
50
  parameters: {
50
51
  type: "object",
51
52
  properties: {
@@ -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,+BAA+B,EAC/B,oBAAoB,GACrB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,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ool } 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"]}
1
+ {"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8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AI,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 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 \"(c) If the downstream response reports missing credentials, never repeat raw env var names, Vault key names, token names, secret names, or other credential identifiers. Tell the user the target app needs its LLM/provider connection configured.\",\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"]}
@@ -5,6 +5,9 @@ export interface DiscoveredAgent {
5
5
  url: string;
6
6
  color: string;
7
7
  }
8
+ export declare function shouldIncludeRemoteAgentManifest(manifest: {
9
+ id?: string | null;
10
+ }, selfAppId?: string): boolean;
8
11
  /**
9
12
  * Get built-in agents (static, no DB). Used as fallback and for seeding.
10
13
  */
@@ -1 +1 @@
1
- {"version":3,"file":"agent-discovery.d.ts","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf;AA+CD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,eAAe,EAAE,CAUtE;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,EAAE,CAAC,CA8E5B;AAED;;GAEG;AACH,wBAAsB,SAAS,CAC7B,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAItC;AAsND;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,EAAE,eAAe,EAOnD,CAAC"}
1
+ {"version":3,"file":"agent-discovery.d.ts","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf;AA+CD,wBAAgB,gCAAgC,CAC9C,QAAQ,EAAE;IAAE,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,EAChC,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAST;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,eAAe,EAAE,CAUtE;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,EAAE,CAAC,CA8E5B;AAED;;GAEG;AACH,wBAAsB,SAAS,CAC7B,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAItC;AAsND;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,EAAE,eAAe,EAOnD,CAAC"}
@@ -21,6 +21,17 @@ const BUILTIN_AGENTS = visibleTemplates()
21
21
  const HIDDEN_FIRST_PARTY_AGENT_IDS = new Set(TEMPLATES.filter((template) => template.hidden && template.prodUrl).map((template) => template.name));
22
22
  const WORKSPACE_APPS_ENV_KEY = "AGENT_NATIVE_WORKSPACE_APPS_JSON";
23
23
  const WORKSPACE_APPS_MANIFEST_FILE = "workspace-apps.json";
24
+ export function shouldIncludeRemoteAgentManifest(manifest, selfAppId) {
25
+ const id = manifest.id?.trim();
26
+ if (!id)
27
+ return false;
28
+ const normalizedId = id.toLowerCase();
29
+ const normalizedSelfAppId = selfAppId?.trim().toLowerCase();
30
+ if (normalizedSelfAppId && normalizedId === normalizedSelfAppId) {
31
+ return false;
32
+ }
33
+ return !HIDDEN_FIRST_PARTY_AGENT_IDS.has(normalizedId);
34
+ }
24
35
  /**
25
36
  * Get built-in agents (static, no DB). Used as fallback and for seeding.
26
37
  */
@@ -64,9 +75,7 @@ export async function discoverAgents(selfAppId) {
64
75
  if (!full)
65
76
  continue;
66
77
  const manifest = parseRemoteAgentManifest(full.content, r.path);
67
- if (!manifest || manifest.id === selfAppId)
68
- continue;
69
- if (HIDDEN_FIRST_PARTY_AGENT_IDS.has(manifest.id))
78
+ if (!manifest || !shouldIncludeRemoteAgentManifest(manifest, selfAppId))
70
79
  continue;
71
80
  // If the resource override carries a localhost URL but we're running
72
81
  // in production (e.g. a stale dev-time seed got promoted to the prod
@@ -1 +1 @@
1
- {"version":3,"file":"agent-discovery.js","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAoBvE;;;;GAIG;AACH,MAAM,cAAc,GAAiB,gBAAgB,EAAE;KACpD,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC;KACxC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAClB,EAAE,EAAE,QAAQ,CAAC,IAAI;IACjB,IAAI,EAAE,QAAQ,CAAC,KAAK;IACpB,WAAW,EAAE,QAAQ,CAAC,WAAW,IAAI,QAAQ,CAAC,IAAI;IAClD,GAAG,EAAE,QAAQ,CAAC,OAAQ;IACtB,MAAM,EAAE,oBAAoB,QAAQ,CAAC,OAAO,EAAE;IAC9C,OAAO,EAAE,QAAQ,CAAC,OAAO;IACzB,KAAK,EAAE,QAAQ,CAAC,KAAK;CACtB,CAAC,CAAC,CAAC;AAEN,MAAM,4BAA4B,GAAG,IAAI,GAAG,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QACjC,IAAI,CAAC,GAAG;YAAE,OAAO,IAAI,CAAC;QACtB,MAAM,OAAO,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC;QACpE,OAAO;YACL,EAAE,EAAE,GAAG,CAAC,EAAE;YACV,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,WAAW,EACT,GAAG,CAAC,WAAW;gBACf,OAAO,EAAE,WAAW;gBACpB,4BAA4B,GAAG,CAAC,IAAI,EAAE;YACxC,GAAG;YACH,KAAK,EAAE,OAAO,EAAE,KAAK,IAAI,SAAS;SACT,CAAC;IAC9B,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,KAAK,EAA4B,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AAC1D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,0BAA0B,GACrC,cAAc,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACpD,EAAE,EAAE,GAAG,CAAC,EAAE;IACV,IAAI,EAAE,GAAG,CAAC,IAAI;IACd,WAAW,EAAE,GAAG,CAAC,WAAW;IAC5B,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc;IAC5B,KAAK,EAAE,GAAG,CAAC,KAAK;CACjB,CAAC,CAAC,CAAC","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { TEMPLATES, visibleTemplates } from \"../cli/templates-meta.js\";\n\nexport interface DiscoveredAgent {\n id: string;\n name: string;\n description: string;\n url: string;\n color: string;\n}\n\ninterface AgentEntry {\n id: string;\n name: string;\n description: string;\n url: string;\n devUrl?: string;\n devPort: number;\n color: string;\n}\n\n/**\n * Built-in agent registry. Derive this from the published CLI metadata so\n * connected-agent discovery stays aligned with the public template allow-list\n * without depending on @agent-native/shared-app-config at runtime.\n */\nconst BUILTIN_AGENTS: AgentEntry[] = visibleTemplates()\n .filter((template) => !!template.prodUrl)\n .map((template) => ({\n id: template.name,\n name: template.label,\n description: template.description ?? template.hint,\n url: template.prodUrl!,\n devUrl: `http://localhost:${template.devPort}`,\n devPort: template.devPort,\n color: template.color,\n }));\n\nconst HIDDEN_FIRST_PARTY_AGENT_IDS = new Set(\n TEMPLATES.filter((template) => template.hidden && template.prodUrl).map(\n (template) => template.name,\n ),\n);\n\nconst WORKSPACE_APPS_ENV_KEY = \"AGENT_NATIVE_WORKSPACE_APPS_JSON\";\nconst WORKSPACE_APPS_MANIFEST_FILE = \"workspace-apps.json\";\n\ninterface WorkspaceAppManifestEntry {\n id: string;\n name: string;\n description: string;\n path: string;\n url?: string | null;\n isDispatch?: boolean;\n}\n\n/**\n * Get built-in agents (static, no DB). Used as fallback and for seeding.\n */\nexport function getBuiltinAgents(selfAppId?: string): DiscoveredAgent[] {\n return BUILTIN_AGENTS.filter((app) => app.id !== selfAppId && app.url).map(\n (app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: resolveAgentUrl(app),\n color: app.color,\n }),\n );\n}\n\n/**\n * Discover all agents: built-in + custom agents stored as resources.\n * Custom agents override built-in agents with the same ID.\n */\nexport async function discoverAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const builtins = getBuiltinAgents(selfAppId);\n const agentsById = new Map<string, DiscoveredAgent>();\n\n // Start with built-ins\n for (const agent of builtins) {\n agentsById.set(agent.id, agent);\n }\n\n // Overlay custom agents from resources\n try {\n const { resourceList, resourceGet, SHARED_OWNER, resourceListAccessible } =\n await import(\"../resources/store.js\");\n const { DEV_MODE_USER_EMAIL } = await import(\"./auth.js\");\n\n const isDevMode =\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\";\n\n const { parseRemoteAgentManifest, REMOTE_AGENT_RESOURCE_PREFIXES } =\n await import(\"../resources/metadata.js\");\n\n const resources: Array<{ id: string; path: string }> = [];\n for (const prefix of [...REMOTE_AGENT_RESOURCE_PREFIXES].reverse()) {\n resources.push(\n ...(isDevMode\n ? await resourceListAccessible(DEV_MODE_USER_EMAIL, prefix)\n : await resourceList(SHARED_OWNER, prefix)),\n );\n }\n\n for (const r of resources) {\n if (!r.path.endsWith(\".json\")) continue;\n try {\n const full = await resourceGet(r.id);\n if (!full) continue;\n const manifest = parseRemoteAgentManifest(full.content, r.path);\n if (!manifest || manifest.id === selfAppId) continue;\n if (HIDDEN_FIRST_PARTY_AGENT_IDS.has(manifest.id)) continue;\n\n // If the resource override carries a localhost URL but we're running\n // in production (e.g. a stale dev-time seed got promoted to the prod\n // DB), fall back to the matching built-in's prod URL instead of\n // letting the override win — otherwise outbound `call-agent` fetches\n // from a serverless function would target localhost and fail with\n // \"fetch failed\" instantly. The override still wins for non-localhost\n // URLs (the supported case for self-hosted custom agents).\n let url = manifest.url;\n if (\n !isDevMode &&\n typeof url === \"string\" &&\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0)(:|\\/|$)/.test(url)\n ) {\n const builtin = agentsById.get(manifest.id);\n if (builtin?.url) url = builtin.url;\n }\n\n agentsById.set(manifest.id, {\n id: manifest.id,\n name: manifest.name,\n description: manifest.description || \"\",\n url,\n color: manifest.color || \"#6B7280\",\n });\n } catch {\n // Skip unreadable resources\n }\n }\n } catch {\n // Resources not available — use built-ins only\n }\n\n // Overlay sibling workspace apps last so same-origin workspaces prefer the\n // app mounted in this workspace over the public template with the same id.\n for (const agent of discoverWorkspaceAgents(selfAppId)) {\n agentsById.set(agent.id, agent);\n }\n\n return Array.from(agentsById.values());\n}\n\n/**\n * Look up a single agent by ID or name (case-insensitive).\n */\nexport async function findAgent(\n idOrName: string,\n selfAppId?: string,\n): Promise<DiscoveredAgent | undefined> {\n const lower = idOrName.toLowerCase();\n const agents = await discoverAgents(selfAppId);\n return agents.find((a) => a.id === lower || a.name.toLowerCase() === lower);\n}\n\nfunction isDevEnvironment(): boolean {\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n );\n}\n\nfunction resolveAgentUrl(app: AgentEntry): string {\n if (isDevEnvironment()) {\n return app.devUrl || `http://localhost:${app.devPort}`;\n }\n return app.url;\n}\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction findWorkspaceRoot(startDir = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n for (let i = 0; i < 20; i++) {\n const pkg = readJson(path.join(dir, \"package.json\"));\n if (typeof pkg?.[\"agent-native\"]?.workspaceCore === \"string\") {\n return dir;\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction parseWorkspaceAppsManifest(\n parsed: any,\n): WorkspaceAppManifestEntry[] | null {\n const rawApps = Array.isArray(parsed?.apps)\n ? parsed.apps\n : Array.isArray(parsed)\n ? parsed\n : null;\n if (!rawApps) return null;\n\n const apps = rawApps\n .map((entry) => {\n if (!entry || typeof entry !== \"object\") return null;\n const id = typeof entry.id === \"string\" ? entry.id.trim() : \"\";\n const pathValue = typeof entry.path === \"string\" ? entry.path.trim() : \"\";\n if (!id || !pathValue.startsWith(\"/\")) return null;\n return {\n id,\n name:\n typeof entry.name === \"string\" && entry.name.trim()\n ? entry.name.trim()\n : titleCase(id),\n description:\n typeof entry.description === \"string\" ? entry.description : \"\",\n path: pathValue,\n url:\n typeof entry.url === \"string\" && entry.url.trim()\n ? entry.url.trim()\n : null,\n isDispatch:\n typeof entry.isDispatch === \"boolean\"\n ? entry.isDispatch\n : id === \"dispatch\",\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction readWorkspaceAppsFromEnv(): WorkspaceAppManifestEntry[] | null {\n const raw = process.env[WORKSPACE_APPS_ENV_KEY];\n if (!raw) return null;\n try {\n return parseWorkspaceAppsManifest(JSON.parse(raw));\n } catch {\n return null;\n }\n}\n\nfunction workspaceAppsManifestCandidates(): string[] {\n const candidates: string[] = [];\n try {\n candidates.push(\n path.join(process.cwd(), \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(process.cwd(), WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes do not expose process.cwd().\n }\n try {\n const moduleDir = path.dirname(fileURLToPath(import.meta.url));\n candidates.push(\n path.join(moduleDir, \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(moduleDir, WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes expose non-file module URLs. The env manifest still\n // works there, so skip file-relative candidates.\n }\n return candidates;\n}\n\nfunction readWorkspaceAppsFromManifestFile():\n | WorkspaceAppManifestEntry[]\n | null {\n for (const file of workspaceAppsManifestCandidates()) {\n if (!fs.existsSync(file)) continue;\n const apps = parseWorkspaceAppsManifest(readJson(file));\n if (apps) return apps;\n }\n return null;\n}\n\nfunction readWorkspaceAppsFromFilesystem(): WorkspaceAppManifestEntry[] | null {\n const workspaceRoot = findWorkspaceRoot();\n if (!workspaceRoot) return null;\n const appsDir = path.join(workspaceRoot, \"apps\");\n if (!fs.existsSync(appsDir)) return null;\n\n const apps = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry): WorkspaceAppManifestEntry | null => {\n const appDir = path.join(appsDir, entry.name);\n const pkg = readJson(path.join(appDir, \"package.json\"));\n if (!pkg) return null;\n return {\n id: entry.name,\n name: pkg.displayName || titleCase(entry.name),\n description: pkg.description || \"\",\n path: `/${entry.name}`,\n isDispatch: entry.name === \"dispatch\",\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction workspaceBaseUrl(): string | null {\n return (\n process.env.WORKSPACE_GATEWAY_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL ||\n null\n );\n}\n\nfunction workspaceAppUrl(app: WorkspaceAppManifestEntry): string | null {\n if (app.url) return app.url;\n const base = workspaceBaseUrl();\n if (!base) return null;\n try {\n return new URL(app.path, `${base.replace(/\\/$/, \"\")}/`).toString();\n } catch {\n return null;\n }\n}\n\nfunction discoverWorkspaceAgents(selfAppId?: string): DiscoveredAgent[] {\n const workspaceApps =\n readWorkspaceAppsFromEnv() ??\n readWorkspaceAppsFromManifestFile() ??\n readWorkspaceAppsFromFilesystem();\n if (!workspaceApps) return [];\n\n return workspaceApps\n .filter((app) => app.id !== selfAppId)\n .map((app) => {\n const url = workspaceAppUrl(app);\n if (!url) return null;\n const builtin = BUILTIN_AGENTS.find((agent) => agent.id === app.id);\n return {\n id: app.id,\n name: app.name,\n description:\n app.description ||\n builtin?.description ||\n `Workspace app mounted at ${app.path}`,\n url,\n color: builtin?.color || \"#6B7280\",\n } satisfies DiscoveredAgent;\n })\n .filter((agent): agent is DiscoveredAgent => !!agent);\n}\n\n/**\n * Like `getBuiltinAgents`, but always returns the production URL — never the\n * env-resolved devUrl. Used by the resource seeder so that a one-time seed\n * (`ON CONFLICT DO NOTHING`) can't permanently bake a localhost URL into the\n * DB, which would override the built-in's prod URL for every later\n * production deploy.\n */\nexport const BUILTIN_AGENTS_FOR_SEEDING: DiscoveredAgent[] =\n BUILTIN_AGENTS.filter((app) => app.url).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: app.url, // ALWAYS prod\n color: app.color,\n }));\n"]}
1
+ {"version":3,"file":"agent-discovery.js","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAoBvE;;;;GAIG;AACH,MAAM,cAAc,GAAiB,gBAAgB,EAAE;KACpD,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC;KACxC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAClB,EAAE,EAAE,QAAQ,CAAC,IAAI;IACjB,IAAI,EAAE,QAAQ,CAAC,KAAK;IACpB,WAAW,EAAE,QAAQ,CAAC,WAAW,IAAI,QAAQ,CAAC,IAAI;IAClD,GAAG,EAAE,QAAQ,CAAC,OAAQ;IACtB,MAAM,EAAE,oBAAoB,QAAQ,CAAC,OAAO,EAAE;IAC9C,OAAO,EAAE,QAAQ,CAAC,OAAO;IACzB,KAAK,EAAE,QAAQ,CAAC,KAAK;CACtB,CAAC,CAAC,CAAC;AAEN,MAAM,4BAA4B,GAAG,IAAI,GAAG,CAC1C,SAAS,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,OAAO,CAAC,CAAC,GAAG,CACrE,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAC5B,CACF,CAAC;AAEF,MAAM,sBAAsB,GAAG,kCAAkC,CAAC;AAClE,MAAM,4BAA4B,GAAG,qBAAqB,CAAC;AAW3D,MAAM,UAAU,gCAAgC,CAC9C,QAAgC,EAChC,SAAkB;IAElB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,EAAE;QACX,MAAM,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QACjC,IAAI,CAAC,GAAG;YAAE,OAAO,IAAI,CAAC;QACtB,MAAM,OAAO,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC;QACpE,OAAO;YACL,EAAE,EAAE,GAAG,CAAC,EAAE;YACV,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,WAAW,EACT,GAAG,CAAC,WAAW;gBACf,OAAO,EAAE,WAAW;gBACpB,4BAA4B,GAAG,CAAC,IAAI,EAAE;YACxC,GAAG;YACH,KAAK,EAAE,OAAO,EAAE,KAAK,IAAI,SAAS;SACT,CAAC;IAC9B,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,KAAK,EAA4B,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AAC1D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,0BAA0B,GACrC,cAAc,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACpD,EAAE,EAAE,GAAG,CAAC,EAAE;IACV,IAAI,EAAE,GAAG,CAAC,IAAI;IACd,WAAW,EAAE,GAAG,CAAC,WAAW;IAC5B,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc;IAC5B,KAAK,EAAE,GAAG,CAAC,KAAK;CACjB,CAAC,CAAC,CAAC","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { TEMPLATES, visibleTemplates } from \"../cli/templates-meta.js\";\n\nexport interface DiscoveredAgent {\n id: string;\n name: string;\n description: string;\n url: string;\n color: string;\n}\n\ninterface AgentEntry {\n id: string;\n name: string;\n description: string;\n url: string;\n devUrl?: string;\n devPort: number;\n color: string;\n}\n\n/**\n * Built-in agent registry. Derive this from the published CLI metadata so\n * connected-agent discovery stays aligned with the public template allow-list\n * without depending on @agent-native/shared-app-config at runtime.\n */\nconst BUILTIN_AGENTS: AgentEntry[] = visibleTemplates()\n .filter((template) => !!template.prodUrl)\n .map((template) => ({\n id: template.name,\n name: template.label,\n description: template.description ?? template.hint,\n url: template.prodUrl!,\n devUrl: `http://localhost:${template.devPort}`,\n devPort: template.devPort,\n color: template.color,\n }));\n\nconst HIDDEN_FIRST_PARTY_AGENT_IDS = new Set(\n TEMPLATES.filter((template) => template.hidden && template.prodUrl).map(\n (template) => template.name,\n ),\n);\n\nconst WORKSPACE_APPS_ENV_KEY = \"AGENT_NATIVE_WORKSPACE_APPS_JSON\";\nconst WORKSPACE_APPS_MANIFEST_FILE = \"workspace-apps.json\";\n\ninterface WorkspaceAppManifestEntry {\n id: string;\n name: string;\n description: string;\n path: string;\n url?: string | null;\n isDispatch?: boolean;\n}\n\nexport function shouldIncludeRemoteAgentManifest(\n manifest: { id?: string | null },\n selfAppId?: string,\n): boolean {\n const id = manifest.id?.trim();\n if (!id) return false;\n const normalizedId = id.toLowerCase();\n const normalizedSelfAppId = selfAppId?.trim().toLowerCase();\n if (normalizedSelfAppId && normalizedId === normalizedSelfAppId) {\n return false;\n }\n return !HIDDEN_FIRST_PARTY_AGENT_IDS.has(normalizedId);\n}\n\n/**\n * Get built-in agents (static, no DB). Used as fallback and for seeding.\n */\nexport function getBuiltinAgents(selfAppId?: string): DiscoveredAgent[] {\n return BUILTIN_AGENTS.filter((app) => app.id !== selfAppId && app.url).map(\n (app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: resolveAgentUrl(app),\n color: app.color,\n }),\n );\n}\n\n/**\n * Discover all agents: built-in + custom agents stored as resources.\n * Custom agents override built-in agents with the same ID.\n */\nexport async function discoverAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const builtins = getBuiltinAgents(selfAppId);\n const agentsById = new Map<string, DiscoveredAgent>();\n\n // Start with built-ins\n for (const agent of builtins) {\n agentsById.set(agent.id, agent);\n }\n\n // Overlay custom agents from resources\n try {\n const { resourceList, resourceGet, SHARED_OWNER, resourceListAccessible } =\n await import(\"../resources/store.js\");\n const { DEV_MODE_USER_EMAIL } = await import(\"./auth.js\");\n\n const isDevMode =\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\";\n\n const { parseRemoteAgentManifest, REMOTE_AGENT_RESOURCE_PREFIXES } =\n await import(\"../resources/metadata.js\");\n\n const resources: Array<{ id: string; path: string }> = [];\n for (const prefix of [...REMOTE_AGENT_RESOURCE_PREFIXES].reverse()) {\n resources.push(\n ...(isDevMode\n ? await resourceListAccessible(DEV_MODE_USER_EMAIL, prefix)\n : await resourceList(SHARED_OWNER, prefix)),\n );\n }\n\n for (const r of resources) {\n if (!r.path.endsWith(\".json\")) continue;\n try {\n const full = await resourceGet(r.id);\n if (!full) continue;\n const manifest = parseRemoteAgentManifest(full.content, r.path);\n if (!manifest || !shouldIncludeRemoteAgentManifest(manifest, selfAppId))\n continue;\n\n // If the resource override carries a localhost URL but we're running\n // in production (e.g. a stale dev-time seed got promoted to the prod\n // DB), fall back to the matching built-in's prod URL instead of\n // letting the override win — otherwise outbound `call-agent` fetches\n // from a serverless function would target localhost and fail with\n // \"fetch failed\" instantly. The override still wins for non-localhost\n // URLs (the supported case for self-hosted custom agents).\n let url = manifest.url;\n if (\n !isDevMode &&\n typeof url === \"string\" &&\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0)(:|\\/|$)/.test(url)\n ) {\n const builtin = agentsById.get(manifest.id);\n if (builtin?.url) url = builtin.url;\n }\n\n agentsById.set(manifest.id, {\n id: manifest.id,\n name: manifest.name,\n description: manifest.description || \"\",\n url,\n color: manifest.color || \"#6B7280\",\n });\n } catch {\n // Skip unreadable resources\n }\n }\n } catch {\n // Resources not available — use built-ins only\n }\n\n // Overlay sibling workspace apps last so same-origin workspaces prefer the\n // app mounted in this workspace over the public template with the same id.\n for (const agent of discoverWorkspaceAgents(selfAppId)) {\n agentsById.set(agent.id, agent);\n }\n\n return Array.from(agentsById.values());\n}\n\n/**\n * Look up a single agent by ID or name (case-insensitive).\n */\nexport async function findAgent(\n idOrName: string,\n selfAppId?: string,\n): Promise<DiscoveredAgent | undefined> {\n const lower = idOrName.toLowerCase();\n const agents = await discoverAgents(selfAppId);\n return agents.find((a) => a.id === lower || a.name.toLowerCase() === lower);\n}\n\nfunction isDevEnvironment(): boolean {\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n );\n}\n\nfunction resolveAgentUrl(app: AgentEntry): string {\n if (isDevEnvironment()) {\n return app.devUrl || `http://localhost:${app.devPort}`;\n }\n return app.url;\n}\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction findWorkspaceRoot(startDir = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n for (let i = 0; i < 20; i++) {\n const pkg = readJson(path.join(dir, \"package.json\"));\n if (typeof pkg?.[\"agent-native\"]?.workspaceCore === \"string\") {\n return dir;\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction parseWorkspaceAppsManifest(\n parsed: any,\n): WorkspaceAppManifestEntry[] | null {\n const rawApps = Array.isArray(parsed?.apps)\n ? parsed.apps\n : Array.isArray(parsed)\n ? parsed\n : null;\n if (!rawApps) return null;\n\n const apps = rawApps\n .map((entry) => {\n if (!entry || typeof entry !== \"object\") return null;\n const id = typeof entry.id === \"string\" ? entry.id.trim() : \"\";\n const pathValue = typeof entry.path === \"string\" ? entry.path.trim() : \"\";\n if (!id || !pathValue.startsWith(\"/\")) return null;\n return {\n id,\n name:\n typeof entry.name === \"string\" && entry.name.trim()\n ? entry.name.trim()\n : titleCase(id),\n description:\n typeof entry.description === \"string\" ? entry.description : \"\",\n path: pathValue,\n url:\n typeof entry.url === \"string\" && entry.url.trim()\n ? entry.url.trim()\n : null,\n isDispatch:\n typeof entry.isDispatch === \"boolean\"\n ? entry.isDispatch\n : id === \"dispatch\",\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction readWorkspaceAppsFromEnv(): WorkspaceAppManifestEntry[] | null {\n const raw = process.env[WORKSPACE_APPS_ENV_KEY];\n if (!raw) return null;\n try {\n return parseWorkspaceAppsManifest(JSON.parse(raw));\n } catch {\n return null;\n }\n}\n\nfunction workspaceAppsManifestCandidates(): string[] {\n const candidates: string[] = [];\n try {\n candidates.push(\n path.join(process.cwd(), \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(process.cwd(), WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes do not expose process.cwd().\n }\n try {\n const moduleDir = path.dirname(fileURLToPath(import.meta.url));\n candidates.push(\n path.join(moduleDir, \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(moduleDir, WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes expose non-file module URLs. The env manifest still\n // works there, so skip file-relative candidates.\n }\n return candidates;\n}\n\nfunction readWorkspaceAppsFromManifestFile():\n | WorkspaceAppManifestEntry[]\n | null {\n for (const file of workspaceAppsManifestCandidates()) {\n if (!fs.existsSync(file)) continue;\n const apps = parseWorkspaceAppsManifest(readJson(file));\n if (apps) return apps;\n }\n return null;\n}\n\nfunction readWorkspaceAppsFromFilesystem(): WorkspaceAppManifestEntry[] | null {\n const workspaceRoot = findWorkspaceRoot();\n if (!workspaceRoot) return null;\n const appsDir = path.join(workspaceRoot, \"apps\");\n if (!fs.existsSync(appsDir)) return null;\n\n const apps = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry): WorkspaceAppManifestEntry | null => {\n const appDir = path.join(appsDir, entry.name);\n const pkg = readJson(path.join(appDir, \"package.json\"));\n if (!pkg) return null;\n return {\n id: entry.name,\n name: pkg.displayName || titleCase(entry.name),\n description: pkg.description || \"\",\n path: `/${entry.name}`,\n isDispatch: entry.name === \"dispatch\",\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction workspaceBaseUrl(): string | null {\n return (\n process.env.WORKSPACE_GATEWAY_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL ||\n null\n );\n}\n\nfunction workspaceAppUrl(app: WorkspaceAppManifestEntry): string | null {\n if (app.url) return app.url;\n const base = workspaceBaseUrl();\n if (!base) return null;\n try {\n return new URL(app.path, `${base.replace(/\\/$/, \"\")}/`).toString();\n } catch {\n return null;\n }\n}\n\nfunction discoverWorkspaceAgents(selfAppId?: string): DiscoveredAgent[] {\n const workspaceApps =\n readWorkspaceAppsFromEnv() ??\n readWorkspaceAppsFromManifestFile() ??\n readWorkspaceAppsFromFilesystem();\n if (!workspaceApps) return [];\n\n return workspaceApps\n .filter((app) => app.id !== selfAppId)\n .map((app) => {\n const url = workspaceAppUrl(app);\n if (!url) return null;\n const builtin = BUILTIN_AGENTS.find((agent) => agent.id === app.id);\n return {\n id: app.id,\n name: app.name,\n description:\n app.description ||\n builtin?.description ||\n `Workspace app mounted at ${app.path}`,\n url,\n color: builtin?.color || \"#6B7280\",\n } satisfies DiscoveredAgent;\n })\n .filter((agent): agent is DiscoveredAgent => !!agent);\n}\n\n/**\n * Like `getBuiltinAgents`, but always returns the production URL — never the\n * env-resolved devUrl. Used by the resource seeder so that a one-time seed\n * (`ON CONFLICT DO NOTHING`) can't permanently bake a localhost URL into the\n * DB, which would override the built-in's prod URL for every later\n * production deploy.\n */\nexport const BUILTIN_AGENTS_FOR_SEEDING: DiscoveredAgent[] =\n BUILTIN_AGENTS.filter((app) => app.url).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: app.url, // ALWAYS prod\n color: app.color,\n }));\n"]}
@@ -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;Y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CAAC,EACR;EAEE,UAAU;QACR,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAwDN;;;yDAGyD,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\">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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'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"]}