@circuitwall/jarela 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +3 -3
  3. package/.next/standalone/.next/prerender-manifest.json +3 -3
  4. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  5. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  6. package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
  7. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  8. package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  11. package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  12. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  14. package/.next/standalone/.next/server/app/_not-found.html +2 -2
  15. package/.next/standalone/.next/server/app/_not-found.rsc +1 -1
  16. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  17. package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  18. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  19. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  20. package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  21. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  22. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js +10 -1
  23. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js.map +1 -1
  24. package/.next/standalone/.next/server/app/api/v1/dashboard/currency/route.js +10 -5
  25. package/.next/standalone/.next/server/app/api/v1/dashboard/currency/route.js.map +1 -1
  26. package/.next/standalone/.next/server/app/api/v1/providers/[provider]/probe/route.js +9 -1
  27. package/.next/standalone/.next/server/app/api/v1/providers/[provider]/probe/route.js.map +1 -1
  28. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js +33 -8
  29. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js.map +1 -1
  30. package/.next/standalone/.next/server/app/page.js +63 -202
  31. package/.next/standalone/.next/server/app/page.js.map +1 -1
  32. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  33. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  34. package/.next/standalone/.next/server/app/setup/page.js +1 -1
  35. package/.next/standalone/.next/server/app/setup/page.js.nft.json +1 -1
  36. package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
  37. package/.next/standalone/.next/server/chunks/1718.js +159 -0
  38. package/.next/standalone/.next/server/chunks/1718.js.map +1 -0
  39. package/.next/standalone/.next/server/chunks/2082.js +6 -3
  40. package/.next/standalone/.next/server/chunks/2082.js.map +1 -1
  41. package/.next/standalone/.next/server/chunks/210.js +28 -0
  42. package/.next/standalone/.next/server/chunks/210.js.map +1 -1
  43. package/.next/standalone/.next/server/chunks/423.js +6 -3
  44. package/.next/standalone/.next/server/chunks/423.js.map +1 -1
  45. package/.next/standalone/.next/server/chunks/4631.js +37 -5
  46. package/.next/standalone/.next/server/chunks/4631.js.map +1 -1
  47. package/.next/standalone/.next/server/chunks/8167.js +255 -204
  48. package/.next/standalone/.next/server/chunks/8167.js.map +1 -1
  49. package/.next/standalone/.next/server/chunks/8866.js +38 -5
  50. package/.next/standalone/.next/server/chunks/8866.js.map +1 -1
  51. package/.next/standalone/.next/server/chunks/9032.js +8 -0
  52. package/.next/standalone/.next/server/chunks/9032.js.map +1 -1
  53. package/.next/standalone/.next/server/chunks/{7883.js → 9557.js} +15 -3
  54. package/.next/standalone/.next/server/chunks/9557.js.map +1 -0
  55. package/.next/standalone/.next/server/middleware-build-manifest.js +3 -3
  56. package/.next/standalone/.next/server/middleware.js +6 -3
  57. package/.next/standalone/.next/server/pages/404.html +2 -2
  58. package/.next/standalone/.next/server/pages/500.html +1 -1
  59. package/.next/standalone/.next/server/proxy.js.map +1 -1
  60. package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
  61. package/.next/standalone/.next/static/chunks/{2351-68d8987bbe17ba2d.js → 2351-1ab119fb3b48f4c9.js} +258 -205
  62. package/.next/standalone/.next/static/chunks/2351-1ab119fb3b48f4c9.js.map +1 -0
  63. package/.next/standalone/.next/static/chunks/{9209-0d46118e502f8bf5.js → 4097-64691f9110cf167c.js} +14 -2
  64. package/.next/standalone/.next/static/chunks/4097-64691f9110cf167c.js.map +1 -0
  65. package/.next/standalone/.next/static/chunks/app/{page-74846c864241b96d.js → page-145150e0468544e7.js} +64 -203
  66. package/.next/standalone/.next/static/chunks/app/page-145150e0468544e7.js.map +1 -0
  67. package/.next/standalone/.next/static/chunks/app/setup/{page-9a465b5fa755b3c3.js → page-a1463a9ace439ff7.js} +2 -2
  68. package/.next/standalone/.next/static/chunks/app/setup/{page-9a465b5fa755b3c3.js.map → page-a1463a9ace439ff7.js.map} +1 -1
  69. package/.next/standalone/.next/static/chunks/{webpack-ff5627013a5e3842.js → webpack-f4ac5c5f92cfd1c1.js} +13 -1
  70. package/.next/standalone/.next/static/chunks/webpack-f4ac5c5f92cfd1c1.js.map +1 -0
  71. package/.next/standalone/package.json +1 -1
  72. package/CHANGELOG.md +60 -0
  73. package/README.md +1 -1
  74. package/api/client.ts +10 -9
  75. package/app/api/v1/dashboard/currency/route.ts +7 -2
  76. package/app/api/v1/providers/[provider]/probe/route.ts +12 -1
  77. package/app/api/v1/threads/[thread_id]/run/route.ts +22 -8
  78. package/components/layout/AppShell.tsx +53 -17
  79. package/components/setup/PinKeypad.tsx +238 -0
  80. package/components/setup/ScreenLock.tsx +8 -173
  81. package/components/setup/UnlockScreen.tsx +25 -192
  82. package/lib/documents/remote/github.ts +16 -2
  83. package/lib/documents/remote/mail.ts +11 -2
  84. package/lib/lifecycle/shutdown.ts +9 -0
  85. package/lib/providers/github-copilot-auth.ts +2 -0
  86. package/lib/providers/github-copilot.ts +1 -0
  87. package/lib/tools/async-results.ts +11 -0
  88. package/package.json +1 -1
  89. package/scripts/install-to-system.ps1 +2 -2
  90. package/scripts/installed-launcher.ps1 +81 -17
  91. package/.next/standalone/.next/server/chunks/7883.js.map +0 -1
  92. package/.next/standalone/.next/static/chunks/2351-68d8987bbe17ba2d.js.map +0 -1
  93. package/.next/standalone/.next/static/chunks/9209-0d46118e502f8bf5.js.map +0 -1
  94. package/.next/standalone/.next/static/chunks/app/page-74846c864241b96d.js.map +0 -1
  95. package/.next/standalone/.next/static/chunks/webpack-ff5627013a5e3842.js.map +0 -1
  96. /package/.next/standalone/.next/static/{AV5AO0yTRABo-NgwxhDe7 → WQdcnm9NyqpeNc0Z8_woo}/_buildManifest.js +0 -0
  97. /package/.next/standalone/.next/static/{AV5AO0yTRABo-NgwxhDe7 → WQdcnm9NyqpeNc0Z8_woo}/_ssgManifest.js +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"static/chunks/2351-68d8987bbe17ba2d.js","mappings":";;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;CAiBC,GAED,MAAMA,WAAqC;IACzC,iEAAiE;IACjE,mEAAmE;IACnEC,QAAQ;QACN;QACA;QACA;QACA;QACA;QACA;QACA;KACD;IACD,kEAAkE;IAClEC,WAAW;QACT;QACA;QACA;QACA;QACA;KACD;IACD,wEAAwE;IACxE,gEAAgE;IAChEC,QAAQ;QAAC;QAAuB;KAAsB;IACtD,2EAA2E;IAC3E,wEAAwE;IACxE,wCAAwC;IACxC,kBAAkB;QAChB;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;KACD;IACD,8DAA8D;IAC9DC,UAAU,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downTextarea.tsx","webpack://_N_E/./api/client.ts","webpack://_N_E/./components/models/CapBadges.tsx","webpack://_N_E/./components/setup/UnlockScreen.tsx","webpack://_N_E/./contexts/AppContext.tsx","webpack://_N_E/./components/setup/OnboardingWizard.tsx","webpack://_N_E/./api/runtime-config.ts","webpack://_N_E/./components/models/ModelFeatureGuide.tsx","webpack://_N_E/./lib/env/app-config.ts","webpack://_N_E/./components/ui/Logo.tsx","webpack://_N_E/./lib/ui/feature-readiness.ts"],"sourcesContent":["/**\n * Static per-provider classification of which model ids accept image inputs.\n *\n * Used purely to surface UI hints — \"this agent's model can read WhatsApp\n * images\" — so a user can pick a vision-capable model BEFORE pointing a\n * bridge route at an agent. The runtime never enforces this: the bridge\n * always forwards whatever payload it captured, and the provider returns\n * whatever ignore/error behaviour the upstream model chose if it isn't\n * actually multi-modal.\n *\n * Patterns intentionally err on the *generous* side. A false positive just\n * means the user sees no warning for a model that quietly ignores images;\n * a false negative would mean users see a scary warning on a model that\n * actually works fine. We update the patterns as new model families ship.\n *\n * NOTE: this module is intentionally free of server-only imports so the\n * BridgeEditor / AgentEditor UIs can import it directly.\n */\n\nconst PATTERNS: Record<string, RegExp[]> = {\n // OpenAI — every modern flagship is multi-modal; only the legacy\n // gpt-3.5-* / text-davinci-* / o3-mini-text family stay text-only.\n openai: [\n /^gpt-4o/i,\n /^gpt-4\\.1/i,\n /^gpt-4-turbo/i,\n /^gpt-4-vision/i,\n /^gpt-5/i,\n /^chatgpt-4o/i,\n /^o[134](?:-|$)/i, // o1, o3, o4-mini (vision-enabled reasoning models)\n ],\n // Anthropic — Claude 3 onwards is vision-native across all tiers.\n anthropic: [\n /^claude-3/i,\n /^claude-sonnet/i,\n /^claude-opus/i,\n /^claude-haiku-4/i,\n /^claude-[45](?:-|$)/i,\n ],\n // Google — Gemini 1.5+ are multi-modal; legacy gemini-pro is text-only,\n // but gemini-pro-vision was the explicit vision SKU before 1.5.\n gemini: [/^gemini-(1\\.5|2|3)/i, /^gemini-pro-vision/i],\n // GitHub Copilot — proxies vision-capable models from OpenAI / Anthropic /\n // Google. Mirror those families (the actual capability is gated server-\n // side by Copilot; we just don't warn).\n \"github-copilot\": [\n /^gpt-4o/i,\n /^gpt-4\\.1/i,\n /^gpt-5/i,\n /^o[134](?:-|$)/i,\n /^claude-3/i,\n /^claude-sonnet/i,\n /^claude-opus/i,\n /^claude-haiku-4/i,\n /^claude-[45](?:-|$)/i,\n /^gemini-(1\\.5|2|3)/i,\n ],\n // DeepSeek / Cohere — current public chat SKUs are text-only.\n deepseek: [],\n cohere: [],\n // LangChain pass-through could be anything; treat as unknown (handled\n // separately below) rather than yes/no.\n langchain: [],\n // Tests assume the mock accepts images.\n mock: [/.*/],\n};\n\n/**\n * Returns true when the given (provider, model_id) pair is known to accept\n * image inputs. Unknown providers / models return false — call\n * `isProviderClassified` if you want to distinguish \"definitely no\" from\n * \"we don't recognize this\".\n */\nexport function modelSupportsImages(provider: string, modelId: string): boolean {\n const pats = PATTERNS[provider.toLowerCase()] ?? [];\n return pats.some((re) => re.test(modelId));\n}\n\n/**\n * True when we have an explicit capability list for the provider. Used by\n * the UI to soften the warning copy (\"might not support images\") for\n * pass-through providers like `langchain` or unknown external ones.\n */\nexport function isProviderClassified(provider: string): boolean {\n return provider.toLowerCase() in PATTERNS;\n}\n\n// ── extended capabilities for badge rendering ────────────────────────────────\n// Mirrors CatalogModel[\"capabilities\"] so saved ModelConfigs can render the\n// same icon set the catalog browser uses. Heuristics err on the conservative\n// side for audio (vanilla gpt-4o is NOT audio-capable — only *-audio-preview /\n// *-realtime are) and generous side for files (PDF / document input).\n\nconst AUDIO_PATTERNS: Record<string, RegExp[]> = {\n openai: [/audio/i, /realtime/i],\n gemini: [/^gemini-(1\\.5|2|3)/i],\n anthropic: [],\n \"github-copilot\": [/audio/i, /realtime/i, /^gemini-(1\\.5|2|3)/i],\n deepseek: [],\n cohere: [],\n langchain: [],\n mock: [/.*/],\n};\n\nconst FILES_PATTERNS: Record<string, RegExp[]> = {\n // PDF / document upload support.\n openai: [/^gpt-4o/i, /^gpt-4\\.1/i, /^gpt-4-turbo/i, /^gpt-5/i, /^o[134](?:-|$)/i, /^chatgpt-4o/i],\n anthropic: [/^claude-3/i, /^claude-sonnet/i, /^claude-opus/i, /^claude-haiku-4/i, /^claude-[45](?:-|$)/i],\n gemini: [/^gemini-(1\\.5|2|3)/i],\n \"github-copilot\": [/^gpt-4o/i, /^gpt-4\\.1/i, /^gpt-5/i, /^o[134](?:-|$)/i, /^claude-3/i, /^claude-sonnet/i, /^claude-opus/i, /^claude-haiku-4/i, /^claude-[45](?:-|$)/i, /^gemini-(1\\.5|2|3)/i],\n deepseek: [],\n cohere: [],\n langchain: [],\n mock: [/.*/],\n};\n\nconst WEB_SEARCH_PATTERNS: Record<string, RegExp[]> = {\n // Built-in provider-side web tool.\n anthropic: [/^claude-3\\.5/i, /^claude-3\\.7/i, /^claude-sonnet/i, /^claude-opus/i, /^claude-haiku-4/i, /^claude-[45](?:-|$)/i],\n openai: [],\n gemini: [],\n \"github-copilot\": [],\n deepseek: [],\n cohere: [],\n langchain: [],\n mock: [],\n};\n\nconst JSON_MODE_PROVIDERS = new Set([\"openai\", \"gemini\", \"deepseek\", \"mock\"]);\n\nfunction matchesAny(map: Record<string, RegExp[]>, provider: string, modelId: string): boolean {\n const pats = map[provider.toLowerCase()] ?? [];\n return pats.some((re) => re.test(modelId));\n}\n\nexport interface ModelCapabilities {\n vision: boolean;\n tools: boolean;\n streaming: boolean;\n json_mode: boolean;\n web_search: boolean;\n audio: boolean;\n files: boolean;\n}\n\n/**\n * Best-effort capability inference for a saved (provider, model_id) pair —\n * used to render capability badges in surfaces that don't have a live\n * catalog fetch (ModelsPanel, AgentEditor dropdowns, etc.).\n */\nexport function modelCapabilities(provider: string, modelId: string): ModelCapabilities {\n const p = provider.toLowerCase();\n // Reasoner-style models that don't expose tool calling.\n const noTools = /^deepseek-reasoner/i.test(modelId);\n return {\n vision: modelSupportsImages(provider, modelId),\n tools: isProviderClassified(p) && !noTools,\n streaming: true,\n json_mode: JSON_MODE_PROVIDERS.has(p),\n web_search: matchesAny(WEB_SEARCH_PATTERNS, provider, modelId),\n audio: matchesAny(AUDIO_PATTERNS, provider, modelId),\n files: matchesAny(FILES_PATTERNS, provider, modelId),\n };\n}\n","\"use client\";\nimport { useState } from \"react\";\nimport ReactMarkdown from \"react-markdown\";\nimport remarkGfm from \"remark-gfm\";\n\ninterface Props {\n value: string;\n onChange: (value: string) => void;\n className?: string;\n placeholder?: string;\n rows?: number;\n maxLength?: number;\n monospace?: boolean;\n}\n\nconst MD_REMARK_PLUGINS = [remarkGfm];\n\nexport function MarkdownTextarea({\n value,\n onChange,\n className = \"\",\n placeholder,\n rows,\n maxLength,\n monospace,\n}: Props) {\n const [mode, setMode] = useState<\"edit\" | \"preview\">(\"edit\");\n const fontClass = monospace ? \"font-mono\" : \"\";\n return (\n <div className=\"space-y-1\">\n {/*\n Toolbar uses span+role=button rather than <button> so the surrounding\n <label> wrapper still implicitly associates with the <textarea> below\n (HTML labels bind to the first labelable descendant, and <button> is\n labelable; spans are not).\n */}\n <div role=\"toolbar\" className=\"flex items-center justify-end gap-1 text-[10px]\">\n <span\n role=\"button\"\n tabIndex={0}\n onClick={() => setMode(\"edit\")}\n onKeyDown={(e) => { if (e.key === \"Enter\" || e.key === \" \") { e.preventDefault(); setMode(\"edit\"); } }}\n className={`px-1.5 py-0.5 rounded transition-colors cursor-pointer select-none ${\n mode === \"edit\" ? \"bg-surface-3 text-fg\" : \"text-fg-subtle hover:text-fg\"\n }`}\n >\n Edit\n </span>\n <span\n role=\"button\"\n tabIndex={value.trim() ? 0 : -1}\n aria-disabled={!value.trim()}\n onClick={() => { if (value.trim()) setMode(\"preview\"); }}\n onKeyDown={(e) => { if ((e.key === \"Enter\" || e.key === \" \") && value.trim()) { e.preventDefault(); setMode(\"preview\"); } }}\n className={`px-1.5 py-0.5 rounded transition-colors select-none ${\n !value.trim() ? \"opacity-40 cursor-not-allowed\" : \"cursor-pointer\"\n } ${mode === \"preview\" ? \"bg-surface-3 text-fg\" : \"text-fg-subtle hover:text-fg\"}`}\n >\n Preview\n </span>\n </div>\n {mode === \"edit\" ? (\n <textarea\n className={`${className} ${fontClass}`.trim()}\n value={value}\n onChange={(e) => onChange(e.target.value)}\n placeholder={placeholder}\n rows={rows}\n maxLength={maxLength}\n />\n ) : (\n <div\n className={`${className} prose prose-invert prose-sm max-w-none jarela-rich overflow-auto`}\n style={{ minHeight: rows ? `${rows * 1.5}em` : undefined }}\n >\n {value.trim() ? (\n <ReactMarkdown remarkPlugins={MD_REMARK_PLUGINS}>{value}</ReactMarkdown>\n ) : (\n <span className=\"text-fg-faint italic\">Nothing to preview</span>\n )}\n </div>\n )}\n </div>\n );\n}\n","import type {\n AgentConfig,\n AgentConfigIn,\n AgentInfo,\n Bridge,\n BridgeChatsResponse,\n BridgeIn,\n BridgeLiveStatus,\n BridgePatch,\n BridgeRoute,\n BridgeRouteIn,\n BridgeRoutePatch,\n DashboardCurrencyInfo,\n DashboardMetrics,\n DashboardPricingRefreshResult,\n ContentPart,\n EnvAllowlistConfig,\n EnvSyncResult,\n ExtensionsListResponse,\n IntegrationsListResponse,\n IntegrationStatus,\n McpRegistryEntry,\n McpServer,\n McpServerIn,\n PendingAction,\n ScheduledTask,\n Watcher,\n DocumentSource,\n DocumentSourceIn,\n DocumentSourcePatch,\n DocumentSettings,\n DocumentHit,\n DocumentReindexResult,\n MemoryItem,\n ModelConfig,\n ModelConfigIn,\n Credential,\n CredentialIn,\n StreamOptions,\n ToolInfo,\n ToolPolicy,\n ToolSecretSlotInfo,\n TaskAssignment,\n ThreadDetail,\n ThreadSummary,\n UserProfile,\n BuiltinToolCategoryInfo,\n Harness,\n HarnessIn,\n HarnessListResponse,\n HarnessPatch,\n} from \"./types\";\nimport { runtimeConfig } from \"./runtime-config\";\n\nconst BASE = \"/api/v1\";\n\nconst LIST_TTL_MS = 30_000;\n\ninterface ListCache<T> {\n data: T[] | null;\n fetchedAt: number;\n inflight: Promise<T[]> | null;\n}\n\nfunction emptyCache<T>(): ListCache<T> {\n return { data: null, fetchedAt: 0, inflight: null };\n}\n\nfunction cloneRows<T>(rows: T[]): T[] {\n return rows.map((row) => ({ ...row }));\n}\n\nconst agentListCache: ListCache<AgentConfig> = emptyCache();\nconst modelListCache: ListCache<ModelConfig> = emptyCache();\nconst taskListCache: ListCache<TaskAssignment> = emptyCache();\n\nfunction setAgentListCache(rows: AgentConfig[], notify = true): AgentConfig[] {\n const snap = cloneRows(rows);\n agentListCache.data = snap;\n agentListCache.fetchedAt = Date.now();\n agentListCache.inflight = null;\n if (notify && typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"jarela:agents-changed\"));\n }\n return cloneRows(snap);\n}\n\nfunction setModelListCache(rows: ModelConfig[], notify = true): ModelConfig[] {\n const snap = cloneRows(rows);\n modelListCache.data = snap;\n modelListCache.fetchedAt = Date.now();\n modelListCache.inflight = null;\n if (notify && typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"jarela:models-changed\"));\n }\n return cloneRows(snap);\n}\n\nfunction setTaskListCache(rows: TaskAssignment[], notify = true): TaskAssignment[] {\n const snap = cloneRows(rows);\n taskListCache.data = snap;\n taskListCache.fetchedAt = Date.now();\n taskListCache.inflight = null;\n if (notify && typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"jarela:tasks-changed\"));\n }\n return cloneRows(snap);\n}\n\nfunction cachedList<T>(\n cache: ListCache<T>,\n fetchFn: () => Promise<T[]>,\n setCache: (rows: T[], notify?: boolean) => T[],\n force: boolean,\n): Promise<T[]> {\n const now = Date.now();\n if (!force && cache.data && now - cache.fetchedAt < LIST_TTL_MS) {\n return Promise.resolve(cloneRows(cache.data));\n }\n if (!force && cache.inflight) return cache.inflight;\n const req = fetchFn().then((rows) => setCache(rows, false));\n cache.inflight = req;\n return req;\n}\n\n// Retry classifier matching the JARELA_HTTP_MAX_ATTEMPTS schema description:\n// network errors, 5xx, and 429. 4xx (client errors) and 408 are not retried —\n// the request is well-formed but the server says no, retrying won't change\n// that. AbortError is also not retried (the caller cancelled deliberately).\nfunction isRetryable(err: unknown, status?: number): boolean {\n if (status !== undefined) return status >= 500 || status === 429;\n if (err instanceof DOMException && err.name === \"AbortError\") return false;\n return true; // network errors / fetch rejections\n}\n\nasync function request<T>(path: string, init?: RequestInit & { timeoutMs?: number }): Promise<T> {\n const cfg = runtimeConfig();\n const maxAttempts = Math.max(1, cfg.httpMaxAttempts);\n const timeoutMs = init?.timeoutMs ?? cfg.httpRequestTimeoutMs;\n const { timeoutMs: _ignoreTimeoutMs, ...fetchInit } = init ?? {};\n const callerSignal = fetchInit.signal ?? null;\n\n let lastErr: unknown = null;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // Per-attempt timeout. Respect a caller-supplied AbortSignal too —\n // if the caller cancels, we abort whichever attempt is in flight and\n // bail out of the retry loop immediately.\n const timeoutCtrl = new AbortController();\n const timer = setTimeout(() => timeoutCtrl.abort(), timeoutMs);\n const onCallerAbort = () => timeoutCtrl.abort();\n callerSignal?.addEventListener(\"abort\", onCallerAbort);\n\n try {\n const res = await fetch(`${BASE}${path}`, {\n headers: { \"Content-Type\": \"application/json\", ...fetchInit.headers },\n ...fetchInit,\n signal: timeoutCtrl.signal,\n });\n if (!res.ok) {\n // 423 screen-locked: surface a window event so the AppShell can\n // mount the ScreenLock overlay. We still throw so the caller\n // sees the failure, but no point retrying — the lock isn't\n // going to clear on its own.\n if (res.status === 423) {\n const cloned = res.clone();\n const body = (await cloned.json().catch(() => null)) as\n | { error?: string }\n | null;\n if (\n body?.error === \"screen-locked\" &&\n typeof window !== \"undefined\"\n ) {\n window.dispatchEvent(new CustomEvent(\"jarela:screen-locked\"));\n }\n throw new Error(`423 ${body?.error ?? \"locked\"}`);\n }\n const text = await res.text().catch(() => res.statusText);\n // Retryable status codes: try again unless we've burned the budget\n // or the caller aborted.\n if (attempt < maxAttempts && isRetryable(null, res.status) && !callerSignal?.aborted) {\n lastErr = new Error(`${res.status} ${text}`);\n continue;\n }\n throw new Error(`${res.status} ${text}`);\n }\n return res.json() as Promise<T>;\n } catch (err) {\n // Bail out immediately on caller cancel — never report it as a\n // network failure.\n if (callerSignal?.aborted) throw err;\n lastErr = err;\n if (attempt < maxAttempts && isRetryable(err)) continue;\n throw err;\n } finally {\n clearTimeout(timer);\n callerSignal?.removeEventListener(\"abort\", onCallerAbort);\n }\n }\n // Unreachable: the loop either returns or throws on every attempt.\n throw lastErr ?? new Error(\"request failed\");\n}\n\nexport const api = {\n agents: {\n list: (opts?: { force?: boolean }) =>\n cachedList(agentListCache, () => request<AgentConfig[]>(\"/agents\"), setAgentListCache, opts?.force === true),\n get: (id: string) => request<AgentConfig>(`/agents/${encodeURIComponent(id)}`),\n create: async (data: AgentConfigIn) => {\n const created = await request<AgentConfig>(\"/agents\", { method: \"POST\", body: JSON.stringify(data) });\n if (agentListCache.data) setAgentListCache([...agentListCache.data, created]);\n if (typeof window !== \"undefined\") window.dispatchEvent(new CustomEvent(\"jarela:agents-changed\"));\n return created;\n },\n update: async (id: string, data: AgentConfigIn) => {\n const updated = await request<AgentConfig>(`/agents/${encodeURIComponent(id)}`, { method: \"PUT\", body: JSON.stringify(data) });\n if (agentListCache.data) setAgentListCache(agentListCache.data.map((a) => (a.id === id ? updated : a)));\n if (typeof window !== \"undefined\") window.dispatchEvent(new CustomEvent(\"jarela:agents-changed\"));\n return updated;\n },\n delete: async (id: string) => {\n const res = await request<{ deleted: boolean }>(`/agents/${encodeURIComponent(id)}`, { method: \"DELETE\" });\n if (res.deleted) {\n if (agentListCache.data) setAgentListCache(agentListCache.data.filter((a) => a.id !== id));\n if (typeof window !== \"undefined\") window.dispatchEvent(new CustomEvent(\"jarela:agents-changed\"));\n }\n return res;\n },\n getThread: (id: string) =>\n request<ThreadSummary>(`/agents/${encodeURIComponent(id)}/thread`),\n compact: (id: string) =>\n request<{ compacted: boolean; summary?: string; reason?: string; message_count?: number; context_chars?: number }>(\n `/agents/${encodeURIComponent(id)}/compact`,\n // Conversation summarization can take longer than normal API calls,\n // so avoid tripping the default HTTP timeout for large threads.\n { method: \"POST\", body: \"{}\", timeoutMs: 180_000 },\n ),\n },\n\n tools: {\n list: () => request<ToolInfo[]>(\"/tools\"),\n },\n\n builtinTools: {\n list: () => request<BuiltinToolCategoryInfo[]>(\"/builtin-tools\"),\n setEnabled: (category: string, enabled: boolean) =>\n request<{ category: string; enabled: boolean }>(\"/builtin-tools\", {\n method: \"PATCH\",\n body: JSON.stringify({ category, enabled }),\n }),\n },\n\n extensions: {\n list: () => request<ExtensionsListResponse>(\"/extensions\"),\n getToolSecrets: (name: string) =>\n request<{ name: string; secrets: ToolSecretSlotInfo[] }>(\n `/extensions/tools/${encodeURIComponent(name)}/secrets`,\n ),\n saveToolSecrets: (name: string, values: Record<string, string>) =>\n request<{ name: string; secrets: ToolSecretSlotInfo[] }>(\n `/extensions/tools/${encodeURIComponent(name)}/secrets`,\n { method: \"PUT\", body: JSON.stringify({ values }) },\n ),\n },\n\n threads: {\n list: (limit = 50, offset = 0) => request<ThreadSummary[]>(`/threads?limit=${limit}&offset=${offset}`),\n create: (agent_id: string, title?: string) =>\n request<ThreadSummary>(\"/threads\", { method: \"POST\", body: JSON.stringify({ agent_id, title }) }),\n get: (thread_id: string, opts?: { limit?: number; before?: string; after?: string }) => {\n const p = new URLSearchParams();\n if (opts?.limit) p.set(\"limit\", String(opts.limit));\n if (opts?.before) p.set(\"before\", opts.before);\n // `after`: only return messages newer than this ISO timestamp. Used\n // by ChatView post-run to fetch the freshly-persisted user+assistant\n // pair instead of re-pulling the whole most-recent page.\n if (opts?.after) p.set(\"after\", opts.after);\n const qs = p.toString() ? `?${p}` : \"\";\n return request<ThreadDetail>(`/threads/${thread_id}${qs}`);\n },\n delete: (thread_id: string) =>\n request<{ deleted: boolean }>(`/threads/${thread_id}`, { method: \"DELETE\" }),\n // Abort the active agent run on this thread. The server's stream loop\n // catches the resulting AbortError and emits an `error` + `done` so\n // any UI queue-drain hook (e.g. ChatView) still fires.\n abortRun: (thread_id: string) =>\n request<{ aborted: boolean }>(`/threads/${thread_id}/run`, { method: \"DELETE\" }),\n // ADR-0042. Move the explicit hot/warm context boundary on this thread.\n // Pass `null` to clear the pin and let the agent's default window apply.\n // Fire-and-forget from the chat — UI updates optimistically and the\n // returned shape just confirms server-side state for resync if needed.\n setContextPin: (thread_id: string, hot_since: string | null) =>\n request<import(\"./types\").ThreadContextPin>(\n `/threads/${thread_id}/context-pin`,\n { method: \"PATCH\", body: JSON.stringify({ hot_since }) },\n ),\n },\n\n memory: {\n list: (namespace?: string, search?: string, limit = 50) => {\n const p = new URLSearchParams();\n if (namespace) p.set(\"namespace\", namespace);\n if (search) p.set(\"search\", search);\n p.set(\"limit\", String(limit));\n return request<MemoryItem[]>(`/memory?${p}`);\n },\n create: (namespace: string, key: string, value: unknown) =>\n request<MemoryItem>(\"/memory\", { method: \"POST\", body: JSON.stringify({ namespace, key, value }) }),\n update: (namespace: string, key: string, value: unknown) =>\n request<MemoryItem>(`/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {\n method: \"PUT\", body: JSON.stringify({ value }),\n }),\n delete: (namespace: string, key: string) =>\n request<{ deleted: boolean }>(`/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, { method: \"DELETE\" }),\n },\n\n models: {\n list: (opts?: { force?: boolean }) =>\n cachedList(modelListCache, () => request<ModelConfig[]>(\"/models\"), setModelListCache, opts?.force === true),\n providers: () => request<string[]>(\"/providers\"),\n catalog: (provider: string, overrides?: Record<string, unknown>) =>\n overrides\n ? request<import(\"./types\").CatalogModel[]>(`/providers/${encodeURIComponent(provider)}/models`, {\n method: \"POST\",\n body: JSON.stringify({ params: overrides }),\n })\n : request<import(\"./types\").CatalogModel[]>(`/providers/${encodeURIComponent(provider)}/models`),\n probe: (provider: string, model_id: string, params?: Record<string, unknown>, name?: string, credential_id?: string) =>\n request<{ ok: boolean; error?: string }>(`/providers/${encodeURIComponent(provider)}/probe`, {\n method: \"POST\",\n body: JSON.stringify({ model_id, params, name, credential_id }),\n timeoutMs: 20_000,\n }),\n compactThreads: (name: string, using: { provider: string; model_id: string; params?: Record<string, unknown> }) =>\n request<{ compacted: number; skipped: number; errors: Array<{ thread_id: string; error: string }> }>(\n `/models/${encodeURIComponent(name)}/compact-threads`,\n {\n method: \"POST\",\n body: JSON.stringify({ using }),\n timeoutMs: 120_000,\n },\n ),\n create: async (name: string, data: ModelConfigIn) => {\n const created = await request<ModelConfig>(\"/models\", { method: \"POST\", body: JSON.stringify({ name, ...data }) });\n if (modelListCache.data) setModelListCache([...modelListCache.data, created]);\n if (typeof window !== \"undefined\") window.dispatchEvent(new CustomEvent(\"jarela:models-changed\"));\n return created;\n },\n update: async (name: string, data: ModelConfigIn) => {\n const updated = await request<ModelConfig>(`/models/${encodeURIComponent(name)}`, { method: \"PUT\", body: JSON.stringify(data) });\n if (modelListCache.data) setModelListCache(modelListCache.data.map((m) => (m.name === name ? updated : m)));\n if (typeof window !== \"undefined\") window.dispatchEvent(new CustomEvent(\"jarela:models-changed\"));\n return updated;\n },\n delete: async (name: string) => {\n const res = await request<{ deleted: boolean }>(`/models/${encodeURIComponent(name)}`, { method: \"DELETE\" });\n if (res.deleted) {\n if (modelListCache.data) setModelListCache(modelListCache.data.filter((m) => m.name !== name));\n if (typeof window !== \"undefined\") window.dispatchEvent(new CustomEvent(\"jarela:models-changed\"));\n // Deleting a model cascades to its assignments server-side; drop the\n // task list cache so the next read reflects the server.\n if (taskListCache.data) setTaskListCache(taskListCache.data.filter((t) => t.model_config_name !== name));\n }\n return res;\n },\n },\n\n credentials: {\n list: (filter?: { type?: string; provider?: string }) => {\n const qs = new URLSearchParams();\n if (filter?.type) qs.set(\"type\", filter.type);\n if (filter?.provider) qs.set(\"provider\", filter.provider);\n const suffix = qs.toString() ? `?${qs.toString()}` : \"\";\n return request<Credential[]>(`/credentials${suffix}`);\n },\n create: async (data: CredentialIn) => {\n const created = await request<Credential>(\"/credentials\", { method: \"POST\", body: JSON.stringify(data) });\n if (typeof window !== \"undefined\") window.dispatchEvent(new CustomEvent(\"jarela:credentials-changed\"));\n return created;\n },\n update: async (id: string, data: Partial<CredentialIn>) => {\n const updated = await request<Credential>(`/credentials/${encodeURIComponent(id)}`, {\n method: \"PUT\", body: JSON.stringify(data),\n });\n if (typeof window !== \"undefined\") window.dispatchEvent(new CustomEvent(\"jarela:credentials-changed\"));\n return updated;\n },\n delete: async (id: string) => {\n const res = await request<{ deleted: boolean }>(`/credentials/${encodeURIComponent(id)}`, { method: \"DELETE\" });\n if (res.deleted && typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"jarela:credentials-changed\"));\n }\n return res;\n },\n },\n\n profile: {\n get: () => request<UserProfile>(\"/profile\"),\n update: (data: Partial<Pick<UserProfile, \"name\" | \"icon\" | \"about\" | \"preset\">>) =>\n request<UserProfile>(\"/profile\", { method: \"PUT\", body: JSON.stringify(data) }),\n setLocationConsent: (consent: boolean) =>\n request<UserProfile>(\"/profile/location\", { method: \"PUT\", body: JSON.stringify({ consent }) }),\n updateLocation: (data: { lat: number; lng: number; accuracy_m?: number | null; label?: string | null }) =>\n request<UserProfile>(\"/profile/location\", { method: \"POST\", body: JSON.stringify(data) }),\n clearLocation: () =>\n request<UserProfile>(\"/profile/location\", { method: \"DELETE\" }),\n },\n\n access: {\n list: () => request<import(\"./types\").AccessWhitelistEntry[]>(\"/access\"),\n add: (identity: string, display_name?: string | null) =>\n request<import(\"./types\").AccessWhitelistEntry>(\"/access\", {\n method: \"POST\", body: JSON.stringify({ identity, display_name }),\n }),\n remove: (identity: string) =>\n request<{ deleted: boolean }>(`/access/${encodeURIComponent(identity)}`, { method: \"DELETE\" }),\n },\n\n tasks: {\n list: (opts?: { force?: boolean }) =>\n cachedList(taskListCache, () => request<TaskAssignment[]>(\"/tasks\"), setTaskListCache, opts?.force === true),\n assign: async (agent_id: string, model_config_name: string, tool_policy?: ToolPolicy) => {\n const assigned = await request<TaskAssignment>(`/tasks/${encodeURIComponent(agent_id)}`, {\n method: \"PUT\", body: JSON.stringify({ model_config_name, tool_policy }),\n });\n if (taskListCache.data) {\n const exists = taskListCache.data.some((t) => t.agent_id === agent_id);\n const next = exists\n ? taskListCache.data.map((t) => (t.agent_id === agent_id ? assigned : t))\n : [...taskListCache.data, assigned];\n setTaskListCache(next);\n } else if (typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"jarela:tasks-changed\"));\n }\n return assigned;\n },\n unassign: async (agent_id: string) => {\n const res = await request<{ deleted: boolean }>(`/tasks/${encodeURIComponent(agent_id)}`, { method: \"DELETE\" });\n if (taskListCache.data) setTaskListCache(taskListCache.data.filter((t) => t.agent_id !== agent_id));\n else if (typeof window !== \"undefined\") window.dispatchEvent(new CustomEvent(\"jarela:tasks-changed\"));\n return res;\n },\n },\n\n dashboard: {\n metrics: (days = 30) => request<DashboardMetrics>(`/dashboard/metrics?days=${encodeURIComponent(String(days))}`),\n refreshPricing: (opts?: { force?: boolean; ttlDays?: number }) => {\n const qs = new URLSearchParams();\n if (opts?.force === true) qs.set(\"force\", \"1\");\n if (typeof opts?.ttlDays === \"number\" && Number.isFinite(opts.ttlDays)) qs.set(\"ttlDays\", String(opts.ttlDays));\n const suffix = qs.toString() ? `?${qs.toString()}` : \"\";\n return request<DashboardPricingRefreshResult>(`/dashboard/pricing${suffix}`, {\n method: \"POST\",\n body: \"{}\",\n });\n },\n currency: (opts?: { lat?: number | null; lng?: number | null; currency?: string | null }) => {\n const qs = new URLSearchParams();\n if (typeof opts?.lat === \"number\" && Number.isFinite(opts.lat)) qs.set(\"lat\", String(opts.lat));\n if (typeof opts?.lng === \"number\" && Number.isFinite(opts.lng)) qs.set(\"lng\", String(opts.lng));\n if (opts?.currency) qs.set(\"currency\", opts.currency);\n const suffix = qs.toString() ? `?${qs.toString()}` : \"\";\n return request<DashboardCurrencyInfo>(`/dashboard/currency${suffix}`);\n },\n },\n\n mcp: {\n list: () => request<McpServer[]>(\"/mcp-servers\"),\n create: (data: McpServerIn) =>\n request<McpServer>(\"/mcp-servers\", { method: \"POST\", body: JSON.stringify(data) }),\n update: (name: string, data: Partial<McpServerIn>) =>\n request<McpServer>(`/mcp-servers/${encodeURIComponent(name)}`, { method: \"PUT\", body: JSON.stringify(data) }),\n delete: (name: string) =>\n request<{ deleted: boolean }>(`/mcp-servers/${encodeURIComponent(name)}`, { method: \"DELETE\" }),\n registry: (params?: { q?: string; cursor?: string; fresh?: boolean }) => {\n const qs = new URLSearchParams();\n if (params?.q) qs.set(\"q\", params.q);\n if (params?.cursor) qs.set(\"cursor\", params.cursor);\n if (params?.fresh) qs.set(\"fresh\", \"1\");\n const suffix = qs.toString() ? `?${qs}` : \"\";\n return request<{ entries: McpRegistryEntry[]; nextCursor?: string }>(`/mcp-servers/registry${suffix}`);\n },\n },\n\n integrations: {\n list: () => request<IntegrationsListResponse>(\"/integrations\"),\n save: (name: string, values: Record<string, string>) =>\n request<IntegrationStatus>(`/integrations/${encodeURIComponent(name)}`, {\n method: \"PUT\", body: JSON.stringify(values),\n }),\n delete: (name: string) =>\n request<{ deleted: boolean }>(`/integrations/${encodeURIComponent(name)}`, { method: \"DELETE\" }),\n test: (name: string) =>\n request<{ ok: boolean; error?: string; detail?: Record<string, unknown> }>(\n `/integrations/${encodeURIComponent(name)}/test`, { method: \"POST\", body: \"{}\" },\n ),\n gmailOauthStart: (creds: { client_id?: string; client_secret?: string }) =>\n request<{ authorize_url: string; state: string; redirect_uri: string }>(\n `/integrations/gmail/oauth/start`,\n { method: \"POST\", body: JSON.stringify(creds) },\n ),\n gmailOauthStatus: (state: string) =>\n request<{ status: \"pending\" | \"done\" | \"error\" | \"unknown\"; error?: string }>(\n `/integrations/gmail/oauth/status?state=${encodeURIComponent(state)}`,\n ),\n outlookOauthStart: (creds: { client_id?: string; client_secret?: string }) =>\n request<{ authorize_url: string; state: string; redirect_uri: string }>(\n `/integrations/outlook/oauth/start`,\n { method: \"POST\", body: JSON.stringify(creds) },\n ),\n outlookOauthStatus: (state: string) =>\n request<{ status: \"pending\" | \"done\" | \"error\" | \"unknown\"; error?: string }>(\n `/integrations/outlook/oauth/status?state=${encodeURIComponent(state)}`,\n ),\n },\n\n envSync: {\n preview: () => request<EnvSyncResult>(\"/env-sync\"),\n apply: () => request<EnvSyncResult>(\"/env-sync\", { method: \"POST\", body: \"{}\" }),\n allowlist: {\n get: () => request<EnvAllowlistConfig>(\"/env-sync/allowlist\"),\n set: (integration: string, field: string, envVars: string[]) =>\n request<EnvAllowlistConfig>(\"/env-sync/allowlist\", {\n method: \"PUT\",\n body: JSON.stringify({ integration, field, envVars }),\n }),\n },\n },\n\n pending: {\n list: (status?: \"pending\" | \"approved\" | \"denied\" | \"failed\") =>\n request<PendingAction[]>(`/pending-actions${status ? `?status=${status}` : \"\"}`),\n // ADR-0010: `extras` carries approval-time secret material (provider keys,\n // integration credentials) that the agent never sees. The route forwards\n // it to applyAction; the agent's pending_actions.payload stays clean.\n approve: (id: string, extras?: Record<string, unknown>) =>\n request<PendingAction>(\n `/pending-actions/${encodeURIComponent(id)}/approve`,\n { method: \"POST\", body: JSON.stringify(extras ? { extras } : {}) },\n ),\n deny: (id: string) =>\n request<PendingAction>(`/pending-actions/${encodeURIComponent(id)}/deny`, { method: \"POST\", body: \"{}\" }),\n },\n\n scheduledTasks: {\n list: (agent_id?: string) =>\n request<ScheduledTask[]>(`/scheduled-tasks${agent_id ? `?agent_id=${encodeURIComponent(agent_id)}` : \"\"}`),\n // ADR-0032 — patch supports the reaction discriminator. Mirrors the\n // watchers.update shape; explicit reaction_kind triggers a full replace.\n update: (id: string, patch: Partial<Pick<ScheduledTask, \"agent_id\" | \"prompt\" | \"description\" | \"kind\" | \"schedule\" | \"enabled\" | \"silent\">> & {\n reaction_kind?: \"agent_prompt\" | \"script\";\n reaction_script?: string | null;\n reaction_script_args?: Record<string, unknown> | null;\n }) =>\n request<ScheduledTask>(`/scheduled-tasks/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(patch) }),\n cancel: (id: string) =>\n request<{ deleted: boolean }>(`/scheduled-tasks/${encodeURIComponent(id)}`, { method: \"DELETE\" }),\n runNow: (id: string) =>\n request<{ accepted: boolean; task_id: string }>(`/scheduled-tasks/${encodeURIComponent(id)}/run`, { method: \"POST\", body: \"{}\" }),\n },\n\n // Event-driven watchers (ADR-0027). Polls a built-in tool every N\n // seconds; only fires the agent when the tool output changes.\n watchers: {\n list: (agent_id?: string) =>\n request<Watcher[]>(`/watchers${agent_id ? `?agent_id=${encodeURIComponent(agent_id)}` : \"\"}`),\n create: (data: {\n agent_id: string;\n label: string;\n tool: string;\n args?: Record<string, unknown>;\n every_seconds: number;\n silent?: boolean;\n reaction_kind?: \"agent_prompt\" | \"script\";\n reaction_prompt?: string | null;\n reaction_script?: string | null;\n reaction_script_args?: Record<string, unknown> | null;\n }) =>\n request<Watcher>(\"/watchers\", { method: \"POST\", body: JSON.stringify(data) }),\n update: (\n id: string,\n patch: Partial<{\n agent_id: string;\n label: string;\n interval_seconds: number;\n enabled: boolean;\n silent: boolean;\n reaction_kind: \"agent_prompt\" | \"script\";\n reaction_prompt: string | null;\n reaction_script: string | null;\n reaction_script_args: Record<string, unknown> | null;\n }>,\n ) =>\n request<Watcher>(`/watchers/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(patch) }),\n cancel: (id: string) =>\n request<{ deleted: boolean }>(`/watchers/${encodeURIComponent(id)}`, { method: \"DELETE\" }),\n runNow: (id: string) =>\n request<{ accepted: boolean; watcher_id: string }>(`/watchers/${encodeURIComponent(id)}/run`, { method: \"POST\", body: \"{}\" }),\n // ADR-0031: list registered reaction scripts (`reaction.*` namespace)\n // for the watcher UI's reaction-kind picker.\n listReactionScripts: () =>\n request<{ scripts: string[] }>(\"/watchers/reaction-scripts\"),\n },\n\n // Document RAG (ADR-0024). Folder sources are scanned by the scheduler\n // every ~10 minutes; the search endpoint is a thin wrapper over the\n // `documents_search` tool so callers can preview hits without invoking\n // an agent.\n documents: {\n listSources: () => request<DocumentSource[]>(\"/documents/sources\"),\n createSource: (data: DocumentSourceIn) =>\n request<DocumentSource>(\"/documents/sources\", { method: \"POST\", body: JSON.stringify(data) }),\n updateSource: (id: string, patch: DocumentSourcePatch) =>\n request<DocumentSource>(`/documents/sources/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(patch) }),\n deleteSource: (id: string) =>\n request<{ deleted: boolean }>(`/documents/sources/${encodeURIComponent(id)}`, { method: \"DELETE\" }),\n reindex: (id: string) =>\n request<DocumentReindexResult>(`/documents/sources/${encodeURIComponent(id)}/reindex`, { method: \"POST\", body: \"{}\" }),\n search: (q: string, opts?: { limit?: number; source_id?: string }) => {\n const p = new URLSearchParams({ q });\n if (opts?.limit) p.set(\"limit\", String(opts.limit));\n if (opts?.source_id) p.set(\"source_id\", opts.source_id);\n return request<{ query: string; hits: DocumentHit[] }>(`/documents/search?${p.toString()}`);\n },\n getSettings: () => request<DocumentSettings>(\"/documents/settings\"),\n setSettings: (patch: DocumentSettings) =>\n request<DocumentSettings>(\"/documents/settings\", { method: \"PUT\", body: JSON.stringify(patch) }),\n },\n\n // Filesystem browse — backs the folder-picker dialog in the Documents\n // panel. Lists immediate subdirectories at an absolute path.\n fs: {\n browse: (p?: string) => {\n const qs = p ? `?path=${encodeURIComponent(p)}` : \"\";\n return request<{\n path: string;\n parent: string | null;\n home: string;\n entries: { name: string; path: string }[];\n }>(`/fs/browse${qs}`);\n },\n },\n\n githubCopilotAuth: {\n status: () => request<{ signed_in: boolean; stored_at: string | null }>(\"/providers/github-copilot/auth\"),\n start: () => request<{ device_code: string; user_code: string; verification_uri: string; expires_in: number; interval: number }>(\n \"/providers/github-copilot/auth\", { method: \"POST\", body: \"{}\" },\n ),\n poll: (device_code: string) => request<{ status: string; access_token?: string; error?: string }>(\n \"/providers/github-copilot/auth\", { method: \"PUT\", body: JSON.stringify({ device_code }) },\n ),\n signOut: () => request<{ deleted: boolean }>(\"/providers/github-copilot/auth\", { method: \"DELETE\" }),\n },\n\n bridges: {\n list: () => request<Bridge[]>(\"/bridges\"),\n get: (id: string) => request<Bridge>(`/bridges/${encodeURIComponent(id)}`),\n create: (data: BridgeIn) =>\n request<Bridge>(\"/bridges\", { method: \"POST\", body: JSON.stringify(data) }),\n update: (id: string, patch: BridgePatch) =>\n request<Bridge>(`/bridges/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(patch) }),\n delete: (id: string) =>\n request<{ deleted: boolean }>(`/bridges/${encodeURIComponent(id)}`, { method: \"DELETE\" }),\n status: (id: string) => request<BridgeLiveStatus>(`/bridges/${encodeURIComponent(id)}/status`),\n pair: (id: string) =>\n request<{ accepted: boolean }>(`/bridges/${encodeURIComponent(id)}/pair`, { method: \"POST\", body: \"{}\" }),\n chats: (id: string) => request<BridgeChatsResponse>(`/bridges/${encodeURIComponent(id)}/chats`),\n lookup: (id: string, phone: string) =>\n request<{ chat: import(\"./types\").BridgeChat | null }>(\n `/bridges/${encodeURIComponent(id)}/lookup`,\n { method: \"POST\", body: JSON.stringify({ phone }) },\n ),\n\n routes: {\n list: (bridge_id: string) =>\n request<BridgeRoute[]>(`/bridges/${encodeURIComponent(bridge_id)}/routes`),\n create: (bridge_id: string, data: BridgeRouteIn) =>\n request<BridgeRoute>(`/bridges/${encodeURIComponent(bridge_id)}/routes`, {\n method: \"POST\", body: JSON.stringify(data),\n }),\n update: (bridge_id: string, route_id: string, patch: BridgeRoutePatch) =>\n request<BridgeRoute>(\n `/bridges/${encodeURIComponent(bridge_id)}/routes/${encodeURIComponent(route_id)}`,\n { method: \"PATCH\", body: JSON.stringify(patch) },\n ),\n delete: (bridge_id: string, route_id: string) =>\n request<{ deleted: boolean }>(\n `/bridges/${encodeURIComponent(bridge_id)}/routes/${encodeURIComponent(route_id)}`,\n { method: \"DELETE\" },\n ),\n },\n },\n\n tailscale: {\n status: () => request<import(\"./types\").TailscaleStatus>(\"/tailscale\"),\n },\n\n harnesses: {\n list: () => request<HarnessListResponse>(\"/harnesses\"),\n get: (id: string) => request<Harness>(`/harnesses/${encodeURIComponent(id)}`),\n create: (data: HarnessIn) =>\n request<Harness>(\"/harnesses\", { method: \"POST\", body: JSON.stringify(data) }),\n update: (id: string, patch: HarnessPatch) =>\n request<Harness>(`/harnesses/${encodeURIComponent(id)}`, {\n method: \"PATCH\",\n body: JSON.stringify(patch),\n }),\n delete: (id: string) =>\n request<{ deleted: boolean }>(`/harnesses/${encodeURIComponent(id)}`, { method: \"DELETE\" }),\n setDefault: (id: string) =>\n request<{ id: string }>(\"/harnesses/default\", {\n method: \"PUT\",\n body: JSON.stringify({ id }),\n }),\n },\n\n proxy: {\n get: () => request<import(\"./types\").ProxyConfigEnvelope>(\"/proxy-config\"),\n save: (input: import(\"./types\").ProxyConfigInput) =>\n request<import(\"./types\").ProxyConfigEnvelope>(\"/proxy-config\", {\n method: \"PUT\",\n body: JSON.stringify(input),\n }),\n clear: () =>\n request<import(\"./types\").ProxyConfigEnvelope & { deleted: boolean }>(\"/proxy-config\", {\n method: \"DELETE\",\n }),\n },\n};\n\n\n// ---------------------------------------------------------------------------\n// Agent run streaming — CQRS transport (ADR-0008)\n// ---------------------------------------------------------------------------\n//\n// One turn = one POST (submit) + one EventSource (subscribe). The previous\n// WS sidecar / SSE-over-POST / SSE-GET-reattach trio is gone; EventSource\n// is the only WebKit-native streaming primitive that survives iOS Safari +\n// HTTP/2 reverse-proxies (Tailscale serve), so we route every browser\n// through it.\n\nexport interface SubmitResult {\n /** true iff the server accepted ownership of this turn (HTTP 202). */\n accepted: boolean;\n /** Present on non-2xx outcomes. `run_in_flight` = another tab/device\n * owns the current turn; caller should re-queue and still subscribe to\n * observe live deltas. */\n code?: \"run_in_flight\" | string;\n error?: string;\n}\n\n/** POST /threads/:id/run — registers a run and returns immediately. The\n * caller is expected to follow up with `subscribeRun()` to receive the\n * chunk stream. Idempotent in the sense that two simultaneous submissions\n * for the same thread will see one 202 and one 409 (`run_in_flight`). */\nexport async function submitRun(\n thread_id: string,\n message: string,\n signal: AbortSignal,\n stream_options?: StreamOptions,\n attachments?: ContentPart[],\n hot_since?: string | null,\n): Promise<SubmitResult> {\n const res = await fetch(`${BASE}/threads/${thread_id}/run`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ message, stream_options, attachments, hot_since }),\n signal,\n });\n // 2xx = accepted (currently always 202); 409 = already running. We treat\n // every other status as a hard error so the consumer's catch fires.\n if (res.status === 202) {\n // Drain the body to free the connection — Next.js sends a small JSON\n // ack but we don't need anything from it.\n try { await res.json(); } catch { /* ignore */ }\n return { accepted: true };\n }\n let body: { code?: string; error?: string } = {};\n try { body = (await res.json()) as { code?: string; error?: string }; } catch { /* */ }\n if (res.status === 409) {\n return { accepted: false, code: body.code ?? \"run_in_flight\" };\n }\n throw new Error(`${res.status} ${body.error ?? res.statusText}`);\n}\n\n/** GET /threads/:id/run — opens an `EventSource` and yields raw `data:`\n * payloads (one JSON event per yield). Closes the source when the consumer\n * stops iterating (either via `break` after a terminal `done`/`error`, or\n * when the abort signal fires).\n *\n * EventSource handles its own reconnection on transient drops. The\n * server-side run keeps publishing into the registry across drops, so a\n * resumed connection replays buffered chunks via `subscribe()` and the\n * consumer sees the run through to its terminal event.\n *\n * `stream_options` filter flags ride as query params (`show_tools`,\n * `show_thinking`); the rest of `StreamOptions` is meaningful only on the\n * POST and is ignored here.\n */\nexport function subscribeRun(\n thread_id: string,\n signal: AbortSignal,\n stream_options?: StreamOptions,\n): AsyncGenerator<string> {\n const params = new URLSearchParams();\n const includeTools = stream_options?.filters?.include_tools;\n const includeThinking = stream_options?.filters?.include_thinking;\n if (includeTools === false) params.set(\"show_tools\", \"false\");\n if (includeThinking === false) params.set(\"show_thinking\", \"false\");\n const qs = params.toString();\n const url = `${BASE}/threads/${thread_id}/run${qs ? `?${qs}` : \"\"}`;\n\n return (async function* () {\n const queue: string[] = [];\n const waiters: Array<() => void> = [];\n let done = false;\n let streamError: Error | null = null;\n const notify = () => { while (waiters.length > 0) waiters.shift()?.(); };\n\n const es = new EventSource(url, { withCredentials: true });\n es.onmessage = (e) => {\n if (typeof e.data === \"string\") {\n queue.push(e.data);\n try {\n const parsed = JSON.parse(e.data) as { type?: string };\n if (parsed.type === \"done\" || parsed.type === \"error\") {\n done = true;\n }\n } catch { /* let consumer surface parse errors */ }\n notify();\n }\n };\n // EventSource auto-reconnects on transient network drops. We only treat\n // it as a hard error if the *first* connect attempt fails (no successful\n // 'open' ever fired) — anything after that is a recoverable drop and\n // the server's replay buffer will deliver missed chunks on reconnect.\n // EXCEPT when the browser flips readyState to CLOSED — that's the spec's\n // terminal state (e.g. the reconnect attempt got a 404 because the run\n // finished + TTL-evicted), and no further events will ever arrive. If\n // we ignored that case the consumer would hang on the waiter forever\n // and the UI activity label (\"Reconnecting…\") would never clear.\n let everOpened = false;\n es.onopen = () => {\n everOpened = true;\n if (connectTimer !== null) {\n clearTimeout(connectTimer);\n connectTimer = null;\n }\n };\n es.onerror = () => {\n if (es.readyState === EventSource.CLOSED) {\n done = true;\n notify();\n return;\n }\n if (!everOpened) {\n streamError = new Error(\"EventSource failed to open\");\n done = true;\n notify();\n }\n // else: ignore — EventSource will try to reconnect.\n };\n\n // Connect-timeout safety net: if onopen hasn't fired within the\n // configured window the server is unreachable (DNS, TLS handshake\n // stuck, proxy black-holing the GET, dev-server still compiling the\n // route, …). EventSource alone won't surface that — it stays in\n // CONNECTING forever, retrying silently. Force the iterator to fail\n // so the caller's catch/finally can release the UI gate. The window\n // is tunable via JARELA_SSE_CONNECT_TIMEOUT_MS (default 30s) so dev\n // cold-compiles and slow proxies don't false-positive.\n const connectTimeoutMs = runtimeConfig().sseConnectTimeoutMs;\n let connectTimer: ReturnType<typeof setTimeout> | null = setTimeout(() => {\n connectTimer = null;\n if (!everOpened && !done) {\n // User-facing: this surfaces verbatim in the chat error toast via\n // useSSE → setError(String(err)). Avoid jargon (\"EventSource\") and\n // name the actual symptom — the server didn't open the response\n // stream within the connect window.\n streamError = new Error(\n `Connection timed out — the server didn't respond within ${Math.round(connectTimeoutMs / 1000)}s.`,\n );\n done = true;\n try { es.close(); } catch { /* */ }\n notify();\n }\n }, connectTimeoutMs);\n\n const onAbort = () => {\n done = true;\n if (connectTimer !== null) {\n clearTimeout(connectTimer);\n connectTimer = null;\n }\n try { es.close(); } catch { /* */ }\n notify();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n\n try {\n while (!done || queue.length > 0) {\n if (queue.length > 0) {\n yield queue.shift() as string;\n continue;\n }\n if (streamError) throw streamError;\n await new Promise<void>((resolve) => waiters.push(resolve));\n }\n if (streamError) throw streamError;\n } finally {\n if (connectTimer !== null) clearTimeout(connectTimer);\n signal.removeEventListener(\"abort\", onAbort);\n try { es.close(); } catch { /* */ }\n }\n })();\n}","\"use client\";\nimport { Braces, Eye, FileText, Globe, Mic, Wrench, Zap, type LucideIcon } from \"lucide-react\";\nimport { modelCapabilities, type ModelCapabilities } from \"@/lib/providers/capabilities\";\n\ntype CapKey = keyof ModelCapabilities;\n\nconst CAP_META: Record<CapKey, { icon: LucideIcon; label: string }> = {\n vision: { icon: Eye, label: \"Vision (image input)\" },\n files: { icon: FileText, label: \"File / document input\" },\n audio: { icon: Mic, label: \"Audio / voice input\" },\n tools: { icon: Wrench, label: \"Tool calling\" },\n web_search: { icon: Globe, label: \"Built-in web search\" },\n json_mode: { icon: Braces, label: \"Structured JSON output\" },\n streaming: { icon: Zap, label: \"Streaming responses\" },\n};\n\nconst CAP_ORDER: CapKey[] = [\"vision\", \"files\", \"audio\", \"tools\", \"web_search\", \"json_mode\", \"streaming\"];\n\ninterface Props {\n caps?: ModelCapabilities;\n provider?: string;\n modelId?: string;\n size?: \"xs\" | \"sm\";\n}\n\nexport function CapBadges({ caps, provider, modelId, size = \"xs\" }: Props) {\n const resolved = caps ?? (provider && modelId ? modelCapabilities(provider, modelId) : null);\n if (!resolved) return null;\n const active = CAP_ORDER.filter((k) => resolved[k]);\n if (!active.length) return null;\n const box = size === \"sm\" ? \"w-5 h-5\" : \"w-4 h-4\";\n const icon = size === \"sm\" ? \"w-3 h-3\" : \"w-2.5 h-2.5\";\n return (\n <span className=\"inline-flex flex-wrap gap-0.5 align-middle\">\n {active.map((k) => {\n const { icon: Icon, label } = CAP_META[k];\n return (\n <span\n key={k}\n title={label}\n aria-label={label}\n className={`inline-flex items-center justify-center ${box} rounded bg-surface text-fg-subtle border border-border`}\n >\n <Icon className={icon} strokeWidth={2} aria-hidden />\n </span>\n );\n })}\n </span>\n );\n}\n","\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { Logo } from \"@/components/ui/Logo\";\n\n// PIN unlock splash for ADR-0063 PIN-wrapped keyfiles. Rendered by the\n// root route when the server detects the master key is locked. Submits\n// the 6-digit PIN to /api/v1/security/unlock; on success, reloads so\n// the server re-renders into the normal authenticated tree.\n\nconst PIN_LENGTH = 6;\n\nexport function UnlockScreen() {\n const [digits, setDigits] = useState(\"\");\n const [error, setError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n const [retryAfterSec, setRetryAfterSec] = useState(0);\n const containerRef = useRef<HTMLDivElement>(null);\n // Hard guard against parallel submits. setState updaters can run more\n // than once (dev StrictMode, concurrent rendering), so if `submit`\n // were called from inside `setDigits` we'd POST twice and the second\n // request would race the first into `unlockMasterKey()` after state\n // already flipped to unlocked - the route would 500.\n const submittingRef = useRef(false);\n\n const submit = useCallback(async (pin: string) => {\n if (submittingRef.current) return;\n submittingRef.current = true;\n setSubmitting(true);\n setError(null);\n try {\n const res = await fetch(\"/api/v1/security/unlock\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ pin }),\n });\n if (res.ok) {\n window.location.reload();\n return;\n }\n const body = (await res.json().catch(() => ({}))) as {\n error?: string;\n retry_after_ms?: number;\n };\n if (res.status === 409 && body.error === \"not-locked\") {\n // Master key was already unlocked (host typed the PIN, or\n // another tab beat us to it). The goal state is reached —\n // reload into the app shell.\n window.location.reload();\n return;\n }\n if (res.status === 429 && typeof body.retry_after_ms === \"number\") {\n setRetryAfterSec(Math.ceil(body.retry_after_ms / 1000));\n setError(\"Too many attempts. Try again later.\");\n } else if (res.status === 401) {\n setError(\"Wrong PIN. Try again.\");\n } else if (res.status === 400) {\n setError(\"Invalid PIN format.\");\n } else {\n setError(body.error ?? `Error (${res.status})`);\n }\n setDigits(\"\");\n } catch (err) {\n setError(err instanceof Error ? err.message : String(err));\n setDigits(\"\");\n } finally {\n submittingRef.current = false;\n setSubmitting(false);\n }\n }, []);\n\n const append = useCallback((d: string) => {\n if (submitting || retryAfterSec > 0) return;\n setError(null);\n setDigits((cur) => (cur.length >= PIN_LENGTH ? cur : cur + d));\n }, [submitting, retryAfterSec]);\n\n // Auto-submit once the buffer hits 6 digits. Effect runs once per\n // state transition (not per updater invocation), so we POST exactly\n // one time even under StrictMode double-render.\n useEffect(() => {\n if (digits.length === PIN_LENGTH && !submittingRef.current) {\n void submit(digits);\n }\n }, [digits, submit]);\n\n const backspace = useCallback(() => {\n if (submitting) return;\n setError(null);\n setDigits((cur) => cur.slice(0, -1));\n }, [submitting]);\n\n // Physical keyboard support.\n useEffect(() => {\n function onKey(e: KeyboardEvent) {\n if (/^[0-9]$/.test(e.key)) {\n e.preventDefault();\n append(e.key);\n } else if (e.key === \"Backspace\") {\n e.preventDefault();\n backspace();\n }\n }\n window.addEventListener(\"keydown\", onKey);\n return () => window.removeEventListener(\"keydown\", onKey);\n }, [append, backspace]);\n\n // Tick down the rate-limit countdown.\n useEffect(() => {\n if (retryAfterSec <= 0) return;\n const t = setInterval(() => {\n setRetryAfterSec((s) => (s > 0 ? s - 1 : 0));\n }, 1000);\n return () => clearInterval(t);\n }, [retryAfterSec]);\n\n return (\n <div\n ref={containerRef}\n className=\"fixed inset-0 z-[1000] flex flex-col items-center justify-center gap-6 bg-surface text-fg\"\n style={{\n paddingTop: \"env(safe-area-inset-top)\",\n paddingBottom: \"env(safe-area-inset-bottom)\",\n }}\n >\n <Logo className=\"h-16 w-auto\" />\n <div className=\"w-full max-w-xs p-6\">\n <h1 className=\"mb-1 text-center text-lg font-semibold text-fg\">\n Unlock Jarela\n </h1>\n <p className=\"mb-6 text-center text-xs text-fg-faint\">\n Enter your 6-digit PIN to decrypt your data.\n </p>\n\n <div className=\"mb-6 flex justify-center gap-3\" aria-label=\"PIN entry progress\">\n {Array.from({ length: PIN_LENGTH }).map((_, i) => (\n <span\n key={i}\n className={`h-3 w-3 rounded-full transition-colors ${\n i < digits.length\n ? error\n ? \"bg-red-500\"\n : \"bg-fg\"\n : \"bg-surface-3\"\n }`}\n />\n ))}\n </div>\n\n <div className=\"grid grid-cols-3 gap-2\">\n {[\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"].map((d) => (\n <PinKey key={d} digit={d} onPress={() => append(d)} disabled={submitting || retryAfterSec > 0} />\n ))}\n <div />\n <PinKey digit=\"0\" onPress={() => append(\"0\")} disabled={submitting || retryAfterSec > 0} />\n <PinKey digit=\"←\" onPress={backspace} disabled={submitting || digits.length === 0} ariaLabel=\"Backspace\" />\n </div>\n\n <p\n className={`mt-4 min-h-[1.5rem] text-center text-xs ${\n error ? \"text-red-400\" : \"text-fg-faint\"\n }`}\n role=\"status\"\n aria-live=\"polite\"\n >\n {retryAfterSec > 0\n ? `Try again in ${retryAfterSec}s`\n : error ?? (submitting ? \"Unlocking…\" : \"\\u00A0\")}\n </p>\n </div>\n </div>\n );\n}\n\nfunction PinKey({\n digit,\n onPress,\n disabled,\n ariaLabel,\n}: {\n digit: string;\n onPress: () => void;\n disabled: boolean;\n ariaLabel?: string;\n}) {\n return (\n <button\n type=\"button\"\n onClick={onPress}\n disabled={disabled}\n aria-label={ariaLabel ?? digit}\n className=\"h-14 rounded-xl bg-surface-3 text-xl font-medium text-fg transition-colors hover:bg-surface-3/70 active:bg-surface-3/50 disabled:cursor-not-allowed disabled:opacity-50\"\n >\n {digit}\n </button>\n );\n}\n","\"use client\";\nimport { createContext, useContext, useEffect, useReducer, type ReactNode } from \"react\";\n\nexport type ExperienceMode = \"essential\" | \"full\";\n\nconst EXPERIENCE_MODE_KEY = \"jarela.experience.mode\";\n\n// Back-compat: pre-rename builds stored \"normal\" / \"advanced\". Read those\n// values silently so an upgrade does not reset the user's choice.\nfunction parseStoredMode(raw: string | null): ExperienceMode | null {\n if (raw === \"essential\" || raw === \"normal\") return \"essential\";\n if (raw === \"full\" || raw === \"advanced\") return \"full\";\n return null;\n}\n\nexport type Tab = \"chat\" | \"dashboard\" | \"agents\" | \"memory\" | \"documents\" | \"models\" | \"credentials\" | \"mcp\" | \"extensions\" | \"tools\" | \"tasks\" | \"bridges\" | \"profile\" | \"harness\" | \"logs\" | \"env\";\n\ninterface AppState {\n activeThreadId: string | null;\n activeAgentId: string | null;\n activeTab: Tab;\n experienceMode: ExperienceMode;\n // Per-tab sub-selection (a sub-tab key under credentials, an mcp server name, an\n // agent uuid, a profile subsection slug, …). Settings panels read their\n // slot to scroll-to + highlight; the URL mirrors this via `?item=<id>`.\n selectedItem: Partial<Record<Tab, string>>;\n}\n\ntype Action =\n | { type: \"SELECT_THREAD\"; threadId: string; agentId: string }\n | { type: \"NEW_CHAT\" }\n | { type: \"SET_AGENT\"; agentId: string }\n | { type: \"SET_TAB\"; tab: Tab }\n | { type: \"SET_EXPERIENCE_MODE\"; mode: ExperienceMode }\n | { type: \"SET_SELECTION\"; tab: Tab; itemId: string | null };\n\nfunction reducer(state: AppState, action: Action): AppState {\n switch (action.type) {\n case \"SELECT_THREAD\":\n return { ...state, activeThreadId: action.threadId, activeAgentId: action.agentId, activeTab: \"chat\" };\n case \"NEW_CHAT\":\n return { ...state, activeThreadId: null, activeAgentId: null, activeTab: \"chat\" };\n case \"SET_AGENT\":\n return { ...state, activeAgentId: action.agentId };\n case \"SET_TAB\":\n return { ...state, activeTab: action.tab };\n case \"SET_EXPERIENCE_MODE\":\n return { ...state, experienceMode: action.mode };\n case \"SET_SELECTION\": {\n const next = { ...state.selectedItem };\n if (action.itemId == null) delete next[action.tab];\n else next[action.tab] = action.itemId;\n return { ...state, selectedItem: next };\n }\n }\n}\n\nconst AppContext = createContext<{ state: AppState; dispatch: React.Dispatch<Action> } | null>(null);\n\nexport function AppProvider({ children }: { children: ReactNode }) {\n const [state, dispatch] = useReducer(reducer, {\n activeThreadId: null,\n activeAgentId: null,\n activeTab: \"chat\",\n experienceMode: \"essential\",\n selectedItem: {},\n });\n\n useEffect(() => {\n try {\n const stored = parseStoredMode(window.localStorage.getItem(EXPERIENCE_MODE_KEY));\n if (stored) {\n dispatch({ type: \"SET_EXPERIENCE_MODE\", mode: stored });\n }\n } catch {\n // ignore storage failures\n }\n }, []);\n\n useEffect(() => {\n try {\n window.localStorage.setItem(EXPERIENCE_MODE_KEY, state.experienceMode);\n } catch {\n // ignore storage failures\n }\n }, [state.experienceMode]);\n\n return <AppContext.Provider value={{ state, dispatch }}>{children}</AppContext.Provider>;\n}\n\nexport function useAppContext() {\n const ctx = useContext(AppContext);\n if (!ctx) throw new Error(\"useAppContext must be used within AppProvider\");\n return ctx;\n}\n","\"use client\";\n\nimport { Bot, Brain, Briefcase, CheckCircle2, Code2, Database, ExternalLink, Image as ImageIcon, Loader2, Mic, ShieldCheck, Sparkles, UserRound, Wand2, XCircle } from \"lucide-react\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport { api } from \"@/api/client\";\nimport type { AgentConfig, IntegrationStatus, ModelConfig, UserProfile } from \"@/api/types\";\nimport { useAppContext } from \"@/contexts/AppContext\";\nimport { getAppName } from \"@/lib/env/app-config\";\nimport { ModelFeatureGuide } from \"@/components/models/ModelFeatureGuide\";\nimport { Logo } from \"@/components/ui/Logo\";\nimport { MarkdownTextarea } from \"@/components/ui/MarkdownTextarea\";\n\ntype Provider = \"anthropic\" | \"openai\" | \"gemini\" | \"deepseek\";\n\nconst PROVIDER_INFO: Record<\n Provider,\n { label: string; signupUrl: string; placeholder: string; defaultModel: string; hint: string }\n> = {\n anthropic: {\n label: \"Anthropic (Claude)\",\n signupUrl: \"https://console.anthropic.com/settings/keys\",\n placeholder: \"sk-ant-…\",\n defaultModel: \"claude-opus-4-7\",\n hint: \"Strong writing and reasoning. Good default if you want a focused assistant.\",\n },\n openai: {\n label: \"OpenAI (GPT)\",\n signupUrl: \"https://platform.openai.com/api-keys\",\n placeholder: \"sk-…\",\n defaultModel: \"gpt-4o\",\n hint: \"Balanced general-purpose setup with broad capability coverage.\",\n },\n gemini: {\n label: \"Google (Gemini)\",\n signupUrl: \"https://aistudio.google.com/apikey\",\n placeholder: \"AIza…\",\n defaultModel: \"gemini-2.5-pro\",\n hint: \"Best fit if you want voice and Google-powered multimodal features with one key.\",\n },\n deepseek: {\n label: \"DeepSeek\",\n signupUrl: \"https://platform.deepseek.com/api_keys\",\n placeholder: \"sk-…\",\n defaultModel: \"deepseek-chat\",\n hint: \"Lean and capable text setup when you want a simpler provider choice.\",\n },\n};\n\nconst PROVIDER_SIGNALS: Record<Provider, {\n image: \"strong\" | \"partial\" | \"limited\";\n voice: \"strong\" | \"partial\" | \"limited\";\n embeddings: \"strong\" | \"partial\" | \"limited\";\n coding: \"strong\" | \"partial\" | \"limited\";\n recommendation: string;\n}> = {\n anthropic: {\n image: \"strong\",\n voice: \"limited\",\n embeddings: \"limited\",\n coding: \"strong\",\n recommendation: \"Excellent coding copilot style responses; pair with a separate embeddings path if Documents recall is critical.\",\n },\n openai: {\n image: \"strong\",\n voice: \"partial\",\n embeddings: \"strong\",\n coding: \"strong\",\n recommendation: \"Best all-round baseline when you want one provider to cover coding plus embeddings-driven workflows.\",\n },\n gemini: {\n image: \"strong\",\n voice: \"strong\",\n embeddings: \"strong\",\n coding: \"strong\",\n recommendation: \"Strong single-provider setup for multimodal + voice without splitting credentials.\",\n },\n deepseek: {\n image: \"limited\",\n voice: \"limited\",\n embeddings: \"limited\",\n coding: \"strong\",\n recommendation: \"Great text/coding value path; pair with another provider if you need richer multimodal or embeddings.\",\n },\n};\n\nfunction signalTone(level: \"strong\" | \"partial\" | \"limited\"): string {\n if (level === \"strong\") return \"border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300\";\n if (level === \"partial\") return \"border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300\";\n return \"border-border bg-surface-3 text-fg-faint\";\n}\n\nconst PROFILE_PRESETS: Array<{ value: NonNullable<UserProfile[\"preset\"]>; label: string; hint: string }> = [\n { value: \"home\", label: \"Home\", hint: \"Personal AI, mail, calendar, and everyday tasks\" },\n { value: \"work\", label: \"Work\", hint: \"Project coordination, docs, issues, and team workflows\" },\n { value: \"dev\", label: \"Developer\", hint: \"Coding, debugging, tools, and infrastructure-heavy usage\" },\n { value: \"custom\", label: \"Everything\", hint: \"Show the full surface without category filtering\" },\n];\n\nconst AGENT_STYLES = {\n assistant: {\n label: \"General Assistant\",\n hint: \"Balanced help across chat, research, and daily tasks\",\n icon: Sparkles,\n identity: \"You are a practical personal assistant. Be clear, concise, and helpful. Focus on getting the user unstuck quickly.\",\n instructions: \"Prefer straightforward answers, ask only necessary follow-up questions, and keep technical detail proportional to the user's request.\",\n },\n builder: {\n label: \"Builder\",\n hint: \"Best when you mostly use the app for coding and implementation\",\n icon: Wand2,\n identity: \"You are a pragmatic software builder who turns vague requests into concrete implementation steps.\",\n instructions: \"Bias toward implementation, explain tradeoffs briefly, and keep momentum high on technical tasks.\",\n },\n researcher: {\n label: \"Research Partner\",\n hint: \"Good for synthesis, comparisons, and exploration\",\n icon: Brain,\n identity: \"You are a research partner who organizes information clearly and highlights the strongest options.\",\n instructions: \"Structure findings cleanly, surface tradeoffs, and focus on decision support instead of raw data dumps.\",\n },\n operator: {\n label: \"Work Coordinator\",\n hint: \"Better for work streams, follow-ups, and operational tasks\",\n icon: Briefcase,\n identity: \"You are an operational coordinator who keeps work moving and communicates with calm clarity.\",\n instructions: \"Prioritize action items, summarize status clearly, and help the user track what matters next.\",\n },\n} as const;\n\ntype AgentStyle = keyof typeof AGENT_STYLES;\n\ninterface TestResult {\n ok: boolean;\n models?: string[];\n error?: string;\n}\n\ninterface Props {\n context: \"setup\" | \"profile\";\n}\n\nfunction supportedProvider(value: string | null | undefined): Provider {\n if (value === \"anthropic\" || value === \"openai\" || value === \"gemini\" || value === \"deepseek\") return value;\n return \"anthropic\";\n}\n\nfunction syntheticGoogleIntegration(): IntegrationStatus {\n return {\n name: \"google\",\n configured: true,\n values: {},\n updated_at: null,\n };\n}\n\nexport function OnboardingWizard({ context }: Props) {\n const { state, dispatch } = useAppContext();\n const [loading, setLoading] = useState(true);\n const [profile, setProfile] = useState<UserProfile | null>(null);\n const [models, setModels] = useState<ModelConfig[]>([]);\n const [agents, setAgents] = useState<AgentConfig[]>([]);\n const [integrations, setIntegrations] = useState<IntegrationStatus[]>([]);\n\n const [name, setName] = useState(\"\");\n const [about, setAbout] = useState(\"\");\n const [preset, setPreset] = useState<NonNullable<UserProfile[\"preset\"]>>(\"home\");\n const [provider, setProvider] = useState<Provider>(\"anthropic\");\n const [apiKey, setApiKey] = useState(\"\");\n const [modelId, setModelId] = useState(PROVIDER_INFO.anthropic.defaultModel);\n const [availableModels, setAvailableModels] = useState<string[]>([]);\n const [test, setTest] = useState<TestResult | null>(null);\n const [testing, setTesting] = useState(false);\n const [reuseGoogleKey, setReuseGoogleKey] = useState(true);\n const [useAsChatDefault, setUseAsChatDefault] = useState(true);\n const [useAsEmbeddingDefault, setUseAsEmbeddingDefault] = useState(true);\n const [useAsVoicePath, setUseAsVoicePath] = useState(true);\n const [agentName, setAgentName] = useState(\"My Assistant\");\n const [agentStyle, setAgentStyle] = useState<AgentStyle>(\"assistant\");\n const [voiceEnabled, setVoiceEnabled] = useState(false);\n const [saving, setSaving] = useState(false);\n const [saveError, setSaveError] = useState<string | null>(null);\n\n useEffect(() => {\n let cancelled = false;\n async function load() {\n setLoading(true);\n try {\n const [profileData, modelRows, agentRows, integrationRows] = await Promise.all([\n api.profile.get().catch(() => null),\n api.models.list().catch(() => []),\n api.agents.list().catch(() => []),\n api.integrations.list().then((res) => res.statuses).catch(() => []),\n ]);\n if (cancelled) return;\n\n const defaultModel = modelRows.find((row) => row.is_default) ?? modelRows[0] ?? null;\n const defaultAgent = agentRows.find((row) => row.is_default) ?? agentRows[0] ?? null;\n\n setProfile(profileData);\n setModels(modelRows);\n setAgents(agentRows);\n setIntegrations(integrationRows);\n\n setName(profileData?.name ?? \"\");\n setAbout(profileData?.about ?? \"\");\n setPreset((profileData?.preset as NonNullable<UserProfile[\"preset\"]> | null) ?? \"home\");\n\n const resolvedProvider = supportedProvider(defaultModel?.provider);\n setProvider(resolvedProvider);\n setApiKey(typeof defaultModel?.params.api_key === \"string\" ? defaultModel.params.api_key : \"\");\n setModelId(defaultModel?.model_id ?? PROVIDER_INFO[resolvedProvider].defaultModel);\n\n setAgentName(defaultAgent?.name ?? `${profileData?.name?.trim() || \"My\"} Assistant`);\n setVoiceEnabled(defaultAgent?.voice_enabled ?? false);\n setUseAsChatDefault(defaultModel?.is_default ?? true);\n setUseAsEmbeddingDefault(true);\n setUseAsVoicePath(defaultAgent?.voice_enabled ?? true);\n } finally {\n if (!cancelled) setLoading(false);\n }\n }\n void load();\n return () => {\n cancelled = true;\n };\n }, []);\n\n const activeModel = models.find((row) => row.is_default) ?? models[0] ?? null;\n const activeAgent = agents.find((row) => row.is_default) ?? agents[0] ?? null;\n const providerInfo = PROVIDER_INFO[provider];\n const providerSignals = PROVIDER_SIGNALS[provider];\n const effectiveIntegrations = useMemo(() => {\n if (provider === \"gemini\" && reuseGoogleKey && apiKey.trim()) {\n const hasGoogle = integrations.some((status) => status.name === \"google\" && status.configured);\n return hasGoogle ? integrations : [...integrations, syntheticGoogleIntegration()];\n }\n return integrations;\n }, [apiKey, integrations, provider, reuseGoogleKey]);\n const modelReady = !!modelId.trim() && (!!test?.ok || (activeModel != null && apiKey.trim().length > 0));\n const canSave = name.trim().length > 0 && agentName.trim().length > 0 && modelReady;\n\n function chooseProvider(next: Provider) {\n setProvider(next);\n setModelId(PROVIDER_INFO[next].defaultModel);\n setAvailableModels([]);\n setTest(null);\n setSaveError(null);\n if (next !== \"gemini\") setVoiceEnabled(false);\n }\n\n async function runTest() {\n if (!apiKey.trim()) return;\n setTesting(true);\n setTest(null);\n setSaveError(null);\n try {\n const res = await fetch(\"/api/v1/setup/test-key\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ provider, api_key: apiKey.trim() }),\n });\n const data = (await res.json()) as TestResult;\n setTest(data);\n setAvailableModels(data.models ?? []);\n if (data.ok && data.models && data.models.length > 0 && !data.models.includes(modelId)) {\n setModelId(data.models[0]);\n }\n } catch (err) {\n setTest({ ok: false, error: `network error: ${err instanceof Error ? err.message : String(err)}` });\n } finally {\n setTesting(false);\n }\n }\n\n async function handleSave() {\n if (!canSave) return;\n setSaving(true);\n setSaveError(null);\n try {\n const updatedProfile = await api.profile.update({ name: name.trim(), about: about.trim(), preset });\n setProfile(updatedProfile);\n\n const modelName = activeModel?.name ?? `${provider}-default`;\n const modelPayload = {\n provider,\n model_id: modelId.trim(),\n params: {\n ...(activeModel?.params ?? {}),\n api_key: apiKey.trim(),\n },\n is_default: useAsChatDefault || !activeModel,\n };\n const savedModel = activeModel\n ? await api.models.update(modelName, modelPayload)\n : await api.models.create(modelName, modelPayload);\n\n if (useAsEmbeddingDefault) {\n await api.documents.setSettings({ embedding_model_config: savedModel.name });\n }\n\n if (provider === \"gemini\" && reuseGoogleKey && apiKey.trim()) {\n await api.integrations.save(\"google\", { api_key: apiKey.trim() });\n }\n\n const style = AGENT_STYLES[agentStyle];\n const agentPayload = {\n name: agentName.trim(),\n identity: style.identity,\n instructions: style.instructions,\n model_config_name: savedModel.name,\n is_default: true,\n voice_enabled: provider === \"gemini\" && reuseGoogleKey && useAsVoicePath && voiceEnabled,\n voice_model: \"gemini-2.5-flash-preview-tts\",\n voice_name: \"Kore\",\n voice_stt_model: \"gemini-2.5-flash\",\n voice_auto_speak: true,\n };\n const savedAgent = activeAgent\n ? await api.agents.update(activeAgent.id, agentPayload)\n : await api.agents.create(agentPayload);\n\n if (context === \"setup\") {\n window.location.href = \"/\";\n return;\n }\n\n dispatch({ type: \"SET_AGENT\", agentId: savedAgent.id });\n dispatch({ type: \"SET_TAB\", tab: \"chat\" });\n } catch (err) {\n setSaveError(err instanceof Error ? err.message : String(err));\n } finally {\n setSaving(false);\n }\n }\n\n const fullScreen = context === \"setup\";\n\n if (loading) {\n return (\n <div className={`flex items-center justify-center ${fullScreen ? \"min-h-screen\" : \"h-full\"}`}>\n <div className=\"inline-flex items-center gap-2 text-sm text-fg-faint\">\n <Loader2 size={16} className=\"animate-spin\" /> Loading setup\n </div>\n </div>\n );\n }\n\n return (\n <main className={`${fullScreen ? \"min-h-screen bg-surface\" : \"h-full bg-surface\"} text-fg`}>\n <div className=\"mx-auto w-full max-w-6xl px-4 py-6 sm:px-6 sm:py-8\">\n <div className=\"mb-6 flex items-start gap-4\">\n {fullScreen && (\n <Logo className=\"mt-1 h-11 w-auto\" />\n )}\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-[11px] font-semibold uppercase tracking-[0.2em] text-fg-faint\">\n {fullScreen ? \"First launch setup\" : state.experienceMode === \"essential\" ? \"Guided setup\" : \"Profile\"}\n </p>\n <h1 className=\"mt-1 text-2xl font-semibold tracking-tight\">\n {fullScreen ? `Set up ${getAppName()} once` : \"Set up your assistant\"}\n </h1>\n <p className=\"mt-2 max-w-2xl text-sm text-fg-subtle leading-relaxed\">\n Configure your profile, choose a model, and create a first agent from one screen. As you change the model, the feature icons below light up to show what the provider and model actually ship.\n </p>\n <div className=\"mt-4 flex flex-col sm:flex-row gap-2 max-w-xl\">\n {([\"essential\", \"full\"] as const).map((mode) => (\n <button\n key={mode}\n type=\"button\"\n onClick={() => dispatch({ type: \"SET_EXPERIENCE_MODE\", mode })}\n aria-pressed={state.experienceMode === mode}\n className={`flex-1 rounded-xl border px-3 py-2.5 text-left transition-colors ${\n state.experienceMode === mode\n ? \"border-accent/60 bg-accent/15 shadow-sm\"\n : \"border-border bg-surface-2 hover:border-border-strong\"\n }`}\n >\n <div className=\"text-sm font-medium capitalize\">{mode === \"essential\" ? \"Guided\" : \"Full controls\"}</div>\n <div className=\"mt-0.5 text-[11px] text-fg-faint leading-snug\">\n {mode === \"essential\"\n ? \"Curated panels and a simpler model editor.\"\n : \"Every panel, context tuning, and engine-room toggles.\"}\n </div>\n </button>\n ))}\n </div>\n </div>\n </div>\n\n <div className=\"grid grid-cols-1 xl:grid-cols-[minmax(0,1.35fr)_minmax(320px,0.9fr)] gap-5\">\n <div className=\"space-y-5\">\n <section className=\"rounded-2xl border border-border bg-surface-2 p-4 sm:p-5 space-y-4 shadow-sm\">\n <div className=\"flex items-center gap-3\">\n <span className=\"inline-flex h-8 w-8 items-center justify-center rounded-xl bg-accent/15 text-accent\">\n <UserRound size={16} />\n </span>\n <div>\n <h2 className=\"text-sm font-semibold\">1. Your profile</h2>\n <p className=\"text-[11px] text-fg-faint\">This shapes the app and tells the assistant who it is helping.</p>\n </div>\n </div>\n\n <div className=\"grid grid-cols-1 sm:grid-cols-2 gap-3\">\n <label className=\"block\">\n <span className=\"text-xs text-fg-subtle mb-1 block\">Your name</span>\n <input\n className=\"w-full rounded-xl border border-border bg-surface-3 px-3 py-2 text-sm\"\n value={name}\n onChange={(e) => setName(e.target.value)}\n placeholder=\"Your name\"\n />\n </label>\n </div>\n\n <label className=\"block\">\n <span className=\"text-xs text-fg-subtle mb-1 block\">About you</span>\n <MarkdownTextarea\n className=\"min-h-[6rem] w-full resize-y rounded-xl border border-border bg-surface-3 px-3 py-2 text-sm\"\n value={about}\n onChange={setAbout}\n rows={4}\n placeholder=\"What should your assistant know about how you work and what you care about?\"\n />\n </label>\n\n <div>\n <span className=\"text-xs text-fg-subtle mb-2 block\">What kind of setup do you want?</span>\n <div className=\"grid grid-cols-1 sm:grid-cols-2 gap-2\">\n {PROFILE_PRESETS.map((option) => (\n <button\n key={option.value}\n type=\"button\"\n onClick={() => setPreset(option.value)}\n className={`rounded-xl border px-3 py-2.5 text-left transition-colors ${\n preset === option.value\n ? \"border-accent/60 bg-accent/15 shadow-sm\"\n : \"border-border bg-surface-3\"\n }`}\n >\n <div className=\"text-xs font-medium\">{option.label}</div>\n <div className=\"mt-1 text-[10px] text-fg-faint leading-snug\">{option.hint}</div>\n </button>\n ))}\n </div>\n </div>\n </section>\n\n <section className=\"rounded-2xl border border-border bg-surface-2 p-4 sm:p-5 space-y-4 shadow-sm\">\n <div className=\"flex items-center gap-3\">\n <span className=\"inline-flex h-8 w-8 items-center justify-center rounded-xl bg-accent/15 text-accent\">\n <ShieldCheck size={16} />\n </span>\n <div>\n <h2 className=\"text-sm font-semibold\">2. Pick your model</h2>\n <p className=\"text-[11px] text-fg-faint\">Choose a provider, test the key, and see which features this model unlocks.</p>\n </div>\n </div>\n\n <div className=\"grid grid-cols-1 sm:grid-cols-2 gap-2\">\n {(Object.keys(PROVIDER_INFO) as Provider[]).map((option) => (\n <button\n key={option}\n type=\"button\"\n onClick={() => chooseProvider(option)}\n className={`rounded-xl border px-3 py-3 text-left transition-colors ${\n provider === option\n ? \"border-accent/60 bg-accent/15 shadow-sm\"\n : \"border-border bg-surface-3\"\n }`}\n >\n <div className=\"text-sm font-medium\">{PROVIDER_INFO[option].label}</div>\n <div className=\"mt-1 text-[11px] text-fg-faint leading-snug\">{PROVIDER_INFO[option].hint}</div>\n </button>\n ))}\n </div>\n\n <div className=\"rounded-xl border border-border bg-surface-3/70 px-3 py-3 space-y-2.5\">\n <div className=\"flex items-center justify-between gap-2\">\n <p className=\"text-xs font-semibold text-fg-muted uppercase tracking-wide\">Provider capability preview</p>\n <p className=\"text-[11px] text-fg-faint\">{PROVIDER_INFO[provider].label}</p>\n </div>\n <div className=\"grid grid-cols-2 sm:grid-cols-4 gap-2\">\n <div className={`rounded-lg border px-2 py-1.5 text-[11px] ${signalTone(providerSignals.image)}`}>\n <div className=\"inline-flex items-center gap-1\"><ImageIcon size={12} /> Image</div>\n </div>\n <div className={`rounded-lg border px-2 py-1.5 text-[11px] ${signalTone(providerSignals.voice)}`}>\n <div className=\"inline-flex items-center gap-1\"><Mic size={12} /> Voice</div>\n </div>\n <div className={`rounded-lg border px-2 py-1.5 text-[11px] ${signalTone(providerSignals.embeddings)}`}>\n <div className=\"inline-flex items-center gap-1\"><Database size={12} /> Embeddings</div>\n </div>\n <div className={`rounded-lg border px-2 py-1.5 text-[11px] ${signalTone(providerSignals.coding)}`}>\n <div className=\"inline-flex items-center gap-1\"><Code2 size={12} /> Coding</div>\n </div>\n </div>\n <p className=\"text-[11px] leading-snug text-fg-subtle\">\n <span className=\"font-medium text-fg\">Recommendation:</span> {providerSignals.recommendation}\n </p>\n </div>\n\n <div className=\"grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_auto] gap-3 items-end\">\n <label className=\"block\">\n <div className=\"mb-1 flex items-center justify-between gap-2\">\n <span className=\"text-xs text-fg-subtle\">API key</span>\n <a\n href={providerInfo.signupUrl}\n target=\"_blank\"\n rel=\"noreferrer noopener\"\n className=\"text-[11px] text-accent hover:text-accent-hover inline-flex items-center gap-1\"\n >\n Get key <ExternalLink size={11} />\n </a>\n </div>\n <input\n type=\"password\"\n value={apiKey}\n onChange={(e) => {\n setApiKey(e.target.value);\n setTest(null);\n }}\n placeholder={providerInfo.placeholder}\n className=\"w-full rounded-xl border border-border bg-surface-3 px-3 py-2 text-sm font-mono\"\n autoComplete=\"off\"\n spellCheck={false}\n />\n </label>\n <button\n type=\"button\"\n onClick={runTest}\n disabled={testing || !apiKey.trim()}\n className=\"inline-flex items-center justify-center gap-2 rounded-xl border border-border px-4 py-2 text-sm hover:border-fg-faint disabled:opacity-50\"\n >\n {testing ? <Loader2 size={14} className=\"animate-spin\" /> : <ShieldCheck size={14} />}\n {testing ? \"Testing\" : \"Test connection\"}\n </button>\n </div>\n\n {provider === \"gemini\" && (\n <label className=\"flex items-start gap-2 rounded-xl border border-border bg-surface-3 px-3 py-2.5\">\n <input\n type=\"checkbox\"\n className=\"mt-0.5 rounded border-border\"\n checked={reuseGoogleKey}\n onChange={(e) => setReuseGoogleKey(e.target.checked)}\n />\n <span className=\"text-[11px] leading-snug text-fg-subtle\">\n Reuse this same Gemini key for Google AI features like voice and image tools. This avoids asking you to configure a second credential for the same provider.\n </span>\n </label>\n )}\n\n <label className=\"block\">\n <span className=\"text-xs text-fg-subtle mb-1 block\">Model</span>\n {availableModels.length > 0 ? (\n <select\n value={modelId}\n onChange={(e) => setModelId(e.target.value)}\n className=\"w-full rounded-xl border border-border bg-surface-3 px-3 py-2 text-sm\"\n >\n {availableModels.map((option) => (\n <option key={option} value={option}>{option}</option>\n ))}\n </select>\n ) : (\n <input\n value={modelId}\n onChange={(e) => setModelId(e.target.value)}\n className=\"w-full rounded-xl border border-border bg-surface-3 px-3 py-2 text-sm font-mono\"\n />\n )}\n </label>\n\n <div className=\"grid grid-cols-1 sm:grid-cols-3 gap-2\">\n <label className=\"flex items-start gap-2 rounded-xl border border-border bg-surface-3 px-3 py-2.5\">\n <input\n type=\"checkbox\"\n className=\"mt-0.5 rounded border-border\"\n checked={useAsChatDefault}\n onChange={(e) => setUseAsChatDefault(e.target.checked)}\n />\n <span className=\"text-[11px] leading-snug text-fg-subtle\">\n Default chat model\n </span>\n </label>\n <label className=\"flex items-start gap-2 rounded-xl border border-border bg-surface-3 px-3 py-2.5\">\n <input\n type=\"checkbox\"\n className=\"mt-0.5 rounded border-border\"\n checked={useAsEmbeddingDefault}\n onChange={(e) => setUseAsEmbeddingDefault(e.target.checked)}\n />\n <span className=\"text-[11px] leading-snug text-fg-subtle\">\n Default embeddings model\n </span>\n </label>\n <label className={`flex items-start gap-2 rounded-xl border px-3 py-2.5 ${provider === \"gemini\" ? \"border-border bg-surface-3\" : \"border-border/60 bg-surface-2 opacity-70\"}`}>\n <input\n type=\"checkbox\"\n className=\"mt-0.5 rounded border-border\"\n checked={useAsVoicePath}\n onChange={(e) => setUseAsVoicePath(e.target.checked)}\n disabled={provider !== \"gemini\"}\n />\n <span className=\"text-[11px] leading-snug text-fg-subtle\">\n Voice-capable path\n </span>\n </label>\n </div>\n\n {test && (\n <div className={`rounded-xl border px-3 py-2.5 text-sm flex items-start gap-2 ${\n test.ok\n ? \"border-emerald-700/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300\"\n : \"border-rose-700/40 bg-rose-500/10 text-rose-700 dark:text-rose-300\"\n }`}>\n {test.ok ? <CheckCircle2 size={16} className=\"mt-0.5 shrink-0\" /> : <XCircle size={16} className=\"mt-0.5 shrink-0\" />}\n <span>{test.ok ? `Connection validated. ${test.models?.length ?? 0} models available.` : test.error}</span>\n </div>\n )}\n </section>\n\n <section className=\"rounded-2xl border border-border bg-surface-2 p-4 sm:p-5 space-y-4 shadow-sm\">\n <div className=\"flex items-center gap-3\">\n <span className=\"inline-flex h-8 w-8 items-center justify-center rounded-xl bg-accent/15 text-accent\">\n <Bot size={16} />\n </span>\n <div>\n <h2 className=\"text-sm font-semibold\">3. Create your first agent</h2>\n <p className=\"text-[11px] text-fg-faint\">Pick a starting style. You can refine this later in the Agents panel.</p>\n </div>\n </div>\n\n <label className=\"block\">\n <span className=\"text-xs text-fg-subtle mb-1 block\">Agent name</span>\n <input\n className=\"w-full rounded-xl border border-border bg-surface-3 px-3 py-2 text-sm\"\n value={agentName}\n onChange={(e) => setAgentName(e.target.value)}\n placeholder=\"My Assistant\"\n />\n </label>\n\n <div className=\"grid grid-cols-1 sm:grid-cols-2 gap-2\">\n {(Object.entries(AGENT_STYLES) as Array<[AgentStyle, typeof AGENT_STYLES[AgentStyle]]>).map(([key, option]) => {\n const Icon = option.icon;\n return (\n <button\n key={key}\n type=\"button\"\n onClick={() => setAgentStyle(key)}\n className={`rounded-xl border px-3 py-3 text-left transition-colors ${\n agentStyle === key\n ? \"border-accent/60 bg-accent/15 shadow-sm\"\n : \"border-border bg-surface-3\"\n }`}\n >\n <div className=\"flex items-center gap-2\">\n <span className=\"inline-flex h-7 w-7 items-center justify-center rounded-lg bg-surface text-fg-subtle border border-border\">\n <Icon size={14} />\n </span>\n <span className=\"text-sm font-medium\">{option.label}</span>\n </div>\n <div className=\"mt-2 text-[11px] text-fg-faint leading-snug\">{option.hint}</div>\n </button>\n );\n })}\n </div>\n\n <label className={`flex items-start gap-2 rounded-xl border px-3 py-2.5 ${provider === \"gemini\" && reuseGoogleKey ? \"border-border bg-surface-3\" : \"border-border/60 bg-surface-2 opacity-70\"}`}>\n <input\n type=\"checkbox\"\n className=\"mt-0.5 rounded border-border\"\n checked={voiceEnabled}\n onChange={(e) => setVoiceEnabled(e.target.checked)}\n disabled={!(provider === \"gemini\" && reuseGoogleKey)}\n />\n <span className=\"text-[11px] leading-snug text-fg-subtle\">\n Enable voice for this first agent. This lights up when your setup can reuse the Gemini key for Google AI features without extra credential steps.\n </span>\n </label>\n </section>\n </div>\n\n <div className=\"space-y-5 xl:sticky xl:top-4 self-start\">\n <ModelFeatureGuide\n provider={provider}\n modelId={modelId}\n models={models}\n integrations={effectiveIntegrations}\n title=\"Feature signals\"\n description=\"These icons update as you choose a provider and model, so you can see what ships with this setup before saving it.\"\n />\n\n <section className=\"rounded-2xl border border-border bg-surface-2 p-4 shadow-sm space-y-3\">\n <div>\n <h2 className=\"text-sm font-semibold\">Ready to continue?</h2>\n <p className=\"mt-1 text-[11px] text-fg-faint leading-snug\">\n This will save your profile, create or update the default model, and create or update your main agent.\n </p>\n </div>\n\n {saveError && (\n <div className=\"rounded-xl border border-rose-700/40 bg-rose-500/10 px-3 py-2 text-sm text-rose-700 dark:text-rose-300\">\n {saveError}\n </div>\n )}\n\n <button\n type=\"button\"\n onClick={handleSave}\n disabled={saving || !canSave}\n className=\"w-full inline-flex items-center justify-center gap-2 rounded-xl bg-accent px-4 py-3 text-sm font-medium text-white shadow-sm transition-colors hover:bg-accent-hover disabled:opacity-50\"\n >\n {saving ? <Loader2 size={15} className=\"animate-spin\" /> : null}\n {context === \"setup\" ? \"Finish setup\" : \"Save setup and open chat\"}\n </button>\n\n <div className=\"rounded-xl border border-border bg-surface-3 px-3 py-2.5 text-[11px] text-fg-faint leading-snug\">\n Normal mode keeps this flow simple. Advanced mode is still available later if you want deeper tuning.\n </div>\n </section>\n </div>\n </div>\n </div>\n </main>\n );\n}\n","// Browser-side cache of the server's effective config snapshot.\n//\n// api/client.ts and a few UI widgets (ServerStatus, the chat SSE consumer)\n// read JARELA_* timeouts that the user can change via the EnvVarsPanel.\n// Browser code can't read process.env directly, so we expose the relevant\n// fields via /api/v1/config and cache the response here.\n//\n// Reads are non-blocking: the schema defaults are used until the first\n// fetch lands, after which subsequent reads pick up overrides.\n\ninterface RuntimeConfigSnapshot {\n httpRequestTimeoutMs: number;\n sseConnectTimeoutMs: number;\n healthCheckTimeoutMs: number;\n httpMaxAttempts: number;\n runMaxMs: number;\n}\n\n// Mirror of ENV_DEFAULTS — these defaults are also the schema defaults so\n// the client behaves identically until the first /api/v1/config response\n// lands. Don't import the schema directly: it pulls in node-only modules\n// (homedir, path) via lib/env/config.ts and breaks the browser bundle.\nconst FALLBACK: RuntimeConfigSnapshot = {\n httpRequestTimeoutMs: 30_000,\n sseConnectTimeoutMs: 30_000,\n healthCheckTimeoutMs: 8_000,\n httpMaxAttempts: 3,\n runMaxMs: 20 * 60_000,\n};\n\nlet current: RuntimeConfigSnapshot = FALLBACK;\nlet inflight: Promise<void> | null = null;\n\nexport function runtimeConfig(): RuntimeConfigSnapshot {\n // Kick off the lazy fetch on first read; subsequent reads see the\n // updated snapshot once it resolves. Failures keep using FALLBACK.\n if (typeof window !== \"undefined\" && !inflight) {\n inflight = fetch(\"/api/v1/config\", { cache: \"no-store\" })\n .then((r) => (r.ok ? (r.json() as Promise<Partial<RuntimeConfigSnapshot>>) : null))\n .then((data) => {\n if (!data) return;\n current = {\n httpRequestTimeoutMs: typeof data.httpRequestTimeoutMs === \"number\" ? data.httpRequestTimeoutMs : current.httpRequestTimeoutMs,\n sseConnectTimeoutMs: typeof data.sseConnectTimeoutMs === \"number\" ? data.sseConnectTimeoutMs : current.sseConnectTimeoutMs,\n healthCheckTimeoutMs: typeof data.healthCheckTimeoutMs === \"number\" ? data.healthCheckTimeoutMs : current.healthCheckTimeoutMs,\n httpMaxAttempts: typeof data.httpMaxAttempts === \"number\" ? data.httpMaxAttempts : current.httpMaxAttempts,\n runMaxMs: typeof data.runMaxMs === \"number\" ? data.runMaxMs : current.runMaxMs,\n };\n })\n .catch(() => { /* keep fallback */ });\n }\n return current;\n}\n\n/** Force a refetch — call after the EnvVarsPanel PATCHes a runtime knob. */\nexport function refreshRuntimeConfig(): void {\n inflight = null;\n runtimeConfig();\n}\n","\"use client\";\n\nimport { Database, Eye, FileText, Globe, MessageSquare, Mic, Wrench } from \"lucide-react\";\nimport type { IntegrationStatus, ModelConfig } from \"@/api/types\";\nimport { CapBadges } from \"./CapBadges\";\nimport { computeFeatureReadiness } from \"@/lib/ui/feature-readiness\";\n\nfunction FeatureCard({\n title,\n description,\n enabled,\n icon: Icon,\n}: {\n title: string;\n description: string;\n enabled: boolean;\n icon: typeof MessageSquare;\n}) {\n return (\n <div className={`rounded-lg border px-3 py-2.5 transition-colors ${\n enabled\n ? \"border-emerald-500/30 bg-emerald-500/10\"\n : \"border-border bg-surface-3/70\"\n }`}>\n <div className=\"flex items-center gap-2\">\n <span className={`inline-flex h-7 w-7 items-center justify-center rounded-md border ${\n enabled\n ? \"border-emerald-500/30 bg-emerald-500/15 text-emerald-700 dark:text-emerald-300\"\n : \"border-border bg-surface text-fg-faint\"\n }`}>\n <Icon size={14} />\n </span>\n <div className=\"min-w-0\">\n <div className={`text-xs font-medium ${enabled ? \"text-fg\" : \"text-fg-subtle\"}`}>{title}</div>\n <div className={`text-[10px] uppercase tracking-wide ${enabled ? \"text-emerald-700 dark:text-emerald-300\" : \"text-fg-faint\"}`}>\n {enabled ? \"ready\" : \"not detected\"}\n </div>\n </div>\n </div>\n <p className=\"mt-2 text-[11px] leading-snug text-fg-faint\">{description}</p>\n </div>\n );\n}\n\ninterface Props {\n provider: string;\n modelId: string;\n models?: ModelConfig[];\n integrations?: IntegrationStatus[];\n title?: string;\n description?: string;\n}\n\nexport function ModelFeatureGuide({\n provider,\n modelId,\n models = [],\n integrations = [],\n title = \"What This Model Unlocks\",\n description = \"Pick a provider/model once here and the compatible app features light up based on what this installation can already use.\",\n}: Props) {\n const trimmedModelId = modelId.trim();\n if (!trimmedModelId) return null;\n\n const readiness = computeFeatureReadiness({\n models,\n integrations,\n selectedProvider: provider,\n selectedModelId: trimmedModelId,\n });\n\n if (!readiness.selectedModelCaps) return null;\n\n const featureCards = [\n {\n title: \"General chat\",\n description: \"Good baseline conversational model for agents and everyday chat.\",\n enabled: true,\n icon: MessageSquare,\n },\n {\n title: \"Images and screenshots\",\n description: \"Lets agents inspect screenshots, bridge images, and file attachments visually.\",\n enabled: readiness.selectedModelCaps.vision,\n icon: Eye,\n },\n {\n title: \"Document and file input\",\n description: \"Useful when the model needs to read uploaded files and richer document payloads.\",\n enabled: readiness.selectedModelCaps.files,\n icon: FileText,\n },\n {\n title: \"Voice and audio workflows\",\n description: readiness.hasGoogleIntegration\n ? \"Best fit for voice-oriented setups and audio-aware experiences.\"\n : \"Requires the existing Google AI integration; without it, voice would need extra setup.\",\n enabled: readiness.voiceReady,\n icon: Mic,\n },\n {\n title: \"Tool calling\",\n description: \"Lets agents use tools reliably for actions, retrieval, and automations.\",\n enabled: readiness.selectedModelCaps.tools,\n icon: Wrench,\n },\n {\n title: \"Built-in web search\",\n description: \"Provider-native web retrieval when the selected model supports it.\",\n enabled: readiness.selectedModelCaps.web_search,\n icon: Globe,\n },\n {\n title: \"Documents semantic search\",\n description: readiness.documentsReady\n ? \"Useful for embeddings-backed recall in the Documents panel.\"\n : \"Needs an embeddings-capable model already available in this installation.\",\n enabled: readiness.documentsReady,\n icon: Database,\n },\n ];\n\n return (\n <div className=\"rounded-xl border border-border bg-surface-3/60 p-3 space-y-2.5\">\n <div className=\"flex items-center justify-between gap-2\">\n <div>\n <p className=\"text-xs font-semibold text-fg-muted uppercase tracking-wide\">{title}</p>\n <p className=\"text-[11px] text-fg-faint mt-1 leading-snug\">{description}</p>\n </div>\n <CapBadges provider={provider} modelId={trimmedModelId} size=\"sm\" />\n </div>\n <div className=\"grid grid-cols-1 sm:grid-cols-2 gap-2\">\n {featureCards.map((feature) => (\n <FeatureCard\n key={feature.title}\n title={feature.title}\n description={feature.description}\n enabled={feature.enabled}\n icon={feature.icon}\n />\n ))}\n </div>\n </div>\n );\n}\n","// Branding knobs sourced from NEXT_PUBLIC_* env vars so forks can rebrand\n// the app without patching source. NEXT_PUBLIC_* is the right\n// channel here because Next.js inlines these at build time, which lets\n// client components read them directly (no React Context, no server\n// round-trip). Server-only modules read the same keys at runtime.\n//\n// Keep this module client-safe — no Node-only imports, no DB/FS access.\n\nconst DEFAULT_APP_NAME = \"Jarela\";\nconst DEFAULT_APP_DESCRIPTION = \"Jarela — local chat interface for LangGraph agents\";\nconst DEFAULT_ISSUE_URL = \"https://github.com/CircuitWall/jarela/issues/new\";\n\nexport function getAppName(): string {\n return process.env.NEXT_PUBLIC_APP_NAME?.trim() || DEFAULT_APP_NAME;\n}\n\nexport function getAppDescription(): string {\n return process.env.NEXT_PUBLIC_APP_DESCRIPTION?.trim() || DEFAULT_APP_DESCRIPTION;\n}\n\nexport function getAppIssueUrl(): string {\n return process.env.NEXT_PUBLIC_APP_ISSUE_URL?.trim() || DEFAULT_ISSUE_URL;\n}\n","\"use client\";\n\nimport type { ImgHTMLAttributes } from \"react\";\n\ntype LogoProps = Omit<ImgHTMLAttributes<HTMLImageElement>, \"src\" | \"alt\"> & {\n alt?: string;\n};\n\n// Theme-aware app mark. Renders both color variants and lets CSS pick which\n// one is visible based on the active theme — `dark:` here resolves through\n// the same `data-theme` attribute that ThemeContext writes on <html>, so a\n// manual Light/Dark override is honored alongside the OS preference.\nexport function Logo({ alt = \"\", className = \"\", ...rest }: LogoProps) {\n return (\n <>\n {/* eslint-disable-next-line @next/next/no-img-element */}\n <img\n src=\"/logo-mark-transparent.png\"\n alt={alt}\n className={`${className} block dark:hidden`}\n {...rest}\n />\n {/* eslint-disable-next-line @next/next/no-img-element */}\n <img\n src=\"/logo-mark-transparent-dark.png\"\n alt=\"\"\n aria-hidden\n className={`${className} hidden dark:block`}\n {...rest}\n />\n </>\n );\n}\n","import type { IntegrationStatus, ModelConfig } from \"@/api/types\";\nimport { modelCapabilities, type ModelCapabilities } from \"@/lib/providers/capabilities\";\n\nfunction providerLikelySupportsEmbeddings(provider: string): boolean {\n return new Set([\"openai\", \"gemini\", \"github-copilot\", \"mock\"]).has(provider.toLowerCase());\n}\n\nfunction isIntegrationConfigured(statuses: IntegrationStatus[], name: string): boolean {\n return statuses.some((status) => status.name === name && status.configured);\n}\n\nexport interface FeatureReadiness {\n selectedModelCaps: ModelCapabilities | null;\n hasGoogleIntegration: boolean;\n hasGeminiModel: boolean;\n hasEmbeddingsModel: boolean;\n voiceReady: boolean;\n documentsReady: boolean;\n}\n\nexport function computeFeatureReadiness({\n models,\n integrations,\n selectedProvider,\n selectedModelId,\n}: {\n models: ModelConfig[];\n integrations?: IntegrationStatus[];\n selectedProvider?: string;\n selectedModelId?: string;\n}): FeatureReadiness {\n const selectedModelCaps = selectedProvider && selectedModelId\n ? modelCapabilities(selectedProvider, selectedModelId)\n : null;\n\n const hasGoogleIntegration = isIntegrationConfigured(integrations ?? [], \"google\");\n const hasGeminiModel = models.some((model) => model.provider === \"gemini\") || selectedProvider === \"gemini\";\n const hasEmbeddingsModel = models.some((model) => providerLikelySupportsEmbeddings(model.provider))\n || !!selectedProvider && providerLikelySupportsEmbeddings(selectedProvider);\n\n return {\n selectedModelCaps,\n hasGoogleIntegration,\n hasGeminiModel,\n hasEmbeddingsModel,\n voiceReady: hasGoogleIntegration && hasGeminiModel,\n documentsReady: hasEmbeddingsModel,\n };\n}\n"],"names":["PATTERNS","openai","anthropic","gemini","deepseek","cohere","langchain","mock","modelSupportsImages","provider","modelId","pats","toLowerCase","some","re","test","isProviderClassified","AUDIO_PATTERNS","FILES_PATTERNS","WEB_SEARCH_PATTERNS","JSON_MODE_PROVIDERS","Set","matchesAny","map","modelCapabilities","p","noTools","vision","tools","streaming","json_mode","has","web_search","audio","files","useState","ReactMarkdown","remarkGfm","MD_REMARK_PLUGINS","MarkdownTextarea","value","onChange","className","placeholder","rows","maxLength","monospace","mode","setMode","fontClass","div","role","span","tabIndex","onClick","onKeyDown","e","key","preventDefault","trim","aria-disabled","textarea","target","style","minHeight","undefined","remarkPlugins","runtimeConfig","BASE","LIST_TTL_MS","emptyCache","data","fetchedAt","inflight","cloneRows","row","agentListCache","modelListCache","taskListCache","setAgentListCache","notify","snap","Date","now","window","dispatchEvent","CustomEvent","setModelListCache","setTaskListCache","cachedList","cache","fetchFn","setCache","force","Promise","resolve","req","then","isRetryable","err","status","DOMException","name","request","path","init","cfg","maxAttempts","Math","max","httpMaxAttempts","timeoutMs","httpRequestTimeoutMs","_ignoreTimeoutMs","fetchInit","callerSignal","signal","lastErr","attempt","timeoutCtrl","AbortController","timer","setTimeout","abort","onCallerAbort","addEventListener","res","fetch","headers","ok","cloned","clone","body","json","catch","error","Error","text","statusText","aborted","clearTimeout","removeEventListener","api","agents","list","opts","get","id","encodeURIComponent","create","created","method","JSON","stringify","update","updated","a","delete","deleted","filter","getThread","compact","builtinTools","setEnabled","category","enabled","extensions","getToolSecrets","saveToolSecrets","values","threads","limit","offset","agent_id","title","thread_id","URLSearchParams","set","String","before","after","qs","toString","abortRun","setContextPin","hot_since","memory","namespace","search","models","providers","catalog","overrides","params","probe","model_id","credential_id","compactThreads","using","m","t","model_config_name","credentials","type","suffix","profile","setLocationConsent","consent","updateLocation","clearLocation","access","add","identity","display_name","remove","tasks","assign","tool_policy","assigned","exists","next","unassign","dashboard","metrics","days","refreshPricing","ttlDays","Number","isFinite","currency","lat","lng","mcp","registry","q","cursor","fresh","integrations","save","gmailOauthStart","creds","gmailOauthStatus","state","outlookOauthStart","outlookOauthStatus","envSync","preview","apply","allowlist","integration","field","envVars","pending","approve","extras","deny","scheduledTasks","patch","cancel","runNow","watchers","listReactionScripts","documents","listSources","createSource","updateSource","deleteSource","reindex","source_id","getSettings","setSettings","fs","browse","githubCopilotAuth","start","poll","device_code","signOut","bridges","pair","chats","lookup","phone","routes","bridge_id","route_id","tailscale","harnesses","setDefault","proxy","input","clear","submitRun","message","stream_options","attachments","accepted","code","subscribeRun","includeTools","filters","include_tools","includeThinking","include_thinking","url","queue","waiters","done","streamError","length","shift","es","EventSource","withCredentials","onmessage","push","parsed","parse","everOpened","onopen","connectTimer","onerror","readyState","CLOSED","connectTimeoutMs","sseConnectTimeoutMs","round","close","onAbort","once","Braces","Eye","FileText","Globe","Mic","Wrench","Zap","CAP_META","icon","label","CAP_ORDER","CapBadges","caps","size","resolved","active","k","box","Icon","aria-label","strokeWidth","aria-hidden","useCallback","useEffect","useRef","Logo","PIN_LENGTH","UnlockScreen","digits","setDigits","setError","submitting","setSubmitting","retryAfterSec","setRetryAfterSec","containerRef","submittingRef","submit","pin","current","location","reload","retry_after_ms","ceil","append","d","cur","backspace","slice","onKey","setInterval","s","clearInterval","ref","paddingTop","paddingBottom","h1","Array","from","_","i","PinKey","digit","onPress","disabled","ariaLabel","aria-live","button","createContext","useContext","useReducer","EXPERIENCE_MODE_KEY","parseStoredMode","raw","reducer","action","activeThreadId","threadId","activeAgentId","agentId","activeTab","tab","experienceMode","selectedItem","itemId","AppContext","AppProvider","children","dispatch","stored","localStorage","getItem","setItem","Provider","useAppContext","ctx","Bot","Brain","Briefcase","CheckCircle2","Code2","Database","ExternalLink","Image","ImageIcon","Loader2","ShieldCheck","Sparkles","UserRound","Wand2","XCircle","useMemo","getAppName","ModelFeatureGuide","PROVIDER_INFO","signupUrl","defaultModel","hint","PROVIDER_SIGNALS","image","voice","embeddings","coding","recommendation","signalTone","level","PROFILE_PRESETS","AGENT_STYLES","assistant","instructions","builder","researcher","operator","supportedProvider","syntheticGoogleIntegration","configured","updated_at","OnboardingWizard","context","loading","setLoading","setProfile","setModels","setAgents","setIntegrations","setName","about","setAbout","preset","setPreset","setProvider","apiKey","setApiKey","setModelId","availableModels","setAvailableModels","setTest","testing","setTesting","reuseGoogleKey","setReuseGoogleKey","useAsChatDefault","setUseAsChatDefault","useAsEmbeddingDefault","setUseAsEmbeddingDefault","useAsVoicePath","setUseAsVoicePath","agentName","setAgentName","agentStyle","setAgentStyle","voiceEnabled","setVoiceEnabled","saving","setSaving","saveError","setSaveError","cancelled","load","profileData","modelRows","agentRows","integrationRows","all","statuses","find","is_default","defaultAgent","resolvedProvider","api_key","voice_enabled","activeModel","activeAgent","providerInfo","providerSignals","effectiveIntegrations","hasGoogle","modelReady","canSave","chooseProvider","runTest","includes","handleSave","updatedProfile","modelName","modelPayload","savedModel","embedding_model_config","agentPayload","voice_model","voice_name","voice_stt_model","voice_auto_speak","savedAgent","href","fullScreen","main","aria-pressed","section","h2","option","Object","keys","rel","autoComplete","spellCheck","checked","select","entries","description","FALLBACK","healthCheckTimeoutMs","runMaxMs","r","refreshRuntimeConfig","MessageSquare","computeFeatureReadiness","FeatureCard","trimmedModelId","readiness","selectedProvider","selectedModelId","selectedModelCaps","featureCards","hasGoogleIntegration","voiceReady","documentsReady","feature","DEFAULT_APP_NAME","DEFAULT_APP_DESCRIPTION","DEFAULT_ISSUE_URL","process","env","NEXT_PUBLIC_APP_NAME","getAppDescription","NEXT_PUBLIC_APP_DESCRIPTION","getAppIssueUrl","NEXT_PUBLIC_APP_ISSUE_URL","alt","rest","img","src","providerLikelySupportsEmbeddings","isIntegrationConfigured","hasGeminiModel","model","hasEmbeddingsModel"],"sourceRoot":"","ignoreList":[]}