@circuitwall/jarela 0.14.0 → 1.0.0

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 (164) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/app-path-routes-manifest.json +1 -1
  3. package/.next/standalone/.next/build-manifest.json +2 -2
  4. package/.next/standalone/.next/prerender-manifest.json +3 -3
  5. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  6. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  7. package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
  8. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  11. package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  12. package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  13. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  15. package/.next/standalone/.next/server/app/_not-found.html +2 -2
  16. package/.next/standalone/.next/server/app/_not-found.rsc +2 -2
  17. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  18. package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  19. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  20. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  21. package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  22. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  23. package/.next/standalone/.next/server/app/api/v1/agents/[id]/route.js +6 -1
  24. package/.next/standalone/.next/server/app/api/v1/agents/[id]/route.js.map +1 -1
  25. package/.next/standalone/.next/server/app/api/v1/agents/route.js +6 -1
  26. package/.next/standalone/.next/server/app/api/v1/agents/route.js.map +1 -1
  27. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js +9 -1
  28. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js.map +1 -1
  29. package/.next/standalone/.next/server/app/api/v1/bridges/route.js +9 -1
  30. package/.next/standalone/.next/server/app/api/v1/bridges/route.js.map +1 -1
  31. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js +36 -29
  32. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js.map +1 -1
  33. package/.next/standalone/.next/server/app/api/v1/events/route.js +7 -1
  34. package/.next/standalone/.next/server/app/api/v1/events/route.js.map +1 -1
  35. package/.next/standalone/.next/server/app/api/v1/extensions/route.js +3 -3
  36. package/.next/standalone/.next/server/app/api/v1/extensions/route.js.map +1 -1
  37. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js +4 -4
  38. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js.map +1 -1
  39. package/.next/standalone/.next/server/app/api/v1/health/route.js +7 -1
  40. package/.next/standalone/.next/server/app/api/v1/health/route.js.map +1 -1
  41. package/.next/standalone/.next/server/app/api/v1/mcp-servers/[name]/route.js +9 -1
  42. package/.next/standalone/.next/server/app/api/v1/mcp-servers/[name]/route.js.map +1 -1
  43. package/.next/standalone/.next/server/app/api/v1/mcp-servers/route.js +9 -1
  44. package/.next/standalone/.next/server/app/api/v1/mcp-servers/route.js.map +1 -1
  45. package/.next/standalone/.next/server/app/api/v1/models/route.js +6 -1
  46. package/.next/standalone/.next/server/app/api/v1/models/route.js.map +1 -1
  47. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js +7 -1
  48. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js.map +1 -1
  49. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js +14 -7
  50. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js.map +1 -1
  51. package/.next/standalone/.next/server/app/api/v1/providers/[provider]/models/route.js +28 -0
  52. package/.next/standalone/.next/server/app/api/v1/providers/[provider]/models/route.js.map +1 -1
  53. package/.next/standalone/.next/server/app/api/v1/providers/route.js +7 -1
  54. package/.next/standalone/.next/server/app/api/v1/providers/route.js.map +1 -1
  55. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/route.js +16 -2
  56. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/route.js.map +1 -1
  57. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js +8 -1
  58. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js.map +1 -1
  59. package/.next/standalone/.next/server/app/api/v1/threads/route.js +6 -1
  60. package/.next/standalone/.next/server/app/api/v1/threads/route.js.map +1 -1
  61. package/.next/standalone/.next/server/app/api/v1/tools/route.js +10 -3
  62. package/.next/standalone/.next/server/app/api/v1/tools/route.js.map +1 -1
  63. package/.next/standalone/.next/server/app/index.html +2 -2
  64. package/.next/standalone/.next/server/app/index.rsc +3 -3
  65. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  66. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
  67. package/.next/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  68. package/.next/standalone/.next/server/app/index.segments/_index.segment.rsc +2 -2
  69. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  70. package/.next/standalone/.next/server/app/page.js +56 -0
  71. package/.next/standalone/.next/server/app/page.js.map +1 -1
  72. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  73. package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
  74. package/.next/standalone/.next/server/app/setup.html +1 -1
  75. package/.next/standalone/.next/server/app/setup.rsc +2 -2
  76. package/.next/standalone/.next/server/app/setup.segments/_full.segment.rsc +2 -2
  77. package/.next/standalone/.next/server/app/setup.segments/_head.segment.rsc +1 -1
  78. package/.next/standalone/.next/server/app/setup.segments/_index.segment.rsc +2 -2
  79. package/.next/standalone/.next/server/app/setup.segments/_tree.segment.rsc +2 -2
  80. package/.next/standalone/.next/server/app/setup.segments/setup/__PAGE__.segment.rsc +1 -1
  81. package/.next/standalone/.next/server/app/setup.segments/setup.segment.rsc +1 -1
  82. package/.next/standalone/.next/server/app-paths-manifest.json +1 -1
  83. package/.next/standalone/.next/server/chunks/1683.js +2 -2
  84. package/.next/standalone/.next/server/chunks/2082.js +122 -13
  85. package/.next/standalone/.next/server/chunks/2082.js.map +1 -1
  86. package/.next/standalone/.next/server/chunks/210.js +3 -3
  87. package/.next/standalone/.next/server/chunks/210.js.map +1 -1
  88. package/.next/standalone/.next/server/chunks/239.js +1902 -1487
  89. package/.next/standalone/.next/server/chunks/239.js.map +1 -1
  90. package/.next/standalone/.next/server/chunks/2447.js +9 -1
  91. package/.next/standalone/.next/server/chunks/2447.js.map +1 -1
  92. package/.next/standalone/.next/server/chunks/423.js +125 -16
  93. package/.next/standalone/.next/server/chunks/423.js.map +1 -1
  94. package/.next/standalone/.next/server/chunks/4631.js +36 -29
  95. package/.next/standalone/.next/server/chunks/4631.js.map +1 -1
  96. package/.next/standalone/.next/server/chunks/5937.js +3 -2
  97. package/.next/standalone/.next/server/chunks/5937.js.map +1 -1
  98. package/.next/standalone/.next/server/chunks/{947.js → 8866.js} +11321 -10883
  99. package/.next/standalone/.next/server/chunks/8866.js.map +1 -0
  100. package/.next/standalone/.next/server/chunks/9032.js +3 -3
  101. package/.next/standalone/.next/server/chunks/9032.js.map +1 -1
  102. package/.next/standalone/.next/server/middleware-build-manifest.js +2 -2
  103. package/.next/standalone/.next/server/middleware.js +122 -13
  104. package/.next/standalone/.next/server/pages/404.html +2 -2
  105. package/.next/standalone/.next/server/pages/500.html +1 -1
  106. package/.next/standalone/.next/server/proxy.js.map +1 -1
  107. package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
  108. package/.next/standalone/.next/static/chunks/app/{page-473b39ec30c7f569.js → page-a7cae65f235e2942.js} +57 -1
  109. package/.next/standalone/.next/static/chunks/app/page-a7cae65f235e2942.js.map +1 -0
  110. package/.next/standalone/.next/static/css/{6f8b1a84bcbcd467.css → e57bdbbbb5a05779.css} +2 -2
  111. package/.next/standalone/.next/static/css/e57bdbbbb5a05779.css.map +1 -0
  112. package/.next/standalone/package.json +9 -1
  113. package/CHANGELOG.md +90 -0
  114. package/README.md +30 -2
  115. package/api/types.ts +8 -0
  116. package/app/api/v1/agents/[id]/route.ts +7 -0
  117. package/app/api/v1/agents/route.ts +7 -0
  118. package/app/api/v1/events/route.ts +8 -0
  119. package/app/api/v1/extensions/route.ts +2 -2
  120. package/app/api/v1/extensions/tools/[name]/secrets/route.ts +3 -3
  121. package/app/api/v1/health/route.ts +8 -0
  122. package/app/api/v1/models/route.ts +7 -0
  123. package/app/api/v1/page-capture/route.ts +8 -0
  124. package/app/api/v1/providers/route.ts +8 -0
  125. package/app/api/v1/threads/[thread_id]/route.ts +8 -0
  126. package/app/api/v1/threads/[thread_id]/run/route.ts +9 -0
  127. package/app/api/v1/threads/route.ts +7 -0
  128. package/app/api/v1/tools/route.ts +9 -0
  129. package/components/chat/ContextUsageBar.tsx +44 -0
  130. package/lib/agents/llm.ts +25 -2
  131. package/lib/agents/run-thread.ts +13 -1
  132. package/lib/agents/stream-collector.ts +9 -1
  133. package/lib/api/serializers.test.ts +15 -0
  134. package/lib/api/serializers.ts +8 -0
  135. package/lib/db/migrations.ts +15 -0
  136. package/lib/health/runner.test.ts +24 -2
  137. package/lib/mcp/registry.ts +14 -6
  138. package/lib/providers/anthropic.test.ts +95 -0
  139. package/lib/providers/anthropic.ts +106 -10
  140. package/lib/providers/jarela-chat-model.ts +9 -1
  141. package/lib/providers/known-context-windows.ts +21 -0
  142. package/lib/providers/types.ts +21 -1
  143. package/lib/stores/message-usage.test.ts +34 -0
  144. package/lib/stores/message-usage.ts +15 -3
  145. package/lib/stores/pricing.test.ts +52 -0
  146. package/lib/stores/pricing.ts +26 -1
  147. package/lib/tools/builtins.ts +4 -0
  148. package/lib/tools/extension-surfaces.test.ts +79 -0
  149. package/lib/tools/extension-surfaces.ts +153 -0
  150. package/lib/tools/index.ts +27 -8
  151. package/lib/tools/list-tools.test.ts +76 -0
  152. package/lib/tools/list-tools.ts +84 -0
  153. package/lib/tools/mcp-servers-info.test.ts +73 -0
  154. package/lib/tools/mcp-servers-info.ts +71 -0
  155. package/lib/tools/providers-info.test.ts +73 -0
  156. package/lib/tools/providers-info.ts +106 -0
  157. package/lib/tools/registry.ts +36 -25
  158. package/lib/tools/types.ts +13 -0
  159. package/package.json +9 -1
  160. package/.next/standalone/.next/server/chunks/947.js.map +0 -1
  161. package/.next/standalone/.next/static/chunks/app/page-473b39ec30c7f569.js.map +0 -1
  162. package/.next/standalone/.next/static/css/6f8b1a84bcbcd467.css.map +0 -1
  163. /package/.next/standalone/.next/static/{T0p2VVPsJPj44rwbmjaFb → d_vhp-lJqfdjRFpnLVIqZ}/_buildManifest.js +0 -0
  164. /package/.next/standalone/.next/static/{T0p2VVPsJPj44rwbmjaFb → d_vhp-lJqfdjRFpnLVIqZ}/_ssgManifest.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"2082.js","mappings":";;;;;;;;;;;;;;;;;;;;;;;;AACoF;AAEpF,MAAMC,MAAM,IAAM,IAAIC,OAAOC,WAAW;AAEjC,SAASC,cAAcC,EAAgB;IAC5CA,GAAGC,IAAI,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,WAAW,GAAG,IAAI,GACpBb,EAAEc,QAAQ,GAAG,IAAI,GACjBZ,OAAOa,QAAQ,EACfb,OAAOc,OAAO,EACdd,OAAOe,cAAc,EACrBf,OAAOgB,SAAS,EAChBlB,EAAEG,IAAI,EACNL,GACAA;IAEJ;IAEAD,sBAAsBxC;AACxB;AAkBA,wEAAwE;AACxE,yEAAyE;AACzE,yEAAyE;AACzE,EAAE;AACF,0EAA0E;AAC1E,0EAA0E;AAC1E,sEAAsE;AACtE,0EAA0E;AAC1E,MAAM4C,sBAA0C;IAC9C;QACEI,IAAI;QACJnB,MAAM;QACNqB,UAAU;QACVC,cACE;QACFG,OAAO,EAAE;QACTR,MAAM;QACNW,UAAU;QACVF,YAAY;IACd;IACA;QACEP,IAAI;QACJnB,MAAM;QACNqB,UACE;QACFC,cACE;QACFG,OAAO;YAAC;YAAc;YAAa;YAAe;YAAgB;SAAc;QAChFR,MAAM;QACNW,UAAU;IACZ;IACA;QACET,IAAI;QACJnB,MAAM;QACNqB,UACE;QACFC,cACE;QACFG,OAAO;YACL;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDR,MAAM;QACNW,UAAU;IACZ;IACA;QACET,IAAI;QACJnB,MAAM;QACNqB,UACE;QACFC,cACE;QACFG,OAAO;YACL;YACA;YACA;YACA;YACA;YACA;SACD;QACDR,MAAM;QACNW,UAAU;IACZ;IACA;QACET,IAAI;QACJnB,MAAM;QACNqB,UACE;QACFC,cACE;QACFG,OAAO;YACL;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDR,MAAM;QACNW,UAAU;IACZ;IACA;QACET,IAAI;QACJnB,MAAM;QACNqB,UACE;QACFC,cACE;QACFG,OAAO;YAAC;YAAe;YAAgB;SAAc;QACrDR,MAAM;QACNW,UAAU;IACZ;IAEA,wEAAwE;IACxE,wEAAwE;IACxE;QACET,IAAI;QAC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zF,IAAI;IACtB,OAAO8vB,QAAQhuB,MAAM,GAAG,IAAIguB,UAAU;AACxC","sources":["webpack://@circuitwall/jarela/./lib/db/migrations.ts","webpack://@circuitwall/jarela/./lib/crypto/migrate.ts","webpack://@circuitwall/jarela/./lib/db/index.ts","webpack://@circuitwall/jarela/./lib/stores/app-settings.ts","webpack://@circuitwall/jarela/./lib/crypto/envelope.ts","webpack://@circuitwall/jarela/./lib/embeddings/index.ts","webpack://@circuitwall/jarela/./lib/env/allowlist.ts","webpack://@circuitwall/jarela/./lib/env/discover.ts","webpack://@circuitwall/jarela/./lib/env/sync.ts","webpack://@circuitwall/jarela/./lib/crypto/sensitive.ts","webpack://@circuitwall/jarela/./lib/db/data-dir.ts","webpack://@circuitwall/jarela/./lib/proxy/keychain.ts","webpack://@circuitwall/jarela/./lib/proxy/dispatcher.ts","webpack://@circuitwall/jarela/./lib/agents/adaptive-persona-presets.ts","webpack://@circuitwall/jarela/./lib/providers/openai.ts","webpack://@circuitwall/jarela/./lib/providers/anthropic.ts","webpack://@circuitwall/jarela/./lib/providers/github-copilot.ts","webpack://@circuitwall/jarela/./lib/providers/deepseek.ts","webpack://@circuitwall/jarela/./lib/providers/streaming.ts","webpack://@circuitwall/jarela/./lib/providers/gemini.ts","webpack://@circuitwall/jarela/./lib/providers/langchain.ts","webpack://@circuitwall/jarela/./lib/providers/mock.ts","webpack://@circuitwall/jarela/./lib/providers/index.ts","webpack://@circuitwall/jarela/./lib/crypto/master-key.ts","webpack://@circuitwall/jarela/./lib/stores/integrations.ts","webpack://@circuitwall/jarela/./lib/stores/model-config.ts","webpack://@circuitwall/jarela/./lib/stores/memory.ts","webpack://@circuitwall/jarela/./lib/providers/external.ts","webpack://@circuitwall/jarela/./lib/providers/github-copilot-auth.ts","webpack://@circuitwall/jarela/./lib/stores/integration_meta.ts","webpack://@circuitwall/jarela/./lib/stores/proxy-config.ts"],"sourcesContent":["import { DatabaseSync } from \"node:sqlite\";\nimport { MBTI_PRESETS, type MbtiType } from \"@/lib/agents/adaptive-persona-presets\";\n\nconst now = () => new Date().toISOString();\n\nexport function runMigrations(db: DatabaseSync): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS threads (\n thread_id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n title TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n message_count INTEGER NOT NULL DEFAULT 0\n );\n CREATE TABLE IF NOT EXISTS messages (\n msg_id TEXT PRIMARY KEY,\n thread_id TEXT NOT NULL,\n role TEXT NOT NULL,\n content TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n -- thread_id is the dominant filter on every messages query\n -- (getMessages, getRecentMessagesWindow, getMessagesPage, clear).\n -- Without this every read full-scans the messages table.\n CREATE INDEX IF NOT EXISTS idx_messages_thread_id ON messages(thread_id, created_at);\n CREATE TABLE IF NOT EXISTS memory_store (\n namespace TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (namespace, key)\n );\n CREATE TABLE IF NOT EXISTS model_configs (\n name TEXT PRIMARY KEY,\n provider TEXT NOT NULL,\n model_id TEXT NOT NULL,\n params TEXT NOT NULL DEFAULT '{}',\n is_default INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS task_assignments (\n agent_id TEXT PRIMARY KEY,\n model_config_name TEXT NOT NULL,\n allow_tools TEXT NOT NULL DEFAULT '[]',\n deny_tools TEXT NOT NULL DEFAULT '[]',\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS user_profile (\n id TEXT PRIMARY KEY DEFAULT 'me',\n name TEXT NOT NULL DEFAULT '',\n icon TEXT,\n about TEXT NOT NULL DEFAULT '',\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS agent_configs (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n icon TEXT,\n identity TEXT NOT NULL DEFAULT '',\n instructions TEXT NOT NULL DEFAULT '',\n tools TEXT NOT NULL DEFAULT '[]',\n model_config_name TEXT,\n is_default INTEGER NOT NULL DEFAULT 0,\n adaptive_persona_enabled INTEGER NOT NULL DEFAULT 0,\n adaptive_persona_strength INTEGER NOT NULL DEFAULT 50,\n adaptive_empathy INTEGER NOT NULL DEFAULT 50,\n adaptive_expressiveness INTEGER NOT NULL DEFAULT 50,\n adaptive_verbosity INTEGER NOT NULL DEFAULT 50,\n adaptive_mbti TEXT NOT NULL DEFAULT 'INTJ',\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS scheduled_tasks (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n prompt TEXT NOT NULL,\n description TEXT,\n kind TEXT NOT NULL,\n schedule TEXT NOT NULL,\n next_run_at TEXT NOT NULL,\n last_run_at TEXT,\n last_error TEXT,\n enabled INTEGER NOT NULL DEFAULT 1,\n silent INTEGER NOT NULL DEFAULT 0,\n reaction_kind TEXT NOT NULL DEFAULT 'agent_prompt', -- ADR-0032\n reaction_script TEXT, -- ADR-0032\n reaction_script_args TEXT, -- ADR-0032\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_due ON scheduled_tasks(enabled, next_run_at);\n -- Event-driven \"watchers\" (ADR-0027). A watcher polls one built-in\n -- tool with fixed args on an interval; when the tool's output changes\n -- (content hash != last_fingerprint) the agent is fired with\n -- {previous, current} as context. Until then the watcher consumes no\n -- LLM tokens — only the polled tool runs. Plugs into the trigger\n -- abstraction (ADR-0025) as a sibling handler to scheduled_task.\n CREATE TABLE IF NOT EXISTS watchers (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n label TEXT NOT NULL,\n tool_name TEXT NOT NULL,\n tool_args TEXT NOT NULL DEFAULT '{}', -- JSON\n interval_seconds INTEGER NOT NULL,\n last_fingerprint TEXT, -- sha256 of last tool result\n last_result TEXT, -- raw tool result (string) for diff context\n last_run_at TEXT,\n last_fired_at TEXT,\n last_error TEXT,\n next_run_at TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 1,\n silent INTEGER NOT NULL DEFAULT 0,\n reaction_prompt TEXT, -- ADR-0030: NULL = default directive\n reaction_kind TEXT NOT NULL DEFAULT 'agent_prompt', -- ADR-0031: 'agent_prompt' | 'script'\n reaction_script TEXT, -- ADR-0031: registry key, only when kind='script'\n reaction_script_args TEXT, -- ADR-0031: JSON object, only when kind='script'\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_watchers_due ON watchers(enabled, next_run_at);\n CREATE TABLE IF NOT EXISTS mcp_servers (\n name TEXT PRIMARY KEY,\n transport TEXT NOT NULL, -- 'stdio' | 'http'\n spec TEXT NOT NULL DEFAULT '{}', -- JSON: { command, args, env } or { url, headers }\n enabled INTEGER NOT NULL DEFAULT 1,\n last_error TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS pending_actions (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL, -- which agent proposed it\n kind TEXT NOT NULL, -- 'install_mcp' | 'toggle_mcp' | 'update_agent_tools' | 'update_agent'\n payload TEXT NOT NULL, -- JSON parameters\n reason TEXT, -- agent's stated rationale\n status TEXT NOT NULL DEFAULT 'pending', -- pending | approved | denied | failed\n result TEXT, -- JSON result on success, error message on failure\n created_at TEXT NOT NULL,\n decided_at TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_pending_actions_status ON pending_actions(status, created_at);\n -- agent_id is a common filter on listPendingActions; without this every\n -- per-agent panel render is a full scan of pending_actions.\n CREATE INDEX IF NOT EXISTS idx_pending_actions_agent_status ON pending_actions(agent_id, status, created_at);\n CREATE TABLE IF NOT EXISTS access_whitelist (\n identity TEXT PRIMARY KEY,\n display_name TEXT,\n added_at TEXT NOT NULL,\n last_seen_at TEXT\n );\n CREATE TABLE IF NOT EXISTS bridges (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL, -- 'whatsapp' (only kind in v1)\n name TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'disconnected',-- disconnected | pairing | connected | error\n qr TEXT, -- base64 data URL while status='pairing'\n last_error TEXT,\n paired_id TEXT, -- the remote-account identifier (e.g. WhatsApp phone JID) once paired\n enabled INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS bridge_routes (\n id TEXT PRIMARY KEY,\n bridge_id TEXT NOT NULL,\n remote_jid TEXT NOT NULL, -- e.g. 5511...@s.whatsapp.net or ...@g.us\n agent_id TEXT NOT NULL,\n label TEXT, -- user-visible name (push_name on first inbound)\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n UNIQUE(bridge_id, remote_jid),\n UNIQUE(agent_id) -- one route per agent (catch-all may intentionally multiplex chats)\n );\n CREATE INDEX IF NOT EXISTS idx_bridge_routes_bridge ON bridge_routes(bridge_id);\n -- HTTP/HTTPS proxy configuration (ADR-0009). Single-row table; the\n -- CHECK constraint enforces it. Non-secret fields are plaintext for\n -- diagnostics; password goes through lib/crypto/envelope.ts.\n CREATE TABLE IF NOT EXISTS proxy_config (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n mode TEXT NOT NULL CHECK (mode IN ('off', 'manual', 'system')),\n scheme TEXT NOT NULL DEFAULT 'http', -- 'http' | 'https' (proxy hop scheme, ADR-0012)\n host TEXT,\n port INTEGER,\n username TEXT,\n password TEXT, -- envelope-encrypted (enc:v1:…)\n no_proxy TEXT,\n ca_bundle TEXT, -- PEM, plaintext (public cert, ADR-0012)\n updated_at TEXT NOT NULL\n );\n -- Document RAG (ADR-0024). A document_sources row is a folder the\n -- user asked Jarela to index for semantic search. Walked on each\n -- scheduler tick (cheap stat()); files whose mtime/size changed get\n -- re-chunked and re-embedded. documents_search exposes recall over\n -- the resulting chunks as an agent tool.\n CREATE TABLE IF NOT EXISTS document_sources (\n id TEXT PRIMARY KEY,\n path TEXT NOT NULL,\n label TEXT,\n enabled INTEGER NOT NULL DEFAULT 1,\n last_scan_at TEXT,\n last_error TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n UNIQUE(path)\n );\n CREATE TABLE IF NOT EXISTS documents (\n id TEXT PRIMARY KEY,\n source_id TEXT NOT NULL REFERENCES document_sources(id) ON DELETE CASCADE,\n path TEXT NOT NULL,\n rel_path TEXT NOT NULL,\n mtime_ms INTEGER NOT NULL,\n size_bytes INTEGER NOT NULL,\n content_hash TEXT NOT NULL,\n last_indexed_at TEXT NOT NULL,\n chunk_count INTEGER NOT NULL DEFAULT 0,\n UNIQUE(source_id, path)\n );\n CREATE INDEX IF NOT EXISTS idx_documents_source ON documents(source_id);\n CREATE TABLE IF NOT EXISTS document_chunks (\n id TEXT PRIMARY KEY,\n document_id TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,\n chunk_index INTEGER NOT NULL,\n text TEXT NOT NULL,\n start_offset INTEGER NOT NULL,\n end_offset INTEGER NOT NULL,\n embedding TEXT,\n UNIQUE(document_id, chunk_index)\n );\n CREATE INDEX IF NOT EXISTS idx_chunks_document ON document_chunks(document_id);\n -- Generic change-tracker primitive (ADR-0025). Lets any subsystem ask\n -- \"has (scope, key) changed since we last looked?\" by recording a\n -- fingerprint (e.g. content hash, mtime+size, etag) per key. Future\n -- triggers (fs_watch, tool_call dedupe) use it; the document indexer\n -- in lib/documents will migrate onto it in a later PR.\n CREATE TABLE IF NOT EXISTS change_tracker (\n scope TEXT NOT NULL,\n key TEXT NOT NULL,\n fingerprint TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (scope, key)\n );\n -- Built-in tool category toggles. Missing row = enabled (default-on).\n -- Disabled categories are filtered out at every tool-list surface so\n -- they vanish from the agent permission UI AND cannot be invoked even\n -- if an old agent config still references one of their tools.\n CREATE TABLE IF NOT EXISTS builtin_tool_categories (\n category TEXT PRIMARY KEY,\n enabled INTEGER NOT NULL DEFAULT 1,\n updated_at TEXT NOT NULL\n );\n -- Aggregated per-tool telemetry used to rank/filter tools in the UI.\n -- used_count is heuristic: a successful result whose payload appears to\n -- feed the assistant's final response for that turn.\n CREATE TABLE IF NOT EXISTS tool_stats (\n tool_name TEXT PRIMARY KEY,\n call_count INTEGER NOT NULL DEFAULT 0,\n success_count INTEGER NOT NULL DEFAULT 0,\n error_count INTEGER NOT NULL DEFAULT 0,\n used_count INTEGER NOT NULL DEFAULT 0,\n last_called_at TEXT,\n updated_at TEXT NOT NULL\n );\n `);\n ensureBridgeRouteColumns(db);\n ensureAgentConfigColumns(db);\n ensureTaskAssignmentColumns(db);\n ensureEmbeddingColumns(db);\n ensureUserProfileLocationColumns(db);\n ensureProxyConfigSchemeAndCaBundle(db);\n ensureThreadsAgentIdUnique(db);\n ensureMessagesCategoryColumn(db);\n ensureMessagesMetadataColumn(db);\n ensureScheduledTasksSilentColumn(db);\n ensureAgentDisplayFiltersColumn(db);\n ensureDocumentSourceRemoteColumns(db);\n ensureWatchersReactionPromptColumn(db);\n ensureWatchersReactionKindColumns(db);\n ensureScheduledTasksReactionKindColumns(db);\n ensureMessageUsageTable(db);\n ensureMessageUsageTierColumns(db);\n ensureThreadContextPinColumns(db);\n ensureThreadChannelSummariesTable(db);\n seedModelConfigs(db);\n seedAgentConfigs(db);\n}\n\n// ADR-0044. Per-channel warm summary so a thread shared across `chat`,\n// `scheduled_task`, `watcher`, and `bridge` channels stops blending\n// automation history into interactive turns. Replaces the single\n// `threads.warm_summary` blob — which is kept one release as a\n// read-only fallback — with one row per (thread_id, channel).\nfunction ensureThreadChannelSummariesTable(db: DatabaseSync): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS thread_channel_summaries (\n thread_id TEXT NOT NULL REFERENCES threads(thread_id) ON DELETE CASCADE,\n channel TEXT NOT NULL,\n summary TEXT NOT NULL,\n summary_before TEXT,\n computed_at TEXT NOT NULL,\n PRIMARY KEY (thread_id, channel)\n );\n CREATE INDEX IF NOT EXISTS idx_thread_channel_summaries_thread ON thread_channel_summaries(thread_id);\n `);\n}\n\n// ADR-0041. Immutable per-assistant-turn snapshot of LLM usage. Written once\n// alongside addMessage(...,\"assistant\",...) and never updated, so the\n// dashboard's token/$ aggregates are not retroactively rewritten when the\n// user reassigns an agent's model, renames a model config, or refreshes\n// pricing. See docs/adr/0041-immutable-message-usage.md.\nfunction ensureMessageUsageTable(db: DatabaseSync): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS message_usage (\n message_id TEXT PRIMARY KEY,\n thread_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n agent_name TEXT NOT NULL,\n provider TEXT NOT NULL,\n model_id TEXT NOT NULL,\n model_config_name TEXT,\n input_tokens INTEGER NOT NULL,\n output_tokens INTEGER NOT NULL,\n input_rate_usd_per_mtok REAL,\n output_rate_usd_per_mtok REAL,\n cost_usd REAL NOT NULL,\n created_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_message_usage_created_at ON message_usage(created_at);\n CREATE INDEX IF NOT EXISTS idx_message_usage_agent_id ON message_usage(agent_id);\n `);\n}\n\nfunction ensureEmbeddingColumns(db: DatabaseSync): void { // Embeddings stored as JSON-encoded float[] in TEXT to keep migration simple.\n // For the corpus sizes we expect (thousands of rows), in-memory cosine\n // similarity in JS is fast enough — no need for sqlite-vec or duckdb yet.\n const memCols = db.prepare(\"PRAGMA table_info(memory_store)\").all() as Array<{ name: string }>;\n if (!new Set(memCols.map((c) => c.name)).has(\"embedding\")) {\n db.exec(\"ALTER TABLE memory_store ADD COLUMN embedding TEXT\");\n }\n const msgColSet = new Set(\n (db.prepare(\"PRAGMA table_info(messages)\").all() as Array<{ name: string }>).map((c) => c.name),\n );\n if (!msgColSet.has(\"embedding\")) {\n db.exec(\"ALTER TABLE messages ADD COLUMN embedding TEXT\");\n }\n if (!msgColSet.has(\"tool_events\")) {\n // JSON array of { id, phase: \"call\"|\"result\", name, payload } captured at\n // stream time. Lets the chat UI render historical tool invocations the\n // same way it renders live ones — instead of only the *— used: x* footer\n // text, which loses arguments + results on reload.\n db.exec(\"ALTER TABLE messages ADD COLUMN tool_events TEXT\");\n }\n}\n\nfunction ensureProxyConfigSchemeAndCaBundle(db: DatabaseSync): void {\n // ADR-0012. Adds scheme (http|https for the proxy hop) and ca_bundle\n // (PEM for proxies that MITM TLS with an internal CA). CA bundle is a\n // public cert and stored plaintext; password remains envelope-wrapped.\n const cols = db.prepare(\"PRAGMA table_info(proxy_config)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"scheme\")) db.exec(\"ALTER TABLE proxy_config ADD COLUMN scheme TEXT NOT NULL DEFAULT 'http'\");\n if (!names.has(\"ca_bundle\")) db.exec(\"ALTER TABLE proxy_config ADD COLUMN ca_bundle TEXT\");\n}\n\nfunction ensureUserProfileLocationColumns(db: DatabaseSync): void {\n // Browser-reported geolocation, opt-in. Lets the agent answer\n // \"what's near me?\" / suggest routes / weather / etc. without the user\n // re-typing their location every turn. `location_consent` is the\n // explicit opt-in flag — when 0 the client must NOT post coordinates\n // and the agent must NOT see a stored value.\n const cols = db.prepare(\"PRAGMA table_info(user_profile)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"location_lat\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_lat REAL\");\n if (!names.has(\"location_lng\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_lng REAL\");\n if (!names.has(\"location_accuracy_m\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_accuracy_m REAL\");\n if (!names.has(\"location_label\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_label TEXT\");\n if (!names.has(\"location_updated_at\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_updated_at TEXT\");\n if (!names.has(\"location_consent\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_consent INTEGER NOT NULL DEFAULT 0\");\n // Persona preset (home/work/dev/custom). Drives the Credentials panel's\n // category filter so a home user doesn't see Jira / infrastructure\n // sections, and a work user doesn't see noise outside the work\n // toolbelt. NULL = unset (treat as \"custom\" → show everything). Set\n // by the Profile editor; consumed by IntegrationsPanel.\n if (!names.has(\"preset\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN preset TEXT\");\n}\n\n// Per-message classification. NULL/empty = ordinary chat content. Known\n// non-null values surface as filterable groups in the chat panel so users\n// can hide scheduled-task firings, bridge traffic, or synthetic page-capture\n// uploads without losing the audit trail. Current categories:\n// 'scheduled_task' - scheduler-injected prompt + its assistant reply\n// 'bridge' - bridge-mediated user inbound + assistant outbound\n// 'synthetic' - page-capture / file-upload generated user messages\nfunction ensureMessagesCategoryColumn(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(messages)\").all() as Array<{ name: string }>;\n if (!cols.some((c) => c.name === \"category\")) {\n db.exec(\"ALTER TABLE messages ADD COLUMN category TEXT\");\n }\n}\n\n// Per-message auxiliary metadata (JSON object). NULL on legacy rows and on\n// rows that don't carry any extra data. Current consumer is the citation\n// checker (`require_source_links`), which attaches a verdict shaped like\n// `{ citations: { claims: [...], unverified: [...] } }`. Adding more keys\n// later is free — readers tolerate unknown fields.\nfunction ensureMessagesMetadataColumn(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(messages)\").all() as Array<{ name: string }>;\n if (!cols.some((c) => c.name === \"metadata\")) {\n db.exec(\"ALTER TABLE messages ADD COLUMN metadata TEXT\");\n }\n}\n\n// ADR-0030 — per-watcher reaction prompt. NULL = use the default\n// \"summarise the diff\" directive baked into buildFiringPrompt. Non-null =\n// substitute that text in place of the default; the diff envelope (label,\n// tool, args, previous, current) is unchanged.\nfunction ensureWatchersReactionPromptColumn(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(watchers)\").all() as Array<{ name: string }>;\n if (!cols.some((c) => c.name === \"reaction_prompt\")) {\n db.exec(\"ALTER TABLE watchers ADD COLUMN reaction_prompt TEXT\");\n }\n}\n\n// ADR-0031 — script-backed watcher reactions. Adds three nullable columns\n// to the watchers table:\n// reaction_kind 'agent_prompt' (default) | 'script'\n// reaction_script registry key, only when kind='script'\n// reaction_script_args JSON object, only when kind='script'\n// Existing rows get reaction_kind='agent_prompt' and continue to behave\n// identically (the agent runs against the diff, optionally guided by\n// ADR-0030's reaction_prompt).\nfunction ensureWatchersReactionKindColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(watchers)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"reaction_kind\")) {\n db.exec(\n \"ALTER TABLE watchers ADD COLUMN reaction_kind TEXT NOT NULL DEFAULT 'agent_prompt'\",\n );\n }\n if (!names.has(\"reaction_script\")) {\n db.exec(\"ALTER TABLE watchers ADD COLUMN reaction_script TEXT\");\n }\n if (!names.has(\"reaction_script_args\")) {\n db.exec(\"ALTER TABLE watchers ADD COLUMN reaction_script_args TEXT\");\n }\n}\n\n// Per-task \"silent\" mode. When 1 the scheduler injects the prompt as a\n// hidden user message and instructs the agent to reply only when there is\n// something worth showing — otherwise the assistant turn is persisted\n// hidden too (or skipped entirely).\nfunction ensureScheduledTasksSilentColumn(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(scheduled_tasks)\").all() as Array<{ name: string }>;\n if (!cols.some((c) => c.name === \"silent\")) {\n db.exec(\"ALTER TABLE scheduled_tasks ADD COLUMN silent INTEGER NOT NULL DEFAULT 0\");\n }\n}\n\n// ADR-0032 — script-backed scheduled tasks. Mirrors the watcher migration\n// in ensureWatchersReactionKindColumns. Adds:\n// reaction_kind 'agent_prompt' (default) | 'script'\n// reaction_script registry key, only when kind='script'\n// reaction_script_args JSON object, only when kind='script'\n// Existing rows take reaction_kind='agent_prompt' (column default) and\n// continue to fire the agent with the saved prompt as before.\nfunction ensureScheduledTasksReactionKindColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(scheduled_tasks)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"reaction_kind\")) {\n db.exec(\n \"ALTER TABLE scheduled_tasks ADD COLUMN reaction_kind TEXT NOT NULL DEFAULT 'agent_prompt'\",\n );\n }\n if (!names.has(\"reaction_script\")) {\n db.exec(\"ALTER TABLE scheduled_tasks ADD COLUMN reaction_script TEXT\");\n }\n if (!names.has(\"reaction_script_args\")) {\n db.exec(\"ALTER TABLE scheduled_tasks ADD COLUMN reaction_script_args TEXT\");\n }\n}\n\n// Per-agent message-channel display filters (ADR-0022). JSON blob:\n// { \"thinking\": true, \"tool_use\": true, \"scheduled_task\": true,\n// \"bridge\": true, \"synthetic\": true }\n// NULL = inherit defaults (all-on). Missing keys also default to true so\n// new channels added in future builds stay visible for existing users.\nfunction ensureAgentDisplayFiltersColumn(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(agent_configs)\").all() as Array<{ name: string }>;\n if (!cols.some((c) => c.name === \"display_filters\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN display_filters TEXT\");\n }\n}\n\n// ADR-0026 — remote document-RAG sources (Jira / Confluence / mail). Extends the\n// ADR-0024 document_sources table with a discriminator + JSON config so a\n// single store + indexer dispatcher serves both local folders and remote\n// content. Existing rows are 'local_folder' (matches pre-0026 behavior).\nfunction ensureDocumentSourceRemoteColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(document_sources)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"kind\")) {\n db.exec(\n \"ALTER TABLE document_sources ADD COLUMN kind TEXT NOT NULL DEFAULT 'local_folder'\",\n );\n }\n if (!names.has(\"config\")) {\n // JSON-encoded per-kind config (e.g. {\"space_key\":\"ENG\"} for\n // confluence_space, {\"jql\":\"...\"} for jira_jql, {\"query\":\"is:unread\"}\n // for gmail_mail). NULL for local_folder.\n db.exec(\"ALTER TABLE document_sources ADD COLUMN config TEXT\");\n }\n if (!names.has(\"last_cursor\")) {\n // Per-source incremental cursor (e.g. max external `updated` ISO\n // timestamp for Jira/Confluence). Lets remote indexers run cheaply\n // after the first full sync. NULL for local_folder.\n db.exec(\"ALTER TABLE document_sources ADD COLUMN last_cursor TEXT\");\n }\n}\n\nfunction ensureThreadsAgentIdUnique(db: DatabaseSync): void {\n // Check if index already exists — skip if so\n const idx = db.prepare(\n \"SELECT name FROM sqlite_master WHERE type='index' AND name='idx_threads_agent_id'\"\n ).get();\n if (idx) return;\n\n // Delete orphaned messages for duplicate threads before removing them\n db.exec(`\n DELETE FROM messages WHERE thread_id IN (\n SELECT thread_id FROM threads\n WHERE rowid NOT IN (SELECT MAX(rowid) FROM threads GROUP BY agent_id)\n )\n `);\n\n // Keep only the last-inserted thread per agent (by rowid)\n db.exec(`\n DELETE FROM threads\n WHERE rowid NOT IN (SELECT MAX(rowid) FROM threads GROUP BY agent_id)\n `);\n\n db.exec(\"CREATE UNIQUE INDEX idx_threads_agent_id ON threads(agent_id)\");\n}\n\nfunction ensureAgentConfigColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(agent_configs)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"is_default\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN is_default INTEGER NOT NULL DEFAULT 0\");\n db.exec(\"UPDATE agent_configs SET is_default=1 WHERE id='assistant'\");\n }\n if (!names.has(\"history_limit\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN history_limit INTEGER NOT NULL DEFAULT 50\");\n }\n if (!names.has(\"history_window_hours\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN history_window_hours INTEGER NOT NULL DEFAULT 8\");\n }\n // never_reply: when 1, the dispatcher records the inbound message and\n // the agent's response in the thread but doesn't send the reply back\n // through the bridge. Useful for read-only / observer agents on group\n // chats where the user wants archival + LLM analysis but no automatic\n // posting.\n if (!names.has(\"never_reply\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN never_reply INTEGER NOT NULL DEFAULT 0\");\n }\n if (!names.has(\"adaptive_persona_enabled\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_persona_enabled INTEGER NOT NULL DEFAULT 0\");\n }\n if (!names.has(\"adaptive_persona_strength\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_persona_strength INTEGER NOT NULL DEFAULT 50\");\n }\n if (!names.has(\"adaptive_empathy\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_empathy INTEGER NOT NULL DEFAULT 50\");\n }\n if (!names.has(\"adaptive_expressiveness\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_expressiveness INTEGER NOT NULL DEFAULT 50\");\n }\n if (!names.has(\"adaptive_verbosity\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_verbosity INTEGER NOT NULL DEFAULT 50\");\n }\n if (!names.has(\"adaptive_mbti\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_mbti TEXT NOT NULL DEFAULT 'INTJ'\");\n }\n // Per-agent voice config. When voice_enabled=0 the chat UI hides the\n // mic + play controls for this agent entirely; STT/TTS endpoints reject\n // requests targeting it. Provider/model/voice are TTS-side; stt_model is\n // STT-side. Defaults pick Gemini flash-tier so a fresh agent with voice\n // turned on works against the existing \"google\" integration api_key.\n if (!names.has(\"voice_enabled\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN voice_enabled INTEGER NOT NULL DEFAULT 0\");\n }\n if (!names.has(\"voice_model\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN voice_model TEXT NOT NULL DEFAULT 'gemini-2.5-flash-preview-tts'\");\n }\n if (!names.has(\"voice_name\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN voice_name TEXT NOT NULL DEFAULT 'Kore'\");\n }\n if (!names.has(\"voice_stt_model\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN voice_stt_model TEXT NOT NULL DEFAULT 'gemini-2.5-flash'\");\n }\n if (!names.has(\"voice_auto_speak\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN voice_auto_speak INTEGER NOT NULL DEFAULT 1\");\n }\n // ADR-0033 — per-agent harness override. NULL = inherit the global default\n // harness (app-settings.default_harness_id, which itself defaults to\n // 'builtin:default'). Non-null is either a builtin id (\"builtin:default\")\n // or a user-created custom id (\"custom:<uuid>\").\n if (!names.has(\"harness_id\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN harness_id TEXT\");\n }\n // Per-agent delegation whitelist (JSON array of agent ids). NULL or empty\n // array means the agent cannot delegate. Read by lib/tools/delegate.ts to\n // gate the delegate_to_agent tool.\n if (!names.has(\"delegate_targets\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN delegate_targets TEXT\");\n }\n // ADR-0043 — per-agent override of context_tier_proportions. JSON-encoded\n // `{ hot, warm, facts }` (any positive numbers — `normalizeTierProportions`\n // divides by sum, so the UI can ship raw weights instead of demanding\n // sum=100 from the user). NULL = inherit from the model config.\n if (!names.has(\"context_tier_proportions\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN context_tier_proportions TEXT\");\n }\n // Per-agent override of the anti-hallucination classifier (ADR-…). NULL\n // on either column = inherit the global JARELA_HALLUCINATION_DETECTOR_*\n // env knob. Mode is one of \"off\" | \"report\" | \"enforce\"; model_config is\n // the name of a saved model config (lib/stores/model-config) used as\n // the classifier model.\n if (!names.has(\"anti_hallucination_mode\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN anti_hallucination_mode TEXT\");\n }\n if (!names.has(\"anti_hallucination_model_config\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN anti_hallucination_model_config TEXT\");\n }\n // Independent of the stall classifier: when 1, the agent's system prompt\n // gets a citation-link directive and the assistant turn is post-checked\n // for {source link present, source previously visited in this thread}.\n // Reuses `anti_hallucination_model_config` as the checker model.\n if (!names.has(\"require_source_links\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN require_source_links INTEGER NOT NULL DEFAULT 0\");\n }\n}\n\n/**\n * `silent_mode` is per-route, not per-agent: the same agent can auto-reply\n * in one chat and stay observer-only in another. Backfills from the legacy\n * per-agent `never_reply` flag on first migration so behavior is preserved\n * for existing installs. After backfill, `never_reply` is no longer read by\n * the dispatcher — the route flag is canonical.\n */\nfunction ensureBridgeRouteColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(bridge_routes)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"silent_mode\")) {\n db.exec(\"ALTER TABLE bridge_routes ADD COLUMN silent_mode INTEGER NOT NULL DEFAULT 0\");\n // Best-effort backfill from the legacy per-agent flag if the column exists.\n const agentCols = db.prepare(\"PRAGMA table_info(agent_configs)\").all() as Array<{ name: string }>;\n if (agentCols.some((c) => c.name === \"never_reply\")) {\n db.exec(`\n UPDATE bridge_routes\n SET silent_mode = 1\n WHERE agent_id IN (SELECT id FROM agent_configs WHERE never_reply = 1)\n `);\n }\n }\n // Per-route reply trigger: which sender role unlocks an outbound reply.\n // 'counterpart' (default) = agent answers the user's chat partner / group\n // members but stays quiet when the user themselves types — the typical\n // \"auto-responder on my behalf\" use case. 'user' = agent only reacts to\n // the user's own messages (e.g. expand/translate-my-draft assistants).\n // silent_mode (above) overrides this — when set, nothing goes out\n // regardless of role match.\n if (!names.has(\"respond_to\")) {\n db.exec(\"ALTER TABLE bridge_routes ADD COLUMN respond_to TEXT NOT NULL DEFAULT 'counterpart'\");\n }\n}\n\nfunction ensureTaskAssignmentColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(task_assignments)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n\n if (!names.has(\"allow_tools\")) {\n db.exec(\"ALTER TABLE task_assignments ADD COLUMN allow_tools TEXT NOT NULL DEFAULT '[]'\");\n }\n if (!names.has(\"deny_tools\")) {\n db.exec(\"ALTER TABLE task_assignments ADD COLUMN deny_tools TEXT NOT NULL DEFAULT '[]'\");\n }\n}\n\n// ADR-0042 — explicit per-thread context pin + persisted warm summary.\n// hot_since: ISO timestamp of the boundary the user has chosen to include in\n// the agent's hot context. NULL = no explicit pin → buildHistoryWindow falls\n// back to the agent's history_window_hours default.\n// warm_summary: latest LLM-summarised recap of messages older than\n// warm_summary_before. The chat UI renders this as an inline card above the\n// boundary divider so the user can see what the agent had to compress.\n// warm_summary_before: the boundary the cached summary covers. The summary is\n// considered fresh only when warm_summary_before === hot_since; otherwise\n// the next run will re-summarise and overwrite both.\nfunction ensureThreadContextPinColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(threads)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"hot_since\")) db.exec(\"ALTER TABLE threads ADD COLUMN hot_since TEXT\");\n if (!names.has(\"warm_summary\")) db.exec(\"ALTER TABLE threads ADD COLUMN warm_summary TEXT\");\n if (!names.has(\"warm_summary_before\")) db.exec(\"ALTER TABLE threads ADD COLUMN warm_summary_before TEXT\");\n if (!names.has(\"warm_summary_computed_at\")) db.exec(\"ALTER TABLE threads ADD COLUMN warm_summary_computed_at TEXT\");\n}\n\n// Per-tier input-token breakdown so the chat UI can show actual\n// hot/warm/facts/overhead consumption per turn (not just the proportional\n// budget). All eight columns are nullable so legacy rows simply render an\n// \"unknown\" bar. Re-derivation isn't possible after the fact (the\n// history-window state isn't preserved), so backfill is intentionally NULL.\nfunction ensureMessageUsageTierColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(message_usage)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"hot_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN hot_tokens INTEGER\");\n if (!names.has(\"warm_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN warm_tokens INTEGER\");\n if (!names.has(\"facts_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN facts_tokens INTEGER\");\n if (!names.has(\"overhead_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN overhead_tokens INTEGER\");\n if (!names.has(\"hot_budget_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN hot_budget_tokens INTEGER\");\n if (!names.has(\"warm_budget_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN warm_budget_tokens INTEGER\");\n if (!names.has(\"facts_budget_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN facts_budget_tokens INTEGER\");\n if (!names.has(\"context_window_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN context_window_tokens INTEGER\");\n}\n\nfunction seedAgentConfigs(db: DatabaseSync): void {\n // Only seed on first run — once the user has any agents we must not\n // resurrect ones they've deleted (e.g. the legacy \"echo\" / \"llm\" defaults).\n const count = (db.prepare(\"SELECT COUNT(*) as n FROM agent_configs\").get() as { n: number }).n;\n if (count > 0) {\n reanchorOrphanThreads(db);\n return;\n }\n\n const t = now();\n const insert = db.prepare(\n `INSERT OR IGNORE INTO agent_configs (\n id, name, icon, identity, instructions, tools, model_config_name, is_default,\n never_reply,\n adaptive_persona_enabled, adaptive_persona_strength, adaptive_empathy, adaptive_expressiveness, adaptive_verbosity, adaptive_mbti,\n created_at, updated_at\n )\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`\n );\n\n for (const p of BASE_AGENT_PROFILES) {\n const preset = MBTI_PRESETS[p.mbti];\n insert.run(\n p.id,\n p.name,\n p.icon ?? null,\n p.identity,\n p.instructions,\n JSON.stringify(p.tools),\n null,\n p.is_default ? 1 : 0,\n p.never_reply ? 1 : 0,\n p.adaptive ? 1 : 0,\n preset.strength,\n preset.empathy,\n preset.expressiveness,\n preset.verbosity,\n p.mbti,\n t,\n t,\n );\n }\n\n reanchorOrphanThreads(db);\n}\n\ninterface BaseAgentProfile {\n id: string;\n name: string;\n icon?: string | null;\n identity: string;\n instructions: string;\n tools: string[];\n mbti: MbtiType;\n adaptive: boolean;\n is_default?: boolean;\n // When true, the agent runs on bridge/scheduled input but does not\n // auto-send replies — it observes and records, only speaking when the\n // user directly addresses it (see lib/bridges/dispatcher.ts).\n never_reply?: boolean;\n}\n\n// Starter profiles shipped on first run. The user can edit, disable, or\n// delete any of them — once they have any agents we stop re-seeding (see\n// the guard at the top of seedAgentConfigs), so user choices are sticky.\n//\n// Each profile pre-binds a small, focused tool set so the agent is useful\n// out of the box without exposing every capability by default. Tools that\n// require integrations (gmail/outlook/calendar) are wired up but will\n// surface a setup hint at call time if the integration is not configured.\nconst BASE_AGENT_PROFILES: BaseAgentProfile[] = [\n {\n id: \"assistant\",\n name: \"Assistant\",\n identity: \"You are a helpful general-purpose assistant.\",\n instructions:\n \"Answer concisely. Ask for clarification only when truly ambiguous. When you don't know something, say so instead of guessing.\",\n tools: [],\n mbti: \"INTJ\",\n adaptive: false,\n is_default: true,\n },\n {\n id: \"researcher\",\n name: \"Researcher\",\n identity:\n \"You are a careful researcher who finds, cross-checks, and summarizes information from the web.\",\n instructions:\n \"Use web_search to discover sources and web_fetch to read them. Prefer primary sources over aggregators. Cite URLs inline. When findings conflict, surface the disagreement instead of picking a side. Save durable facts with memory_write so future sessions can build on them.\",\n tools: [\"web_search\", \"web_fetch\", \"memory_read\", \"memory_write\", \"memory_list\"],\n mbti: \"INTP\",\n adaptive: true,\n },\n {\n id: \"developer\",\n name: \"Developer\",\n identity:\n \"You are a pragmatic software engineer working in the user's local repo with a real build/test harness.\",\n instructions:\n \"Read before you write. Use file_list / file_read / file_stat to map the code, then file_edit for surgical changes and file_write only for new files. After every meaningful edit, run the project's build, lint, or test command via shell_exec (or local_exec for a single binary) and read the output before declaring success — never claim a fix without proof. Use github_* to look up issues/PRs for context. Prefer the smallest change that solves the problem; never invent paths or APIs.\",\n tools: [\n \"file_read\",\n \"file_write\",\n \"file_edit\",\n \"file_list\",\n \"file_stat\",\n \"file_mkdir\",\n \"file_move\",\n \"file_copy\",\n \"file_delete\",\n \"local_exec\",\n \"shell_exec\",\n \"web_fetch\",\n \"web_search\",\n \"github_search_issues\",\n \"github_get_issue\",\n \"github_list_pulls\",\n \"github_get_pull\",\n \"github_get_repo\",\n \"memory_read\",\n \"memory_write\",\n \"memory_list\",\n ],\n mbti: \"INTJ\",\n adaptive: true,\n },\n {\n id: \"planner\",\n name: \"Planner\",\n identity:\n \"You are a planning partner who turns vague intentions into concrete, scheduled actions.\",\n instructions:\n \"When the user describes something they want to happen later or recurrently, propose a schedule_task with a clear prompt and a cron or ISO schedule, then confirm before creating it. Use list_scheduled_tasks before adding to avoid duplicates. Keep memory_write notes on the user's recurring goals so plans stay aligned over time.\",\n tools: [\n \"schedule_task\",\n \"list_scheduled_tasks\",\n \"cancel_scheduled_task\",\n \"memory_read\",\n \"memory_write\",\n \"memory_list\",\n ],\n mbti: \"ENTJ\",\n adaptive: true,\n },\n {\n id: \"inbox\",\n name: \"Inbox Triage\",\n identity:\n \"You help triage email and calendar. You summarize, draft, and surface what actually needs attention.\",\n instructions:\n \"When asked about mail, search first, then read the specific message before drafting. Drafts are created — never sent automatically. For calendar requests, list the relevant window before creating events. If an integration is not configured, tell the user which one and stop.\",\n tools: [\n \"gmail_search\",\n \"gmail_get_message\",\n \"gmail_create_draft\",\n \"outlook_search\",\n \"outlook_get_message\",\n \"outlook_create_draft\",\n \"calendar_list_events\",\n \"calendar_create_event\",\n \"outlook_calendar_list_events\",\n \"outlook_calendar_create_event\",\n ],\n mbti: \"ESFJ\",\n adaptive: true,\n },\n {\n id: \"companion\",\n name: \"Companion\",\n identity:\n \"You are a reflective companion for journaling and thinking out loud.\",\n instructions:\n \"Listen more than you advise. Ask one open question at a time. Mirror back themes you notice across sessions; use memory_read at the start of a thread and memory_write to record durable insights (values, ongoing struggles, wins), never raw content.\",\n tools: [\"memory_read\", \"memory_write\", \"memory_list\"],\n mbti: \"INFJ\",\n adaptive: true,\n },\n\n // Backward-compat: pre-migration threads used agent_id=\"llm\" or \"echo\".\n // Kept so historical threads still resolve to a real agent_configs row.\n {\n id: \"llm\",\n name: \"LLM Agent\",\n identity: \"You are a helpful assistant.\",\n instructions: \"\",\n tools: [],\n mbti: \"INTJ\",\n adaptive: false,\n },\n {\n id: \"echo\",\n name: \"Echo\",\n identity: \"\",\n instructions: \"\",\n tools: [],\n mbti: \"INTJ\",\n adaptive: false,\n },\n];\n\n// Threads have a UNIQUE(agent_id) index (one thread per agent), so we can't\n// bulk-repoint orphan threads to a single fallback — that would violate the\n// constraint as soon as there are 2+ orphans. Instead we drop orphan threads\n// (and their messages); the agent they pointed at no longer exists.\nfunction reanchorOrphanThreads(db: DatabaseSync): void {\n db.exec(`\n DELETE FROM messages WHERE thread_id IN (\n SELECT thread_id FROM threads WHERE agent_id NOT IN (SELECT id FROM agent_configs)\n )\n `);\n db.exec(`\n DELETE FROM threads WHERE agent_id NOT IN (SELECT id FROM agent_configs)\n `);\n}\n\nfunction seedModelConfigs(db: DatabaseSync): void {\n // Only seed on first run — if any row exists, the user has already managed\n // their configs and we must not resurrect anything they deleted.\n const count = (db.prepare(\"SELECT COUNT(*) as n FROM model_configs\").get() as { n: number }).n;\n if (count > 0) return;\n\n const insert = db.prepare(\n `INSERT OR IGNORE INTO model_configs (name, provider, model_id, params, is_default, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`\n );\n const t = now();\n const seeds: [string, string, string, string, number, string, string][] = [\n [\"claude-sonnet\", \"anthropic\", \"claude-sonnet-4-6\", \"{}\", 0, t, t],\n [\"gpt-4o\", \"openai\", \"gpt-4o\", \"{}\", 0, t, t],\n [\"github-copilot\", \"github-copilot\", \"gpt-4o\", \"{}\", 0, t, t],\n\n ];\n for (const s of seeds) insert.run(...s);\n}\n","// One-time, idempotent migration that rewrites legacy plaintext values\n// in the four secret-bearing surfaces with `enc:v1:` envelopes\n// (ADR-0005). Safe to run on every boot — already-encrypted rows are\n// detected by the prefix and skipped.\n\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { encrypt, isEncrypted } from \"./envelope\";\nimport { SENSITIVE_MEMORY_NAMESPACES } from \"./sensitive\";\n\ninterface MemoryStoreRow { namespace: string; key: string; value: string }\ninterface ModelConfigRow { name: string; params: string }\ninterface McpServerRow { name: string; spec: string }\n\nexport function runCryptoMigration(db: DatabaseSync): void {\n let touched = 0;\n\n // 1) memory_store rows in sensitive namespaces.\n const nsList = [...SENSITIVE_MEMORY_NAMESPACES];\n const placeholders = nsList.map(() => \"?\").join(\",\");\n const memoryRows = db\n .prepare(`SELECT namespace, key, value FROM memory_store WHERE namespace IN (${placeholders})`)\n .all(...nsList) as unknown as MemoryStoreRow[];\n const memUpdate = db.prepare(\n \"UPDATE memory_store SET value=?, updated_at=? WHERE namespace=? AND key=?\",\n );\n const now = new Date().toISOString();\n for (const row of memoryRows) {\n if (isEncrypted(row.value)) continue;\n memUpdate.run(encrypt(row.value), now, row.namespace, row.key);\n touched++;\n }\n\n // 2) model_configs.params — every row.\n const modelRows = db\n .prepare(\"SELECT name, params FROM model_configs\")\n .all() as unknown as ModelConfigRow[];\n const modelUpdate = db.prepare(\n \"UPDATE model_configs SET params=?, updated_at=? WHERE name=?\",\n );\n for (const row of modelRows) {\n if (isEncrypted(row.params)) continue;\n modelUpdate.run(encrypt(row.params), now, row.name);\n touched++;\n }\n\n // 3) mcp_servers.spec — every row.\n const mcpRows = db\n .prepare(\"SELECT name, spec FROM mcp_servers\")\n .all() as unknown as McpServerRow[];\n const mcpUpdate = db.prepare(\n \"UPDATE mcp_servers SET spec=?, updated_at=? WHERE name=?\",\n );\n for (const row of mcpRows) {\n if (isEncrypted(row.spec)) continue;\n mcpUpdate.run(encrypt(row.spec), now, row.name);\n touched++;\n }\n\n if (touched > 0) {\n console.info(`[jarela] encrypted ${touched} legacy plaintext secret row(s) at rest`);\n }\n}\n","import { DatabaseSync } from \"node:sqlite\";\nimport { join } from \"node:path\";\nimport { runMigrations } from \"./migrations\";\nimport { getDataDir } from \"./data-dir\";\nimport { initMasterKey } from \"@/lib/crypto/master-key\";\nimport { runCryptoMigration } from \"@/lib/crypto/migrate\";\nimport { applyProxyConfigFromDb } from \"@/lib/proxy/dispatcher\"; // env-var dispatcher applied at module load; DB layer applied below\nimport { runEnvSyncOnce } from \"@/lib/env/sync\";\n\nexport const DB_PATH = join(getDataDir(), \"jarela.db\");\n\nlet _db: DatabaseSync | null = null;\n\nexport function getDb(): DatabaseSync {\n if (!_db) {\n // Bootstrap the at-rest encryption master key (ADR-0005) before any\n // store touches the DB. initMasterKey is synchronous and idempotent.\n const { source } = initMasterKey(getDataDir());\n if (source === \"keyfile\") {\n console.warn(\n \"[jarela] using keyfile fallback for at-rest encryption — keychain \" +\n \"access failed. The master key lives next to the DB; protect the \" +\n \"data directory accordingly. See ADR-0005.\",\n );\n }\n const db = new DatabaseSync(DB_PATH);\n db.exec(\"PRAGMA journal_mode = WAL\");\n db.exec(\"PRAGMA foreign_keys = ON\");\n runMigrations(db);\n // One-time encryption migration: rewrites legacy plaintext rows in\n // the four secret-bearing surfaces with enc:v1: envelopes. Idempotent.\n runCryptoMigration(db);\n _db = db; // only assign after migrations succeed\n // Layer DB-backed proxy config on top of the env-var dispatcher\n // (ADR-0009). Fire-and-forget — keeps getDb() synchronous so existing\n // call sites stay unchanged. Errors are logged but don't break boot;\n // worst case we fall back to direct connection.\n applyProxyConfigFromDb().catch((err) =>\n console.warn(\"[jarela/proxy] applyProxyConfigFromDb failed at boot:\", err),\n );\n // Pull rc-defined credential env vars into the encrypted integration\n // store so installed launchers (LaunchAgent / systemd-user) — which\n // never source the user's shell rc — pick up tokens automatically\n // and survive rotation. Best-effort; never blocks boot.\n runEnvSyncOnce().then((r) => {\n if (r && r.applied_count > 0) {\n console.log(\n `[jarela/env-sync] applied ${r.applied_count} field(s) from ${r.discovered.source}`,\n );\n }\n });\n }\n return _db;\n}\n\n// Close the SQLite handle so WAL is checkpointed and the lock is released\n// before the process exits. Called from the graceful-shutdown path. Safe\n// to call when the DB was never opened (no-op). Best-effort: WAL files\n// stay valid even on hard kills because SQLite is crash-resilient, but\n// a clean close means no stale -shm/-wal sidecars and a faster next boot.\nexport function closeDb(): void {\n if (!_db) return;\n const db = _db;\n _db = null;\n try {\n // PRAGMA optimize is cheap (<1ms typically) and lets SQLite run any\n // pending analyze work it would otherwise defer; safe on shutdown.\n db.exec(\"PRAGMA optimize\");\n } catch { /* not fatal — proceed with close */ }\n try {\n db.close();\n } catch (err) {\n console.warn(\"[jarela] closeDb: close failed:\", err);\n }\n}\n","import { getDb } from \"@/lib/db\";\n\nconst now = () => new Date().toISOString();\n\nconst NS = \"app-settings\";\nconst EMBEDDING_MODEL_KEY = \"embedding_model_config\";\n\nexport function getEmbeddingModelConfigName(): string | null {\n const row = getDb()\n .prepare(\"SELECT value FROM memory_store WHERE namespace=? AND key=?\")\n .get(NS, EMBEDDING_MODEL_KEY) as { value?: string } | undefined;\n const raw = row?.value;\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as unknown;\n return typeof parsed === \"string\" && parsed.trim() ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function setEmbeddingModelConfigName(name: string | null): string | null {\n if (!name) {\n getDb().prepare(\"DELETE FROM memory_store WHERE namespace=? AND key=?\").run(NS, EMBEDDING_MODEL_KEY);\n return null;\n }\n const existing = getDb()\n .prepare(\"SELECT created_at FROM memory_store WHERE namespace=? AND key=?\")\n .get(NS, EMBEDDING_MODEL_KEY) as { created_at?: string } | undefined;\n const t = now();\n const created = existing?.created_at ?? t;\n getDb()\n .prepare(\n \"INSERT OR REPLACE INTO memory_store (namespace,key,value,created_at,updated_at,embedding) VALUES (?,?,?,?,?,NULL)\",\n )\n .run(NS, EMBEDDING_MODEL_KEY, JSON.stringify(name), created, t);\n return name;\n}\n","// AES-256-GCM envelope for at-rest secret storage (ADR-0005).\n//\n// Wire format: `enc:v1:<base64url(iv ‖ ciphertext ‖ tag)>`\n// - iv: 12 bytes (random per value)\n// - ciphertext: variable\n// - tag: 16 bytes (GCM auth tag)\n//\n// The `enc:v1:` prefix is the on-disk marker for \"this value is encrypted\n// under the current scheme\". `decryptIfNeeded` returns plaintext for\n// either prefixed or legacy unprefixed values, so a partially-migrated\n// DB keeps working.\n\nimport { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\nimport { getMasterKey } from \"./master-key\";\n\nconst PREFIX = \"enc:v1:\";\nconst IV_LEN = 12;\nconst TAG_LEN = 16;\n\nexport function isEncrypted(value: string): boolean {\n return value.startsWith(PREFIX);\n}\n\nexport function encrypt(plaintext: string): string {\n const key = getMasterKey();\n const iv = randomBytes(IV_LEN);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n const ct = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n const tag = cipher.getAuthTag();\n return PREFIX + Buffer.concat([iv, ct, tag]).toString(\"base64url\");\n}\n\nexport function decrypt(envelope: string): string {\n if (!isEncrypted(envelope)) {\n throw new Error(\"decrypt() called on non-encrypted value\");\n }\n const buf = Buffer.from(envelope.slice(PREFIX.length), \"base64url\");\n if (buf.length < IV_LEN + TAG_LEN) {\n throw new Error(`encrypted payload too short: ${buf.length} bytes`);\n }\n const iv = buf.subarray(0, IV_LEN);\n const tag = buf.subarray(buf.length - TAG_LEN);\n const ct = buf.subarray(IV_LEN, buf.length - TAG_LEN);\n const key = getMasterKey();\n const decipher = createDecipheriv(\"aes-256-gcm\", key, iv);\n decipher.setAuthTag(tag);\n const pt = Buffer.concat([decipher.update(ct), decipher.final()]);\n return pt.toString(\"utf8\");\n}\n\n// Idempotent read-side helper. Plaintext (legacy) passes through; an\n// encrypted value is decrypted; an unparseable encrypted value throws.\nexport function decryptIfNeeded(value: string): string {\n return isEncrypted(value) ? decrypt(value) : value;\n}\n\n// Idempotent write-side helper. An already-encrypted value passes\n// through unchanged, which keeps the eager migration safe to re-run.\nexport function encryptIfNeeded(value: string): string {\n return isEncrypted(value) ? value : encrypt(value);\n}\n","import { getProvider } from \"@/lib/providers\";\nimport { getModelConfig, getDefaultModelConfig, getModelParams, listModelConfigs, type ModelConfigRow } from \"@/lib/stores/model-config\";\nimport { getEmbeddingModelConfigName } from \"@/lib/stores/app-settings\";\nimport { getDb } from \"@/lib/db\";\nimport { SENSITIVE_MEMORY_NAMESPACES } from \"@/lib/crypto/sensitive\";\nimport type { ProviderParams } from \"@/lib/providers/types\";\n\n// Sensitive namespaces (ADR-0005) are never surfaced via recall: their\n// values are encrypted at rest, and credentials should not reach agent\n// context via semantic search regardless.\nconst EXCLUDED_NS = [...SENSITIVE_MEMORY_NAMESPACES];\nconst EXCLUDED_NS_PLACEHOLDERS = EXCLUDED_NS.map(() => \"?\").join(\",\");\n\n// Embedding model resolution:\n// 1. EMBEDDING_MODEL_CONFIG env var → name of a row in model_configs\n// 2. Else: same provider as the default chat model + a sane default model_id\n// (text-embedding-3-small for OpenAI-compatible providers).\n// Embedding generation is best-effort: any failure returns null and the caller\n// falls back to substring search.\nasync function resolveEmbeddingClient(): Promise<{\n provider: ReturnType<typeof getProvider>;\n modelId: string;\n params: ProviderParams;\n} | null> {\n function fromConfig(cfg: ModelConfigRow | null): {\n provider: ReturnType<typeof getProvider>;\n modelId: string;\n params: ProviderParams;\n } | null {\n if (!cfg) return null;\n const params: ProviderParams = getModelParams(cfg);\n const provider = getProvider(cfg.provider);\n if (!provider.embed) return null;\n // Default to a small embedding model for the OpenAI-compatible providers if\n // the chat model_id was used (e.g. \"gpt-4o\", \"claude-...\"). Override via\n // params.embedding_model_id.\n const overridden = (params as Record<string, unknown>).embedding_model_id;\n const modelId = typeof overridden === \"string\" && overridden\n ? overridden\n : isChatModelId(cfg.model_id)\n ? \"text-embedding-3-small\"\n : cfg.model_id;\n return { provider, modelId, params };\n }\n\n const explicitName = process.env.EMBEDDING_MODEL_CONFIG;\n // 1) explicit embedding model name (if provided).\n if (explicitName) {\n const explicit = fromConfig(getModelConfig(explicitName));\n if (explicit) return explicit;\n }\n\n // 2) persisted app-level embedding model selection.\n const configuredName = getEmbeddingModelConfigName();\n if (configuredName) {\n const configured = fromConfig(getModelConfig(configuredName));\n if (configured) return configured;\n }\n\n // 3) default chat model if it also supports embeddings.\n const fromDefault = fromConfig(getDefaultModelConfig());\n if (fromDefault) return fromDefault;\n\n // 4) installation-safe fallback: any configured model with embed support.\n // This avoids \"silent 0 embeddings forever\" when default chat provider\n // (e.g. github-copilot) has no embed API but another model is configured.\n const configs = listModelConfigs();\n for (const cfg of configs) {\n if (explicitName && cfg.name === explicitName) continue;\n const candidate = fromConfig(cfg);\n if (candidate) return candidate;\n }\n return null;\n}\n\nfunction isChatModelId(id: string): boolean {\n return /^(gpt-|claude-|deepseek-chat|deepseek-reasoner)/.test(id);\n}\n\nexport async function embed(texts: string[]): Promise<number[][] | null> {\n if (texts.length === 0) return [];\n const client = await resolveEmbeddingClient();\n if (!client) return null;\n try {\n return await client.provider.embed!(client.modelId, texts, client.params);\n } catch (err) {\n console.warn(\"[embeddings] failed:\", err instanceof Error ? err.message : String(err));\n return null;\n }\n}\n\nexport async function embedOne(text: string): Promise<number[] | null> {\n const out = await embed([text]);\n return out?.[0] ?? null;\n}\n\n// HTTP status / error message → \"should we retry?\"\n// 429 = rate limit, 5xx = transient server, plus a small set of node fetch\n// codes that show up under load. Anything else is a real config / input\n// problem that retrying won't fix.\nconst TRANSIENT_RE = /\\b(429|5\\d\\d|ECONNRESET|ETIMEDOUT|EAI_AGAIN|UND_ERR_(SOCKET|CONNECT_TIMEOUT)|fetch failed)\\b/;\nfunction isTransient(err: unknown): boolean {\n return TRANSIENT_RE.test(err instanceof Error ? err.message : String(err));\n}\n\nasync function callEmbedWithRetry(\n client: { provider: ReturnType<typeof getProvider>; modelId: string; params: ProviderParams },\n texts: string[],\n): Promise<number[][]> {\n // 250ms → 1s → 4s. Three attempts is enough to ride through a brief\n // rate-limit blip without dragging out a whole reindex run.\n const backoffs = [250, 1000, 4000];\n let lastErr: unknown;\n for (let attempt = 0; attempt <= backoffs.length; attempt++) {\n try {\n return await client.provider.embed!(client.modelId, texts, client.params);\n } catch (err) {\n lastErr = err;\n if (attempt >= backoffs.length || !isTransient(err)) break;\n await new Promise((r) => setTimeout(r, backoffs[attempt]));\n }\n }\n throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));\n}\n\nexport interface EmbedBestEffortResult {\n /** One slot per input text. `null` means embedding failed for that input. */\n vectors: (number[] | null)[];\n /** First error message seen, useful for surfacing on the source row. */\n error: string | null;\n /** Count of inputs that didn't get a vector. */\n failed: number;\n}\n\n/**\n * Like `embed()` but resilient: retries transient errors (429/5xx) with\n * exponential backoff, then on persistent failure splits the batch in half\n * and recurses, so one bad input doesn't lose embeddings for every other\n * chunk in the same document.\n *\n * Returns per-input results so the caller can persist whichever vectors\n * came back and report an aggregate count of failures up to the source\n * row instead of swallowing the error.\n */\nexport async function embedBestEffort(texts: string[]): Promise<EmbedBestEffortResult> {\n if (texts.length === 0) return { vectors: [], error: null, failed: 0 };\n const client = await resolveEmbeddingClient();\n if (!client) {\n return {\n vectors: texts.map(() => null),\n error: \"no embedding provider configured\",\n failed: texts.length,\n };\n }\n return embedBestEffortInternal(client, texts);\n}\n\nasync function embedBestEffortInternal(\n client: { provider: ReturnType<typeof getProvider>; modelId: string; params: ProviderParams },\n texts: string[],\n): Promise<EmbedBestEffortResult> {\n try {\n const vectors = await callEmbedWithRetry(client, texts);\n if (vectors.length === texts.length) return { vectors, error: null, failed: 0 };\n // Provider returned a short array — pad with nulls so indices line up.\n const padded: (number[] | null)[] = texts.map((_, i) => vectors[i] ?? null);\n const failed = padded.filter((v) => v === null).length;\n return {\n vectors: padded,\n error: `embedding provider returned ${vectors.length}/${texts.length} vectors`,\n failed,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (texts.length === 1) {\n console.warn(\"[embeddings] failed:\", msg);\n return { vectors: [null], error: msg, failed: 1 };\n }\n // Halve and recurse: a single oversized input shouldn't poison its\n // batchmates. The two halves run sequentially because the typical\n // failure (rate limit) doesn't get better by parallelising.\n const mid = Math.floor(texts.length / 2);\n const left = await embedBestEffortInternal(client, texts.slice(0, mid));\n const right = await embedBestEffortInternal(client, texts.slice(mid));\n return {\n vectors: [...left.vectors, ...right.vectors],\n error: left.error ?? right.error,\n failed: left.failed + right.failed,\n };\n }\n}\n\nexport function cosine(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length === 0) return 0;\n let dot = 0, na = 0, nb = 0;\n for (let i = 0; i < a.length; i++) {\n dot += a[i] * b[i];\n na += a[i] * a[i];\n nb += b[i] * b[i];\n }\n const denom = Math.sqrt(na) * Math.sqrt(nb);\n return denom === 0 ? 0 : dot / denom;\n}\n\nexport interface RecalledMemory {\n source: \"memory\" | \"message\";\n namespace?: string;\n key?: string;\n thread_id?: string;\n role?: string;\n content: string;\n score: number;\n created_at: string;\n}\n\n// Cross-source recall: compares the query embedding against every memory entry\n// and chat message that has an embedding. Returns top-k by cosine. Falls back\n// to a recent-rows substring scan for entries that don't have an embedding yet\n// (write-then-immediate-query case where the async embed hasn't landed).\nexport async function recall(query: string, limit = 5): Promise<RecalledMemory[]> {\n const qVec = await embedOne(query);\n const db = getDb();\n const scored: RecalledMemory[] = [];\n\n // ── semantic pass ─────────────────────────────────────────────────────────\n if (qVec) {\n const memRows = db.prepare(\n // Exclude sensitive namespaces (ADR-0005) — encrypted blobs would\n // surface as enc:v1:… strings and credentials should never reach\n // the agent context via recall regardless.\n `SELECT namespace, key, value, embedding, created_at FROM memory_store\n WHERE embedding IS NOT NULL AND namespace NOT IN (${EXCLUDED_NS_PLACEHOLDERS})`,\n ).all(...EXCLUDED_NS) as Array<{ namespace: string; key: string; value: string; embedding: string; created_at: string }>;\n\n const msgRows = db.prepare(\n \"SELECT thread_id, role, content, embedding, created_at FROM messages WHERE embedding IS NOT NULL\",\n ).all() as Array<{ thread_id: string; role: string; content: string; embedding: string; created_at: string }>;\n\n for (const r of memRows) {\n const v = parseEmbedding(r.embedding);\n if (!v) continue;\n scored.push({\n source: \"memory\", namespace: r.namespace, key: r.key,\n content: r.value, score: cosine(qVec, v), created_at: r.created_at,\n });\n }\n for (const r of msgRows) {\n const v = parseEmbedding(r.embedding);\n if (!v) continue;\n scored.push({\n source: \"message\", thread_id: r.thread_id, role: r.role,\n content: r.content, score: cosine(qVec, v), created_at: r.created_at,\n });\n }\n }\n\n // ── unembedded fallback: keyword overlap on rows still pending embedding ─\n // This catches the write-then-immediately-query case where async embed\n // hasn't completed. Score is capped below the embedding floor so a real\n // semantic match always wins.\n const tokens = tokenize(query);\n if (tokens.length > 0) {\n const recentMem = db.prepare(\n `SELECT namespace, key, value, created_at FROM memory_store\n WHERE embedding IS NULL AND namespace NOT IN (${EXCLUDED_NS_PLACEHOLDERS})\n ORDER BY updated_at DESC LIMIT 50`,\n ).all(...EXCLUDED_NS) as Array<{ namespace: string; key: string; value: string; created_at: string }>;\n const recentMsg = db.prepare(\n \"SELECT thread_id, role, content, created_at FROM messages WHERE embedding IS NULL ORDER BY created_at DESC LIMIT 50\",\n ).all() as Array<{ thread_id: string; role: string; content: string; created_at: string }>;\n\n for (const r of recentMem) {\n const score = keywordOverlap(tokens, r.value);\n if (score > 0) {\n scored.push({ source: \"memory\", namespace: r.namespace, key: r.key, content: r.value, score: 0.26 + score * 0.1, created_at: r.created_at });\n }\n }\n for (const r of recentMsg) {\n const score = keywordOverlap(tokens, r.content);\n if (score > 0) {\n scored.push({ source: \"message\", thread_id: r.thread_id, role: r.role, content: r.content, score: 0.26 + score * 0.1, created_at: r.created_at });\n }\n }\n }\n\n // Dedup by a short content prefix. When several entries share the same prefix\n // (e.g. multiple revisions of the same fact: \"My codename for X is...\"),\n // keep the most recently updated one rather than the highest-scoring one —\n // semantically they're \"the same fact\" and the user wants the latest version.\n const groups = new Map<string, RecalledMemory>();\n for (const s of scored) {\n if (s.score <= 0.25) continue;\n const key = `${s.source}:${normalizeForDedup(s.content)}`;\n const existing = groups.get(key);\n if (!existing) {\n groups.set(key, s);\n } else if (s.created_at > existing.created_at) {\n // Keep the newer one but propagate the highest score we've seen for the group\n // so it doesn't lose ranking against stale duplicates.\n groups.set(key, { ...s, score: Math.max(s.score, existing.score) });\n }\n }\n return Array.from(groups.values())\n .sort((a, b) => b.score - a.score)\n .slice(0, limit);\n}\n\nfunction normalizeForDedup(text: string): string {\n // First 80 chars after collapsing whitespace — long enough to distinguish\n // different topics but short enough that \"My X for Y is FOO\" and\n // \"My X for Y is BAR\" collapse into the same group.\n return text.replace(/\\s+/g, \" \").trim().toLowerCase().slice(0, 80);\n}\n\nconst STOP_WORDS = new Set([\n \"the\", \"a\", \"an\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\", \"of\", \"to\", \"in\",\n \"on\", \"at\", \"by\", \"for\", \"with\", \"about\", \"as\", \"what\", \"which\", \"who\", \"whose\", \"why\",\n \"how\", \"do\", \"does\", \"did\", \"i\", \"me\", \"my\", \"you\", \"your\", \"it\", \"its\", \"this\", \"that\",\n \"and\", \"or\", \"but\", \"if\", \"then\", \"than\", \"so\", \"have\", \"has\", \"had\", \"can\", \"will\",\n]);\n\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9_-]+/)\n .filter((w) => w.length >= 3 && !STOP_WORDS.has(w));\n}\n\nfunction keywordOverlap(queryTokens: string[], text: string): number {\n const textLower = text.toLowerCase();\n let hits = 0;\n for (const t of queryTokens) {\n if (textLower.includes(t)) hits++;\n }\n return queryTokens.length === 0 ? 0 : hits / queryTokens.length;\n}\n\nfunction parseEmbedding(raw: string): number[] | null {\n try {\n const arr = JSON.parse(raw) as unknown;\n return Array.isArray(arr) && arr.every((n) => typeof n === \"number\") ? (arr as number[]) : null;\n } catch {\n return null;\n }\n}\n","// Mapping from \"standard\" environment variable names to integration store\n// fields. Used by the env-sync feature (lib/env/sync.ts) so common\n// rc-defined credentials (GITHUB_TOKEN, ATLASSIAN_API_TOKEN, …) populate\n// the encrypted DB automatically and survive rotation without the user\n// re-typing them in the Integrations panel.\n//\n// `ENV_ALLOWLIST` is the static, code-owned default. Users can extend any\n// row's `envVars` list at runtime via the allowlist overrides API\n// (`POST /api/v1/env-sync/allowlist`) — see ADR-0034. They cannot point a\n// new env var at a *new* (integration, field): the target side is fixed\n// here so we never write rc values into a row that has no schema.\n//\n// Adding a new mapping is one line. The integration name MUST exist in\n// `INTEGRATIONS` (lib/stores/integrations.ts) and the field key MUST\n// match — there is a build-time check in scripts/check-env-allowlist.mjs\n// that fails the lint step otherwise.\n\nimport { getMemory, listMemory, putMemory, deleteMemory } from \"@/lib/stores/memory\";\nimport { INTEGRATIONS, getIntegrationRaw, isKnownIntegration, type IntegrationName } from \"@/lib/stores/integrations\";\n\nconst OVERRIDES_NS = \"env_allowlist_overrides\";\n\nexport interface EnvFieldMapping {\n /**\n * Env var names in priority order. The first one that is present and\n * non-empty wins. Lets us support both vendor-canonical names and the\n * older aliases users tend to have in their dotfiles.\n */\n envVars: string[];\n integration: IntegrationName;\n field: string;\n}\n\nexport const ENV_ALLOWLIST: readonly EnvFieldMapping[] = [\n // Anthropic (Claude) — primary LLM provider\n { envVars: [\"ANTHROPIC_API_KEY\"], integration: \"anthropic\", field: \"api_key\" },\n\n // GitHub — used by github_* tools (ADR-0015)\n { envVars: [\"GITHUB_TOKEN\", \"GH_TOKEN\"], integration: \"github\", field: \"token\" },\n\n // Atlassian — Jira + Confluence\n { envVars: [\"ATLASSIAN_URL\", \"JIRA_URL\"], integration: \"atlassian\", field: \"url\" },\n { envVars: [\"ATLASSIAN_EMAIL\", \"JIRA_EMAIL\"], integration: \"atlassian\", field: \"email\" },\n { envVars: [\"ATLASSIAN_API_TOKEN\", \"JIRA_API_TOKEN\", \"JIRA_TOKEN\"], integration: \"atlassian\", field: \"api_token\" },\n\n // Google AI (Gemini / Imagen) — used by generate_image\n { envVars: [\"GOOGLE_API_KEY\", \"GEMINI_API_KEY\"], integration: \"google\", field: \"api_key\" },\n];\n\n// ── User overrides ───────────────────────────────────────────────────────────\n// Stored as `memory_store` rows in namespace `\"env_allowlist_overrides\"`.\n// Key is `\"<integration>:<field>\"`, value is `{ envVars: string[] }`. The\n// listed names are *additional* aliases — defaults always remain so a\n// user who renames their dotfile var doesn't lose the canonical fallback.\n\nconst OVERRIDE_KEY = (integration: string, field: string): string => `${integration}:${field}`;\n\ninterface StoredOverride { envVars: string[] }\n\nfunction parseOverride(raw: string): string[] {\n try {\n const parsed = JSON.parse(raw) as StoredOverride;\n if (parsed && Array.isArray(parsed.envVars)) {\n return parsed.envVars.filter((v) => typeof v === \"string\" && v.trim().length > 0);\n }\n } catch { /* fall through */ }\n return [];\n}\n\n/** Read every (integration, field) override the user has saved. */\nexport function listOverrides(): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const row of listMemory(OVERRIDES_NS, undefined, 200)) {\n out[row.key] = parseOverride(row.value);\n }\n return out;\n}\n\n/** Read one override; returns the empty list when none is stored. */\nexport function getOverride(integration: string, field: string): string[] {\n const row = getMemory(OVERRIDES_NS, OVERRIDE_KEY(integration, field));\n return row ? parseOverride(row.value) : [];\n}\n\n/**\n * Persist an override. Validates that the (integration, field) pair points\n * at an existing schema entry — env-var renames cannot create new targets.\n * Names are uppercased and de-duplicated; defaults are stripped from the\n * stored payload so a future schema change to canonical names doesn't\n * leave dead duplicates behind.\n */\nexport function setOverride(integration: string, field: string, envVars: string[]):\n | { ok: true; envVars: string[] }\n | { ok: false; error: string }\n{\n if (!isKnownIntegration(integration)) {\n return { ok: false, error: `unknown integration \"${integration}\"` };\n }\n const def = INTEGRATIONS[integration];\n if (!def.fields.some((f) => f.key === field)) {\n return { ok: false, error: `unknown field \"${field}\" on integration \"${integration}\"` };\n }\n const defaults = defaultAliasesFor(integration, field);\n const cleaned: string[] = [];\n const seen = new Set<string>(defaults);\n for (const raw of envVars) {\n if (typeof raw !== \"string\") continue;\n const name = raw.trim().toUpperCase();\n if (!name) continue;\n if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) {\n return { ok: false, error: `\"${raw}\" is not a valid env var name` };\n }\n if (seen.has(name)) continue;\n seen.add(name);\n cleaned.push(name);\n }\n if (cleaned.length === 0) {\n deleteMemory(OVERRIDES_NS, OVERRIDE_KEY(integration, field));\n return { ok: true, envVars: [] };\n }\n putMemory(OVERRIDES_NS, OVERRIDE_KEY(integration, field), { envVars: cleaned } satisfies StoredOverride);\n return { ok: true, envVars: cleaned };\n}\n\n/** Drop the override row for one (integration, field). */\nexport function deleteOverride(integration: string, field: string): boolean {\n return deleteMemory(OVERRIDES_NS, OVERRIDE_KEY(integration, field));\n}\n\nfunction defaultAliasesFor(integration: string, field: string): string[] {\n const m = ENV_ALLOWLIST.find((m) => m.integration === integration && m.field === field);\n return m ? [...m.envVars] : [];\n}\n\n// ── Effective allowlist ──────────────────────────────────────────────────────\n\n/**\n * `ENV_ALLOWLIST` merged with stored overrides. Default aliases come first\n * so they keep their priority during sync; user-added aliases are appended\n * after them. The shape is identical to `ENV_ALLOWLIST` so call sites can\n * iterate either one — only `runSync` and `getAllEnvVarNames` need the\n * effective view today.\n */\nexport function getEffectiveAllowlist(): EnvFieldMapping[] {\n const overrides = listOverrides();\n return ENV_ALLOWLIST.map((m) => {\n const extra = overrides[OVERRIDE_KEY(m.integration, m.field)] ?? [];\n if (extra.length === 0) return { ...m, envVars: [...m.envVars] };\n const merged = [...m.envVars];\n const seen = new Set(merged);\n for (const name of extra) {\n if (!seen.has(name)) {\n merged.push(name);\n seen.add(name);\n }\n }\n return { ...m, envVars: merged };\n });\n}\n\n/** Flat list of every env var name we look at — defaults + user overrides. */\nexport function getAllEnvVarNames(): string[] {\n const set = new Set<string>();\n for (const m of getEffectiveAllowlist()) for (const n of m.envVars) set.add(n);\n return [...set];\n}\n\n/**\n * Render the encrypted integration store back into a `Record<envVarName, value>`\n * so subprocesses (MCP children, `local_exec` shells) can read credentials\n * even when they were never exported in the launching shell — e.g. when\n * Jarela is installed as a service. For each `(integration, field)` row in\n * the effective allowlist that has a stored value, every alias name (default\n * + user-added override) is set to that value. The first alias to be\n * inserted wins if two different rows would somehow collide.\n */\nexport function getInjectedSubprocessEnv(): Record<string, string> {\n const out: Record<string, string> = {};\n for (const m of getEffectiveAllowlist()) {\n const value = getIntegrationRaw(m.integration)?.[m.field];\n if (!value) continue;\n for (const name of m.envVars) {\n if (!(name in out)) out[name] = value;\n }\n }\n return out;\n}\n","// Cross-platform discovery of \"shell-defined\" environment variables.\n//\n// The problem: Jarela installed as a macOS LaunchAgent or a Linux systemd\n// user unit doesn't run inside a login shell, so it never sees vars\n// defined in `.zshrc`/`.bashrc`. Windows is the opposite — User-scope\n// vars set via the Settings UI/registry ARE inherited by every process,\n// but vars set only inside a PowerShell `$PROFILE` are not.\n//\n// Strategy:\n// - macOS / Linux: spawn `$SHELL -ic '<print-allowlisted>'`. Sourcing\n// the rc file is the whole point of the `-i` flag. Output is\n// framed with a unique sentinel so user rc echo doesn't poison the\n// parser.\n// - Windows: read the User-scope environment block via\n// `[Environment]::GetEnvironmentVariable($name, 'User')`. This hits\n// the registry directly — no rc-equivalent to source.\n//\n// Always falls back gracefully to whatever is already in `process.env`.\n// Hard 4 s timeout per probe so a hung shell can't stall startup.\n\nimport { spawn } from \"node:child_process\";\nimport { platform } from \"node:os\";\n\nexport type DiscoverySource =\n | \"process\"\n | \"shell-rc\"\n | \"windows-registry\"\n | \"unavailable\";\n\nexport interface DiscoveredEnv {\n values: Record<string, string>;\n source: DiscoverySource;\n /** Path to the shell that ran (unix), or \"powershell\" on Windows. */\n shell: string | null;\n warnings: string[];\n /** Probe wall-time in ms — useful for telemetry / debugging. */\n elapsed_ms: number;\n}\n\nconst TIMEOUT_MS = 4000;\nconst SENTINEL_OPEN = \"__JARELA_ENV_BEGIN__\";\nconst SENTINEL_CLOSE = \"__JARELA_ENV_END__\";\n\n/**\n * Discover values for the given allowlist of env-var names. Always\n * returns; never throws. On platforms or shells we can't probe, falls\n * back to `process.env`.\n */\nexport async function discoverEnvVars(allowlist: readonly string[]): Promise<DiscoveredEnv> {\n const t0 = Date.now();\n const warnings: string[] = [];\n\n // Baseline: whatever the running process already has. On Windows this\n // already includes registry User vars. In dev mode (`npm run dev` from\n // a terminal) it includes the parent shell's exports.\n const fromProcess: Record<string, string> = {};\n for (const name of allowlist) {\n const v = process.env[name];\n if (v && v.trim()) fromProcess[name] = v.trim();\n }\n\n if (platform() === \"win32\") {\n const reg = await queryWindowsUserEnv(allowlist).catch((e: unknown): null => {\n warnings.push(`windows registry probe failed: ${String(e)}`);\n return null;\n });\n if (reg) {\n // Registry wins over process.env: the registry is the *current*\n // truth, while process.env is frozen at process-spawn time. This\n // is what makes rotation pickup work after the user updates a\n // var in the Settings UI without restarting the app.\n return {\n values: { ...fromProcess, ...reg },\n source: \"windows-registry\",\n shell: \"powershell\",\n warnings,\n elapsed_ms: Date.now() - t0,\n };\n }\n return {\n values: fromProcess,\n source: \"process\",\n shell: null,\n warnings,\n elapsed_ms: Date.now() - t0,\n };\n }\n\n // macOS / Linux\n const shell = process.env.SHELL || \"/bin/sh\";\n const fromShell = await queryUnixShellEnv(shell, allowlist).catch((e: unknown): null => {\n warnings.push(`shell rc probe (${shell}) failed: ${String(e)}`);\n return null;\n });\n if (fromShell) {\n return {\n values: { ...fromProcess, ...fromShell },\n source: \"shell-rc\",\n shell,\n warnings,\n elapsed_ms: Date.now() - t0,\n };\n }\n return {\n values: fromProcess,\n source: \"process\",\n shell,\n warnings,\n elapsed_ms: Date.now() - t0,\n };\n}\n\nfunction queryUnixShellEnv(shell: string, allowlist: readonly string[]): Promise<Record<string, string>> {\n return new Promise((resolve, reject) => {\n // Frame each var with sentinels so any noise the user's rc prints\n // (oh-my-zsh banners, version-manager init logs, etc.) gets\n // skipped by the parser. Single-quoted names are JS-side string\n // constants, double-quoted \"$VAR\" lets the shell expand.\n const lines = allowlist\n .map(\n (n) =>\n `printf '${SENTINEL_OPEN}%s=%s${SENTINEL_CLOSE}\\\\n' '${n}' \"$${n}\"`,\n )\n .join(\"; \");\n // Suppress prompts and history side-effects. Pipe stderr to /dev/null\n // — we don't care about rc-emitted warnings.\n const child = spawn(shell, [\"-ic\", lines], {\n env: { ...process.env, PS1: \"\", PROMPT: \"\", HISTFILE: \"/dev/null\" },\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n let stdout = \"\";\n const t = setTimeout(() => {\n child.kill(\"SIGKILL\");\n reject(new Error(\"timeout\"));\n }, TIMEOUT_MS);\n child.stdout.on(\"data\", (b: Buffer) => {\n stdout += b.toString();\n });\n child.on(\"close\", (code: number | null) => {\n clearTimeout(t);\n if (code !== 0 && code !== null) {\n // Some shells return non-zero from `-ic` if rc has any failing\n // command, but our printfs still ran first — try parsing anyway.\n // Only reject if we got nothing usable.\n const parsed = parseSentinelStream(stdout, allowlist);\n if (Object.keys(parsed).length === 0) {\n return reject(new Error(`shell exited ${code} with no parseable output`));\n }\n return resolve(parsed);\n }\n resolve(parseSentinelStream(stdout, allowlist));\n });\n child.on(\"error\", (e: Error) => {\n clearTimeout(t);\n reject(e);\n });\n });\n}\n\nasync function queryWindowsUserEnv(allowlist: readonly string[]): Promise<Record<string, string>> {\n // Try modern PowerShell 7+ (pwsh) first, then fall back to the always-\n // present Windows PowerShell 5.1 (powershell.exe). pwsh defaults to\n // UTF-8 stdout; powershell.exe 5.1 defaults to UTF-16, so we force\n // UTF-8 inside the script either way.\n try {\n return await runWindowsProbe(\"pwsh.exe\", allowlist);\n } catch {\n return await runWindowsProbe(\"powershell.exe\", allowlist);\n }\n}\n\nfunction runWindowsProbe(exe: string, allowlist: readonly string[]): Promise<Record<string, string>> {\n return new Promise((resolve, reject) => {\n const namesArr = allowlist.map((n) => `'${n.replace(/'/g, \"''\")}'`).join(\",\");\n // Force UTF-8 stdout — Windows PowerShell 5.1 emits UTF-16 LE by\n // default, which would garble the sentinel parser. The\n // `[Console]::OutputEncoding` line is a no-op on pwsh 7+ but\n // critical on legacy powershell.exe.\n const script =\n `[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ` +\n `$names = @(${namesArr}); ` +\n `foreach ($n in $names) { ` +\n ` $v = [Environment]::GetEnvironmentVariable($n, 'User'); ` +\n ` if ($v) { Write-Output ('${SENTINEL_OPEN}' + $n + '=' + $v + '${SENTINEL_CLOSE}') } ` +\n `}`;\n const child = spawn(\n exe,\n [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-Command\", script],\n { stdio: [\"ignore\", \"pipe\", \"ignore\"], windowsHide: true },\n );\n let stdout = \"\";\n const t = setTimeout(() => {\n child.kill(\"SIGKILL\");\n reject(new Error(\"timeout\"));\n }, TIMEOUT_MS);\n child.stdout.on(\"data\", (b: Buffer) => {\n stdout += b.toString(\"utf8\");\n });\n child.on(\"close\", (code: number | null) => {\n clearTimeout(t);\n if (code !== 0 && code !== null) return reject(new Error(`${exe} exited ${code}`));\n resolve(parseSentinelStream(stdout, allowlist));\n });\n child.on(\"error\", (e: Error) => {\n clearTimeout(t);\n reject(e);\n });\n });\n}\n\n/**\n * Pull `__OPEN__NAME=VALUE__CLOSE__` segments out of a stream, ignoring\n * everything else. Tolerates rc-line noise and partial reads.\n */\nfunction parseSentinelStream(stream: string, allowlist: readonly string[]): Record<string, string> {\n const allow = new Set(allowlist);\n const out: Record<string, string> = {};\n // Non-greedy, case-sensitive, multi-line capable. Use `split` so we\n // don't depend on regex flags that some Node versions surface oddly.\n const parts = stream.split(SENTINEL_OPEN);\n for (let i = 1; i < parts.length; i += 1) {\n const seg = parts[i];\n const end = seg.indexOf(SENTINEL_CLOSE);\n if (end < 0) continue;\n const body = seg.slice(0, end);\n const eq = body.indexOf(\"=\");\n if (eq <= 0) continue;\n const name = body.slice(0, eq);\n const value = body.slice(eq + 1).trim();\n if (allow.has(name) && value) out[name] = value;\n }\n return out;\n}\n","// Env-sync orchestrator. Reads \"standard\" credential env vars from the\n// user's shell rc (or Windows User registry), writes them into the\n// encrypted integration store, and tracks per-field provenance so user\n// edits in the Integrations panel are never overwritten.\n//\n// Conflict rule: \"panel-wins-once-touched\". A field whose meta source\n// is `\"user\"` is skipped on every sync; one whose source is `\"rc\"` (or\n// absent) gets the rc value written through. This is what makes\n// rotation flow through automatically — the user updates `.zshrc`, the\n// next sync picks it up, the encrypted DB row updates, and the\n// existing env-then-store fallback in `lib/tools/atlassian.ts` /\n// `lib/tools/github.ts` reads the fresh value on the next tool call.\n//\n// Triggered:\n// - Once per process from `lib/db/index.ts` after DB init (silent,\n// fire-and-forget).\n// - On demand via POST /api/v1/env-sync (returns a SyncResult so the\n// UI can show what happened).\n\nimport { getEffectiveAllowlist, getAllEnvVarNames, type EnvFieldMapping } from \"./allowlist\";\nimport { discoverEnvVars, type DiscoveredEnv } from \"./discover\";\nimport {\n INTEGRATIONS,\n getIntegrationRaw,\n isKnownIntegration,\n type IntegrationName,\n} from \"@/lib/stores/integrations\";\nimport { getIntegrationMeta, setFieldSources, type FieldSource } from \"@/lib/stores/integration_meta\";\nimport { putMemory } from \"@/lib/stores/memory\";\n\nconst INTEGRATIONS_NS = \"integrations\";\n\nexport type SyncAction =\n | \"would-write\" // candidate is eligible, will (or did) overwrite\n | \"skipped-user\" // user has touched this field — leave it alone\n | \"skipped-equal\" // rc value matches what's already stored\n | \"skipped-empty\" // env var was set but empty after trim\n | \"absent\"; // env var not set in any allowlist alias\n\nexport interface SyncCandidate {\n /** Which env var name actually held the value (first present alias). */\n envVar: string | null;\n integration: string;\n field: string;\n /** Current meta source for this field — what's in the DB right now. */\n current_source: FieldSource | \"absent\";\n current_value_present: boolean;\n /** Masked preview of the rc value (full value for non-secret fields). */\n rc_value_preview: string | null;\n action: SyncAction;\n}\n\nexport interface SyncResult {\n discovered: DiscoveredEnv;\n candidates: SyncCandidate[];\n /** Subset of `candidates` where action === \"would-write\" and apply=true. */\n applied_count: number;\n ts: string;\n}\n\n/** Public — non-mutating; lets the UI show what *would* happen. */\nexport async function previewEnvSync(): Promise<SyncResult> {\n return runSync(false);\n}\n\n/** Public — mutates the DB (writes \"rc\"-sourced fields). */\nexport async function applyEnvSync(): Promise<SyncResult> {\n return runSync(true);\n}\n\n// Module-level guard so we run at most once per process from the\n// fire-and-forget startup hook. The on-demand API endpoint bypasses\n// this and re-runs every call.\nlet _bootRanPromise: Promise<SyncResult> | null = null;\n\n/**\n * Idempotent boot-time apply. First call kicks off; subsequent calls\n * within the same process return the same promise. Errors are\n * swallowed (logged) — env-sync is best-effort, never blocks startup.\n */\nexport function runEnvSyncOnce(): Promise<SyncResult | null> {\n if (_bootRanPromise) return _bootRanPromise.catch(() => null);\n _bootRanPromise = applyEnvSync();\n return _bootRanPromise.catch((err) => {\n console.warn(\"[jarela/env-sync] boot apply failed:\", err);\n return null;\n });\n}\n\nasync function runSync(apply: boolean): Promise<SyncResult> {\n const discovered = await discoverEnvVars(getAllEnvVarNames());\n const ts = new Date().toISOString();\n const candidates: SyncCandidate[] = [];\n\n // Group writes by integration so we issue one putMemory per row.\n const writesByIntegration = new Map<string, Record<string, string>>();\n const metaUpdates: Array<{ name: string; field: string; source: FieldSource }> = [];\n\n for (const m of getEffectiveAllowlist()) {\n if (!isKnownIntegration(m.integration)) continue; // allowlist drift; ignore\n const cand = evaluateCandidate(m, discovered.values);\n candidates.push(cand);\n\n if (apply && cand.action === \"would-write\") {\n const existing = getIntegrationRaw(m.integration) ?? {};\n const w = writesByIntegration.get(m.integration) ?? { ...existing };\n const value = pickEnvValue(m, discovered.values);\n if (value !== null) w[m.field] = value;\n writesByIntegration.set(m.integration, w);\n metaUpdates.push({ name: m.integration, field: m.field, source: \"rc\" });\n }\n }\n\n let applied_count = 0;\n if (apply && writesByIntegration.size > 0) {\n for (const [name, fields] of writesByIntegration) {\n putMemory(INTEGRATIONS_NS, name, fields);\n }\n setFieldSources(metaUpdates, ts);\n applied_count = metaUpdates.length;\n }\n\n return { discovered, candidates, applied_count, ts };\n}\n\nfunction evaluateCandidate(\n m: EnvFieldMapping,\n values: Record<string, string>,\n): SyncCandidate {\n const envVar = m.envVars.find((n) => values[n]) ?? null;\n const rcValue = envVar ? values[envVar] : null;\n const meta = getIntegrationMeta(m.integration);\n const sourceFlag = meta.source[m.field];\n const existing = getIntegrationRaw(m.integration);\n const currentValue = existing?.[m.field] ?? null;\n const currentSource: SyncCandidate[\"current_source\"] = sourceFlag ?? \"absent\";\n const isSecret = isFieldSecret(m.integration, m.field);\n\n let action: SyncAction;\n if (envVar === null || rcValue === null) {\n action = \"absent\";\n } else if (sourceFlag === \"user\") {\n action = \"skipped-user\";\n } else if (!rcValue.trim()) {\n action = \"skipped-empty\";\n } else if (currentValue === rcValue) {\n action = \"skipped-equal\";\n } else {\n action = \"would-write\";\n }\n\n return {\n envVar,\n integration: m.integration,\n field: m.field,\n current_source: currentSource,\n current_value_present: !!currentValue,\n rc_value_preview: rcValue ? maskValue(rcValue, isSecret) : null,\n action,\n };\n}\n\nfunction pickEnvValue(m: EnvFieldMapping, values: Record<string, string>): string | null {\n for (const n of m.envVars) {\n const v = values[n];\n if (v && v.trim()) return v.trim();\n }\n return null;\n}\n\nfunction isFieldSecret(integration: IntegrationName, field: string): boolean {\n const def = INTEGRATIONS[integration];\n return def.fields.find((f) => f.key === field)?.secret ?? true;\n}\n\nfunction maskValue(value: string, isSecret: boolean): string {\n if (!isSecret) return value;\n if (value.length <= 6) return \"***\";\n return value.slice(0, 4) + \"…\" + value.slice(-2);\n}\n","// Sensitive namespaces in `memory_store` whose `value` column holds\n// secret material that must be encrypted at rest (ADR-0005).\n//\n// Centralised here so stores and the migration agree on the same list.\n\nexport const SENSITIVE_MEMORY_NAMESPACES: ReadonlySet<string> = new Set([\n \"integrations\", // Atlassian / Gmail OAuth / Gemini keys\n \"github-copilot-auth\", // GitHub Copilot device-flow OAuth token\n \"tool-secrets\", // Secrets for external tools (ADR-0023)\n]);\n\nexport function isSensitiveMemoryNamespace(ns: string): boolean {\n return SENSITIVE_MEMORY_NAMESPACES.has(ns);\n}\n","// Resolves the Jarela data directory and performs one-time migrations:\n//\n// 1. Legacy LangGUI layout (~/.langgui with langgui.db) — rebrand\n// migration: rename the dir + the DB files.\n// 2. On Windows, ~/.jarela → %LOCALAPPDATA%\\Jarela (ADR-0006) to escape\n// OneDrive-synced user-profile paths.\n//\n// No backward-compat for env vars is retained at the code level; both\n// migrations are best-effort renames on first launch against a populated\n// machine so existing users keep their data.\n\nimport { existsSync, mkdirSync, renameSync, readdirSync, rmdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nlet cached: string | null = null;\n\nfunction expandHome(p: string): string {\n return p.startsWith(\"~\") ? p.replace(/^~/, homedir()) : p;\n}\n\n// A dir \"has DB\" iff it contains jarela.db OR langgui.db. We treat the\n// presence of a DB as the signal that the dir holds real user state;\n// otherwise it may just be a vestigial launcher working dir\n// (e.g. %LOCALAPPDATA%\\Jarela created by installed-launcher.vbs with\n// only files/ and logs/ inside).\nfunction hasDb(dir: string): boolean {\n if (!existsSync(dir)) return false;\n try {\n return readdirSync(dir).some((n) => n === \"jarela.db\" || n === \"langgui.db\");\n } catch {\n return false;\n }\n}\n\nfunction migrateLegacyDir(legacyDir: string, newDir: string): void {\n if (!existsSync(legacyDir)) return;\n if (hasDb(newDir)) return; // new dir already has user state — never overwrite.\n\n mkdirSync(newDir, { recursive: true });\n\n // Move contents item-by-item so we can merge into a partially-existing\n // newDir (e.g. one containing only logs/ from a prior launcher run).\n // Skips items that already exist on the destination side.\n let entries: string[] = [];\n try { entries = readdirSync(legacyDir); } catch { entries = []; }\n\n let moved = 0;\n for (const name of entries) {\n const from = join(legacyDir, name);\n const to = join(newDir, name);\n if (existsSync(to)) continue;\n try {\n renameSync(from, to);\n moved++;\n } catch (err) {\n // EXDEV: cross-volume rename. EPERM/EBUSY: locked by another\n // process. Non-fatal: skip this item and continue with the rest.\n console.warn(\n `[jarela] could not move ${from} -> ${to}: ${(err as Error).message}`,\n );\n }\n }\n\n // Rename DB files: langgui.db -> jarela.db (and any -wal / -shm sidecars).\n let postEntries: string[] = [];\n try { postEntries = readdirSync(newDir); } catch { postEntries = []; }\n for (const name of postEntries) {\n if (!name.startsWith(\"langgui.db\")) continue;\n const suffix = name.slice(\"langgui.db\".length); // \"\", \"-wal\", \"-shm\", \"-journal\"\n const from = join(newDir, name);\n const to = join(newDir, `jarela.db${suffix}`);\n if (existsSync(to)) continue;\n try { renameSync(from, to); } catch { /* leave as-is; DB layer recreates */ }\n }\n\n // Best-effort cleanup of an emptied legacy dir. If anything remained\n // (locked files, dotfiles we declined to move) leave the dir in place.\n try {\n if (readdirSync(legacyDir).length === 0) {\n rmdirSync(legacyDir);\n }\n } catch { /* */ }\n\n if (moved > 0) {\n console.info(`[jarela] migrated ${moved} entries from ${legacyDir} -> ${newDir}`);\n }\n}\n\nexport function getDataDir(): string {\n if (cached) return cached;\n\n const envDir = process.env.JARELA_DB_DIR;\n const newDir = envDir ? expandHome(envDir) : defaultDataDir();\n\n // Only run automatic migrations for the default location; if the user\n // customized JARELA_DB_DIR they're explicitly opting out.\n if (!envDir) {\n // Chain order matters: rebrand first so a ~/.langgui from the old\n // build lands at ~/.jarela, then the Windows-only move lifts that to\n // %LOCALAPPDATA%\\Jarela in the same boot.\n migrateLegacyDir(join(homedir(), \".langgui\"), join(homedir(), \".jarela\"));\n if (process.platform === \"win32\" && newDir !== join(homedir(), \".jarela\")) {\n migrateLegacyDir(join(homedir(), \".jarela\"), newDir);\n }\n }\n\n mkdirSync(newDir, { recursive: true });\n cached = newDir;\n return newDir;\n}\n\nfunction defaultDataDir(): string {\n if (process.platform === \"win32\") {\n const local = process.env.LOCALAPPDATA ?? join(homedir(), \"AppData\", \"Local\");\n return join(local, \"Jarela\");\n }\n return join(homedir(), \".jarela\");\n}\n","// macOS keychain → PEM bundle export (ADR-0020).\n//\n// macOS hosts behind a TLS-intercepting corporate proxy receive the\n// internal root (used by the proxy to re-sign outbound TLS) via MDM or\n// manual install, which lands it in the System and Login keychains. We\n// extract those certs to a single\n// PEM file under the Jarela data dir, then point both undici's\n// `requestTls.ca` (live) and the launchd plist's `NODE_EXTRA_CA_CERTS`\n// (next restart) at it. End result: one source of truth (the OS), one\n// destination (~/.jarela/system-ca.pem), zero manual paste.\n//\n// Sibling to `parseScutilProxy()` in dispatcher.ts — both turn an OS-level\n// settings surface into something the dispatcher can consume.\n\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync, writeFileSync, chmodSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { getDataDir } from \"@/lib/db/data-dir\";\n\nexport interface KeychainExtractResult {\n pemPath: string; // absolute path to the written bundle\n certCount: number; // unique BEGIN CERTIFICATE blocks\n source: \"macos-keychain\";\n keychains: string[]; // which keychains contributed\n}\n\nconst KEYCHAINS_TO_TRY = [\n \"/Library/Keychains/System.keychain\",\n \"/System/Library/Keychains/SystemRootCertificates.keychain\",\n // login.keychain-db lives under each user's home; resolved at runtime.\n];\n\nconst PEM_BLOCK_RE = /-----BEGIN CERTIFICATE-----[\\s\\S]+?-----END CERTIFICATE-----/g;\n\n// Exported for unit testing — the bare parser side, no fs / spawn.\n// Returns deduped PEM blocks in first-seen order so callers can attribute\n// \"this cert came from system\" vs \"from login\".\nexport function parseSecurityFindCertificate(stdout: string): string[] {\n const seen = new Set<string>();\n const blocks: string[] = [];\n const matches = stdout.match(PEM_BLOCK_RE) ?? [];\n for (const raw of matches) {\n // Normalise line endings so a CR-different copy of the same cert\n // doesn't slip past the dedupe.\n const normalised = raw.replace(/\\r\\n/g, \"\\n\").trim();\n if (seen.has(normalised)) continue;\n seen.add(normalised);\n blocks.push(normalised);\n }\n return blocks;\n}\n\n// Extract all certificates from the user's macOS trust stores into a\n// single PEM bundle at <dataDir>/system-ca.pem. Returns the path + count.\n//\n// On non-darwin platforms returns { error } — callers should treat this\n// as \"no system trust available, proceed without an injected bundle\".\nexport function extractSystemKeychainCAs(): KeychainExtractResult | { error: string } {\n if (process.platform !== \"darwin\") {\n return { error: \"system trust extraction is macOS-only in v1\" };\n }\n\n const candidates = [...KEYCHAINS_TO_TRY, join(homedir(), \"Library/Keychains/login.keychain-db\")];\n const used: string[] = [];\n const allPem: string[] = [];\n\n for (const kc of candidates) {\n if (!existsSync(kc)) continue;\n try {\n // -a = all matches, -p = output PEM. The path positional arg\n // restricts the search to this keychain. Fixed argv (no shell)\n // — safe even though no part of this is user-controlled.\n const out = execFileSync(\n \"/usr/bin/security\",\n [\"find-certificate\", \"-a\", \"-p\", kc],\n { encoding: \"utf8\", maxBuffer: 16 * 1024 * 1024 },\n );\n const blocks = parseSecurityFindCertificate(out);\n if (blocks.length > 0) {\n used.push(kc);\n allPem.push(...blocks);\n }\n } catch (err) {\n // Empty keychain or permission refusal — skip and continue.\n // We still want partial extraction (system but not login, etc.)\n // to succeed.\n console.warn(`[jarela/keychain] could not read ${kc}: ${(err as Error).message}`);\n }\n }\n\n // Dedupe across keychains: the same root commonly appears in System\n // and SystemRootCertificates.\n const deduped = parseSecurityFindCertificate(allPem.join(\"\\n\"));\n\n if (deduped.length === 0) {\n return { error: \"no certificates extracted from any keychain (security find-certificate returned empty)\" };\n }\n\n const pemPath = join(getDataDir(), \"system-ca.pem\");\n const body =\n `# Jarela system trust bundle — generated from macOS keychains.\\n` +\n `# Source keychains: ${used.join(\", \")}\\n` +\n `# ${deduped.length} unique certificates. Regenerate via the Proxy panel\\n` +\n `# \"Refresh trust store\" button, or by re-running 'jarela install-service'.\\n\\n` +\n deduped.join(\"\\n\") +\n \"\\n\";\n writeFileSync(pemPath, body, \"utf8\");\n // Trust bundle is not secret but is user-scoped state; 0600 keeps it\n // tidy alongside the SQLite file's permissions.\n try { chmodSync(pemPath, 0o600); } catch { /* best-effort */ }\n\n return {\n pemPath,\n certCount: deduped.length,\n source: \"macos-keychain\",\n keychains: used,\n };\n}\n","// HTTP proxy dispatcher (ADR-0009).\n//\n// Routes every undici-backed `fetch` in the server through an HTTP proxy\n// when one is configured, so corporate-network installs reach LLM\n// providers, MCP servers, and integration APIs.\n//\n// Two configuration sources, in priority order:\n// 1. process.env.HTTP_PROXY / HTTPS_PROXY / NO_PROXY (and their\n// lowercase aliases). Captured at process start so a later DB\n// change cannot accidentally override an explicit env override.\n// 2. proxy_config row in SQLite. Read after DB init via\n// applyProxyConfigFromDb(); re-applied from the settings save\n// handler so changes take effect without a server restart.\n//\n// All paths funnel through `setGlobalDispatcher` so existing call sites\n// (providers, tools, MCP, embeddings) inherit the dispatcher at fetch\n// time. SDK clients are constructed per-call inside provider methods so\n// the next outbound request after a swap picks up the new proxy\n// immediately (see ADR-0009 \"Live-swap caveats\" for the two narrow\n// exceptions: in-flight long-lived streams and child-process MCP\n// servers).\n\nimport { exec } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { promisify } from \"node:util\";\nimport {\n Agent,\n EnvHttpProxyAgent,\n ProxyAgent,\n getGlobalDispatcher,\n setGlobalDispatcher,\n type Dispatcher,\n} from \"undici\";\nimport { getProxyConfigRaw, type ProxyConfigRaw, type ProxyScheme } from \"@/lib/stores/proxy-config\";\nimport { extractSystemKeychainCAs } from \"@/lib/proxy/keychain\";\n\nconst execAsync = promisify(exec);\n\n// Snapshot of HTTP proxy env vars at module load. If the user set them\n// before launch (terminal session, plist EnvironmentVariables, …) we\n// honor that and ignore the DB config. This preserves the documented\n// override path: env > DB.\nconst ENV_HAD_PROXY_AT_BOOT = !!(\n process.env.HTTP_PROXY ||\n process.env.HTTPS_PROXY ||\n process.env.http_proxy ||\n process.env.https_proxy\n);\n\nlet baselineDispatcher: Dispatcher | null = null;\nlet envInstalled = false;\n\n// ---------------------------------------------------------------------\n// Synchronous boot-time setup\n// ---------------------------------------------------------------------\n// Runs at module import (before DB init). Installs the env-var-based\n// dispatcher synchronously so any keychain / migration path that does\n// outbound HTTP from boot can use the proxy. The DB-based layer applies\n// later via applyProxyConfigFromDb().\nexport function ensureProxyDispatcher(): void {\n if (envInstalled) return;\n envInstalled = true;\n // Capture whatever undici initialized as the default so we can revert\n // to it when the user picks `mode = off` and there are no env vars.\n baselineDispatcher = getGlobalDispatcher();\n if (ENV_HAD_PROXY_AT_BOOT) {\n setGlobalDispatcher(new EnvHttpProxyAgent());\n }\n}\n\nensureProxyDispatcher();\n\n// ---------------------------------------------------------------------\n// Async DB-backed apply\n// ---------------------------------------------------------------------\n\nexport interface ApplyResult {\n source: \"env\" | \"manual\" | \"system\" | \"off\";\n proxyUrl: string | null;\n note?: string;\n // ADR-0020: system mode also auto-extracts the macOS keychain trust\n // store into a managed PEM file. Surfaced so the UI can show\n // \"System trust: 187 certs from ~/.jarela/system-ca.pem\".\n caBundlePath?: string;\n caBundleCertCount?: number;\n caBundleSource?: \"macos-keychain\";\n}\n\n// Reads the DB row and reconciles with env vars. Idempotent and safe to\n// call after every settings save. Returns a small descriptor that the\n// settings save handler can echo back to the UI.\nexport async function applyProxyConfigFromDb(): Promise<ApplyResult> {\n if (ENV_HAD_PROXY_AT_BOOT) {\n return {\n source: \"env\",\n proxyUrl: null,\n note: \"Honoring HTTPS_PROXY env var; in-app proxy config is ignored while it is set.\",\n };\n }\n\n let cfg: ProxyConfigRaw | null = null;\n try {\n cfg = getProxyConfigRaw();\n } catch (err) {\n // Migration ordering safety net: if proxy_config table doesn't exist\n // yet (older DB about to be migrated), fall back to no-proxy.\n console.warn(\"[jarela/proxy] could not read proxy_config:\", err);\n }\n\n if (!cfg || cfg.mode === \"off\") {\n resetToBaseline();\n return { source: \"off\", proxyUrl: null };\n }\n\n if (cfg.mode === \"manual\") {\n if (!cfg.host || !cfg.port) {\n resetToBaseline();\n return { source: \"off\", proxyUrl: null, note: \"manual mode missing host/port; reverted to no proxy\" };\n }\n const url = buildProxyUrl(cfg.scheme, cfg.host, cfg.port, cfg.username, cfg.password);\n installProxy(url, cfg.no_proxy, cfg.ca_bundle);\n return { source: \"manual\", proxyUrl: redactAuth(url) };\n }\n\n if (cfg.mode === \"system\") {\n // ADR-0020: in `system` mode the OS is the source of truth for both\n // proxy URL (System Preferences → Network → Proxies, via scutil) AND\n // trust store (System + Login keychains, via `security`). Extract\n // the keychain bundle every apply so MDM-pushed cert rotations land\n // without manual intervention.\n const trust = extractSystemKeychainCAs();\n let caBundleText: string | null = cfg.ca_bundle; // user-pasted override, if any\n let caBundlePath: string | undefined;\n let caBundleCertCount: number | undefined;\n let caBundleSource: \"macos-keychain\" | undefined;\n if (!(\"error\" in trust)) {\n try {\n caBundleText = readFileSync(trust.pemPath, \"utf8\");\n caBundlePath = trust.pemPath;\n caBundleCertCount = trust.certCount;\n caBundleSource = trust.source;\n } catch (err) {\n console.warn(\"[jarela/proxy] could not read extracted keychain bundle:\", err);\n }\n } else {\n // Non-fatal: fall back to whatever the user pasted into the UI,\n // or to no bundle if they didn't.\n console.info(`[jarela/proxy] keychain extraction skipped: ${trust.error}`);\n }\n\n const detected = await detectSystemProxy();\n if (!detected) {\n // No HTTPS proxy at the OS level (common when macOS uses a PAC URL\n // — scutil reports ProxyAutoConfigEnable=1 but HTTPSEnable=0 — or\n // when an on-host steering agent like Zscaler/Netskope handles\n // egress transparently). If we extracted a keychain bundle, apply\n // it to a direct-egress dispatcher so TLS interception by the\n // on-host agent still validates against the corporate root.\n if (caBundleText) {\n installDirectWithCa(caBundleText);\n return {\n source: \"off\",\n proxyUrl: null,\n note: caBundleSource\n ? `scutil --proxy reported no HTTPS proxy (likely PAC or on-host agent); applied ${caBundleCertCount} keychain CAs to direct-egress TLS so on-host MITM validates.`\n : \"scutil --proxy reported no HTTPS proxy; using direct connection\",\n caBundlePath,\n caBundleCertCount,\n caBundleSource,\n };\n }\n resetToBaseline();\n return {\n source: \"off\",\n proxyUrl: null,\n note:\n process.platform === \"darwin\"\n ? \"scutil --proxy reported no HTTPS proxy; using direct connection\"\n : \"system mode is macOS-only in v1; using direct connection\",\n caBundlePath,\n caBundleCertCount,\n caBundleSource,\n };\n }\n // scutil only reports host/port — the proxy hop is plain http.\n const url = buildProxyUrl(\"http\", detected.host, detected.port, null, null);\n installProxy(url, cfg.no_proxy, caBundleText);\n return {\n source: \"system\",\n proxyUrl: redactAuth(url),\n note: caBundleSource\n ? `Imported ${caBundleCertCount} CAs from macOS keychain → ${caBundlePath}. Restart the service for non-undici code paths to pick up the new trust store.`\n : undefined,\n caBundlePath,\n caBundleCertCount,\n caBundleSource,\n };\n }\n\n resetToBaseline();\n return { source: \"off\", proxyUrl: null };\n}\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nfunction buildProxyUrl(\n scheme: ProxyScheme,\n host: string,\n port: number,\n username: string | null,\n password: string | null,\n): string {\n const auth = username\n ? `${encodeURIComponent(username)}${password ? `:${encodeURIComponent(password)}` : \"\"}@`\n : \"\";\n return `${scheme}://${auth}${host}:${port}`;\n}\n\nfunction installProxy(url: string, noProxy: string | null, caBundle: string | null): void {\n // Set process.env so EnvHttpProxyAgent honors NO_PROXY semantics\n // (per-host bypass) without us reimplementing the matching logic.\n // We still treat the boot-time env snapshot as authoritative for the\n // \"env beats DB\" rule — this mutation only happens after we've\n // confirmed the user did NOT set HTTP_PROXY at launch.\n process.env.HTTP_PROXY = url;\n process.env.HTTPS_PROXY = url;\n if (noProxy && noProxy.trim().length > 0) {\n process.env.NO_PROXY = noProxy.trim();\n } else {\n delete process.env.NO_PROXY;\n }\n // ADR-0012: when the user pasted a corporate root CA, inject it on\n // both TLS legs — the proxy hop (proxyTls) for https-scheme proxies\n // signed by the corporate root, and the upstream tunnel (requestTls)\n // for proxies that MITM outbound HTTPS with the same internal CA.\n // Same blob is correct: the corporate trust chain typically signs\n // both ends.\n const opts = caBundle\n ? { requestTls: { ca: caBundle }, proxyTls: { ca: caBundle } }\n : {};\n setGlobalDispatcher(new EnvHttpProxyAgent(opts));\n}\n\nfunction resetToBaseline(): void {\n if (ENV_HAD_PROXY_AT_BOOT) return; // never tear down a user-set env proxy\n delete process.env.HTTP_PROXY;\n delete process.env.HTTPS_PROXY;\n delete process.env.NO_PROXY;\n if (baselineDispatcher) setGlobalDispatcher(baselineDispatcher);\n}\n\n// ADR-0020 follow-up: install a direct-egress dispatcher whose TLS trust\n// store includes the supplied CA bundle. Used when the OS reports no\n// HTTPS proxy (e.g. macOS PAC, or no proxy at all) but on-host agents\n// (Zscaler ZIA, Netskope SteeringAgent, Cisco Umbrella, GlobalProtect)\n// still intercept and re-sign outbound TLS with an internal root.\n// Without this, `mode=system` extracts a useful bundle but never applies\n// it to direct-egress code paths and the user gets\n// UNABLE_TO_GET_ISSUER_CERT_LOCALLY despite a green \"242 certs\" status.\nfunction installDirectWithCa(caBundle: string): void {\n // Clear proxy env so EnvHttpProxyAgent isn't re-summoned by some other\n // import path; we want unambiguous direct egress with custom trust.\n delete process.env.HTTP_PROXY;\n delete process.env.HTTPS_PROXY;\n delete process.env.NO_PROXY;\n setGlobalDispatcher(new Agent({ connect: { ca: caBundle } }));\n}\n\nfunction redactAuth(url: string): string {\n try {\n const u = new URL(url);\n if (u.password) u.password = \"***\";\n return u.toString();\n } catch {\n return url;\n }\n}\n\n// ---------------------------------------------------------------------\n// macOS scutil --proxy parser\n// ---------------------------------------------------------------------\n// Output is a heredoc-style block of `key : value` lines, one section\n// per network service. We only care about the HTTPS bag.\n\ninterface DetectedProxy {\n host: string;\n port: number;\n}\n\nasync function detectSystemProxy(): Promise<DetectedProxy | null> {\n if (process.platform !== \"darwin\") return null;\n try {\n const { stdout } = await execAsync(\"scutil --proxy\", { timeout: 3_000 });\n return parseScutilProxy(stdout);\n } catch (err) {\n console.warn(\"[jarela/proxy] scutil --proxy failed:\", err);\n return null;\n }\n}\n\n// Exported for unit-test use. Parses the relevant fields out of\n// `scutil --proxy` stdout. Returns null when HTTPSEnable is 0 or the\n// host/port pair is missing.\nexport function parseScutilProxy(output: string): DetectedProxy | null {\n const fields = new Map<string, string>();\n for (const raw of output.split(\"\\n\")) {\n const line = raw.trim();\n const m = /^([A-Za-z0-9]+)\\s*:\\s*(.+?)\\s*$/.exec(line);\n if (!m) continue;\n // Only the first occurrence of each key is meaningful — later\n // sections (FTP, SOCKS, …) reuse some names.\n if (!fields.has(m[1])) fields.set(m[1], m[2]);\n }\n if (fields.get(\"HTTPSEnable\") !== \"1\") return null;\n const host = fields.get(\"HTTPSProxy\");\n const portStr = fields.get(\"HTTPSPort\");\n if (!host || !portStr) return null;\n const port = Number.parseInt(portStr, 10);\n if (!Number.isFinite(port) || port <= 0 || port > 65535) return null;\n return { host, port };\n}\n\n// Test-only / diagnostics export: was an env-var proxy set at boot?\nexport function envProxyWasSetAtBoot(): boolean {\n return ENV_HAD_PROXY_AT_BOOT;\n}\n","export type MbtiType =\n | \"INTJ\" | \"INTP\" | \"ENTJ\" | \"ENTP\"\n | \"INFJ\" | \"INFP\" | \"ENFJ\" | \"ENFP\"\n | \"ISTJ\" | \"ISFJ\" | \"ESTJ\" | \"ESFJ\"\n | \"ISTP\" | \"ISFP\" | \"ESTP\" | \"ESFP\";\n\nexport interface MbtiPreset {\n label: string;\n strength: number;\n empathy: number;\n expressiveness: number;\n verbosity: number;\n}\n\n// Presets are intentionally conservative: they shape tone while leaving\n// truthfulness and execution behavior to core agent policies.\nexport const MBTI_PRESETS: Record<MbtiType, MbtiPreset> = {\n INTJ: { label: \"Architect\", strength: 55, empathy: 35, expressiveness: 30, verbosity: 45 },\n INTP: { label: \"Logician\", strength: 50, empathy: 35, expressiveness: 30, verbosity: 55 },\n ENTJ: { label: \"Commander\", strength: 65, empathy: 30, expressiveness: 45, verbosity: 40 },\n ENTP: { label: \"Debater\", strength: 60, empathy: 40, expressiveness: 60, verbosity: 50 },\n\n INFJ: { label: \"Advocate\", strength: 55, empathy: 75, expressiveness: 50, verbosity: 55 },\n INFP: { label: \"Mediator\", strength: 50, empathy: 80, expressiveness: 55, verbosity: 60 },\n ENFJ: { label: \"Protagonist\", strength: 65, empathy: 80, expressiveness: 70, verbosity: 55 },\n ENFP: { label: \"Campaigner\", strength: 60, empathy: 75, expressiveness: 75, verbosity: 60 },\n\n ISTJ: { label: \"Logistician\", strength: 50, empathy: 30, expressiveness: 25, verbosity: 40 },\n ISFJ: { label: \"Defender\", strength: 50, empathy: 70, expressiveness: 40, verbosity: 50 },\n ESTJ: { label: \"Executive\", strength: 60, empathy: 35, expressiveness: 45, verbosity: 40 },\n ESFJ: { label: \"Consul\", strength: 60, empathy: 80, expressiveness: 65, verbosity: 50 },\n\n ISTP: { label: \"Virtuoso\", strength: 50, empathy: 30, expressiveness: 30, verbosity: 35 },\n ISFP: { label: \"Adventurer\", strength: 50, empathy: 65, expressiveness: 55, verbosity: 45 },\n ESTP: { label: \"Entrepreneur\", strength: 60, empathy: 40, expressiveness: 70, verbosity: 40 },\n ESFP: { label: \"Entertainer\", strength: 60, empathy: 70, expressiveness: 80, verbosity: 50 },\n};\n\nexport const MBTI_TYPES: MbtiType[] = Object.keys(MBTI_PRESETS) as MbtiType[];\n","import OpenAI from \"openai\";\nimport type { ContentPart } from \"@/lib/tools/types\";\nimport type {\n ModelProvider,\n ProviderMessage,\n ProviderParams,\n ProviderStreamResult,\n ProviderStreamEvent,\n InvokeMessage,\n InvokeResult,\n OpenAITool,\n} from \"./types\";\n\nfunction pickOpenAICompatOptions(params: ProviderParams): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const p = params as Record<string, unknown>;\n const keys = [\n \"top_p\",\n \"presence_penalty\",\n \"frequency_penalty\",\n \"stop\",\n \"response_format\",\n \"logprobs\",\n \"top_logprobs\",\n \"reasoning_effort\",\n \"thinking\",\n \"stream_options\",\n \"user\",\n \"user_id\",\n ];\n for (const k of keys) {\n if (p[k] !== undefined) out[k] = p[k];\n }\n return out;\n}\n\nfunction makeClient(\n params: ProviderParams,\n baseURL?: string,\n extraHeaders?: Record<string, string>,\n): OpenAI {\n return new OpenAI({\n apiKey: params.api_key ?? process.env.OPENAI_API_KEY,\n baseURL: params.base_url ?? baseURL,\n defaultHeaders: { ...params.extra_headers, ...extraHeaders },\n });\n}\n\n// Convert ContentPart[] to OpenAI multipart content\nfunction toOpenAIContent(\n content: string | ContentPart[],\n): string | OpenAI.Chat.ChatCompletionContentPart[] {\n if (typeof content === \"string\") return content;\n return content.map((part): OpenAI.Chat.ChatCompletionContentPart => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n if (part.type === \"image\") {\n return {\n type: \"image_url\",\n image_url: { url: `data:${part.media_type};base64,${part.data}` },\n };\n }\n // Files rendered as text for OpenAI\n return { type: \"text\", text: `[File: ${(part as ContentPart & { type: \"file\" }).name}]\\n${part.data}` };\n });\n}\n\nfunction toOpenAIMessages(\n messages: InvokeMessage[],\n): OpenAI.Chat.ChatCompletionMessageParam[] {\n return messages.map((m) => {\n if (m.role === \"tool\") {\n return { role: \"tool\", tool_call_id: m.tool_call_id!, content: String(m.content) };\n }\n if (m.role === \"assistant\") {\n const msg: OpenAI.Chat.ChatCompletionAssistantMessageParam & { reasoning_content?: string } = {\n role: \"assistant\",\n content: typeof m.content === \"string\" ? m.content : null,\n tool_calls: m.tool_calls as OpenAI.Chat.ChatCompletionMessageToolCall[] | undefined,\n };\n // DeepSeek's reasoning models reject follow-up requests that omit the\n // assistant's prior reasoning_content. The OpenAI SDK's type doesn't\n // know about this field, but the underlying HTTP body forwards it.\n if (m.reasoning_content) msg.reasoning_content = m.reasoning_content;\n return msg as OpenAI.Chat.ChatCompletionAssistantMessageParam;\n }\n return {\n role: m.role as \"system\" | \"user\",\n content: toOpenAIContent(m.content),\n } as OpenAI.Chat.ChatCompletionMessageParam;\n });\n}\n\n// Re-export so other OpenAI-compatible providers (github-copilot, etc.) can\n// share the same ContentPart -> wire-format conversion instead of casting\n// raw InvokeMessage shapes that the OpenAI SDK then rejects for images/files.\nexport { toOpenAIContent, toOpenAIMessages };\n\ntype OpenAIStreamDelta = {\n content?: string | null;\n reasoning_content?: string | null;\n tool_calls?: Array<{ index?: number; id?: string; function?: { name?: string; arguments?: string } }>;\n};\n\ntype OpenAIStreamChoice = {\n delta?: OpenAIStreamDelta;\n finish_reason?: string | null;\n};\n\ntype OpenAIInvokeChoice = {\n message?: {\n content?: string | null;\n tool_calls?: Array<{ type?: string; id?: string; function?: { name?: string; arguments?: string } }>;\n };\n finish_reason?: string | null;\n};\n\nfunction parseStopReason(reason: string | null | undefined): InvokeResult[\"stop_reason\"] {\n if (reason === \"tool_calls\") return \"tool_use\";\n if (reason === \"length\") return \"length\";\n return \"stop\";\n}\n\nexport function parseOpenAIInvokeChoice(choice: OpenAIInvokeChoice): InvokeResult {\n return {\n text: choice.message?.content ?? null,\n tool_calls: (choice.message?.tool_calls ?? []).flatMap((tc) => {\n if (tc?.type !== \"function\" || !tc.function?.name) return [];\n return [{\n id: tc.id ?? \"\",\n name: tc.function.name,\n arguments: (() => {\n try {\n return JSON.parse(tc.function.arguments ?? \"{}\") as Record<string, unknown>;\n } catch {\n return {};\n }\n })(),\n }];\n }),\n stop_reason: parseStopReason(choice.finish_reason),\n };\n}\n\nexport async function* streamOpenAIEvents(\n stream: AsyncIterable<{\n choices?: OpenAIStreamChoice[];\n usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null;\n }>,\n): AsyncIterable<ProviderStreamEvent> {\n for await (const chunk of stream) {\n if (chunk.usage) {\n yield {\n type: \"usage\",\n input_tokens: chunk.usage.prompt_tokens,\n output_tokens: chunk.usage.completion_tokens,\n total_tokens: chunk.usage.total_tokens,\n };\n }\n const choice = chunk.choices?.[0];\n if (!choice) continue;\n const delta = choice.delta;\n if (!delta) continue;\n if (delta.content) yield { type: \"text\", delta: delta.content };\n if (typeof delta.reasoning_content === \"string\" && delta.reasoning_content) {\n yield { type: \"thinking\", delta: delta.reasoning_content };\n }\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n yield {\n type: \"tool_call_chunk\",\n index: tc.index ?? 0,\n id: tc.id,\n name: tc.function?.name,\n args_delta: tc.function?.arguments,\n };\n }\n }\n if (choice.finish_reason) {\n yield { type: \"stop\", reason: parseStopReason(choice.finish_reason) };\n }\n }\n}\n\nasync function streamOpenAIText(\n stream: AsyncIterable<{ choices?: Array<{ delta?: { content?: string | null } }> }>,\n): Promise<ProviderStreamResult> {\n return {\n stream: (async function* () {\n for await (const chunk of stream) {\n const delta = chunk.choices?.[0]?.delta?.content;\n if (delta) yield delta;\n }\n })(),\n };\n}\n\nfunction ollamaOriginFromParams(params: ProviderParams): string | null {\n const raw = typeof params.base_url === \"string\" ? params.base_url : \"\";\n if (!raw) return null;\n try {\n const u = new URL(raw);\n const isLocal = u.hostname === \"localhost\" || u.hostname === \"127.0.0.1\";\n const isOllamaPort = u.port === \"11434\";\n if (!isLocal || !isOllamaPort) return null;\n return `${u.protocol}//${u.host}`;\n } catch {\n return null;\n }\n}\n\nasync function tryPullOllamaModel(model_id: string, params: ProviderParams): Promise<boolean> {\n const origin = ollamaOriginFromParams(params);\n if (!origin) return false;\n try {\n const res = await fetch(`${origin}/api/pull`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ name: model_id, stream: false }),\n });\n return res.ok;\n } catch {\n return false;\n }\n}\n\nfunction isModelNotFoundError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err);\n return /\\b404\\b|model.*not found|unsupported.*embed/i.test(msg);\n}\n\nexport const openaiProvider: ModelProvider = {\n name: \"openai\",\n\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n const client = makeClient(params);\n const mapped = messages.map((m): InvokeMessage => ({\n role: m.role,\n content: m.content,\n }));\n const stream = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(mapped),\n stream: true,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickOpenAICompatOptions(params) as Record<string, unknown>),\n });\n return streamOpenAIText(stream);\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n const client = makeClient(params);\n const resp = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(messages),\n tools: tools as OpenAI.Chat.ChatCompletionTool[],\n tool_choice: \"auto\",\n stream: false,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickOpenAICompatOptions(params) as Record<string, unknown>),\n });\n return parseOpenAIInvokeChoice(resp.choices[0] as OpenAIInvokeChoice);\n },\n\n streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n return openaiStreamInvoke(makeClient(params), model_id, messages, params, tools);\n },\n\n async embed(model_id, inputs, params): Promise<number[][]> {\n return openaiEmbed(makeClient(params), model_id, inputs, params);\n },\n};\n\nasync function openaiEmbed(\n client: OpenAI,\n model_id: string,\n inputs: string[],\n params: ProviderParams,\n): Promise<number[][]> {\n if (inputs.length === 0) return [];\n try {\n const resp = await client.embeddings.create({ model: model_id, input: inputs });\n return resp.data.map((d) => d.embedding);\n } catch (err) {\n // Self-host ergonomics: when pointed at local Ollama and the embedding\n // model isn't present yet, pull it on-demand and retry once.\n if (isModelNotFoundError(err) && await tryPullOllamaModel(model_id, params)) {\n const resp = await client.embeddings.create({ model: model_id, input: inputs });\n return resp.data.map((d) => d.embedding);\n }\n throw err;\n }\n}\n\nasync function* openaiStreamInvoke(\n client: OpenAI,\n model_id: string,\n messages: InvokeMessage[],\n params: ProviderParams,\n tools: OpenAITool[],\n): AsyncIterable<ProviderStreamEvent> {\n const compatOptions = pickOpenAICompatOptions(params) as Record<string, unknown>;\n const body: OpenAI.Chat.ChatCompletionCreateParamsStreaming = {\n model: model_id,\n messages: toOpenAIMessages(messages),\n stream: true,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...compatOptions,\n stream_options: { include_usage: true, ...(compatOptions.stream_options as object | undefined) },\n };\n if (tools.length > 0) {\n body.tools = tools as OpenAI.Chat.ChatCompletionTool[];\n body.tool_choice = \"auto\";\n }\n const stream = await client.chat.completions.create(body);\n yield* streamOpenAIEvents(\n stream as AsyncIterable<{\n choices?: OpenAIStreamChoice[];\n usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null;\n }>,\n );\n}\n\nexport function makeOpenAICompatProvider(\n providerName: string,\n defaultBaseURL: string,\n fixedHeaders: Record<string, string>,\n): ModelProvider {\n return {\n name: providerName,\n\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n const client = makeClient(params, defaultBaseURL, fixedHeaders);\n const mapped = messages.map((m): InvokeMessage => ({\n role: m.role,\n content: m.content,\n }));\n const stream = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(mapped),\n stream: true,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickOpenAICompatOptions(params) as Record<string, unknown>),\n });\n return streamOpenAIText(stream);\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n const client = makeClient(params, defaultBaseURL, fixedHeaders);\n const resp = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(messages),\n tools: tools as OpenAI.Chat.ChatCompletionTool[],\n tool_choice: \"auto\",\n stream: false,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickOpenAICompatOptions(params) as Record<string, unknown>),\n });\n return parseOpenAIInvokeChoice(resp.choices[0] as OpenAIInvokeChoice);\n },\n\n streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n return openaiStreamInvoke(makeClient(params, defaultBaseURL, fixedHeaders), model_id, messages, params, tools);\n },\n\n async embed(model_id, inputs, params): Promise<number[][]> {\n return openaiEmbed(makeClient(params, defaultBaseURL, fixedHeaders), model_id, inputs, params);\n },\n };\n}\n\n\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport type { ContentPart } from \"@/lib/tools/types\";\nimport { getIntegrationRaw } from \"@/lib/stores/integrations\";\nimport type {\n ModelProvider,\n ProviderMessage,\n ProviderParams,\n ProviderStreamResult,\n ProviderStreamEvent,\n InvokeMessage,\n InvokeResult,\n OpenAITool,\n} from \"./types\";\n\n// Resolves the API key in fallback order:\n// 1. params.api_key — explicit per-call override\n// 2. integration store — value put there by the user (UI) or env-sync (rc)\n// 3. process.env.ANTHROPIC_API_KEY — last-resort process inheritance\nfunction resolveApiKey(params: ProviderParams): string | undefined {\n return params.api_key ?? getIntegrationRaw(\"anthropic\")?.api_key ?? process.env.ANTHROPIC_API_KEY;\n}\n\nfunction pickAnthropicOptions(params: ProviderParams): Record<string, unknown> {\n const p = params as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n const keys = [\n \"temperature\",\n \"top_p\",\n \"top_k\",\n \"stop_sequences\",\n \"metadata\",\n \"tool_choice\",\n \"service_tier\",\n ];\n for (const k of keys) {\n if (p[k] !== undefined) out[k] = p[k];\n }\n return out;\n}\n\nfunction appendServerTools(\n anthropicTools: Anthropic.Tool[],\n params: ProviderParams,\n): Anthropic.Tool[] {\n const native = (params as Record<string, unknown>).anthropic_server_tools;\n if (!Array.isArray(native)) return anthropicTools;\n const merged = [...anthropicTools];\n for (const t of native) {\n if (t && typeof t === \"object\") {\n merged.push(t as Anthropic.Tool);\n }\n }\n return merged;\n}\n\nexport const anthropicProvider: ModelProvider = {\n name: \"anthropic\",\n\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n const client = new Anthropic({\n apiKey: resolveApiKey(params),\n baseURL: params.base_url,\n defaultHeaders: params.extra_headers,\n });\n\n const systemMsg = messages.find((m) => m.role === \"system\");\n const systemText = typeof systemMsg?.content === \"string\"\n ? systemMsg.content\n : (systemMsg?.content ?? [])\n .filter((p): p is ContentPart & { type: \"text\" } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\\n\");\n const userMessages = messages\n .filter((m) => m.role !== \"system\")\n .map((m): Anthropic.MessageParam => ({\n role: (m.role === \"assistant\" ? \"assistant\" : \"user\"),\n content: toAnthropicContent(m.content),\n }));\n\n const stream = await client.messages.stream({\n model: model_id,\n max_tokens: params.max_tokens ?? 4096,\n system: systemText || undefined,\n messages: userMessages,\n });\n\n return {\n stream: (async function* () {\n for await (const event of stream) {\n if (event.type === \"content_block_delta\" && event.delta.type === \"text_delta\") {\n yield event.delta.text;\n }\n }\n })(),\n };\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n const client = new Anthropic({\n apiKey: resolveApiKey(params),\n baseURL: params.base_url,\n defaultHeaders: params.extra_headers,\n });\n\n const systemMsg = messages.find((m) => m.role === \"system\");\n const msgList = toAnthropicMessages(messages.filter((m) => m.role !== \"system\"));\n const anthropicTools = appendServerTools(toAnthropicTools(tools), params);\n\n const resp = await client.messages.create({\n model: model_id,\n max_tokens: params.max_tokens ?? 4096,\n system: typeof systemMsg?.content === \"string\" ? systemMsg.content : undefined,\n messages: msgList,\n tools: anthropicTools,\n ...(params.thinking ? { thinking: params.thinking } : {}),\n ...(pickAnthropicOptions(params) as Record<string, unknown>),\n });\n\n const textContent = resp.content\n .filter((b): b is Anthropic.TextBlock => b.type === \"text\")\n .map((b) => b.text)\n .join(\"\");\n\n const toolCalls = resp.content\n .filter((b): b is Anthropic.ToolUseBlock => b.type === \"tool_use\")\n .map((b) => ({ id: b.id, name: b.name, arguments: b.input as Record<string, unknown> }));\n\n return {\n text: textContent || null,\n tool_calls: toolCalls,\n stop_reason: resp.stop_reason === \"tool_use\" ? \"tool_use\" : \"stop\",\n };\n },\n\n streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n return (async function* () {\n const client = new Anthropic({\n apiKey: resolveApiKey(params),\n baseURL: params.base_url,\n defaultHeaders: params.extra_headers,\n });\n\n const systemMsg = messages.find((m) => m.role === \"system\");\n const msgList = toAnthropicMessages(messages.filter((m) => m.role !== \"system\"));\n const anthropicTools = appendServerTools(toAnthropicTools(tools), params);\n\n const body: Anthropic.Messages.MessageStreamParams = {\n model: model_id,\n max_tokens: params.max_tokens ?? 4096,\n messages: msgList,\n ...(pickAnthropicOptions(params) as Record<string, unknown>),\n };\n if (typeof systemMsg?.content === \"string\") body.system = systemMsg.content;\n if (anthropicTools.length > 0) body.tools = anthropicTools;\n if (params.thinking) {\n (body as unknown as Record<string, unknown>).thinking = params.thinking;\n }\n if (params.temperature !== undefined) body.temperature = params.temperature;\n\n const stream = client.messages.stream(body);\n const blockType = new Map<number, \"text\" | \"thinking\" | \"tool_use\">();\n\n for await (const event of stream) {\n if (event.type === \"content_block_start\") {\n const cb = event.content_block;\n if (cb.type === \"tool_use\") {\n blockType.set(event.index, \"tool_use\");\n yield { type: \"tool_call_chunk\", index: event.index, id: cb.id, name: cb.name };\n } else if (cb.type === \"thinking\") {\n blockType.set(event.index, \"thinking\");\n } else if (cb.type === \"text\") {\n blockType.set(event.index, \"text\");\n }\n } else if (event.type === \"content_block_delta\") {\n const d = event.delta as { type: string; text?: string; thinking?: string; partial_json?: string };\n if (d.type === \"text_delta\" && d.text) {\n yield { type: \"text\", delta: d.text };\n } else if (d.type === \"thinking_delta\" && d.thinking) {\n yield { type: \"thinking\", delta: d.thinking };\n } else if (d.type === \"input_json_delta\" && d.partial_json !== undefined) {\n yield { type: \"tool_call_chunk\", index: event.index, args_delta: d.partial_json };\n }\n } else if (event.type === \"message_delta\" && event.delta?.stop_reason) {\n const reason = event.delta.stop_reason;\n yield { type: \"stop\", reason: reason === \"tool_use\" ? \"tool_use\" : reason === \"max_tokens\" ? \"length\" : \"stop\" };\n }\n }\n })();\n },\n};\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nexport function toAnthropicContent(\n content: string | ContentPart[],\n): Anthropic.MessageParam[\"content\"] {\n if (typeof content === \"string\") return content;\n return content.flatMap((part): Anthropic.ContentBlockParam[] => {\n if (part.type === \"text\") {\n return [{ type: \"text\", text: part.text }];\n }\n if (part.type === \"image\") {\n const mt = part.media_type as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\";\n return [{ type: \"image\", source: { type: \"base64\", media_type: mt, data: part.data } }];\n }\n if (part.type === \"file\") {\n if (part.media_type === \"application/pdf\") {\n return [\n {\n type: \"document\",\n source: { type: \"base64\", media_type: \"application/pdf\", data: part.data },\n title: part.name,\n } as unknown as Anthropic.ContentBlockParam,\n ];\n }\n return [{ type: \"text\", text: `[File: ${part.name}]\\n${part.data}` }];\n }\n return [];\n });\n}\n\nfunction toAnthropicMessages(messages: InvokeMessage[]): Anthropic.MessageParam[] {\n const result: Anthropic.MessageParam[] = [];\n for (const m of messages) {\n if (m.role === \"tool\") {\n result.push({\n role: \"user\",\n content: [{ type: \"tool_result\", tool_use_id: m.tool_call_id!, content: String(m.content) }],\n });\n } else if (m.role === \"assistant\" && m.tool_calls?.length) {\n const blocks: Anthropic.ContentBlockParam[] = [];\n if (m.content) blocks.push({ type: \"text\", text: String(m.content) });\n for (const tc of m.tool_calls) {\n blocks.push({\n type: \"tool_use\",\n id: tc.id,\n name: tc.function?.name ?? \"\",\n input: (() => {\n try {\n return JSON.parse(tc.function?.arguments ?? \"{}\");\n } catch {\n return {};\n }\n })(),\n });\n }\n result.push({ role: \"assistant\", content: blocks });\n } else {\n result.push({\n role: m.role as \"user\" | \"assistant\",\n content: toAnthropicContent(m.content),\n });\n }\n }\n return result;\n}\n\nfunction toAnthropicTools(tools: OpenAITool[]): Anthropic.Tool[] {\n return tools.flatMap((t) => {\n if (!t.function?.name) return [];\n return [{ name: t.function.name, description: t.function.description, input_schema: t.function.parameters as Anthropic.Tool.InputSchema }];\n });\n}\n\n// ── Plain-text helper for streaming path (no tool calls) ────────────────────\n\nexport function providerMessagesFromHistory(\n messages: Array<{ role: \"user\" | \"assistant\"; content: string | ContentPart[] }>,\n): ProviderMessage[] {\n return messages.map((m) => ({\n role: m.role,\n content: typeof m.content === \"string\"\n ? m.content\n : m.content.filter((p): p is ContentPart & { type: \"text\" } => p.type === \"text\").map((p) => p.text).join(\"\\n\"),\n }));\n}\n","import OpenAI from \"openai\";\nimport type {\n ModelProvider,\n ProviderParams,\n ProviderStreamResult,\n ProviderStreamEvent,\n InvokeResult,\n} from \"./types\";\nimport { getStoredOAuthToken } from \"./github-copilot-auth\";\nimport { parseOpenAIInvokeChoice, streamOpenAIEvents, toOpenAIMessages } from \"./openai\";\n\nfunction pickGitHubCompatOptions(params: ProviderParams): Record<string, unknown> {\n const p = params as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n const keys = [\n \"top_p\",\n \"presence_penalty\",\n \"frequency_penalty\",\n \"stop\",\n \"response_format\",\n \"logprobs\",\n \"top_logprobs\",\n \"reasoning_effort\",\n \"thinking\",\n \"stream_options\",\n \"user\",\n \"user_id\",\n ];\n for (const k of keys) {\n if (p[k] !== undefined) out[k] = p[k];\n }\n return out;\n}\n\ninterface SessionToken {\n token: string;\n expiresAt: number;\n}\n\nconst tokenCache = new Map<string, SessionToken>();\n\nfunction isLikelyGitHubPat(token: string): boolean {\n return token.startsWith(\"ghp_\") || token.startsWith(\"github_pat_\") || token.startsWith(\"gho_\");\n}\n\nasync function getCopilotToken(pat: string): Promise<string> {\n if (!pat) throw new Error(\"GitHub Copilot: no API key configured for token exchange.\");\n const cached = tokenCache.get(pat);\n if (cached && cached.expiresAt - Date.now() > 60_000) return cached.token;\n\n const res = await fetch(\"https://api.github.com/copilot_internal/v2/token\", {\n headers: {\n Authorization: `token ${pat}`,\n \"User-Agent\": \"Jarela/1.0\",\n },\n });\n\n if (!res.ok) {\n const body = await res.text().catch(() => res.statusText);\n if (res.status === 401) {\n throw new Error(\n `GitHub Copilot: token exchange failed (401). ` +\n `Ensure your PAT has the \"copilot\" scope and that you have an active Copilot subscription. ` +\n `Details: ${body}`,\n );\n }\n if (res.status === 404) {\n throw new Error(\n \"GitHub Copilot token exchange endpoint was not found for this credential. \" +\n \"Personal Access Tokens are not accepted directly by Copilot chat. \" +\n \"Use a Copilot session token in params.copilot_session_token, or a credential that supports token exchange.\",\n );\n }\n throw new Error(`GitHub Copilot: token exchange failed (${res.status}): ${body}`);\n }\n\n const json = await res.json() as { token: string; expires_at: string };\n if (!json.token) throw new Error(\"GitHub Copilot: token exchange returned no token\");\n\n const expiresAt = json.expires_at ? new Date(json.expires_at).getTime() : Date.now() + 28 * 60_000;\n tokenCache.set(pat, { token: json.token, expiresAt });\n return json.token;\n}\n\nconst FIXED_HEADERS = {\n \"Editor-Version\": \"vscode/1.85.0\",\n \"Copilot-Integration-Id\": \"vscode-chat\",\n \"openai-intent\": \"conversation-ai\",\n // Required by the Copilot proxy to accept image_url content parts. Without\n // this header the upstream models silently drop attached images (or 400).\n \"Copilot-Vision-Request\": \"true\",\n};\n\nasync function resolvedClient(params: ProviderParams): Promise<OpenAI> {\n const apiKey = (params.api_key as string | undefined) ?? \"\";\n const explicitSessionToken = (params.copilot_session_token as string | undefined)?.trim();\n\n // Highest priority: an explicit pre-exchanged Copilot session token.\n if (explicitSessionToken && explicitSessionToken.length > 0) {\n return new OpenAI({\n apiKey: explicitSessionToken,\n baseURL: params.base_url ?? \"https://api.githubcopilot.com\",\n defaultHeaders: { ...FIXED_HEADERS, ...params.extra_headers },\n });\n }\n\n // Next: a device-flow OAuth token persisted by the in-app sign-in. This is\n // exchangeable for a Copilot session token, so we get full model context.\n const oauthToken = getStoredOAuthToken();\n if (oauthToken) {\n const token = await getCopilotToken(oauthToken);\n return new OpenAI({\n apiKey: token,\n baseURL: params.base_url ?? \"https://api.githubcopilot.com\",\n defaultHeaders: { ...FIXED_HEADERS, ...params.extra_headers },\n });\n }\n\n // Fallback: a raw PAT. PATs can't be exchanged for Copilot tokens, so they\n // route to the GitHub Models REST API (which enforces tight per-request\n // token caps, e.g. 8000 for gpt-4o). Users who want larger contexts should\n // sign in via the device flow instead.\n if (apiKey && isLikelyGitHubPat(apiKey)) {\n return new OpenAI({\n apiKey,\n baseURL: params.base_url ?? \"https://models.github.ai/inference\",\n defaultHeaders: {\n Accept: \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2026-03-10\",\n ...params.extra_headers,\n },\n });\n }\n\n // Otherwise, treat the credential as an OAuth-capable token and exchange.\n if (!apiKey) {\n throw new Error(\n \"GitHub Copilot: not signed in. Use the in-app device-flow login, or set api_key / copilot_session_token.\",\n );\n }\n const token = await getCopilotToken(apiKey);\n return new OpenAI({\n apiKey: token,\n baseURL: params.base_url ?? \"https://api.githubcopilot.com\",\n defaultHeaders: { ...FIXED_HEADERS, ...params.extra_headers },\n });\n}\n\nexport const githubCopilotProvider: ModelProvider = {\n name: \"github-copilot\",\n\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n const client = await resolvedClient(params);\n const stream = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(messages),\n stream: true,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickGitHubCompatOptions(params) as Record<string, unknown>),\n });\n return {\n stream: (async function* () {\n for await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta?.content;\n if (delta) yield delta;\n }\n })(),\n };\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n const client = await resolvedClient(params);\n const resp = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(messages),\n tools: tools as OpenAI.Chat.ChatCompletionTool[],\n tool_choice: \"auto\",\n stream: false,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickGitHubCompatOptions(params) as Record<string, unknown>),\n });\n return parseOpenAIInvokeChoice(resp.choices[0]);\n },\n\n async *streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n const client = await resolvedClient(params);\n const compat = pickGitHubCompatOptions(params) as Record<string, unknown>;\n const stream = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(messages),\n tools: tools as OpenAI.Chat.ChatCompletionTool[],\n tool_choice: \"auto\",\n stream: true,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...compat,\n stream_options: { include_usage: true, ...(compat.stream_options as object | undefined) },\n });\n\n yield* streamOpenAIEvents(\n stream as AsyncIterable<{\n choices?: Array<{\n delta?: {\n content?: string | null;\n reasoning_content?: string | null;\n tool_calls?: Array<{ index?: number; id?: string; function?: { name?: string; arguments?: string } }>;\n };\n finish_reason?: string | null;\n }>;\n usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null;\n }>,\n );\n },\n\n async embed(model_id, inputs, params): Promise<number[][]> {\n if (inputs.length === 0) return [];\n const client = await resolvedClient(params);\n const resp = await client.embeddings.create({\n model: model_id,\n input: inputs,\n });\n return resp.data.map((d) => d.embedding);\n },\n};\n","import { makeOpenAICompatProvider } from \"./openai\";\n\n// DeepSeek API is OpenAI-compatible. Reasoning models (deepseek-reasoner, etc.)\n// emit `reasoning_content` in delta chunks — handled by the shared OpenAI stream parser.\n// Auth: set params.api_key to your DeepSeek API key.\nexport const deepseekProvider = makeOpenAICompatProvider(\n \"deepseek\",\n \"https://api.deepseek.com\",\n {},\n);\n","import type { ProviderStreamEvent } from \"./types\";\n\n// Reads `data: ...` lines from an SSE response body.\nexport async function* readSSELines(body: ReadableStream<Uint8Array>): AsyncIterable<string> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n for (const line of lines) {\n if (line.startsWith(\"data: \")) yield line.slice(6).trim();\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n// Parses an Anthropic SSE stream into ProviderStreamEvents.\n// Tracks per-block-index type so deltas route to the right event.\nexport async function* parseAnthropicStream(\n body: ReadableStream<Uint8Array>,\n): AsyncIterable<ProviderStreamEvent> {\n const blockType = new Map<number, \"text\" | \"thinking\" | \"tool_use\">();\n\n for await (const line of readSSELines(body)) {\n if (!line || line === \"[DONE]\") continue;\n let event: AnthropicStreamEvent;\n try { event = JSON.parse(line) as AnthropicStreamEvent; } catch { continue; }\n\n if (event.type === \"content_block_start\" && event.content_block) {\n const cb = event.content_block;\n if (cb.type === \"tool_use\") {\n blockType.set(event.index, \"tool_use\");\n yield { type: \"tool_call_chunk\", index: event.index, id: cb.id, name: cb.name };\n } else if (cb.type === \"thinking\") {\n blockType.set(event.index, \"thinking\");\n } else {\n blockType.set(event.index, \"text\");\n }\n } else if (event.type === \"content_block_delta\" && event.delta) {\n const d = event.delta;\n if (d.type === \"text_delta\" && d.text) {\n yield { type: \"text\", delta: d.text };\n } else if (d.type === \"thinking_delta\" && d.thinking) {\n yield { type: \"thinking\", delta: d.thinking };\n } else if (d.type === \"input_json_delta\" && d.partial_json !== undefined) {\n yield { type: \"tool_call_chunk\", index: event.index, args_delta: d.partial_json };\n }\n } else if (event.type === \"message_delta\" && event.delta?.stop_reason) {\n const reason = event.delta.stop_reason;\n yield { type: \"stop\", reason: reason === \"tool_use\" ? \"tool_use\" : reason === \"max_tokens\" ? \"length\" : \"stop\" };\n }\n }\n}\n\ninterface AnthropicStreamEvent {\n type: string;\n index: number;\n content_block?: { type: string; id?: string; name?: string };\n delta?: {\n type?: string;\n text?: string;\n thinking?: string;\n partial_json?: string;\n stop_reason?: string;\n };\n}\n\n// Parses an OpenAI-style SSE stream (chat.completions with stream:true) into ProviderStreamEvents.\n// Handles delta.content (text), delta.reasoning_content (DeepSeek thinking), delta.tool_calls fragments.\nexport async function* parseOpenAIStream(\n body: ReadableStream<Uint8Array>,\n): AsyncIterable<ProviderStreamEvent> {\n for await (const line of readSSELines(body)) {\n if (!line || line === \"[DONE]\") continue;\n let event: OpenAIStreamEvent;\n try { event = JSON.parse(line) as OpenAIStreamEvent; } catch { continue; }\n\n const choice = event.choices?.[0];\n if (!choice) continue;\n const delta = choice.delta;\n\n if (delta?.content) {\n yield { type: \"text\", delta: delta.content };\n }\n if (typeof delta?.reasoning_content === \"string\" && delta.reasoning_content) {\n yield { type: \"thinking\", delta: delta.reasoning_content };\n }\n if (delta?.tool_calls) {\n for (const tc of delta.tool_calls) {\n const idx = tc.index ?? 0;\n yield {\n type: \"tool_call_chunk\",\n index: idx,\n id: tc.id,\n name: tc.function?.name,\n args_delta: tc.function?.arguments,\n };\n }\n }\n if (choice.finish_reason) {\n const fr = choice.finish_reason;\n yield { type: \"stop\", reason: fr === \"tool_calls\" ? \"tool_use\" : fr === \"length\" ? \"length\" : \"stop\" };\n }\n }\n}\n\ninterface OpenAIStreamEvent {\n choices?: Array<{\n index?: number;\n delta?: {\n content?: string | null;\n reasoning_content?: string | null;\n tool_calls?: Array<{\n index?: number;\n id?: string;\n function?: { name?: string; arguments?: string };\n }>;\n };\n finish_reason?: string | null;\n }>;\n}\n","import { makeOpenAICompatProvider } from \"./openai\";\nimport { readSSELines } from \"./streaming\";\nimport type { ContentPart, InvokeMessage, InvokeResult, OpenAITool } from \"@/lib/tools/types\";\nimport type { ModelProvider, ProviderMessage, ProviderParams, ProviderStreamEvent, ProviderStreamResult } from \"./types\";\n\n// Google Gemini via its OpenAI-compatible endpoint.\n// Auth: set params.api_key to your Google AI Studio API key.\n// Models: gemini-2.0-flash, gemini-2.5-pro, gemini-1.5-flash, etc.\nconst geminiCompat = makeOpenAICompatProvider(\n \"gemini\",\n \"https://generativelanguage.googleapis.com/v1beta/openai/\",\n {},\n);\n\ntype GeminiPart =\n | { text: string }\n | { inlineData: { mimeType: string; data: string } }\n | { functionCall: { name: string; args?: Record<string, unknown> } }\n | { functionResponse: { name: string; response: Record<string, unknown> } };\n\nfunction isCompatMode(params: ProviderParams): boolean {\n return (params as Record<string, unknown>).gemini_use_openai_compat === true;\n}\n\nfunction nativeBaseUrl(params: ProviderParams): string {\n const raw = (params as Record<string, unknown>).gemini_native_base_url;\n if (typeof raw === \"string\" && raw.trim()) return raw.trim().replace(/\\/+$/, \"\");\n return \"https://generativelanguage.googleapis.com/v1beta\";\n}\n\nfunction geminiApiKey(params: ProviderParams): string {\n const key = typeof params.api_key === \"string\" ? params.api_key : process.env.GEMINI_API_KEY;\n if (!key) throw new Error(\"Gemini: no api_key configured\");\n return key;\n}\n\nfunction contentToGeminiParts(content: string | ContentPart[]): GeminiPart[] {\n if (typeof content === \"string\") return [{ text: content }];\n const parts: GeminiPart[] = [];\n for (const p of content) {\n if (p.type === \"text\") {\n parts.push({ text: p.text });\n continue;\n }\n if (p.type === \"image\") {\n parts.push({ inlineData: { mimeType: p.media_type, data: p.data } });\n continue;\n }\n // Files map to inlineData when possible; otherwise tool-agnostic text fallback.\n if (p.type === \"file\") {\n if (p.media_type && p.data) {\n parts.push({ inlineData: { mimeType: p.media_type, data: p.data } });\n } else {\n parts.push({ text: `[File: ${p.name}]` });\n }\n }\n }\n return parts.length > 0 ? parts : [{ text: \"\" }];\n}\n\nfunction parseJsonObject(v: string | undefined): Record<string, unknown> {\n if (!v) return {};\n try {\n const parsed = JSON.parse(v);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : { value: parsed };\n } catch {\n return {};\n }\n}\n\nfunction providerMessagesToGemini(messages: ProviderMessage[]): {\n systemInstruction?: { parts: GeminiPart[] };\n contents: Array<{ role: \"user\" | \"model\"; parts: GeminiPart[] }>;\n} {\n const system = messages.find((m) => m.role === \"system\");\n const contents = messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({\n role: (m.role === \"assistant\" ? \"model\" : \"user\") as \"user\" | \"model\",\n parts: contentToGeminiParts(m.content),\n }));\n return {\n systemInstruction: system ? { parts: contentToGeminiParts(system.content) } : undefined,\n contents,\n };\n}\n\nfunction invokeMessagesToGemini(messages: InvokeMessage[]): {\n systemInstruction?: { parts: GeminiPart[] };\n contents: Array<{ role: \"user\" | \"model\"; parts: GeminiPart[] }>;\n} {\n const toolNameById = new Map<string, string>();\n const contents: Array<{ role: \"user\" | \"model\"; parts: GeminiPart[] }> = [];\n let systemInstruction: { parts: GeminiPart[] } | undefined;\n\n for (const m of messages) {\n if (m.role === \"system\") {\n const text = typeof m.content === \"string\" ? m.content : contentToGeminiParts(m.content)\n .flatMap((p) => (\"text\" in p ? [p.text] : []))\n .join(\"\\n\");\n if (text.trim()) systemInstruction = { parts: [{ text }] };\n continue;\n }\n\n if (m.role === \"assistant\") {\n const parts = contentToGeminiParts(m.content);\n for (const tc of m.tool_calls ?? []) {\n const name = tc.function?.name ?? \"tool\";\n if (tc.id) toolNameById.set(tc.id, name);\n parts.push({ functionCall: { name, args: parseJsonObject(tc.function?.arguments) } });\n }\n contents.push({ role: \"model\", parts });\n continue;\n }\n\n if (m.role === \"tool\") {\n const name = m.tool_call_id ? toolNameById.get(m.tool_call_id) ?? \"tool\" : \"tool\";\n const raw = typeof m.content === \"string\" ? m.content : \"\";\n const response = parseJsonObject(raw);\n if (Object.keys(response).length === 0 && raw) response.content = raw;\n contents.push({\n role: \"user\",\n parts: [{ functionResponse: { name, response } }],\n });\n continue;\n }\n\n contents.push({ role: \"user\", parts: contentToGeminiParts(m.content) });\n }\n\n return { systemInstruction, contents };\n}\n\nfunction toGeminiTools(tools: OpenAITool[], params: ProviderParams): unknown[] | undefined {\n const out: unknown[] = [];\n if (tools.length > 0) {\n out.push({\n functionDeclarations: tools\n .filter((t) => t.function?.name)\n .map((t) => ({\n name: t.function.name,\n description: t.function.description ?? \"\",\n parameters: t.function.parameters,\n })),\n });\n }\n const builtins = (params as Record<string, unknown>).gemini_builtin_tools;\n if (Array.isArray(builtins)) {\n for (const t of builtins) {\n if (t && typeof t === \"object\") out.push(t);\n }\n }\n return out.length > 0 ? out : undefined;\n}\n\nfunction toGenerationConfig(params: ProviderParams): Record<string, unknown> | undefined {\n const p = params as Record<string, unknown>;\n const base: Record<string, unknown> = {};\n if (params.temperature !== undefined) base.temperature = params.temperature;\n if (params.max_tokens !== undefined) base.maxOutputTokens = params.max_tokens;\n if (p.top_p !== undefined) base.topP = p.top_p;\n if (p.top_k !== undefined) base.topK = p.top_k;\n if (Array.isArray(p.stop)) base.stopSequences = p.stop;\n const rf = p.response_format as Record<string, unknown> | undefined;\n if (rf?.type === \"json_object\") {\n base.responseMimeType = \"application/json\";\n }\n if (typeof p.gemini_response_mime_type === \"string\") {\n base.responseMimeType = p.gemini_response_mime_type;\n }\n if (p.gemini_response_schema && typeof p.gemini_response_schema === \"object\") {\n base.responseSchema = p.gemini_response_schema;\n if (!base.responseMimeType) base.responseMimeType = \"application/json\";\n }\n if (p.gemini_thinking_config && typeof p.gemini_thinking_config === \"object\") {\n base.thinkingConfig = p.gemini_thinking_config;\n }\n const merged = p.gemini_generation_config && typeof p.gemini_generation_config === \"object\"\n ? { ...base, ...(p.gemini_generation_config as Record<string, unknown>) }\n : base;\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\nasync function geminiNativeGenerate(\n model_id: string,\n body: Record<string, unknown>,\n params: ProviderParams,\n): Promise<Record<string, unknown>> {\n const apiKey = geminiApiKey(params);\n const res = await fetch(\n `${nativeBaseUrl(params)}/models/${encodeURIComponent(model_id)}:generateContent?key=${encodeURIComponent(apiKey)}`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n );\n if (!res.ok) {\n const msg = await res.text().catch(() => res.statusText);\n throw new Error(`Gemini generateContent error: ${res.status} ${msg}`);\n }\n return await res.json() as Record<string, unknown>;\n}\n\nfunction mapGeminiStopReason(reason: string | undefined): \"stop\" | \"tool_use\" | \"length\" {\n if (reason === \"MAX_TOKENS\") return \"length\";\n return \"stop\";\n}\n\nfunction extractGeminiInvokeResult(data: Record<string, unknown>): InvokeResult {\n const candidates = (data.candidates as Array<Record<string, unknown>> | undefined) ?? [];\n const first = candidates[0] ?? {};\n const content = (first.content as Record<string, unknown> | undefined) ?? {};\n const parts = (content.parts as Array<Record<string, unknown>> | undefined) ?? [];\n\n let text = \"\";\n const tool_calls: InvokeResult[\"tool_calls\"] = [];\n for (const part of parts) {\n if (typeof part.text === \"string\") text += part.text;\n if (part.functionCall && typeof part.functionCall === \"object\") {\n const fc = part.functionCall as Record<string, unknown>;\n const name = typeof fc.name === \"string\" ? fc.name : \"tool\";\n const args = fc.args && typeof fc.args === \"object\" ? fc.args as Record<string, unknown> : {};\n tool_calls.push({\n id: typeof fc.id === \"string\" ? fc.id : `call_${tool_calls.length + 1}`,\n name,\n arguments: args,\n });\n }\n }\n\n const finishReason = typeof first.finishReason === \"string\" ? first.finishReason : undefined;\n return {\n text: text || null,\n tool_calls,\n stop_reason: tool_calls.length > 0 ? \"tool_use\" : mapGeminiStopReason(finishReason),\n };\n}\n\nasync function* geminiNativeStreamInvoke(\n model_id: string,\n messages: InvokeMessage[],\n params: ProviderParams,\n tools: OpenAITool[],\n): AsyncIterable<ProviderStreamEvent> {\n const { systemInstruction, contents } = invokeMessagesToGemini(messages);\n const body: Record<string, unknown> = {\n contents,\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(toGeminiTools(tools, params) ? { tools: toGeminiTools(tools, params) } : {}),\n ...(toGenerationConfig(params) ? { generationConfig: toGenerationConfig(params) } : {}),\n };\n const p = params as Record<string, unknown>;\n if (p.gemini_tool_config && typeof p.gemini_tool_config === \"object\") body.toolConfig = p.gemini_tool_config;\n if (Array.isArray(p.gemini_safety_settings)) body.safetySettings = p.gemini_safety_settings;\n\n const apiKey = geminiApiKey(params);\n const res = await fetch(\n `${nativeBaseUrl(params)}/models/${encodeURIComponent(model_id)}:streamGenerateContent?alt=sse&key=${encodeURIComponent(apiKey)}`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n );\n if (!res.ok || !res.body) {\n const msg = await res.text().catch(() => res.statusText);\n throw new Error(`Gemini streamGenerateContent error: ${res.status} ${msg}`);\n }\n\n for await (const line of readSSELines(res.body)) {\n if (!line || line === \"[DONE]\") continue;\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue;\n }\n const candidates = (data.candidates as Array<Record<string, unknown>> | undefined) ?? [];\n const first = candidates[0] ?? {};\n const content = (first.content as Record<string, unknown> | undefined) ?? {};\n const parts = (content.parts as Array<Record<string, unknown>> | undefined) ?? [];\n for (const part of parts) {\n const isThought = part.thought === true;\n if (typeof part.text === \"string\" && part.text) {\n if (isThought) {\n yield { type: \"thinking\", delta: part.text };\n } else {\n yield { type: \"text\", delta: part.text };\n }\n }\n if (part.functionCall && typeof part.functionCall === \"object\") {\n const fc = part.functionCall as Record<string, unknown>;\n const name = typeof fc.name === \"string\" ? fc.name : \"tool\";\n const args = fc.args && typeof fc.args === \"object\" ? fc.args as Record<string, unknown> : {};\n yield {\n type: \"tool_call_chunk\",\n index: 0,\n id: typeof fc.id === \"string\" ? fc.id : undefined,\n name,\n args_delta: JSON.stringify(args),\n };\n }\n }\n if (typeof first.finishReason === \"string\") {\n yield { type: \"stop\", reason: mapGeminiStopReason(first.finishReason) };\n }\n }\n}\n\nasync function geminiNativeInvoke(\n model_id: string,\n messages: InvokeMessage[],\n params: ProviderParams,\n tools: OpenAITool[],\n): Promise<InvokeResult> {\n const { systemInstruction, contents } = invokeMessagesToGemini(messages);\n const body: Record<string, unknown> = {\n contents,\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(toGeminiTools(tools, params) ? { tools: toGeminiTools(tools, params) } : {}),\n ...(toGenerationConfig(params) ? { generationConfig: toGenerationConfig(params) } : {}),\n };\n const p = params as Record<string, unknown>;\n if (p.gemini_tool_config && typeof p.gemini_tool_config === \"object\") body.toolConfig = p.gemini_tool_config;\n if (Array.isArray(p.gemini_safety_settings)) body.safetySettings = p.gemini_safety_settings;\n const data = await geminiNativeGenerate(model_id, body, params);\n return extractGeminiInvokeResult(data);\n}\n\nasync function geminiNativeChat(\n model_id: string,\n messages: ProviderMessage[],\n params: ProviderParams,\n): Promise<ProviderStreamResult> {\n const { systemInstruction, contents } = providerMessagesToGemini(messages);\n const body: Record<string, unknown> = {\n contents,\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(toGenerationConfig(params) ? { generationConfig: toGenerationConfig(params) } : {}),\n };\n const p = params as Record<string, unknown>;\n if (Array.isArray(p.gemini_safety_settings)) body.safetySettings = p.gemini_safety_settings;\n\n const apiKey = geminiApiKey(params);\n const res = await fetch(\n `${nativeBaseUrl(params)}/models/${encodeURIComponent(model_id)}:streamGenerateContent?alt=sse&key=${encodeURIComponent(apiKey)}`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n );\n if (!res.ok || !res.body) {\n const msg = await res.text().catch(() => res.statusText);\n throw new Error(`Gemini chat stream error: ${res.status} ${msg}`);\n }\n\n return {\n stream: (async function* () {\n for await (const line of readSSELines(res.body!)) {\n if (!line || line === \"[DONE]\") continue;\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue;\n }\n const candidates = (data.candidates as Array<Record<string, unknown>> | undefined) ?? [];\n const first = candidates[0] ?? {};\n const content = (first.content as Record<string, unknown> | undefined) ?? {};\n const parts = (content.parts as Array<Record<string, unknown>> | undefined) ?? [];\n for (const part of parts) {\n if (typeof part.text === \"string\" && part.text && part.thought !== true) {\n yield part.text;\n }\n }\n }\n })(),\n };\n}\n\nfunction resolveGeminiEmbeddingModel(model_id: string, params: ProviderParams): string {\n const overridden = (params as Record<string, unknown>).embedding_model_id;\n if (typeof overridden === \"string\" && overridden.trim()) return overridden.trim();\n // When chat model ids (gemini-*) are passed into embed(), switch to a\n // dedicated embedding model by default.\n if (/^gemini-/i.test(model_id)) return \"text-embedding-004\";\n return model_id;\n}\n\nasync function geminiEmbed(model_id: string, inputs: string[], params: ProviderParams): Promise<number[][]> {\n if (inputs.length === 0) return [];\n const apiKey = typeof params.api_key === \"string\" ? params.api_key : process.env.GEMINI_API_KEY;\n if (!apiKey) throw new Error(\"Gemini: no api_key configured\");\n\n const model = resolveGeminiEmbeddingModel(model_id, params);\n const body = {\n requests: inputs.map((text) => ({\n model: `models/${model}`,\n content: { parts: [{ text }] },\n })),\n };\n\n const res = await fetch(\n `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:batchEmbedContents?key=${encodeURIComponent(apiKey)}`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n );\n if (!res.ok) {\n const msg = await res.text().catch(() => res.statusText);\n throw new Error(`Gemini embeddings error: ${res.status} ${msg}`);\n }\n const data = await res.json() as {\n embeddings?: Array<{ values?: number[] }>;\n error?: { message?: string };\n };\n if (data.error?.message) throw new Error(data.error.message);\n const vectors = (data.embeddings ?? []).map((e) => e.values ?? []);\n if (vectors.length !== inputs.length) {\n throw new Error(`Gemini embeddings returned ${vectors.length}/${inputs.length} vectors`);\n }\n return vectors;\n}\n\nexport const geminiProvider: ModelProvider = {\n ...geminiCompat,\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n if (isCompatMode(params)) return geminiCompat.chat(model_id, messages, params);\n try {\n return await geminiNativeChat(model_id, messages, params);\n } catch {\n return geminiCompat.chat(model_id, messages, params);\n }\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n if (isCompatMode(params)) {\n if (!geminiCompat.invoke) throw new Error(\"Gemini compat provider has no invoke() implementation\");\n return geminiCompat.invoke(model_id, messages, params, tools);\n }\n try {\n return await geminiNativeInvoke(model_id, messages, params, tools);\n } catch {\n if (!geminiCompat.invoke) throw new Error(\"Gemini compat provider has no invoke() implementation\");\n return geminiCompat.invoke(model_id, messages, params, tools);\n }\n },\n\n streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n if (isCompatMode(params)) {\n if (!geminiCompat.streamInvoke) throw new Error(\"Gemini compat provider has no streamInvoke() implementation\");\n return geminiCompat.streamInvoke(model_id, messages, params, tools);\n }\n return (async function* (): AsyncIterable<ProviderStreamEvent> {\n try {\n yield* geminiNativeStreamInvoke(model_id, messages, params, tools);\n } catch {\n if (!geminiCompat.streamInvoke) throw new Error(\"Gemini compat provider has no streamInvoke() implementation\");\n yield* geminiCompat.streamInvoke(model_id, messages, params, tools);\n }\n })();\n },\n\n async embed(model_id, inputs, params): Promise<number[][]> {\n return geminiEmbed(model_id, inputs, params);\n },\n};\n","/**\n * Bridge provider: wraps any LangChain `BaseChatModel` so that Jarela's\n * `ModelProvider` interface can surface the entire LangChain ecosystem of\n * model integrations (Gemini, Bedrock, Cohere, Ollama-native, etc.) without\n * us writing a custom adapter for each one.\n *\n * Config (params on a `model_configs` row with `provider: \"langchain\"`):\n * - lc_class: required. The exported class name to instantiate\n * (e.g. \"ChatGoogleGenerativeAI\", \"ChatCohere\").\n * - All other params are forwarded to the class constructor as-is, so any\n * vendor-specific option (apiKey, region, projectId, ...) \"just works\".\n *\n * Adding a new LangChain integration:\n * 1. `npm install @langchain/<vendor>`\n * 2. Add a case to the `loadLangChainModel` switch below.\n * 3. Create a model_config: provider=\"langchain\", model_id=\"<vendor's model id>\",\n * params={ lc_class: \"ChatXxx\", apiKey: \"...\" }.\n *\n * Why a switch instead of dynamic import(\"@langchain/\" + vendor)? Next.js\n * bundles server code at build time; dynamic specifiers can't be statically\n * traced and the package wouldn't end up in the bundle. A small switch keeps\n * the bundling explicit and the dependency footprint visible.\n */\nimport { AIMessage, AIMessageChunk, HumanMessage, SystemMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { Runnable } from \"@langchain/core/runnables\";\nimport type {\n ModelProvider,\n ProviderMessage,\n ProviderParams,\n ProviderStreamResult,\n ProviderStreamEvent,\n InvokeMessage,\n InvokeResult,\n OpenAITool,\n} from \"./types\";\n\n// ── Module-cached model instances ────────────────────────────────────────────\n// LangChain model classes are usually cheap to construct, but caching keeps\n// the proxy/HTTP-client setup amortized across requests.\nconst cache = new Map<string, BaseChatModel>();\nfunction cacheKey(model_id: string, params: ProviderParams): string {\n return `${params.lc_class}:${model_id}:${JSON.stringify({ ...params, lc_class: undefined })}`;\n}\n\nasync function loadLangChainModel(model_id: string, params: ProviderParams): Promise<BaseChatModel> {\n const k = cacheKey(model_id, params);\n const hit = cache.get(k);\n if (hit) return hit;\n\n const cls = params.lc_class as string | undefined;\n if (!cls) throw new Error(`langchain provider: params.lc_class is required (e.g. \"ChatGoogleGenerativeAI\")`);\n\n // Strip our control fields from the args we pass to the class constructor.\n const { lc_class: _ignore1, lc_module: _ignore2, ...ctorArgs } = params as Record<string, unknown>;\n void _ignore1; void _ignore2;\n // Convention: if the user puts `model_id` on the config row, forward it as\n // `model` to the class (LangChain's standard option name).\n const args: Record<string, unknown> = { ...ctorArgs, model: model_id };\n\n let model: BaseChatModel;\n switch (cls) {\n case \"ChatGoogleGenerativeAI\": {\n const { ChatGoogleGenerativeAI } = await import(\"@langchain/google-genai\");\n model = new ChatGoogleGenerativeAI(args as unknown as ConstructorParameters<typeof ChatGoogleGenerativeAI>[0]);\n break;\n }\n case \"ChatCohere\": {\n const { ChatCohere } = await import(\"@langchain/cohere\");\n model = new ChatCohere(args as unknown as ConstructorParameters<typeof ChatCohere>[0]);\n break;\n }\n case \"ChatDeepSeek\": {\n const { ChatDeepSeek } = await import(\"@langchain/deepseek\");\n model = new ChatDeepSeek(args as unknown as ConstructorParameters<typeof ChatDeepSeek>[0]);\n break;\n }\n default:\n throw new Error(\n `langchain provider: unknown lc_class \"${cls}\". ` +\n `Supported: ChatGoogleGenerativeAI, ChatCohere, ChatDeepSeek. ` +\n `To add another, install @langchain/<vendor> and extend lib/providers/langchain.ts.`\n );\n }\n cache.set(k, model);\n return model;\n}\n\n// ── Message conversion ──────────────────────────────────────────────────────\nfunction toLCMessages(messages: ProviderMessage[]): BaseMessage[] {\n return messages.map((m) => {\n if (m.role === \"system\") return new SystemMessage(m.content);\n if (m.role === \"assistant\") return new AIMessage(m.content);\n return new HumanMessage(m.content);\n });\n}\n\nfunction toLCInvokeMessages(messages: InvokeMessage[]): BaseMessage[] {\n return messages.map((m) => {\n if (m.role === \"system\") return new SystemMessage(typeof m.content === \"string\" ? m.content : \"\");\n if (m.role === \"tool\") {\n return new ToolMessage({\n content: typeof m.content === \"string\" ? m.content : JSON.stringify(m.content),\n tool_call_id: m.tool_call_id ?? \"\",\n });\n }\n if (m.role === \"assistant\") {\n const ai = new AIMessage({\n content: typeof m.content === \"string\" ? m.content : \"\",\n tool_calls: m.tool_calls?.map((tc) => ({\n id: tc.id,\n name: tc.function?.name ?? \"\",\n args: (() => { try { return JSON.parse(tc.function?.arguments ?? \"{}\"); } catch { return {}; } })(),\n type: \"tool_call\" as const,\n })) ?? [],\n });\n return ai;\n }\n return new HumanMessage(typeof m.content === \"string\" ? m.content : \"\");\n });\n}\n\nfunction toLCTools(tools: OpenAITool[]): Array<{ name: string; description: string; schema: unknown }> {\n return tools.flatMap((t) => {\n if (!t.function?.name) return [];\n return [{\n name: t.function.name,\n description: t.function.description ?? \"\",\n schema: t.function.parameters,\n }];\n });\n}\n\n// ── ModelProvider methods ───────────────────────────────────────────────────\nexport const langchainProvider: ModelProvider = {\n name: \"langchain\",\n\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n const model = await loadLangChainModel(model_id, params);\n const stream = await model.stream(toLCMessages(messages));\n return {\n stream: (async function* () {\n for await (const chunk of stream) {\n if (typeof chunk.content === \"string\" && chunk.content) yield chunk.content;\n }\n })(),\n };\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n const model = await loadLangChainModel(model_id, params);\n const bound: Runnable = tools.length > 0 && (model as { bindTools?: unknown }).bindTools\n ? (model as unknown as { bindTools: (t: unknown) => Runnable }).bindTools(toLCTools(tools))\n : model;\n const result = await bound.invoke(toLCInvokeMessages(messages)) as AIMessage;\n\n const text = typeof result.content === \"string\" ? result.content : extractText(result.content);\n const toolCalls = (result.tool_calls ?? []).map((tc) => ({\n id: tc.id ?? \"\",\n name: tc.name ?? \"\",\n arguments: (tc.args ?? {}) as Record<string, unknown>,\n }));\n return {\n text: text || null,\n tool_calls: toolCalls,\n stop_reason: toolCalls.length > 0 ? \"tool_use\" : \"stop\",\n };\n },\n\n streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n return (async function* () {\n const model = await loadLangChainModel(model_id, params);\n const bound: Runnable = tools.length > 0 && (model as { bindTools?: unknown }).bindTools\n ? (model as unknown as { bindTools: (t: unknown) => Runnable }).bindTools(toLCTools(tools))\n : model;\n\n const stream = await bound.stream(toLCInvokeMessages(messages)) as AsyncIterable<AIMessageChunk>;\n\n // Track which tool_call_chunk indices we've already announced an id for —\n // some providers send id once at start, others repeat it on every chunk.\n for await (const chunk of stream) {\n if (typeof chunk.content === \"string\" && chunk.content) {\n yield { type: \"text\", delta: chunk.content };\n } else if (Array.isArray(chunk.content)) {\n // Multi-modal content blocks (Gemini): pull text out, drop the rest.\n for (const block of chunk.content) {\n if (typeof block === \"object\" && block && \"type\" in block && block.type === \"text\" && \"text\" in block) {\n yield { type: \"text\", delta: String(block.text) };\n }\n }\n }\n const reasoning = chunk.additional_kwargs?.reasoning_content;\n if (typeof reasoning === \"string\" && reasoning) {\n yield { type: \"thinking\", delta: reasoning };\n }\n for (const tcc of chunk.tool_call_chunks ?? []) {\n yield {\n type: \"tool_call_chunk\",\n index: tcc.index ?? 0,\n id: tcc.id,\n name: tcc.name,\n args_delta: tcc.args,\n };\n }\n }\n })();\n },\n\n // Embeddings: LangChain has separate `Embeddings` classes per vendor and the\n // mapping isn't 1:1 with chat-model classes. Skipping here — recall falls\n // back to its substring path for langchain-provided models, which is fine.\n};\n\nfunction extractText(content: unknown): string {\n if (Array.isArray(content)) {\n return content\n .filter((b) => typeof b === \"object\" && b && (b as { type?: string }).type === \"text\")\n .map((b) => String((b as { text?: string }).text ?? \"\"))\n .join(\"\");\n }\n return \"\";\n}\n","// Mock/dummy model provider for tests, demos, and offline development.\n//\n// Behaviour is scripted via directives embedded in the *last user message*:\n//\n// MOCK:reply=Hello world // stream back exactly \"Hello world\"\n// MOCK:echo // echo the user message verbatim\n// MOCK:tool=web_search:{\"q\":\"x\"} // emit one tool_call (id=mock-1, args = JSON)\n// MOCK:think=reasoning here // emit a thinking delta before text\n// MOCK:slow=50 // sleep 50ms between word chunks\n// MOCK:error=overloaded // throw \"overloaded\"\n// MOCK:stop=length // override stop_reason (default \"stop\")\n//\n// Multiple directives may appear on separate lines; everything else in the\n// message is treated as plain context.\n//\n// Default behaviour (no directives): streams back \"Hello from the mock\n// provider. You said: <last user message>\".\n//\n// Registration is gated by JARELA_ENABLE_MOCK_PROVIDER=1 in index.ts so the\n// provider can't be accidentally enabled in production.\n\nimport { createHash } from \"node:crypto\";\nimport type {\n ModelProvider,\n ProviderMessage,\n ProviderParams,\n ProviderStreamResult,\n ProviderStreamEvent,\n InvokeMessage,\n InvokeResult,\n OpenAITool,\n} from \"./types\";\n\nconst DEFAULT_REPLY = \"Hello from the mock provider. You said: \";\nconst EMBED_DIM = 384;\n\nexport type MockDirectives = {\n reply?: string;\n echo?: boolean;\n tool?: { name: string; args: Record<string, unknown> };\n think?: string;\n slowMs?: number;\n error?: string;\n stopReason?: \"stop\" | \"tool_use\" | \"length\";\n};\n\n/** Parse `MOCK:<key>[=<value>]` directives out of a message string. Exported\n * for unit tests. */\nexport function parseMockDirectives(text: string): MockDirectives {\n const out: MockDirectives = {};\n for (const line of text.split(/\\r?\\n/)) {\n const m = /^\\s*MOCK:([a-zA-Z]+)(?:=(.*))?\\s*$/.exec(line);\n if (!m) continue;\n const key = m[1].toLowerCase();\n const value = m[2] ?? \"\";\n switch (key) {\n case \"reply\":\n out.reply = value;\n break;\n case \"echo\":\n out.echo = true;\n break;\n case \"tool\": {\n // tool=<name>[:<json-args>]\n const colon = value.indexOf(\":\");\n if (colon === -1) {\n out.tool = { name: value, args: {} };\n } else {\n const name = value.slice(0, colon);\n const argsRaw = value.slice(colon + 1);\n let args: Record<string, unknown> = {};\n try { args = JSON.parse(argsRaw) as Record<string, unknown>; } catch { /* leave empty */ }\n out.tool = { name, args };\n }\n break;\n }\n case \"think\":\n out.think = value;\n break;\n case \"slow\": {\n const n = Number(value);\n if (Number.isFinite(n) && n >= 0) out.slowMs = n;\n break;\n }\n case \"error\":\n out.error = value || \"mock error\";\n break;\n case \"stop\":\n if (value === \"stop\" || value === \"tool_use\" || value === \"length\") out.stopReason = value;\n break;\n }\n }\n return out;\n}\n\nfunction lastUserText(messages: { role: string; content: unknown }[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i];\n if (m.role !== \"user\") continue;\n if (typeof m.content === \"string\") return m.content;\n if (Array.isArray(m.content)) {\n const parts = m.content as { type: string; text?: string }[];\n return parts.filter((p) => p.type === \"text\").map((p) => p.text ?? \"\").join(\"\\n\");\n }\n return \"\";\n }\n return \"\";\n}\n\nfunction pickReply(directives: MockDirectives, userText: string): string {\n if (directives.reply !== undefined) return directives.reply;\n if (directives.echo) return userText;\n return DEFAULT_REPLY + userText;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction tokenize(text: string): string[] {\n // Split into whitespace-preserving chunks so the streaming feels real and\n // round-trips through the UI's incremental rendering.\n return text.match(/\\S+\\s*|\\s+/g) ?? (text ? [text] : []);\n}\n\nasync function* streamText(text: string, slowMs?: number): AsyncIterable<string> {\n for (const chunk of tokenize(text)) {\n if (slowMs) await sleep(slowMs);\n yield chunk;\n }\n}\n\nexport const mockProvider: ModelProvider = {\n name: \"mock\",\n\n async chat(_model_id, messages, _params: ProviderParams): Promise<ProviderStreamResult> {\n const userText = lastUserText(messages as ProviderMessage[]);\n const directives = parseMockDirectives(userText);\n if (directives.error) throw new Error(directives.error);\n const reply = pickReply(directives, userText);\n return {\n stream: streamText(reply, directives.slowMs),\n };\n },\n\n async invoke(_model_id, messages, _params, _tools: OpenAITool[]): Promise<InvokeResult> {\n const userText = lastUserText(messages as InvokeMessage[]);\n const directives = parseMockDirectives(userText);\n if (directives.error) throw new Error(directives.error);\n\n if (directives.tool) {\n return {\n text: null,\n tool_calls: [{\n id: \"mock-1\",\n name: directives.tool.name,\n arguments: directives.tool.args,\n }],\n stop_reason: \"tool_use\",\n };\n }\n return {\n text: pickReply(directives, userText),\n tool_calls: [],\n stop_reason: directives.stopReason ?? \"stop\",\n };\n },\n\n async *streamInvoke(\n _model_id,\n messages,\n _params,\n _tools: OpenAITool[],\n ): AsyncIterable<ProviderStreamEvent> {\n const userText = lastUserText(messages as InvokeMessage[]);\n const directives = parseMockDirectives(userText);\n if (directives.error) throw new Error(directives.error);\n\n if (directives.think) {\n for (const chunk of tokenize(directives.think)) {\n if (directives.slowMs) await sleep(directives.slowMs);\n yield { type: \"thinking\", delta: chunk };\n }\n }\n\n if (directives.tool) {\n const argsJson = JSON.stringify(directives.tool.args);\n yield { type: \"tool_call_chunk\", index: 0, id: \"mock-1\", name: directives.tool.name };\n yield { type: \"tool_call_chunk\", index: 0, args_delta: argsJson };\n yield { type: \"stop\", reason: \"tool_use\" };\n return;\n }\n\n const reply = pickReply(directives, userText);\n for (const chunk of tokenize(reply)) {\n if (directives.slowMs) await sleep(directives.slowMs);\n yield { type: \"text\", delta: chunk };\n }\n yield { type: \"stop\", reason: directives.stopReason ?? \"stop\" };\n },\n\n async embed(_model_id, inputs, _params): Promise<number[][]> {\n // Deterministic per-input vector seeded by sha256 of the input. Same\n // input always produces the same vector so semantic-recall tests can\n // assert stable rankings.\n return inputs.map((input) => {\n const hash = createHash(\"sha256\").update(input).digest();\n const vec = new Array<number>(EMBED_DIM);\n for (let i = 0; i < EMBED_DIM; i++) {\n // Repeat the 32-byte digest to fill EMBED_DIM. Map [0,255] -> [-1,1].\n vec[i] = (hash[i % hash.length] / 127.5) - 1;\n }\n // L2-normalise so cosine == dot product.\n let norm = 0;\n for (const x of vec) norm += x * x;\n norm = Math.sqrt(norm) || 1;\n for (let i = 0; i < EMBED_DIM; i++) vec[i] /= norm;\n return vec;\n });\n },\n};\n","import type { ModelProvider } from \"./types\";\nimport { openaiProvider } from \"./openai\";\nimport { anthropicProvider } from \"./anthropic\";\nimport { githubCopilotProvider } from \"./github-copilot\";\nimport { deepseekProvider } from \"./deepseek\";\nimport { geminiProvider } from \"./gemini\";\nimport { langchainProvider } from \"./langchain\";\nimport { mockProvider } from \"./mock\";\nimport { loadExternalProviders } from \"./external\";\n\nconst BUILTINS: Record<string, ModelProvider> = {\n openai: openaiProvider,\n anthropic: anthropicProvider,\n \"github-copilot\": githubCopilotProvider,\n deepseek: deepseekProvider,\n gemini: geminiProvider,\n langchain: langchainProvider,\n};\n\n// The mock provider is opt-in via env so production deployments never\n// expose it as a selectable backend. Tests / offline dev set the flag.\nfunction isMockEnabled(): boolean {\n return process.env.JARELA_ENABLE_MOCK_PROVIDER === \"1\";\n}\n\nexport const BUILTIN_PROVIDER_NAMES: ReadonlySet<string> = new Set([\n ...Object.keys(BUILTINS),\n \"mock\",\n]);\n\n// Recompute on every call so external providers dropped into ~/.jarela/providers/\n// are picked up without a process restart. loadExternalProviders cache-busts\n// require() per file, so edits are reflected immediately too.\nfunction getProviders(): Record<string, ModelProvider> {\n const base: Record<string, ModelProvider> = { ...BUILTINS };\n if (isMockEnabled()) base.mock = mockProvider;\n return { ...base, ...loadExternalProviders(BUILTIN_PROVIDER_NAMES) };\n}\n\nexport function listProviderNames(): string[] {\n return Object.keys(getProviders()).sort((a, b) => a.localeCompare(b));\n}\n\nexport function getProvider(name: string): ModelProvider {\n const all = getProviders();\n const p = all[name];\n if (!p) throw new Error(`Unknown provider: \"${name}\". Available: ${Object.keys(all).join(\", \")}`);\n return p;\n}\n\nexport { type ModelProvider };\nexport type { ProviderMessage, ProviderParams, ProviderStreamResult } from \"./types\";\n","// Master key management for at-rest encryption (ADR-0005).\n//\n// The key is a 32-byte value used by lib/crypto/envelope.ts for AES-256-GCM.\n// Primary storage is the host OS keychain via @napi-rs/keyring (its\n// keytar-compatible shim). We bootstrap synchronously by spawning a\n// one-shot child Node process so the rest of the codebase keeps its\n// synchronous store API.\n//\n// Fallback (when keychain access fails — headless Linux, locked Mac\n// keychain, missing keyring native binary): a 0600-permissioned file at\n// ${dataDir}/.secret-key. Same threat model as today's plaintext DB for\n// adversaries with filesystem read, but uniform so the encrypt/decrypt\n// code path stays single-shape.\n\nimport { execFileSync } from \"node:child_process\";\nimport {\n chmodSync,\n existsSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { randomBytes } from \"node:crypto\";\nimport { join } from \"node:path\";\n\nconst KEYCHAIN_SERVICE = \"jarela\";\nconst KEYCHAIN_ACCOUNT = \"master-key.v1\";\nconst KEYFILE_NAME = \".secret-key\";\n\nexport type MasterKeySource = \"keychain\" | \"keyfile\";\n\nlet _key: Buffer | null = null;\nlet _source: MasterKeySource | null = null;\n\n// Synchronously read or generate the master key. Idempotent; only does\n// real work on first call. Returns where the key ended up living so\n// callers can warn the user about the keyfile fallback.\n//\n// Resolution order:\n// 1. If ${dataDir}/.secret-key exists, use it. The keyfile is\n// authoritative once present: the on-disk rows were encrypted\n// with that key, and silently switching to a different key\n// source would orphan them. To migrate to the keychain, decrypt\n// with the keyfile + re-encrypt + delete the keyfile (see\n// scripts/rekey-to-keychain.mjs — TODO).\n// 2. Otherwise try the OS keychain via keytar (child process).\n// 3. Otherwise generate a fresh keyfile and warn the user.\nexport function initMasterKey(dataDir: string): { source: MasterKeySource } {\n if (_key && _source) return { source: _source };\n\n const path = join(dataDir, KEYFILE_NAME);\n\n // 1) Existing keyfile — authoritative.\n if (existsSync(path)) {\n _key = readFileSync(path);\n if (_key.length !== 32) throw new Error(`keyfile wrong length: ${_key.length}`);\n _source = \"keyfile\";\n return { source: \"keyfile\" };\n }\n\n // 2) Try keychain via a one-shot child process so we can stay sync.\n try {\n const keyB64 = loadOrCreateViaKeychain();\n _key = Buffer.from(keyB64, \"base64\");\n if (_key.length !== 32) throw new Error(`keychain key wrong length: ${_key.length}`);\n _source = \"keychain\";\n return { source: \"keychain\" };\n } catch (err) {\n console.warn(\n `[jarela] keychain unavailable, falling back to keyfile: ${(err as Error).message}`,\n );\n }\n\n // 3) Fallback: generate a fresh keyfile.\n _key = randomBytes(32);\n writeFileSync(path, _key, { mode: 0o600 });\n try { chmodSync(path, 0o600); } catch { /* */ }\n\n _source = \"keyfile\";\n return { source: \"keyfile\" };\n}\n\nexport function getMasterKey(): Buffer {\n if (!_key) {\n throw new Error(\n \"master key not initialized — initMasterKey() must run before any encrypted store access\",\n );\n }\n return _key;\n}\n\nexport function getMasterKeySource(): MasterKeySource | null {\n return _source;\n}\n\n// Spawn a child Node process that talks to the OS keyring and prints the\n// base64 key on stdout. Either reads the existing entry or generates a\n// new one and stores it. Synchronous from the caller's perspective.\nfunction loadOrCreateViaKeychain(): string {\n const script = `\n const keytar = require('@napi-rs/keyring/keytar');\n const { randomBytes } = require('crypto');\n (async () => {\n const SERVICE = ${JSON.stringify(KEYCHAIN_SERVICE)};\n const ACCOUNT = ${JSON.stringify(KEYCHAIN_ACCOUNT)};\n let v = await keytar.getPassword(SERVICE, ACCOUNT);\n if (!v) {\n v = randomBytes(32).toString('base64');\n await keytar.setPassword(SERVICE, ACCOUNT, v);\n }\n process.stdout.write(v);\n })().catch((e) => {\n process.stderr.write(String(e && e.message ? e.message : e));\n process.exit(1);\n });\n `;\n const out = execFileSync(process.execPath, [\"-e\", script], {\n encoding: \"utf8\",\n cwd: process.cwd(),\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n // Cap at 10s in case keytar hangs (e.g. macOS prompt with no user).\n timeout: 10_000,\n });\n return out.trim();\n}\n","// Thin wrapper over memory_store for integration credentials. The data lives\n// under namespace=\"integrations\", key=<integration name>, value=<JSON>. We\n// reuse memory_store so the existing Atlassian tool's fallback resolution\n// path \"just works\" without a second source of truth.\n//\n// Secret fields are echoed back to clients as a fixed sentinel string so\n// nothing sensitive ends up in the UI / network logs / browser inspector.\n\nimport { getMemory, putMemory, deleteMemory, listMemory } from \"@/lib/stores/memory\";\nimport { getIntegrationMeta, markFieldsAsUserTouched } from \"@/lib/stores/integration_meta\";\n\nexport const SECRET_MASK = \"********\";\nconst NAMESPACE = \"integrations\";\n\n// Persona-filter category. Mirrors the category enum in\n// lib/integrations/manifest.ts so we can drive the Credentials panel\n// off the same vocabulary the agent uses when explaining setup.\n// llm - LLM provider keys (Google, OpenAI, …)\n// mail - inbox + draft tools (Gmail, Outlook)\n// calendar - calendar event tools\n// issue-tracker - Jira / Jira Align / etc.\n// chat - messaging bridges (future)\n// infrastructure - GitHub / cloud / k8s / …\n// other - everything else\nexport type IntegrationCategory =\n | \"llm\"\n | \"mail\"\n | \"calendar\"\n | \"issue-tracker\"\n | \"chat\"\n | \"infrastructure\"\n | \"other\";\n\n// Per-integration shape. Adding a new integration means:\n// 1. Add an entry here naming its fields and which are secrets.\n// 2. The Atlassian tool (or a future tool) reads via getIntegration().\nexport const INTEGRATIONS = {\n anthropic: {\n label: \"Anthropic (Claude)\",\n category: \"llm\" as IntegrationCategory,\n description: \"Used by Claude-family chat models. Get a key at console.anthropic.com → API keys.\",\n fields: [\n { key: \"api_key\", label: \"API key\", placeholder: \"sk-ant-…\", secret: true, required: true },\n ],\n },\n atlassian: {\n label: \"Atlassian (Jira + Confluence)\",\n category: \"issue-tracker\" as IntegrationCategory,\n description: \"Used by jira_* and confluence_* tools. Get an API token at id.atlassian.com → Security → API tokens.\",\n fields: [\n { key: \"url\", label: \"Site URL\", placeholder: \"https://your-team.atlassian.net\", secret: false, required: true },\n { key: \"email\", label: \"Account email\", placeholder: \"you@company.com\", secret: false, required: true },\n { key: \"api_token\", label: \"API token\", placeholder: \"ATATT3xFfGF0…\", secret: true, required: true },\n ],\n },\n jira_align: {\n label: \"Jira Align\",\n category: \"issue-tracker\" as IntegrationCategory,\n description:\n \"Used by jira_align_* tools (read/search/walk hierarchy, create/update/transition/delete \" +\n \"work items, comment). Generate an API token in Jira Align under Settings → Personal \" +\n \"Access Tokens. Different surface from Jira Cloud — this is the portfolio-level product.\",\n fields: [\n { key: \"url\", label: \"Instance URL\", placeholder: \"https://your-company.jiraalign.com\", secret: false, required: true },\n { key: \"api_token\", label: \"API token\", placeholder: \"eyJ…\", secret: true, required: true },\n ],\n },\n google: {\n label: \"Google AI (Gemini + Imagen)\",\n category: \"llm\" as IntegrationCategory,\n description: \"Used by the generate_image tool (Gemini / Imagen). Get a key at aistudio.google.com → API keys.\",\n fields: [\n { key: \"api_key\", label: \"API key\", placeholder: \"AIza…\", secret: true, required: true },\n ],\n },\n gmail: {\n label: \"Gmail + Calendar\",\n category: \"mail\" as IntegrationCategory,\n description:\n \"Used by the gmail_* and calendar_* tools (search/read/draft/label/archive mail; \" +\n \"list/create/update/delete calendar events). Drafts only \\u2014 this integration \" +\n \"intentionally cannot send mail. See the Setup guide below for how to create the \" +\n \"OAuth client. Existing connections must reconnect to grant the new Calendar scope.\",\n fields: [\n { key: \"client_id\", label: \"OAuth client ID\", placeholder: \"<id>.apps.googleusercontent.com\", secret: false, required: true },\n { key: \"client_secret\", label: \"OAuth client secret\", placeholder: \"GOCSPX-…\", secret: true, required: true },\n { key: \"refresh_token\", label: \"Refresh token\", placeholder: \"1//0…\", secret: true, required: true },\n ],\n }, github: {\n label: \"GitHub\",\n category: \"infrastructure\" as IntegrationCategory,\n description:\n \"Used by github_* tools (search/read/create/comment on issues + PRs, list PRs, get repo info). \" +\n \"Create a Personal Access Token at github.com/settings/tokens. Scopes: `repo` (private repos) or \" +\n \"`public_repo` (public only); add `read:org` if you target org repos.\",\n fields: [\n { key: \"token\", label: \"Personal Access Token\", placeholder: \"ghp_… or github_pat_…\", secret: true, required: true },\n ],\n },\n outlook: {\n label: \"Outlook + Calendar\",\n category: \"mail\" as IntegrationCategory,\n description:\n \"Used by the outlook_* and outlook_calendar_* tools (search/read/draft/move/trash mail; \" +\n \"list/create/update/delete calendar events). Drafts only — this integration intentionally \" +\n \"cannot send mail. Requires an Azure app registration. See the Setup guide below.\",\n fields: [\n { key: \"client_id\", label: \"Application (client) ID\", placeholder: \"00000000-0000-0000-0000-000000000000\", secret: false, required: true },\n { key: \"client_secret\", label: \"Client secret value\", placeholder: \"abc~…\", secret: true, required: true },\n { key: \"refresh_token\", label: \"Refresh token\", placeholder: \"0.AXoA…\", secret: true, required: true },\n ],\n },} as const;\n\nexport type IntegrationName = keyof typeof INTEGRATIONS;\n\nexport function isKnownIntegration(name: string): name is IntegrationName {\n return Object.prototype.hasOwnProperty.call(INTEGRATIONS, name);\n}\n\nexport interface IntegrationStatus {\n name: string;\n configured: boolean;\n values: Record<string, string>; // secrets masked\n updated_at: string | null;\n /**\n * Per-field provenance. `\"rc\"` = pulled from a shell rc / Windows\n * registry env var by the env-syncer. `\"user\"` = the user typed it\n * into the panel. Absent fields haven't been seen by either path.\n * Drives the \"from your shell\" badge in the IntegrationsPanel.\n */\n source?: Record<string, \"rc\" | \"user\">;\n /** Last successful rc-sync write time, ISO. Null until the first sync. */\n rc_synced_at?: string | null;\n}\n\nexport function listIntegrations(): IntegrationStatus[] {\n const rows = listMemory(NAMESPACE, undefined, 100);\n const byKey = new Map(rows.map((r) => [r.key, r]));\n return Object.keys(INTEGRATIONS).map((name) => {\n const row = byKey.get(name);\n const meta = getIntegrationMeta(name);\n if (!row) {\n return {\n name,\n configured: false,\n values: {},\n updated_at: null,\n source: meta.source,\n rc_synced_at: meta.rc_synced_at,\n };\n }\n return {\n name,\n configured: true,\n values: maskSecrets(name as IntegrationName, parseValue(row.value)),\n updated_at: row.updated_at,\n source: meta.source,\n rc_synced_at: meta.rc_synced_at,\n };\n });\n}\n\nexport function getIntegrationStatus(name: string): IntegrationStatus | null {\n if (!isKnownIntegration(name)) return null;\n const row = getMemory(NAMESPACE, name);\n const meta = getIntegrationMeta(name);\n if (!row) {\n return {\n name,\n configured: false,\n values: {},\n updated_at: null,\n source: meta.source,\n rc_synced_at: meta.rc_synced_at,\n };\n }\n return {\n name,\n configured: true,\n values: maskSecrets(name, parseValue(row.value)),\n updated_at: row.updated_at,\n source: meta.source,\n rc_synced_at: meta.rc_synced_at,\n };\n}\n\n// Internal: server-side resolution that returns RAW secrets. Only callable\n// from server code (the integration tools).\nexport function getIntegrationRaw(name: string): Record<string, string> | null {\n const row = getMemory(NAMESPACE, name);\n if (!row) return null;\n return parseValue(row.value);\n}\n\n// Save credentials. Any field whose value matches SECRET_MASK is preserved\n// from the existing record (so unchanged secret fields don't get blanked\n// when the UI sends back the masked form).\nexport function saveIntegration(name: string, incoming: Record<string, string>): IntegrationStatus | { error: string } {\n if (!isKnownIntegration(name)) return { error: `unknown integration \"${name}\"` };\n const def = INTEGRATIONS[name];\n const existing = getIntegrationRaw(name) ?? {};\n const merged: Record<string, string> = {};\n // Track which fields the user actually changed (vs preserved via SECRET_MASK).\n // Only changed fields flip source to \"user\" — if they re-saved without\n // touching the secret, it stays whatever it was (rc or user).\n const touched: string[] = [];\n for (const f of def.fields) {\n const v = incoming[f.key];\n if (v === undefined) {\n if (existing[f.key]) merged[f.key] = existing[f.key];\n else if (f.required) return { error: `missing required field \"${f.key}\"` };\n continue;\n }\n if (f.secret && v === SECRET_MASK) {\n // UI returned masked sentinel — keep existing secret untouched.\n if (existing[f.key]) merged[f.key] = existing[f.key];\n else if (f.required) return { error: `missing required secret \"${f.key}\"` };\n } else {\n if (f.required && !v.trim()) return { error: `\"${f.key}\" cannot be empty` };\n merged[f.key] = v;\n if (existing[f.key] !== v) touched.push(f.key);\n }\n }\n putMemory(NAMESPACE, name, merged);\n if (touched.length > 0) markFieldsAsUserTouched(name, touched);\n return getIntegrationStatus(name)!;\n}\n\nexport function deleteIntegration(name: string): boolean {\n if (!isKnownIntegration(name)) return false;\n return deleteMemory(NAMESPACE, name);\n}\n\nfunction parseValue(raw: string): Record<string, string> {\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (parsed && typeof parsed === \"object\") {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof v === \"string\") out[k] = v;\n }\n return out;\n }\n } catch { /* */ }\n return {};\n}\n\nfunction maskSecrets(name: IntegrationName, values: Record<string, string>): Record<string, string> {\n const out: Record<string, string> = {};\n for (const f of INTEGRATIONS[name].fields) {\n const v = values[f.key];\n if (v === undefined) continue;\n out[f.key] = f.secret ? SECRET_MASK : v;\n }\n return out;\n}\n","import { getDb } from \"@/lib/db\";\nimport { encrypt, decryptIfNeeded } from \"@/lib/crypto/envelope\";\nimport type { ProviderParams } from \"@/lib/providers/types\";\n\nconst now = () => new Date().toISOString();\n\nexport interface ModelConfigRow {\n name: string; provider: string; model_id: string;\n params: string; is_default: number;\n created_at: string; updated_at: string;\n}\n\n// `params` holds the provider API key alongside hyperparameters and is\n// stored encrypted at rest (ADR-0005). Decrypt before returning rows.\nfunction decryptRow<T extends { params: string }>(row: T): T {\n return { ...row, params: decryptIfNeeded(row.params) };\n}\n\nexport function listModelConfigs(): ModelConfigRow[] {\n const rows = getDb()\n .prepare(\"SELECT * FROM model_configs ORDER BY is_default DESC, name ASC\")\n .all() as unknown as ModelConfigRow[];\n return rows.map(decryptRow);\n}\n\nexport function getModelConfig(name: string): ModelConfigRow | null {\n const row = (getDb().prepare(\"SELECT * FROM model_configs WHERE name=?\").get(name) as unknown as ModelConfigRow) ?? null;\n return row ? decryptRow(row) : null;\n}\n\nexport function getDefaultModelConfig(): ModelConfigRow | null {\n const row = (getDb().prepare(\"SELECT * FROM model_configs WHERE is_default=1 LIMIT 1\").get() as unknown as ModelConfigRow) ?? null;\n return row ? decryptRow(row) : null;\n}\n\nexport function upsertModelConfig(\n name: string, provider: string, model_id: string,\n params: Record<string, unknown>, is_default: boolean\n): ModelConfigRow {\n const t = now();\n const existing = getModelConfig(name);\n const created_at = existing?.created_at ?? t;\n const db = getDb();\n if (is_default) db.prepare(\"UPDATE model_configs SET is_default=0\").run();\n db.prepare(\n \"INSERT OR REPLACE INTO model_configs (name,provider,model_id,params,is_default,created_at,updated_at) VALUES (?,?,?,?,?,?,?)\"\n ).run(name, provider, model_id, encrypt(JSON.stringify(params)), is_default ? 1 : 0, created_at, t);\n return getModelConfig(name)!;\n}\n\nexport function deleteModelConfig(name: string): boolean {\n return (getDb().prepare(\"DELETE FROM model_configs WHERE name=?\").run(name) as { changes: number }).changes > 0;\n}\n\n/**\n * Decode the JSON-encoded provider params (api_key, model overrides, etc.).\n * Returns an empty object on NULL/blank/malformed JSON. Callers that\n * previously did `JSON.parse(cfg.params)` inline should switch to this\n * getter so the serialization contract stays owned by this store.\n */\nexport function getModelParams(cfg: Pick<ModelConfigRow, \"params\"> | null | undefined): ProviderParams {\n if (!cfg?.params) return {};\n try {\n const parsed = JSON.parse(cfg.params);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as ProviderParams;\n }\n return {};\n } catch {\n return {};\n }\n}\n","import { getDb } from \"@/lib/db\";\nimport { embedOne } from \"@/lib/embeddings\";\nimport { encrypt, decryptIfNeeded } from \"@/lib/crypto/envelope\";\nimport { isSensitiveMemoryNamespace } from \"@/lib/crypto/sensitive\";\n\nconst now = () => new Date().toISOString();\n\n// Explicit column list for memory reads — omits `embedding` (~20KB of\n// JSON-encoded float[] per row), which only the embeddings module reads.\n// Avoids dragging it through the listMemory / getMemory result set.\nconst MEM_COLS_SQL = \"SELECT namespace, key, value, created_at, updated_at FROM memory_store\";\n\n// Decrypt rows in sensitive namespaces before handing them back to\n// callers. Non-sensitive namespaces pass through untouched (their values\n// are not encrypted at rest, by design — see ADR-0005).\nfunction decryptRow(row: MemoryRow): MemoryRow {\n if (!isSensitiveMemoryNamespace(row.namespace)) return row;\n return { ...row, value: decryptIfNeeded(row.value) };\n}\n\n// Fire-and-forget: compute and persist an embedding without blocking the write.\n// Failures (no embed provider, network down) are logged in embeddings/index.ts\n// and the row simply stays without an embedding — recall falls back to substring.\nfunction asyncEmbed(text: string, persist: (vec: number[]) => void): void {\n embedOne(text).then((vec) => { if (vec) persist(vec); }).catch(() => { /* already logged */ });\n}\n\nexport interface MemoryRow {\n namespace: string; key: string; value: string;\n created_at: string; updated_at: string;\n}\n\nexport function listMemory(namespace?: string, search?: string, limit = 50): MemoryRow[] {\n let sql = MEM_COLS_SQL + \" WHERE 1=1\";\n const params: (string | number)[] = [];\n if (namespace) { sql += \" AND namespace=?\"; params.push(namespace); }\n if (search) { sql += \" AND (key LIKE ? OR value LIKE ?)\"; params.push(`%${search}%`, `%${search}%`); }\n sql += \" ORDER BY updated_at DESC LIMIT ?\";\n params.push(limit);\n const rows = getDb().prepare(sql).all(...params) as unknown as MemoryRow[];\n // P2.7: when the caller pinned the namespace and it isn't in the\n // sensitive set, every row's value is plaintext anyway — skip the\n // per-row decryptRow allocation. The unfiltered case still has to\n // check each row since namespaces vary.\n if (namespace && !isSensitiveMemoryNamespace(namespace)) return rows;\n return rows.map(decryptRow);\n}\n\nexport function getMemory(namespace: string, key: string): MemoryRow | null {\n const row = (getDb().prepare(MEM_COLS_SQL + \" WHERE namespace=? AND key=?\").get(namespace, key) as unknown as MemoryRow) ?? null;\n return row ? decryptRow(row) : null;\n}\n\nexport function putMemory(namespace: string, key: string, value: unknown): MemoryRow {\n const t = now();\n // Only the original created_at is needed to preserve insertion time on\n // upsert; reading the full row would force an unnecessary AES-GCM\n // decrypt of an existing sensitive value just to discard it.\n const existing = getDb()\n .prepare(\"SELECT created_at FROM memory_store WHERE namespace=? AND key=?\")\n .get(namespace, key) as { created_at?: string } | undefined;\n const created_at = existing?.created_at ?? t;\n const json = JSON.stringify(value);\n // Encrypt the value column at rest for sensitive namespaces (ADR-0005).\n // Embeddings (below) keep using the plaintext text so semantic recall\n // still works for non-sensitive namespaces; sensitive namespaces are\n // not the kind of content we expect semantic recall against anyway.\n const stored = isSensitiveMemoryNamespace(namespace) ? encrypt(json) : json;\n getDb()\n .prepare(\"INSERT OR REPLACE INTO memory_store (namespace,key,value,created_at,updated_at,embedding) VALUES (?,?,?,?,?,NULL)\")\n .run(namespace, key, stored, created_at, t);\n // Embed the value text (not the JSON wrapping) so recall matches the semantic content.\n const text = typeof value === \"string\" ? value : json;\n asyncEmbed(`${namespace}/${key}: ${text}`, (vec) => {\n getDb()\n .prepare(\"UPDATE memory_store SET embedding=? WHERE namespace=? AND key=?\")\n .run(JSON.stringify(vec), namespace, key);\n });\n return { namespace, key, value: json, created_at, updated_at: t };\n}\n\nexport function deleteMemory(namespace: string, key: string): boolean {\n return (getDb().prepare(\"DELETE FROM memory_store WHERE namespace=? AND key=?\").run(namespace, key) as { changes: number }).changes > 0;\n}\n","import { join } from \"node:path\";\nimport { existsSync, readdirSync, statSync } from \"node:fs\";\nimport type { ModelProvider } from \"./types\";\nimport { getDataDir } from \"@/lib/db/data-dir\";\n\nexport const PROVIDERS_DIR = join(getDataDir(), \"providers\");\n\nexport interface ExtensionLoadError {\n file: string;\n error: string;\n}\n\nexport interface ExternalProvidersResult {\n providers: Record<string, ModelProvider>;\n files: Map<string, string>;\n errors: ExtensionLoadError[];\n}\n\nfunction isValid(p: unknown): p is ModelProvider {\n if (!p || typeof p !== \"object\") return false;\n const o = p as Record<string, unknown>;\n return typeof o.name === \"string\" && typeof o.chat === \"function\";\n}\n\nexport function loadExternalProvidersDetailed(\n builtins: ReadonlySet<string>,\n): ExternalProvidersResult {\n const providers: Record<string, ModelProvider> = {};\n const files = new Map<string, string>();\n const errors: ExtensionLoadError[] = [];\n if (!existsSync(PROVIDERS_DIR)) return { providers, files, errors };\n\n // Reach for node:module via process.getBuiltinModule so webpack cannot\n // see the dependency and tree-shake it. With a normal `import { createRequire }\n // from \"node:module\"`, Next/webpack drops the call entirely (the result is\n // judged side-effect-free), leaving the require binding undefined at runtime.\n // process.getBuiltinModule is a Node 22+ API that bypasses both the module\n // graph and webpack's static analysis. Anchor to a real on-disk path — not\n // import.meta.url, which is rewritten to a virtual chunk URL that would\n // route absolute requires back through webpack's resolver.\n const { createRequire } = (\n process as unknown as { getBuiltinModule: (id: string) => typeof import(\"node:module\") }\n ).getBuiltinModule(\"node:module\");\n const req = createRequire(join(PROVIDERS_DIR, \"_anchor\"));\n\n let entries: string[];\n try {\n entries = readdirSync(PROVIDERS_DIR);\n } catch {\n return { providers, files, errors };\n }\n\n for (const entry of entries) {\n if (!/\\.(c?js|ts)$/i.test(entry)) continue;\n const path = join(PROVIDERS_DIR, entry);\n try {\n if (!statSync(path).isFile()) continue;\n } catch {\n continue;\n }\n\n let mod: unknown;\n try {\n delete req.cache[req.resolve(path)];\n mod = req(path);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n errors.push({ file: entry, error: message });\n console.error(`[providers] failed to load ${entry}:`, err);\n continue;\n }\n\n const candidate =\n (mod as { default?: unknown })?.default ?? (mod as unknown);\n if (!isValid(candidate)) {\n const msg = \"does not export a valid ModelProvider (need { name, chat })\";\n errors.push({ file: entry, error: msg });\n console.error(`[providers] ${entry} ${msg}`);\n continue;\n }\n\n const name = candidate.name;\n if (builtins.has(name)) {\n const msg = `name \"${name}\" collides with a built-in provider — built-in takes precedence`;\n errors.push({ file: entry, error: msg });\n console.warn(`[providers] external ${entry}: ${msg}`);\n continue;\n }\n if (providers[name]) {\n const msg = `duplicate external provider \"${name}\"`;\n errors.push({ file: entry, error: msg });\n console.warn(`[providers] ${entry}: ${msg}`);\n continue;\n }\n providers[name] = candidate;\n files.set(name, entry);\n }\n\n return { providers, files, errors };\n}\n\n// Convenience for callers that only need the provider map (the existing\n// pattern in lib/providers/index.ts).\nexport function loadExternalProviders(\n builtins: ReadonlySet<string>,\n): Record<string, ModelProvider> {\n return loadExternalProvidersDetailed(builtins).providers;\n}\n","// GitHub Copilot device-flow login. Lets users sign in with their Copilot\n// subscription instead of pasting a PAT (which can't be exchanged for a\n// Copilot session token and gets rate-limited on the Models REST API).\n//\n// Flow (RFC 8628):\n// 1. POST github.com/login/device/code with the VS Code Copilot client_id.\n// 2. Show the user_code + verification_uri so the user can approve.\n// 3. Poll github.com/login/oauth/access_token until success/expiry.\n// 4. Persist the resulting OAuth access token (gho_...) in memory_store.\n// 5. At request time, exchange that OAuth token for a Copilot session token\n// via api.github.com/copilot_internal/v2/token (already implemented in\n// github-copilot.ts).\n\nimport { getMemory, putMemory, deleteMemory } from \"@/lib/stores/memory\";\n\n// Public client ID used by the official VS Code GitHub Copilot extension.\n// Same value is hard-coded into many open-source Copilot clients.\nconst COPILOT_CLIENT_ID = \"Iv1.b507a08c87ecfe98\";\nconst SCOPE = \"read:user\";\n\nconst NAMESPACE = \"github-copilot-auth\";\nconst KEY_OAUTH = \"oauth_token\";\n\nexport interface DeviceCodeResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n expires_in: number;\n interval: number;\n}\n\nexport interface PollResult {\n status: \"pending\" | \"success\" | \"slow_down\" | \"expired\" | \"denied\" | \"error\";\n access_token?: string;\n error?: string;\n}\n\nexport async function startDeviceFlow(): Promise<DeviceCodeResponse> {\n const res = await fetch(\"https://github.com/login/device/code\", {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"Jarela/1.0\",\n },\n body: JSON.stringify({ client_id: COPILOT_CLIENT_ID, scope: SCOPE }),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => res.statusText);\n throw new Error(`GitHub device code request failed (${res.status}): ${body}`);\n }\n const json = await res.json() as DeviceCodeResponse;\n if (!json.device_code || !json.user_code) {\n throw new Error(\"GitHub device code response missing required fields\");\n }\n return json;\n}\n\nexport async function pollDeviceFlow(device_code: string): Promise<PollResult> {\n const res = await fetch(\"https://github.com/login/oauth/access_token\", {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"Jarela/1.0\",\n },\n body: JSON.stringify({\n client_id: COPILOT_CLIENT_ID,\n device_code,\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n }),\n });\n if (!res.ok) {\n return { status: \"error\", error: `HTTP ${res.status}` };\n }\n const json = await res.json() as {\n access_token?: string;\n error?: string;\n error_description?: string;\n };\n if (json.access_token) {\n storeOAuthToken(json.access_token);\n return { status: \"success\", access_token: json.access_token };\n }\n switch (json.error) {\n case \"authorization_pending\": return { status: \"pending\" };\n case \"slow_down\": return { status: \"slow_down\" };\n case \"expired_token\": return { status: \"expired\" };\n case \"access_denied\": return { status: \"denied\" };\n default: return { status: \"error\", error: json.error_description || json.error || \"unknown\" };\n }\n}\n\nexport function storeOAuthToken(token: string): void {\n putMemory(NAMESPACE, KEY_OAUTH, { token, stored_at: new Date().toISOString() });\n}\n\nexport function getStoredOAuthToken(): string | null {\n const row = getMemory(NAMESPACE, KEY_OAUTH);\n if (!row) return null;\n try {\n const parsed = JSON.parse(row.value) as { token?: string };\n return parsed.token ?? null;\n } catch {\n return null;\n }\n}\n\nexport function clearStoredOAuthToken(): boolean {\n return deleteMemory(NAMESPACE, KEY_OAUTH);\n}\n\nexport function getAuthStatus(): { signed_in: boolean; stored_at: string | null } {\n const row = getMemory(NAMESPACE, KEY_OAUTH);\n if (!row) return { signed_in: false, stored_at: null };\n try {\n const parsed = JSON.parse(row.value) as { stored_at?: string };\n return { signed_in: true, stored_at: parsed.stored_at ?? row.updated_at };\n } catch {\n return { signed_in: true, stored_at: row.updated_at };\n }\n}\n","// Per-field metadata for integration credentials. Sits beside the\n// integration values (lib/stores/integrations.ts) and tracks where each\n// field's value came from — `\"rc\"` means env-sync wrote it, `\"user\"`\n// means the user typed it into the Integrations panel.\n//\n// The env-syncer (lib/env/sync.ts) only overwrites fields whose source\n// is `\"rc\"` (or absent). The moment a user edits the field in the panel\n// the source flips to `\"user\"` and the syncer leaves it alone — this is\n// the \"panel-wins-once-touched\" conflict rule.\n//\n// Stored in its own memory_store namespace `integration_meta`. Not\n// encrypted — the metadata itself contains no secrets, just provenance\n// flags + a sync timestamp.\n\nimport { getMemory, putMemory } from \"@/lib/stores/memory\";\n\nconst NAMESPACE = \"integration_meta\";\n\nexport type FieldSource = \"rc\" | \"user\";\n\nexport interface IntegrationMeta {\n /** Source flag per field key (e.g. `{ token: \"rc\" }`). */\n source: Record<string, FieldSource>;\n /** ISO timestamp of the last successful rc sync that wrote this row. */\n rc_synced_at: string | null;\n}\n\nconst EMPTY: IntegrationMeta = { source: {}, rc_synced_at: null };\n\nexport function getIntegrationMeta(name: string): IntegrationMeta {\n const row = getMemory(NAMESPACE, name);\n if (!row) return { ...EMPTY, source: {} };\n try {\n const parsed = JSON.parse(row.value) as Partial<IntegrationMeta> | null;\n return {\n source: (parsed?.source && typeof parsed.source === \"object\") ? parsed.source as Record<string, FieldSource> : {},\n rc_synced_at: parsed?.rc_synced_at ?? null,\n };\n } catch {\n return { ...EMPTY, source: {} };\n }\n}\n\n/**\n * Update many fields across many integrations in one pass. Keeps DB\n * writes proportional to changed integrations, not changed fields.\n */\nexport function setFieldSources(\n updates: Array<{ name: string; field: string; source: FieldSource }>,\n rcSyncedAt?: string,\n): void {\n if (updates.length === 0) return;\n const byName = new Map<string, IntegrationMeta>();\n for (const u of updates) {\n let m = byName.get(u.name);\n if (!m) {\n m = getIntegrationMeta(u.name);\n byName.set(u.name, m);\n }\n m.source[u.field] = u.source;\n if (rcSyncedAt && u.source === \"rc\") m.rc_synced_at = rcSyncedAt;\n }\n for (const [name, meta] of byName) putMemory(NAMESPACE, name, meta);\n}\n\n/** Convenience for the common \"user just edited these fields\" case. */\nexport function markFieldsAsUserTouched(name: string, fields: string[]): void {\n if (fields.length === 0) return;\n setFieldSources(fields.map((f) => ({ name, field: f, source: \"user\" })));\n}\n","// Proxy configuration store (ADR-0009, extended ADR-0012).\n//\n// Single-row table proxy_config. Non-secret columns are plaintext for\n// diagnostics; only `password` is wrapped through lib/crypto/envelope.ts\n// so the on-disk DB cannot reveal the proxy credential. `ca_bundle` is\n// a PEM (public cert) so it stays plaintext as well.\n//\n// Two read shapes:\n// - getProxyConfigStatus(): UI shape — password masked as SECRET_MASK\n// - getProxyConfigRaw(): server-only — returns the real password\n// so lib/proxy/dispatcher.ts can build a\n// ProxyAgent\n//\n// The save handler accepts SECRET_MASK as the sentinel for \"keep\n// existing password\" so the UI can echo back the masked form without\n// blanking the secret.\n\nimport { getDb } from \"@/lib/db\";\nimport { decryptIfNeeded, encrypt } from \"@/lib/crypto/envelope\";\nimport { SECRET_MASK } from \"@/lib/stores/integrations\";\n\nexport type ProxyMode = \"off\" | \"manual\" | \"system\";\nexport type ProxyScheme = \"http\" | \"https\";\n\nexport interface ProxyConfigStatus {\n mode: ProxyMode;\n scheme: ProxyScheme;\n host: string | null;\n port: number | null;\n username: string | null;\n password: string | null; // SECRET_MASK when set, null when unset\n no_proxy: string | null;\n ca_bundle: string | null; // PEM, plaintext\n updated_at: string | null;\n}\n\nexport interface ProxyConfigRaw {\n mode: ProxyMode;\n scheme: ProxyScheme;\n host: string | null;\n port: number | null;\n username: string | null;\n password: string | null; // plaintext\n no_proxy: string | null;\n ca_bundle: string | null;\n updated_at: string;\n}\n\nexport interface ProxyConfigInput {\n mode: ProxyMode;\n scheme?: ProxyScheme;\n host?: string | null;\n port?: number | null;\n username?: string | null;\n password?: string | null;\n no_proxy?: string | null;\n ca_bundle?: string | null;\n}\n\ninterface Row {\n mode: string;\n scheme: string | null;\n host: string | null;\n port: number | null;\n username: string | null;\n password: string | null;\n no_proxy: string | null;\n ca_bundle: string | null;\n updated_at: string;\n}\n\nconst DEFAULT_STATUS: ProxyConfigStatus = {\n mode: \"off\",\n scheme: \"http\",\n host: null,\n port: null,\n username: null,\n password: null,\n no_proxy: null,\n ca_bundle: null,\n updated_at: null,\n};\n\nexport function getProxyConfigStatus(): ProxyConfigStatus {\n const row = readRow();\n if (!row) return DEFAULT_STATUS;\n return {\n mode: normaliseMode(row.mode),\n scheme: normaliseScheme(row.scheme),\n host: row.host,\n port: row.port,\n username: row.username,\n password: row.password ? SECRET_MASK : null,\n no_proxy: row.no_proxy,\n ca_bundle: row.ca_bundle,\n updated_at: row.updated_at,\n };\n}\n\n// Server-only. Decrypts the password envelope. Never expose this to the\n// API surface — the dispatcher and any future test endpoint are the only\n// legitimate callers.\nexport function getProxyConfigRaw(): ProxyConfigRaw | null {\n const row = readRow();\n if (!row) return null;\n return {\n mode: normaliseMode(row.mode),\n scheme: normaliseScheme(row.scheme),\n host: row.host,\n port: row.port,\n username: row.username,\n password: row.password ? decryptIfNeeded(row.password) : null,\n no_proxy: row.no_proxy,\n ca_bundle: row.ca_bundle,\n updated_at: row.updated_at,\n };\n}\n\nexport function saveProxyConfig(input: ProxyConfigInput): ProxyConfigStatus | { error: string } {\n if (!isValidMode(input.mode)) return { error: `invalid mode \"${input.mode}\"` };\n\n const scheme: ProxyScheme = input.scheme === \"https\" ? \"https\" : \"http\";\n\n // Manual mode requires host + port. system / off don't.\n if (input.mode === \"manual\") {\n if (!input.host || !input.host.trim()) return { error: \"host is required in manual mode\" };\n if (input.port == null || !Number.isFinite(input.port) || input.port <= 0 || input.port > 65535) {\n return { error: \"port must be between 1 and 65535\" };\n }\n }\n\n // CA bundle: empty/null clears; non-empty must look like PEM.\n let storedCaBundle: string | null = null;\n if (input.ca_bundle != null && input.ca_bundle.trim().length > 0) {\n if (!input.ca_bundle.includes(\"-----BEGIN CERTIFICATE-----\")) {\n return { error: \"ca_bundle must be PEM (no BEGIN CERTIFICATE block found)\" };\n }\n storedCaBundle = input.ca_bundle;\n }\n\n // Preserve existing password when the UI echoes back the masked sentinel.\n const existing = readRow();\n let storedPassword: string | null = null;\n if (input.password === SECRET_MASK) {\n storedPassword = existing?.password ?? null;\n } else if (input.password && input.password.length > 0) {\n storedPassword = encrypt(input.password);\n } else {\n storedPassword = null;\n }\n\n const now = new Date().toISOString();\n const db = getDb();\n db.prepare(\n `INSERT INTO proxy_config (id, mode, scheme, host, port, username, password, no_proxy, ca_bundle, updated_at)\n VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n mode = excluded.mode,\n scheme = excluded.scheme,\n host = excluded.host,\n port = excluded.port,\n username = excluded.username,\n password = excluded.password,\n no_proxy = excluded.no_proxy,\n ca_bundle = excluded.ca_bundle,\n updated_at = excluded.updated_at`,\n ).run(\n input.mode,\n scheme,\n nullable(input.host),\n input.port ?? null,\n nullable(input.username),\n storedPassword,\n nullable(input.no_proxy),\n storedCaBundle,\n now,\n );\n\n return getProxyConfigStatus();\n}\n\nexport function deleteProxyConfig(): boolean {\n const db = getDb();\n const r = db.prepare(\"DELETE FROM proxy_config WHERE id = 1\").run();\n return r.changes > 0;\n}\n\nfunction readRow(): Row | null {\n const db = getDb();\n const r = db\n .prepare(\n \"SELECT mode, scheme, host, port, username, password, no_proxy, ca_bundle, updated_at FROM proxy_config WHERE id = 1\",\n )\n .get() as Row | undefined;\n return r ?? null;\n}\n\nfunction isValidMode(m: string): m is ProxyMode {\n return m === \"off\" || m === \"manual\" || m === \"system\";\n}\n\nfunction normaliseMode(m: string): ProxyMode {\n return isValidMode(m) ? m : \"off\";\n}\n\nfunction normaliseScheme(s: string | null | undefined): ProxyScheme {\n return s === \"https\" ? \"https\" : \"http\";\n}\n\nfunction nullable(v: string | null | undefined): string | null {\n if (v == null) return null;\n const trimmed = v.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n"],"names":["MBTI_PRESETS","now","Date","toISOString","runMigrations","db","exec","ensureBridgeRouteColumns","ensureAgentConfigColumns","ensureTaskAssignmentColumns","ensureEmbeddingColumns","ensureUserProfileLocationColumns","ensureProxyConfigSchemeAndCaBundle","ensureThreadsAgentIdUnique","ensureMessagesCategoryColumn","ensureMessagesMetadataColumn","ensureScheduledTasksSilentColumn","ensureAgentDisplayFiltersColumn","ensureDocumentSourceRemoteColumns","ensureWatchersReactionPromptColumn","ensureWatchersReactionKindColumns","ensureScheduledTasksReactionKindColumns","ensureMessageUsageTable","ensureMessageUsageTierColumns","ensureThreadContextPinColumns","ensureThreadChannelSummariesTable","seedModelConfigs","seedAgentConfigs","memCols","prepare","all","Set","map","c","name","has","msgColSet","cols","names","some","idx","get","agentCols","count","n","reanchorOrphanThreads","t","insert","p","BASE_AGENT_PROFILES","preset","mbti","run","id","icon","identity","instructions","JSON","stringify","tools","is_default","never_reply","adaptive","strength","empathy","expressiveness","verbosity","seeds","s","encrypt","isEncrypted","SENSITIVE_MEMORY_NAMESPACES","runCryptoMigration","touched","nsList","placeholders","join","memoryRows","memUpdate","row","value","namespace","key","modelRows","modelUpdate","params","mcpRows","mcpUpdate","spec","console","info","DatabaseSync","getDataDir","initMasterKey","applyProxyConfigFromDb","runEnvSyncOnce","DB_PATH","_db","getDb","source","warn","catch","err","then","r","applied_count","log","discovered","closeDb","close","NS","EMBEDDING_MODEL_KEY","getEmbeddingModelConfigName","raw","parsed","parse","trim","setEmbeddingModelConfigName","existing","created","created_at","createCipheriv","createDecipheriv","randomBytes","getMasterKey","PREFIX","IV_LEN","TAG_LEN","startsWith","plaintext","iv","cipher","ct","Buffer","concat","update","final","tag","getAuthTag","toString","decrypt","envelope","Error","buf","from","slice","length","subarray","decipher","setAuthTag","pt","decryptIfNeeded","encryptIfNeeded","getProvider","getModelConfig","getDefaultModelConfig","getModelParams","listModelConfigs","EXCLUDED_NS","EXCLUDED_NS_PLACEHOLDERS","resolveEmbeddingClient","fromConfig","cfg","provider","embed","overridden","embedding_model_id","modelId","isChatModelId","model_id","explicitName","process","env","EMBEDDING_MODEL_CONFIG","explicit","configuredName","configured","fromDefault","configs","candidate","test","texts","client","message","String","embedOne","text","out","TRANSIENT_RE","isTransient","callEmbedWithRetry","backoffs","lastErr","attempt","Promise","setTimeout","embedBestEffort","vectors","error","failed","embedBestEffortInternal","padded","_","i","filter","v","msg","mid","Math","floor","left","right","cosine","a","b","dot","na","nb","denom","sqrt","recall","query","limit","qVec","scored","memRows","msgRows","parseEmbedding","embedding","push","content","score","thread_id","role","tokens","tokenize","recentMem","recentMsg","keywordOverlap","groups","Map","normalizeForDedup","set","max","Array","values","sort","replace","toLowerCase","STOP_WORDS","split","w","queryTokens","textLower","hits","includes","arr","isArray","every","getMemory","listMemory","putMemory","deleteMemory","INTEGRATIONS","getIntegrationRaw","isKnownIntegration","OVERRIDES_NS","ENV_ALLOWLIST","envVars","integration","field","OVERRIDE_KEY","parseOverride","listOverrides","undefined","getOverride","setOverride","ok","def","fields","f","defaults","defaultAliasesFor","cleaned","seen","toUpperCase","add","deleteOverride","m","find","getEffectiveAllowlist","overrides","extra","merged","getAllEnvVarNames","getInjectedSubprocessEnv","spawn","platform","TIMEOUT_MS","SENTINEL_OPEN","SENTINEL_CLOSE","discoverEnvVars","allowlist","t0","warnings","fromProcess","reg","queryWindowsUserEnv","e","shell","elapsed_ms","SHELL","fromShell","queryUnixShellEnv","resolve","reject","lines","child","PS1","PROMPT","HISTFILE","stdio","stdout","kill","on","code","clearTimeout","parseSentinelStream","Object","keys","runWindowsProbe","exe","namesArr","script","windowsHide","stream","allow","parts","seg","end","indexOf","body","eq","getIntegrationMeta","setFieldSources","INTEGRATIONS_NS","previewEnvSync","runSync","applyEnvSync","_bootRanPromise","apply","ts","candidates","writesByIntegration","metaUpdates","cand","evaluateCandidate","action","pickEnvValue","size","envVar","rcValue","meta","sourceFlag","currentValue","currentSource","isSecret","isFieldSecret","current_source","current_value_present","rc_value_preview","maskValue","secret","isSensitiveMemoryNamespace","ns","existsSync","mkdirSync","renameSync","readdirSync","rmdirSync","homedir","cached","expandHome","hasDb","dir","migrateLegacyDir","legacyDir","newDir","recursive","entries","moved","to","postEntries","suffix","envDir","JARELA_DB_DIR","defaultDataDir","local","LOCALAPPDATA","execFileSync","writeFileSync","chmodSync","KEYCHAINS_TO_TRY","PEM_BLOCK_RE","parseSecurityFindCertificate","blocks","matches","match","normalised","extractSystemKeychainCAs","used","allPem","kc","encoding","maxBuffer","deduped","pemPath","certCount","keychains","readFileSync","promisify","Agent","EnvHttpProxyAgent","getGlobalDispatcher","setGlobalDispatcher","getProxyConfigRaw","execAsync","ENV_HAD_PROXY_AT_BOOT","HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy","baselineDispatcher","envInstalled","ensureProxyDispatcher","proxyUrl","note","mode","resetToBaseline","host","port","url","buildProxyUrl","scheme","username","password","installProxy","no_proxy","ca_bundle","redactAuth","trust","caBundleText","caBundlePath","caBundleCertCount","caBundleSource","detected","detectSystemProxy","installDirectWithCa","auth","encodeURIComponent","noProxy","caBundle","NO_PROXY","opts","requestTls","ca","proxyTls","connect","u","URL","timeout","parseScutilProxy","output","line","portStr","Number","parseInt","isFinite","envProxyWasSetAtBoot","INTJ","label","INTP","ENTJ","ENTP","INFJ","INFP","ENFJ","ENFP","ISTJ","ISFJ","ESTJ","ESFJ","ISTP","ISFP","ESTP","ESFP","MBTI_TYPES","OpenAI","pickOpenAICompatOptions","k","makeClient","baseURL","extraHeaders","apiKey","api_key","OPENAI_API_KEY","base_url","defaultHeaders","extra_headers","toOpenAIContent","part","type","image_url","media_type","data","toOpenAIMessages","messages","tool_call_id","tool_calls","reasoning_content","parseStopReason","reason","parseOpenAIInvokeChoice","choice","flatMap","tc","function","arguments","stop_reason","finish_reason","streamOpenAIEvents","chunk","usage","input_tokens","prompt_tokens","output_tokens","completion_tokens","total_tokens","choices","delta","index","args_delta","streamOpenAIText","ollamaOriginFromParams","isLocal","hostname","isOllamaPort","protocol","tryPullOllamaModel","origin","res","fetch","method","headers","isModelNotFoundError","openaiProvider","chat","mapped","completions","create","model","temperature","max_tokens","invoke","resp","tool_choice","streamInvoke","openaiStreamInvoke","inputs","openaiEmbed","embeddings","input","d","compatOptions","stream_options","include_usage","makeOpenAICompatProvider","providerName","defaultBaseURL","fixedHeaders","Anthropic","resolveApiKey","ANTHROPIC_API_KEY","pickAnthropicOptions","appendServerTools","anthropicTools","native","anthropic_server_tools","anthropicProvider","systemMsg","systemText","userMessages","toAnthropicContent","system","event","msgList","toAnthropicMessages","toAnthropicTools","thinking","textContent","toolCalls","blockType","cb","content_block","partial_json","mt","title","result","tool_use_id","description","input_schema","parameters","providerMessagesFromHistory","getStoredOAuthToken","pickGitHubCompatOptions","tokenCache","isLikelyGitHubPat","token","getCopilotToken","pat","expiresAt","Authorization","statusText","status","json","expires_at","getTime","FIXED_HEADERS","resolvedClient","explicitSessionToken","copilot_session_token","oauthToken","Accept","githubCopilotProvider","compat","deepseekProvider","readSSELines","reader","getReader","decoder","TextDecoder","buffer","done","read","decode","pop","releaseLock","parseAnthropicStream","parseOpenAIStream","fr","geminiCompat","isCompatMode","gemini_use_openai_compat","nativeBaseUrl","gemini_native_base_url","geminiApiKey","GEMINI_API_KEY","contentToGeminiParts","inlineData","mimeType","parseJsonObject","providerMessagesToGemini","contents","systemInstruction","invokeMessagesToGemini","toolNameById","functionCall","args","response","functionResponse","toGeminiTools","functionDeclarations","builtins","gemini_builtin_tools","toGenerationConfig","base","maxOutputTokens","top_p","topP","top_k","topK","stop","stopSequences","rf","response_format","responseMimeType","gemini_response_mime_type","gemini_response_schema","responseSchema","gemini_thinking_config","thinkingConfig","gemini_generation_config","geminiNativeGenerate","mapGeminiStopReason","extractGeminiInvokeResult","first","fc","finishReason","geminiNativeStreamInvoke","generationConfig","gemini_tool_config","toolConfig","gemini_safety_settings","safetySettings","isThought","thought","geminiNativeInvoke","geminiNativeChat","resolveGeminiEmbeddingModel","geminiEmbed","requests","geminiProvider","AIMessage","HumanMessage","SystemMessage","ToolMessage","cache","cacheKey","lc_class","loadLangChainModel","hit","cls","_ignore1","lc_module","_ignore2","ctorArgs","ChatGoogleGenerativeAI","ChatCohere","ChatDeepSeek","toLCMessages","toLCInvokeMessages","ai","toLCTools","schema","langchainProvider","bound","bindTools","extractText","block","reasoning","additional_kwargs","tcc","tool_call_chunks","createHash","DEFAULT_REPLY","EMBED_DIM","parseMockDirectives","reply","echo","colon","tool","argsRaw","think","slowMs","stopReason","lastUserText","pickReply","directives","userText","sleep","ms","streamText","mockProvider","_model_id","_params","_tools","argsJson","hash","digest","vec","norm","x","loadExternalProviders","BUILTINS","openai","anthropic","deepseek","gemini","langchain","isMockEnabled","JARELA_ENABLE_MOCK_PROVIDER","BUILTIN_PROVIDER_NAMES","getProviders","mock","listProviderNames","localeCompare","KEYCHAIN_SERVICE","KEYCHAIN_ACCOUNT","KEYFILE_NAME","_key","_source","dataDir","path","keyB64","loadOrCreateViaKeychain","getMasterKeySource","execPath","cwd","markFieldsAsUserTouched","SECRET_MASK","NAMESPACE","category","placeholder","required","atlassian","jira_align","google","gmail","github","outlook","prototype","hasOwnProperty","call","listIntegrations","rows","byKey","updated_at","rc_synced_at","maskSecrets","parseValue","getIntegrationStatus","saveIntegration","incoming","deleteIntegration","decryptRow","upsertModelConfig","deleteModelConfig","changes","MEM_COLS_SQL","asyncEmbed","persist","search","sql","stored","statSync","PROVIDERS_DIR","isValid","o","loadExternalProvidersDetailed","providers","files","errors","createRequire","getBuiltinModule","req","entry","isFile","mod","file","default","COPILOT_CLIENT_ID","SCOPE","KEY_OAUTH","startDeviceFlow","client_id","scope","device_code","user_code","pollDeviceFlow","grant_type","access_token","storeOAuthToken","error_description","stored_at","clearStoredOAuthToken","getAuthStatus","signed_in","EMPTY","updates","rcSyncedAt","byName","DEFAULT_STATUS","getProxyConfigStatus","readRow","normaliseMode","normaliseScheme","saveProxyConfig","isValidMode","storedCaBundle","storedPassword","nullable","deleteProxyConfig","trimmed"],"sourceRoot":"","ignoreList":[]}
1
+ {"version":3,"file":"2082.js","mappings":";;;;;;;;;;;;;;;;;;;;;;;;AACoF;AAEpF,MAAMC,MAAM,IAAM,IAAIC,OAAOC,WAAW;AAEjC,SAASC,cAAcC,EAAgB;IAC5CA,GAAGC,IAAI,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqQT,CAAC;IACDC,yBAAyBF;IACzBG,yBAAyBH;IACzBI,4BAA4BJ;IAC5BK,uBAAuBL;IACvBM,iCAAiCN;IACjCO,mCAAmCP;IACnCQ,2BAA2BR;IAC3BS,6BAA6BT;IAC7BU,6BAA6BV;IAC7BW,iCAAiCX;IACjCY,gCAAgCZ;IAChCa,kCAAkCb;IAClCc,mCAAmCd;IACnCe,kCAAkCf;IAClCgB,wCAAwChB;IACxCiB,wBAAwBjB;IACxBkB,8BAA8BlB;IAC9BmB,+BAA+BnB;IAC/BoB,8BAA8BpB;IAC9BqB,kCAAkCrB;IAClCsB,iBAAiBtB;IACjBuB,iBAAiBvB;AACnB;AAEA,uEAAuE;AACvE,oEAAoE;AACpE,iEAAiE;AACjE,+DAA+D;AAC/D,8DAA8D;AAC9D,SAASqB,kCAAkCrB,EAAgB;IACzDA,GAAGC,IAAI,CAAC,CAAC;;;;;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J;IAEAD,sBAAsBzC;AACxB;AAkBA,wEAAwE;AACxE,yEAAyE;AACzE,yEAAyE;AACzE,EAAE;AACF,0EAA0E;AAC1E,0EAA0E;AAC1E,sEAAsE;AACtE,0EAA0E;AAC1E,MAAM6C,sBAA0C;IAC9C;QACEI,IAAI;QACJnB,MAAM;QACNqB,UAAU;QACVC,cACE;QACFG,OAAO,EAAE;QACTR,MAAM;QACNW,UAAU;QACVF,YAAY;IACd;IACA;QACEP,IAAI;QACJnB,MAAM;QACNqB,UACE;QACFC,cACE;QACFG,OAAO;YAAC;YAAc;YAAa;YAAe;YAAgB;SAAc;QAChFR,MAAM;QACNW,UAAU;IACZ;IACA;QACET,IAAI;QACJnB,MAAM;QACNqB,UACE;QACFC,cACE;QACFG,OAAO;YACL;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDR,MAAM;QACNW,UAAU;IACZ;IACA;QACET,IAAI;QACJnB,MAAM;QACNqB,UACE;QACFC,cACE;QACFG,OAAO;YACL;YACA;YACA;YACA;YACA;YACA;SACD;QACDR,MAAM;QACNW,UAAU;IACZ;IACA;QACET,IAAI;QACJnB,MAAM;QACNqB,UACE;QACFC,cACE;QACFG,OAAO;YACL;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDR,MAAM;QACNW,UAAU;IACZ;IACA;QACET,IAAI;QACJnB,MAAM;QACNqB,UACE;QACFC,cACE;QACFG,OAAO;YAAC;YAAe;YAAgB;SAAc;QACrDR,MAAM;QACNW,UAAU;IACZ;IAEA,wEAAwE;IACxE,wEAAwE;IACxE;QACET,IAAI;QACJnB,MAAM;QACNqB,UAAU;QACVC,cAAc;QACdG,OAAO,EAAE;QACTR,MAAM;QACNW,UAAU;IACZ;IACA;QACET,IAAI;QACJnB,MAAM;QACNqB,UAAU;QACVC,cAAc;QACdG,OAAO,EAAE;QACTR,MAAM;QACNW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AMnI,IAAI,IAAI,MACduc,SAASpU,MAAM/H,QAAQ,GACvBkc,gBACAC,SAASpU,MAAM5H,QAAQ,GACvB8b,gBACA73B;IAGF,OAAOu3B;AACT;AAEO,SAASS;IACd,MAAM53B,KAAK8F,wDAAKA;IAChB,MAAMM,IAAIpG,GAAGyB,OAAO,CAAC,yCAAyCuB,GAAG;IACjE,OAAOoD,EAAEkuB,OAAO,GAAG;AACrB;AAEA,SAAS8C;IACP,MAAMp3B,KAAK8F,wDAAKA;IAChB,MAAMM,IAAIpG,GACPyB,OAAO,CACN,uHAEDY,GAAG;IACN,OAAO+D,KAAK;AACd;AAEA,SAASoxB,YAAY5lB,CAAS;IAC5B,OAAOA,MAAM,SAASA,MAAM,YAAYA,MAAM;AAChD;AAEA,SAASylB,cAAczlB,CAAS;IAC9B,OAAO4lB,YAAY5lB,KAAKA,IAAI;AAC9B;AAEA,SAAS0lB,gBAAgBtzB,CAA4B;IACnD,OAAOA,MAAM,UAAU,UAAU;AACnC;AAEA,SAAS2zB,SAASlrB,CAA4B;IAC5C,IAAIA,KAAK,MAAM,OAAO;IACtB,MAAMorB,UAAUprB,EAAEzF,IAAI;IACtB,OAAO6wB,QAAQ/uB,MAAM,GAAG,IAAI+uB,UAAU;AACxC","sources":["webpack://@circuitwall/jarela/./lib/db/migrations.ts","webpack://@circuitwall/jarela/./lib/crypto/migrate.ts","webpack://@circuitwall/jarela/./lib/db/index.ts","webpack://@circuitwall/jarela/./lib/stores/app-settings.ts","webpack://@circuitwall/jarela/./lib/crypto/envelope.ts","webpack://@circuitwall/jarela/./lib/embeddings/index.ts","webpack://@circuitwall/jarela/./lib/env/allowlist.ts","webpack://@circuitwall/jarela/./lib/env/discover.ts","webpack://@circuitwall/jarela/./lib/env/sync.ts","webpack://@circuitwall/jarela/./lib/crypto/sensitive.ts","webpack://@circuitwall/jarela/./lib/db/data-dir.ts","webpack://@circuitwall/jarela/./lib/proxy/keychain.ts","webpack://@circuitwall/jarela/./lib/proxy/dispatcher.ts","webpack://@circuitwall/jarela/./lib/agents/adaptive-persona-presets.ts","webpack://@circuitwall/jarela/./lib/providers/openai.ts","webpack://@circuitwall/jarela/./lib/providers/anthropic.ts","webpack://@circuitwall/jarela/./lib/providers/github-copilot.ts","webpack://@circuitwall/jarela/./lib/providers/deepseek.ts","webpack://@circuitwall/jarela/./lib/providers/streaming.ts","webpack://@circuitwall/jarela/./lib/providers/gemini.ts","webpack://@circuitwall/jarela/./lib/providers/langchain.ts","webpack://@circuitwall/jarela/./lib/providers/mock.ts","webpack://@circuitwall/jarela/./lib/providers/index.ts","webpack://@circuitwall/jarela/./lib/crypto/master-key.ts","webpack://@circuitwall/jarela/./lib/stores/integrations.ts","webpack://@circuitwall/jarela/./lib/stores/model-config.ts","webpack://@circuitwall/jarela/./lib/stores/memory.ts","webpack://@circuitwall/jarela/./lib/providers/external.ts","webpack://@circuitwall/jarela/./lib/providers/github-copilot-auth.ts","webpack://@circuitwall/jarela/./lib/stores/integration_meta.ts","webpack://@circuitwall/jarela/./lib/stores/proxy-config.ts"],"sourcesContent":["import { DatabaseSync } from \"node:sqlite\";\nimport { MBTI_PRESETS, type MbtiType } from \"@/lib/agents/adaptive-persona-presets\";\n\nconst now = () => new Date().toISOString();\n\nexport function runMigrations(db: DatabaseSync): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS threads (\n thread_id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n title TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n message_count INTEGER NOT NULL DEFAULT 0\n );\n CREATE TABLE IF NOT EXISTS messages (\n msg_id TEXT PRIMARY KEY,\n thread_id TEXT NOT NULL,\n role TEXT NOT NULL,\n content TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n -- thread_id is the dominant filter on every messages query\n -- (getMessages, getRecentMessagesWindow, getMessagesPage, clear).\n -- Without this every read full-scans the messages table.\n CREATE INDEX IF NOT EXISTS idx_messages_thread_id ON messages(thread_id, created_at);\n CREATE TABLE IF NOT EXISTS memory_store (\n namespace TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (namespace, key)\n );\n CREATE TABLE IF NOT EXISTS model_configs (\n name TEXT PRIMARY KEY,\n provider TEXT NOT NULL,\n model_id TEXT NOT NULL,\n params TEXT NOT NULL DEFAULT '{}',\n is_default INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS task_assignments (\n agent_id TEXT PRIMARY KEY,\n model_config_name TEXT NOT NULL,\n allow_tools TEXT NOT NULL DEFAULT '[]',\n deny_tools TEXT NOT NULL DEFAULT '[]',\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS user_profile (\n id TEXT PRIMARY KEY DEFAULT 'me',\n name TEXT NOT NULL DEFAULT '',\n icon TEXT,\n about TEXT NOT NULL DEFAULT '',\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS agent_configs (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n icon TEXT,\n identity TEXT NOT NULL DEFAULT '',\n instructions TEXT NOT NULL DEFAULT '',\n tools TEXT NOT NULL DEFAULT '[]',\n model_config_name TEXT,\n is_default INTEGER NOT NULL DEFAULT 0,\n adaptive_persona_enabled INTEGER NOT NULL DEFAULT 0,\n adaptive_persona_strength INTEGER NOT NULL DEFAULT 50,\n adaptive_empathy INTEGER NOT NULL DEFAULT 50,\n adaptive_expressiveness INTEGER NOT NULL DEFAULT 50,\n adaptive_verbosity INTEGER NOT NULL DEFAULT 50,\n adaptive_mbti TEXT NOT NULL DEFAULT 'INTJ',\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS scheduled_tasks (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n prompt TEXT NOT NULL,\n description TEXT,\n kind TEXT NOT NULL,\n schedule TEXT NOT NULL,\n next_run_at TEXT NOT NULL,\n last_run_at TEXT,\n last_error TEXT,\n enabled INTEGER NOT NULL DEFAULT 1,\n silent INTEGER NOT NULL DEFAULT 0,\n reaction_kind TEXT NOT NULL DEFAULT 'agent_prompt', -- ADR-0032\n reaction_script TEXT, -- ADR-0032\n reaction_script_args TEXT, -- ADR-0032\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_due ON scheduled_tasks(enabled, next_run_at);\n -- Event-driven \"watchers\" (ADR-0027). A watcher polls one built-in\n -- tool with fixed args on an interval; when the tool's output changes\n -- (content hash != last_fingerprint) the agent is fired with\n -- {previous, current} as context. Until then the watcher consumes no\n -- LLM tokens — only the polled tool runs. Plugs into the trigger\n -- abstraction (ADR-0025) as a sibling handler to scheduled_task.\n CREATE TABLE IF NOT EXISTS watchers (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n label TEXT NOT NULL,\n tool_name TEXT NOT NULL,\n tool_args TEXT NOT NULL DEFAULT '{}', -- JSON\n interval_seconds INTEGER NOT NULL,\n last_fingerprint TEXT, -- sha256 of last tool result\n last_result TEXT, -- raw tool result (string) for diff context\n last_run_at TEXT,\n last_fired_at TEXT,\n last_error TEXT,\n next_run_at TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 1,\n silent INTEGER NOT NULL DEFAULT 0,\n reaction_prompt TEXT, -- ADR-0030: NULL = default directive\n reaction_kind TEXT NOT NULL DEFAULT 'agent_prompt', -- ADR-0031: 'agent_prompt' | 'script'\n reaction_script TEXT, -- ADR-0031: registry key, only when kind='script'\n reaction_script_args TEXT, -- ADR-0031: JSON object, only when kind='script'\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_watchers_due ON watchers(enabled, next_run_at);\n CREATE TABLE IF NOT EXISTS mcp_servers (\n name TEXT PRIMARY KEY,\n transport TEXT NOT NULL, -- 'stdio' | 'http'\n spec TEXT NOT NULL DEFAULT '{}', -- JSON: { command, args, env } or { url, headers }\n enabled INTEGER NOT NULL DEFAULT 1,\n last_error TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS pending_actions (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL, -- which agent proposed it\n kind TEXT NOT NULL, -- 'install_mcp' | 'toggle_mcp' | 'update_agent_tools' | 'update_agent'\n payload TEXT NOT NULL, -- JSON parameters\n reason TEXT, -- agent's stated rationale\n status TEXT NOT NULL DEFAULT 'pending', -- pending | approved | denied | failed\n result TEXT, -- JSON result on success, error message on failure\n created_at TEXT NOT NULL,\n decided_at TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_pending_actions_status ON pending_actions(status, created_at);\n -- agent_id is a common filter on listPendingActions; without this every\n -- per-agent panel render is a full scan of pending_actions.\n CREATE INDEX IF NOT EXISTS idx_pending_actions_agent_status ON pending_actions(agent_id, status, created_at);\n CREATE TABLE IF NOT EXISTS access_whitelist (\n identity TEXT PRIMARY KEY,\n display_name TEXT,\n added_at TEXT NOT NULL,\n last_seen_at TEXT\n );\n CREATE TABLE IF NOT EXISTS bridges (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL, -- 'whatsapp' (only kind in v1)\n name TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'disconnected',-- disconnected | pairing | connected | error\n qr TEXT, -- base64 data URL while status='pairing'\n last_error TEXT,\n paired_id TEXT, -- the remote-account identifier (e.g. WhatsApp phone JID) once paired\n enabled INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS bridge_routes (\n id TEXT PRIMARY KEY,\n bridge_id TEXT NOT NULL,\n remote_jid TEXT NOT NULL, -- e.g. 5511...@s.whatsapp.net or ...@g.us\n agent_id TEXT NOT NULL,\n label TEXT, -- user-visible name (push_name on first inbound)\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n UNIQUE(bridge_id, remote_jid),\n UNIQUE(agent_id) -- one route per agent (catch-all may intentionally multiplex chats)\n );\n CREATE INDEX IF NOT EXISTS idx_bridge_routes_bridge ON bridge_routes(bridge_id);\n -- HTTP/HTTPS proxy configuration (ADR-0009). Single-row table; the\n -- CHECK constraint enforces it. Non-secret fields are plaintext for\n -- diagnostics; password goes through lib/crypto/envelope.ts.\n CREATE TABLE IF NOT EXISTS proxy_config (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n mode TEXT NOT NULL CHECK (mode IN ('off', 'manual', 'system')),\n scheme TEXT NOT NULL DEFAULT 'http', -- 'http' | 'https' (proxy hop scheme, ADR-0012)\n host TEXT,\n port INTEGER,\n username TEXT,\n password TEXT, -- envelope-encrypted (enc:v1:…)\n no_proxy TEXT,\n ca_bundle TEXT, -- PEM, plaintext (public cert, ADR-0012)\n updated_at TEXT NOT NULL\n );\n -- Document RAG (ADR-0024). A document_sources row is a folder the\n -- user asked Jarela to index for semantic search. Walked on each\n -- scheduler tick (cheap stat()); files whose mtime/size changed get\n -- re-chunked and re-embedded. documents_search exposes recall over\n -- the resulting chunks as an agent tool.\n CREATE TABLE IF NOT EXISTS document_sources (\n id TEXT PRIMARY KEY,\n path TEXT NOT NULL,\n label TEXT,\n enabled INTEGER NOT NULL DEFAULT 1,\n last_scan_at TEXT,\n last_error TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n UNIQUE(path)\n );\n CREATE TABLE IF NOT EXISTS documents (\n id TEXT PRIMARY KEY,\n source_id TEXT NOT NULL REFERENCES document_sources(id) ON DELETE CASCADE,\n path TEXT NOT NULL,\n rel_path TEXT NOT NULL,\n mtime_ms INTEGER NOT NULL,\n size_bytes INTEGER NOT NULL,\n content_hash TEXT NOT NULL,\n last_indexed_at TEXT NOT NULL,\n chunk_count INTEGER NOT NULL DEFAULT 0,\n UNIQUE(source_id, path)\n );\n CREATE INDEX IF NOT EXISTS idx_documents_source ON documents(source_id);\n CREATE TABLE IF NOT EXISTS document_chunks (\n id TEXT PRIMARY KEY,\n document_id TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,\n chunk_index INTEGER NOT NULL,\n text TEXT NOT NULL,\n start_offset INTEGER NOT NULL,\n end_offset INTEGER NOT NULL,\n embedding TEXT,\n UNIQUE(document_id, chunk_index)\n );\n CREATE INDEX IF NOT EXISTS idx_chunks_document ON document_chunks(document_id);\n -- Generic change-tracker primitive (ADR-0025). Lets any subsystem ask\n -- \"has (scope, key) changed since we last looked?\" by recording a\n -- fingerprint (e.g. content hash, mtime+size, etag) per key. Future\n -- triggers (fs_watch, tool_call dedupe) use it; the document indexer\n -- in lib/documents will migrate onto it in a later PR.\n CREATE TABLE IF NOT EXISTS change_tracker (\n scope TEXT NOT NULL,\n key TEXT NOT NULL,\n fingerprint TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (scope, key)\n );\n -- Built-in tool category toggles. Missing row = enabled (default-on).\n -- Disabled categories are filtered out at every tool-list surface so\n -- they vanish from the agent permission UI AND cannot be invoked even\n -- if an old agent config still references one of their tools.\n CREATE TABLE IF NOT EXISTS builtin_tool_categories (\n category TEXT PRIMARY KEY,\n enabled INTEGER NOT NULL DEFAULT 1,\n updated_at TEXT NOT NULL\n );\n -- Aggregated per-tool telemetry used to rank/filter tools in the UI.\n -- used_count is heuristic: a successful result whose payload appears to\n -- feed the assistant's final response for that turn.\n CREATE TABLE IF NOT EXISTS tool_stats (\n tool_name TEXT PRIMARY KEY,\n call_count INTEGER NOT NULL DEFAULT 0,\n success_count INTEGER NOT NULL DEFAULT 0,\n error_count INTEGER NOT NULL DEFAULT 0,\n used_count INTEGER NOT NULL DEFAULT 0,\n last_called_at TEXT,\n updated_at TEXT NOT NULL\n );\n `);\n ensureBridgeRouteColumns(db);\n ensureAgentConfigColumns(db);\n ensureTaskAssignmentColumns(db);\n ensureEmbeddingColumns(db);\n ensureUserProfileLocationColumns(db);\n ensureProxyConfigSchemeAndCaBundle(db);\n ensureThreadsAgentIdUnique(db);\n ensureMessagesCategoryColumn(db);\n ensureMessagesMetadataColumn(db);\n ensureScheduledTasksSilentColumn(db);\n ensureAgentDisplayFiltersColumn(db);\n ensureDocumentSourceRemoteColumns(db);\n ensureWatchersReactionPromptColumn(db);\n ensureWatchersReactionKindColumns(db);\n ensureScheduledTasksReactionKindColumns(db);\n ensureMessageUsageTable(db);\n ensureMessageUsageTierColumns(db);\n ensureMessageUsageCacheColumns(db);\n ensureThreadContextPinColumns(db);\n ensureThreadChannelSummariesTable(db);\n seedModelConfigs(db);\n seedAgentConfigs(db);\n}\n\n// ADR-0044. Per-channel warm summary so a thread shared across `chat`,\n// `scheduled_task`, `watcher`, and `bridge` channels stops blending\n// automation history into interactive turns. Replaces the single\n// `threads.warm_summary` blob — which is kept one release as a\n// read-only fallback — with one row per (thread_id, channel).\nfunction ensureThreadChannelSummariesTable(db: DatabaseSync): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS thread_channel_summaries (\n thread_id TEXT NOT NULL REFERENCES threads(thread_id) ON DELETE CASCADE,\n channel TEXT NOT NULL,\n summary TEXT NOT NULL,\n summary_before TEXT,\n computed_at TEXT NOT NULL,\n PRIMARY KEY (thread_id, channel)\n );\n CREATE INDEX IF NOT EXISTS idx_thread_channel_summaries_thread ON thread_channel_summaries(thread_id);\n `);\n}\n\n// ADR-0041. Immutable per-assistant-turn snapshot of LLM usage. Written once\n// alongside addMessage(...,\"assistant\",...) and never updated, so the\n// dashboard's token/$ aggregates are not retroactively rewritten when the\n// user reassigns an agent's model, renames a model config, or refreshes\n// pricing. See docs/adr/0041-immutable-message-usage.md.\nfunction ensureMessageUsageTable(db: DatabaseSync): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS message_usage (\n message_id TEXT PRIMARY KEY,\n thread_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n agent_name TEXT NOT NULL,\n provider TEXT NOT NULL,\n model_id TEXT NOT NULL,\n model_config_name TEXT,\n input_tokens INTEGER NOT NULL,\n output_tokens INTEGER NOT NULL,\n input_rate_usd_per_mtok REAL,\n output_rate_usd_per_mtok REAL,\n cost_usd REAL NOT NULL,\n created_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_message_usage_created_at ON message_usage(created_at);\n CREATE INDEX IF NOT EXISTS idx_message_usage_agent_id ON message_usage(agent_id);\n `);\n}\n\nfunction ensureEmbeddingColumns(db: DatabaseSync): void { // Embeddings stored as JSON-encoded float[] in TEXT to keep migration simple.\n // For the corpus sizes we expect (thousands of rows), in-memory cosine\n // similarity in JS is fast enough — no need for sqlite-vec or duckdb yet.\n const memCols = db.prepare(\"PRAGMA table_info(memory_store)\").all() as Array<{ name: string }>;\n if (!new Set(memCols.map((c) => c.name)).has(\"embedding\")) {\n db.exec(\"ALTER TABLE memory_store ADD COLUMN embedding TEXT\");\n }\n const msgColSet = new Set(\n (db.prepare(\"PRAGMA table_info(messages)\").all() as Array<{ name: string }>).map((c) => c.name),\n );\n if (!msgColSet.has(\"embedding\")) {\n db.exec(\"ALTER TABLE messages ADD COLUMN embedding TEXT\");\n }\n if (!msgColSet.has(\"tool_events\")) {\n // JSON array of { id, phase: \"call\"|\"result\", name, payload } captured at\n // stream time. Lets the chat UI render historical tool invocations the\n // same way it renders live ones — instead of only the *— used: x* footer\n // text, which loses arguments + results on reload.\n db.exec(\"ALTER TABLE messages ADD COLUMN tool_events TEXT\");\n }\n}\n\nfunction ensureProxyConfigSchemeAndCaBundle(db: DatabaseSync): void {\n // ADR-0012. Adds scheme (http|https for the proxy hop) and ca_bundle\n // (PEM for proxies that MITM TLS with an internal CA). CA bundle is a\n // public cert and stored plaintext; password remains envelope-wrapped.\n const cols = db.prepare(\"PRAGMA table_info(proxy_config)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"scheme\")) db.exec(\"ALTER TABLE proxy_config ADD COLUMN scheme TEXT NOT NULL DEFAULT 'http'\");\n if (!names.has(\"ca_bundle\")) db.exec(\"ALTER TABLE proxy_config ADD COLUMN ca_bundle TEXT\");\n}\n\nfunction ensureUserProfileLocationColumns(db: DatabaseSync): void {\n // Browser-reported geolocation, opt-in. Lets the agent answer\n // \"what's near me?\" / suggest routes / weather / etc. without the user\n // re-typing their location every turn. `location_consent` is the\n // explicit opt-in flag — when 0 the client must NOT post coordinates\n // and the agent must NOT see a stored value.\n const cols = db.prepare(\"PRAGMA table_info(user_profile)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"location_lat\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_lat REAL\");\n if (!names.has(\"location_lng\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_lng REAL\");\n if (!names.has(\"location_accuracy_m\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_accuracy_m REAL\");\n if (!names.has(\"location_label\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_label TEXT\");\n if (!names.has(\"location_updated_at\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_updated_at TEXT\");\n if (!names.has(\"location_consent\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN location_consent INTEGER NOT NULL DEFAULT 0\");\n // Persona preset (home/work/dev/custom). Drives the Credentials panel's\n // category filter so a home user doesn't see Jira / infrastructure\n // sections, and a work user doesn't see noise outside the work\n // toolbelt. NULL = unset (treat as \"custom\" → show everything). Set\n // by the Profile editor; consumed by IntegrationsPanel.\n if (!names.has(\"preset\")) db.exec(\"ALTER TABLE user_profile ADD COLUMN preset TEXT\");\n}\n\n// Per-message classification. NULL/empty = ordinary chat content. Known\n// non-null values surface as filterable groups in the chat panel so users\n// can hide scheduled-task firings, bridge traffic, or synthetic page-capture\n// uploads without losing the audit trail. Current categories:\n// 'scheduled_task' - scheduler-injected prompt + its assistant reply\n// 'bridge' - bridge-mediated user inbound + assistant outbound\n// 'synthetic' - page-capture / file-upload generated user messages\nfunction ensureMessagesCategoryColumn(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(messages)\").all() as Array<{ name: string }>;\n if (!cols.some((c) => c.name === \"category\")) {\n db.exec(\"ALTER TABLE messages ADD COLUMN category TEXT\");\n }\n}\n\n// Per-message auxiliary metadata (JSON object). NULL on legacy rows and on\n// rows that don't carry any extra data. Current consumer is the citation\n// checker (`require_source_links`), which attaches a verdict shaped like\n// `{ citations: { claims: [...], unverified: [...] } }`. Adding more keys\n// later is free — readers tolerate unknown fields.\nfunction ensureMessagesMetadataColumn(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(messages)\").all() as Array<{ name: string }>;\n if (!cols.some((c) => c.name === \"metadata\")) {\n db.exec(\"ALTER TABLE messages ADD COLUMN metadata TEXT\");\n }\n}\n\n// ADR-0030 — per-watcher reaction prompt. NULL = use the default\n// \"summarise the diff\" directive baked into buildFiringPrompt. Non-null =\n// substitute that text in place of the default; the diff envelope (label,\n// tool, args, previous, current) is unchanged.\nfunction ensureWatchersReactionPromptColumn(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(watchers)\").all() as Array<{ name: string }>;\n if (!cols.some((c) => c.name === \"reaction_prompt\")) {\n db.exec(\"ALTER TABLE watchers ADD COLUMN reaction_prompt TEXT\");\n }\n}\n\n// ADR-0031 — script-backed watcher reactions. Adds three nullable columns\n// to the watchers table:\n// reaction_kind 'agent_prompt' (default) | 'script'\n// reaction_script registry key, only when kind='script'\n// reaction_script_args JSON object, only when kind='script'\n// Existing rows get reaction_kind='agent_prompt' and continue to behave\n// identically (the agent runs against the diff, optionally guided by\n// ADR-0030's reaction_prompt).\nfunction ensureWatchersReactionKindColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(watchers)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"reaction_kind\")) {\n db.exec(\n \"ALTER TABLE watchers ADD COLUMN reaction_kind TEXT NOT NULL DEFAULT 'agent_prompt'\",\n );\n }\n if (!names.has(\"reaction_script\")) {\n db.exec(\"ALTER TABLE watchers ADD COLUMN reaction_script TEXT\");\n }\n if (!names.has(\"reaction_script_args\")) {\n db.exec(\"ALTER TABLE watchers ADD COLUMN reaction_script_args TEXT\");\n }\n}\n\n// Per-task \"silent\" mode. When 1 the scheduler injects the prompt as a\n// hidden user message and instructs the agent to reply only when there is\n// something worth showing — otherwise the assistant turn is persisted\n// hidden too (or skipped entirely).\nfunction ensureScheduledTasksSilentColumn(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(scheduled_tasks)\").all() as Array<{ name: string }>;\n if (!cols.some((c) => c.name === \"silent\")) {\n db.exec(\"ALTER TABLE scheduled_tasks ADD COLUMN silent INTEGER NOT NULL DEFAULT 0\");\n }\n}\n\n// ADR-0032 — script-backed scheduled tasks. Mirrors the watcher migration\n// in ensureWatchersReactionKindColumns. Adds:\n// reaction_kind 'agent_prompt' (default) | 'script'\n// reaction_script registry key, only when kind='script'\n// reaction_script_args JSON object, only when kind='script'\n// Existing rows take reaction_kind='agent_prompt' (column default) and\n// continue to fire the agent with the saved prompt as before.\nfunction ensureScheduledTasksReactionKindColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(scheduled_tasks)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"reaction_kind\")) {\n db.exec(\n \"ALTER TABLE scheduled_tasks ADD COLUMN reaction_kind TEXT NOT NULL DEFAULT 'agent_prompt'\",\n );\n }\n if (!names.has(\"reaction_script\")) {\n db.exec(\"ALTER TABLE scheduled_tasks ADD COLUMN reaction_script TEXT\");\n }\n if (!names.has(\"reaction_script_args\")) {\n db.exec(\"ALTER TABLE scheduled_tasks ADD COLUMN reaction_script_args TEXT\");\n }\n}\n\n// Per-agent message-channel display filters (ADR-0022). JSON blob:\n// { \"thinking\": true, \"tool_use\": true, \"scheduled_task\": true,\n// \"bridge\": true, \"synthetic\": true }\n// NULL = inherit defaults (all-on). Missing keys also default to true so\n// new channels added in future builds stay visible for existing users.\nfunction ensureAgentDisplayFiltersColumn(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(agent_configs)\").all() as Array<{ name: string }>;\n if (!cols.some((c) => c.name === \"display_filters\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN display_filters TEXT\");\n }\n}\n\n// ADR-0026 — remote document-RAG sources (Jira / Confluence / mail). Extends the\n// ADR-0024 document_sources table with a discriminator + JSON config so a\n// single store + indexer dispatcher serves both local folders and remote\n// content. Existing rows are 'local_folder' (matches pre-0026 behavior).\nfunction ensureDocumentSourceRemoteColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(document_sources)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"kind\")) {\n db.exec(\n \"ALTER TABLE document_sources ADD COLUMN kind TEXT NOT NULL DEFAULT 'local_folder'\",\n );\n }\n if (!names.has(\"config\")) {\n // JSON-encoded per-kind config (e.g. {\"space_key\":\"ENG\"} for\n // confluence_space, {\"jql\":\"...\"} for jira_jql, {\"query\":\"is:unread\"}\n // for gmail_mail). NULL for local_folder.\n db.exec(\"ALTER TABLE document_sources ADD COLUMN config TEXT\");\n }\n if (!names.has(\"last_cursor\")) {\n // Per-source incremental cursor (e.g. max external `updated` ISO\n // timestamp for Jira/Confluence). Lets remote indexers run cheaply\n // after the first full sync. NULL for local_folder.\n db.exec(\"ALTER TABLE document_sources ADD COLUMN last_cursor TEXT\");\n }\n}\n\nfunction ensureThreadsAgentIdUnique(db: DatabaseSync): void {\n // Check if index already exists — skip if so\n const idx = db.prepare(\n \"SELECT name FROM sqlite_master WHERE type='index' AND name='idx_threads_agent_id'\"\n ).get();\n if (idx) return;\n\n // Delete orphaned messages for duplicate threads before removing them\n db.exec(`\n DELETE FROM messages WHERE thread_id IN (\n SELECT thread_id FROM threads\n WHERE rowid NOT IN (SELECT MAX(rowid) FROM threads GROUP BY agent_id)\n )\n `);\n\n // Keep only the last-inserted thread per agent (by rowid)\n db.exec(`\n DELETE FROM threads\n WHERE rowid NOT IN (SELECT MAX(rowid) FROM threads GROUP BY agent_id)\n `);\n\n db.exec(\"CREATE UNIQUE INDEX idx_threads_agent_id ON threads(agent_id)\");\n}\n\nfunction ensureAgentConfigColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(agent_configs)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"is_default\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN is_default INTEGER NOT NULL DEFAULT 0\");\n db.exec(\"UPDATE agent_configs SET is_default=1 WHERE id='assistant'\");\n }\n if (!names.has(\"history_limit\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN history_limit INTEGER NOT NULL DEFAULT 50\");\n }\n if (!names.has(\"history_window_hours\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN history_window_hours INTEGER NOT NULL DEFAULT 8\");\n }\n // never_reply: when 1, the dispatcher records the inbound message and\n // the agent's response in the thread but doesn't send the reply back\n // through the bridge. Useful for read-only / observer agents on group\n // chats where the user wants archival + LLM analysis but no automatic\n // posting.\n if (!names.has(\"never_reply\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN never_reply INTEGER NOT NULL DEFAULT 0\");\n }\n if (!names.has(\"adaptive_persona_enabled\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_persona_enabled INTEGER NOT NULL DEFAULT 0\");\n }\n if (!names.has(\"adaptive_persona_strength\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_persona_strength INTEGER NOT NULL DEFAULT 50\");\n }\n if (!names.has(\"adaptive_empathy\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_empathy INTEGER NOT NULL DEFAULT 50\");\n }\n if (!names.has(\"adaptive_expressiveness\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_expressiveness INTEGER NOT NULL DEFAULT 50\");\n }\n if (!names.has(\"adaptive_verbosity\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_verbosity INTEGER NOT NULL DEFAULT 50\");\n }\n if (!names.has(\"adaptive_mbti\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN adaptive_mbti TEXT NOT NULL DEFAULT 'INTJ'\");\n }\n // Per-agent voice config. When voice_enabled=0 the chat UI hides the\n // mic + play controls for this agent entirely; STT/TTS endpoints reject\n // requests targeting it. Provider/model/voice are TTS-side; stt_model is\n // STT-side. Defaults pick Gemini flash-tier so a fresh agent with voice\n // turned on works against the existing \"google\" integration api_key.\n if (!names.has(\"voice_enabled\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN voice_enabled INTEGER NOT NULL DEFAULT 0\");\n }\n if (!names.has(\"voice_model\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN voice_model TEXT NOT NULL DEFAULT 'gemini-2.5-flash-preview-tts'\");\n }\n if (!names.has(\"voice_name\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN voice_name TEXT NOT NULL DEFAULT 'Kore'\");\n }\n if (!names.has(\"voice_stt_model\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN voice_stt_model TEXT NOT NULL DEFAULT 'gemini-2.5-flash'\");\n }\n if (!names.has(\"voice_auto_speak\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN voice_auto_speak INTEGER NOT NULL DEFAULT 1\");\n }\n // ADR-0033 — per-agent harness override. NULL = inherit the global default\n // harness (app-settings.default_harness_id, which itself defaults to\n // 'builtin:default'). Non-null is either a builtin id (\"builtin:default\")\n // or a user-created custom id (\"custom:<uuid>\").\n if (!names.has(\"harness_id\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN harness_id TEXT\");\n }\n // Per-agent delegation whitelist (JSON array of agent ids). NULL or empty\n // array means the agent cannot delegate. Read by lib/tools/delegate.ts to\n // gate the delegate_to_agent tool.\n if (!names.has(\"delegate_targets\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN delegate_targets TEXT\");\n }\n // ADR-0043 — per-agent override of context_tier_proportions. JSON-encoded\n // `{ hot, warm, facts }` (any positive numbers — `normalizeTierProportions`\n // divides by sum, so the UI can ship raw weights instead of demanding\n // sum=100 from the user). NULL = inherit from the model config.\n if (!names.has(\"context_tier_proportions\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN context_tier_proportions TEXT\");\n }\n // Per-agent override of the anti-hallucination classifier (ADR-…). NULL\n // on either column = inherit the global JARELA_HALLUCINATION_DETECTOR_*\n // env knob. Mode is one of \"off\" | \"report\" | \"enforce\"; model_config is\n // the name of a saved model config (lib/stores/model-config) used as\n // the classifier model.\n if (!names.has(\"anti_hallucination_mode\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN anti_hallucination_mode TEXT\");\n }\n if (!names.has(\"anti_hallucination_model_config\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN anti_hallucination_model_config TEXT\");\n }\n // Independent of the stall classifier: when 1, the agent's system prompt\n // gets a citation-link directive and the assistant turn is post-checked\n // for {source link present, source previously visited in this thread}.\n // Reuses `anti_hallucination_model_config` as the checker model.\n if (!names.has(\"require_source_links\")) {\n db.exec(\"ALTER TABLE agent_configs ADD COLUMN require_source_links INTEGER NOT NULL DEFAULT 0\");\n }\n}\n\n/**\n * `silent_mode` is per-route, not per-agent: the same agent can auto-reply\n * in one chat and stay observer-only in another. Backfills from the legacy\n * per-agent `never_reply` flag on first migration so behavior is preserved\n * for existing installs. After backfill, `never_reply` is no longer read by\n * the dispatcher — the route flag is canonical.\n */\nfunction ensureBridgeRouteColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(bridge_routes)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"silent_mode\")) {\n db.exec(\"ALTER TABLE bridge_routes ADD COLUMN silent_mode INTEGER NOT NULL DEFAULT 0\");\n // Best-effort backfill from the legacy per-agent flag if the column exists.\n const agentCols = db.prepare(\"PRAGMA table_info(agent_configs)\").all() as Array<{ name: string }>;\n if (agentCols.some((c) => c.name === \"never_reply\")) {\n db.exec(`\n UPDATE bridge_routes\n SET silent_mode = 1\n WHERE agent_id IN (SELECT id FROM agent_configs WHERE never_reply = 1)\n `);\n }\n }\n // Per-route reply trigger: which sender role unlocks an outbound reply.\n // 'counterpart' (default) = agent answers the user's chat partner / group\n // members but stays quiet when the user themselves types — the typical\n // \"auto-responder on my behalf\" use case. 'user' = agent only reacts to\n // the user's own messages (e.g. expand/translate-my-draft assistants).\n // silent_mode (above) overrides this — when set, nothing goes out\n // regardless of role match.\n if (!names.has(\"respond_to\")) {\n db.exec(\"ALTER TABLE bridge_routes ADD COLUMN respond_to TEXT NOT NULL DEFAULT 'counterpart'\");\n }\n}\n\nfunction ensureTaskAssignmentColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(task_assignments)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n\n if (!names.has(\"allow_tools\")) {\n db.exec(\"ALTER TABLE task_assignments ADD COLUMN allow_tools TEXT NOT NULL DEFAULT '[]'\");\n }\n if (!names.has(\"deny_tools\")) {\n db.exec(\"ALTER TABLE task_assignments ADD COLUMN deny_tools TEXT NOT NULL DEFAULT '[]'\");\n }\n}\n\n// ADR-0042 — explicit per-thread context pin + persisted warm summary.\n// hot_since: ISO timestamp of the boundary the user has chosen to include in\n// the agent's hot context. NULL = no explicit pin → buildHistoryWindow falls\n// back to the agent's history_window_hours default.\n// warm_summary: latest LLM-summarised recap of messages older than\n// warm_summary_before. The chat UI renders this as an inline card above the\n// boundary divider so the user can see what the agent had to compress.\n// warm_summary_before: the boundary the cached summary covers. The summary is\n// considered fresh only when warm_summary_before === hot_since; otherwise\n// the next run will re-summarise and overwrite both.\nfunction ensureThreadContextPinColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(threads)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"hot_since\")) db.exec(\"ALTER TABLE threads ADD COLUMN hot_since TEXT\");\n if (!names.has(\"warm_summary\")) db.exec(\"ALTER TABLE threads ADD COLUMN warm_summary TEXT\");\n if (!names.has(\"warm_summary_before\")) db.exec(\"ALTER TABLE threads ADD COLUMN warm_summary_before TEXT\");\n if (!names.has(\"warm_summary_computed_at\")) db.exec(\"ALTER TABLE threads ADD COLUMN warm_summary_computed_at TEXT\");\n}\n\n// Per-tier input-token breakdown so the chat UI can show actual\n// hot/warm/facts/overhead consumption per turn (not just the proportional\n// budget). All eight columns are nullable so legacy rows simply render an\n// \"unknown\" bar. Re-derivation isn't possible after the fact (the\n// history-window state isn't preserved), so backfill is intentionally NULL.\nfunction ensureMessageUsageTierColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(message_usage)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"hot_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN hot_tokens INTEGER\");\n if (!names.has(\"warm_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN warm_tokens INTEGER\");\n if (!names.has(\"facts_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN facts_tokens INTEGER\");\n if (!names.has(\"overhead_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN overhead_tokens INTEGER\");\n if (!names.has(\"hot_budget_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN hot_budget_tokens INTEGER\");\n if (!names.has(\"warm_budget_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN warm_budget_tokens INTEGER\");\n if (!names.has(\"facts_budget_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN facts_budget_tokens INTEGER\");\n if (!names.has(\"context_window_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN context_window_tokens INTEGER\");\n}\n\n// PR #181 enabled Anthropic prompt caching, but the per-turn usage snapshot\n// only captured `input_tokens` / `output_tokens`. Anthropic returns cache\n// reads and writes as separate counts (priced at 0.1× and 1.25× the input\n// rate respectively), so without these columns the dashboard underreports\n// cost on cache-creating turns and *over*reports on cache-hitting turns.\n// Both columns are nullable: legacy rows and non-Anthropic providers leave\n// them NULL.\nfunction ensureMessageUsageCacheColumns(db: DatabaseSync): void {\n const cols = db.prepare(\"PRAGMA table_info(message_usage)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"cache_creation_input_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN cache_creation_input_tokens INTEGER\");\n if (!names.has(\"cache_read_input_tokens\")) db.exec(\"ALTER TABLE message_usage ADD COLUMN cache_read_input_tokens INTEGER\");\n}\n\nfunction seedAgentConfigs(db: DatabaseSync): void {\n // Only seed on first run — once the user has any agents we must not\n // resurrect ones they've deleted (e.g. the legacy \"echo\" / \"llm\" defaults).\n const count = (db.prepare(\"SELECT COUNT(*) as n FROM agent_configs\").get() as { n: number }).n;\n if (count > 0) {\n reanchorOrphanThreads(db);\n return;\n }\n\n const t = now();\n const insert = db.prepare(\n `INSERT OR IGNORE INTO agent_configs (\n id, name, icon, identity, instructions, tools, model_config_name, is_default,\n never_reply,\n adaptive_persona_enabled, adaptive_persona_strength, adaptive_empathy, adaptive_expressiveness, adaptive_verbosity, adaptive_mbti,\n created_at, updated_at\n )\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`\n );\n\n for (const p of BASE_AGENT_PROFILES) {\n const preset = MBTI_PRESETS[p.mbti];\n insert.run(\n p.id,\n p.name,\n p.icon ?? null,\n p.identity,\n p.instructions,\n JSON.stringify(p.tools),\n null,\n p.is_default ? 1 : 0,\n p.never_reply ? 1 : 0,\n p.adaptive ? 1 : 0,\n preset.strength,\n preset.empathy,\n preset.expressiveness,\n preset.verbosity,\n p.mbti,\n t,\n t,\n );\n }\n\n reanchorOrphanThreads(db);\n}\n\ninterface BaseAgentProfile {\n id: string;\n name: string;\n icon?: string | null;\n identity: string;\n instructions: string;\n tools: string[];\n mbti: MbtiType;\n adaptive: boolean;\n is_default?: boolean;\n // When true, the agent runs on bridge/scheduled input but does not\n // auto-send replies — it observes and records, only speaking when the\n // user directly addresses it (see lib/bridges/dispatcher.ts).\n never_reply?: boolean;\n}\n\n// Starter profiles shipped on first run. The user can edit, disable, or\n// delete any of them — once they have any agents we stop re-seeding (see\n// the guard at the top of seedAgentConfigs), so user choices are sticky.\n//\n// Each profile pre-binds a small, focused tool set so the agent is useful\n// out of the box without exposing every capability by default. Tools that\n// require integrations (gmail/outlook/calendar) are wired up but will\n// surface a setup hint at call time if the integration is not configured.\nconst BASE_AGENT_PROFILES: BaseAgentProfile[] = [\n {\n id: \"assistant\",\n name: \"Assistant\",\n identity: \"You are a helpful general-purpose assistant.\",\n instructions:\n \"Answer concisely. Ask for clarification only when truly ambiguous. When you don't know something, say so instead of guessing.\",\n tools: [],\n mbti: \"INTJ\",\n adaptive: false,\n is_default: true,\n },\n {\n id: \"researcher\",\n name: \"Researcher\",\n identity:\n \"You are a careful researcher who finds, cross-checks, and summarizes information from the web.\",\n instructions:\n \"Use web_search to discover sources and web_fetch to read them. Prefer primary sources over aggregators. Cite URLs inline. When findings conflict, surface the disagreement instead of picking a side. Save durable facts with memory_write so future sessions can build on them.\",\n tools: [\"web_search\", \"web_fetch\", \"memory_read\", \"memory_write\", \"memory_list\"],\n mbti: \"INTP\",\n adaptive: true,\n },\n {\n id: \"developer\",\n name: \"Developer\",\n identity:\n \"You are a pragmatic software engineer working in the user's local repo with a real build/test harness.\",\n instructions:\n \"Read before you write. Use file_list / file_read / file_stat to map the code, then file_edit for surgical changes and file_write only for new files. After every meaningful edit, run the project's build, lint, or test command via shell_exec (or local_exec for a single binary) and read the output before declaring success — never claim a fix without proof. Use github_* to look up issues/PRs for context. Prefer the smallest change that solves the problem; never invent paths or APIs.\",\n tools: [\n \"file_read\",\n \"file_write\",\n \"file_edit\",\n \"file_list\",\n \"file_stat\",\n \"file_mkdir\",\n \"file_move\",\n \"file_copy\",\n \"file_delete\",\n \"local_exec\",\n \"shell_exec\",\n \"web_fetch\",\n \"web_search\",\n \"github_search_issues\",\n \"github_get_issue\",\n \"github_list_pulls\",\n \"github_get_pull\",\n \"github_get_repo\",\n \"memory_read\",\n \"memory_write\",\n \"memory_list\",\n ],\n mbti: \"INTJ\",\n adaptive: true,\n },\n {\n id: \"planner\",\n name: \"Planner\",\n identity:\n \"You are a planning partner who turns vague intentions into concrete, scheduled actions.\",\n instructions:\n \"When the user describes something they want to happen later or recurrently, propose a schedule_task with a clear prompt and a cron or ISO schedule, then confirm before creating it. Use list_scheduled_tasks before adding to avoid duplicates. Keep memory_write notes on the user's recurring goals so plans stay aligned over time.\",\n tools: [\n \"schedule_task\",\n \"list_scheduled_tasks\",\n \"cancel_scheduled_task\",\n \"memory_read\",\n \"memory_write\",\n \"memory_list\",\n ],\n mbti: \"ENTJ\",\n adaptive: true,\n },\n {\n id: \"inbox\",\n name: \"Inbox Triage\",\n identity:\n \"You help triage email and calendar. You summarize, draft, and surface what actually needs attention.\",\n instructions:\n \"When asked about mail, search first, then read the specific message before drafting. Drafts are created — never sent automatically. For calendar requests, list the relevant window before creating events. If an integration is not configured, tell the user which one and stop.\",\n tools: [\n \"gmail_search\",\n \"gmail_get_message\",\n \"gmail_create_draft\",\n \"outlook_search\",\n \"outlook_get_message\",\n \"outlook_create_draft\",\n \"calendar_list_events\",\n \"calendar_create_event\",\n \"outlook_calendar_list_events\",\n \"outlook_calendar_create_event\",\n ],\n mbti: \"ESFJ\",\n adaptive: true,\n },\n {\n id: \"companion\",\n name: \"Companion\",\n identity:\n \"You are a reflective companion for journaling and thinking out loud.\",\n instructions:\n \"Listen more than you advise. Ask one open question at a time. Mirror back themes you notice across sessions; use memory_read at the start of a thread and memory_write to record durable insights (values, ongoing struggles, wins), never raw content.\",\n tools: [\"memory_read\", \"memory_write\", \"memory_list\"],\n mbti: \"INFJ\",\n adaptive: true,\n },\n\n // Backward-compat: pre-migration threads used agent_id=\"llm\" or \"echo\".\n // Kept so historical threads still resolve to a real agent_configs row.\n {\n id: \"llm\",\n name: \"LLM Agent\",\n identity: \"You are a helpful assistant.\",\n instructions: \"\",\n tools: [],\n mbti: \"INTJ\",\n adaptive: false,\n },\n {\n id: \"echo\",\n name: \"Echo\",\n identity: \"\",\n instructions: \"\",\n tools: [],\n mbti: \"INTJ\",\n adaptive: false,\n },\n];\n\n// Threads have a UNIQUE(agent_id) index (one thread per agent), so we can't\n// bulk-repoint orphan threads to a single fallback — that would violate the\n// constraint as soon as there are 2+ orphans. Instead we drop orphan threads\n// (and their messages); the agent they pointed at no longer exists.\nfunction reanchorOrphanThreads(db: DatabaseSync): void {\n db.exec(`\n DELETE FROM messages WHERE thread_id IN (\n SELECT thread_id FROM threads WHERE agent_id NOT IN (SELECT id FROM agent_configs)\n )\n `);\n db.exec(`\n DELETE FROM threads WHERE agent_id NOT IN (SELECT id FROM agent_configs)\n `);\n}\n\nfunction seedModelConfigs(db: DatabaseSync): void {\n // Only seed on first run — if any row exists, the user has already managed\n // their configs and we must not resurrect anything they deleted.\n const count = (db.prepare(\"SELECT COUNT(*) as n FROM model_configs\").get() as { n: number }).n;\n if (count > 0) return;\n\n const insert = db.prepare(\n `INSERT OR IGNORE INTO model_configs (name, provider, model_id, params, is_default, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`\n );\n const t = now();\n const seeds: [string, string, string, string, number, string, string][] = [\n [\"claude-sonnet\", \"anthropic\", \"claude-sonnet-4-6\", \"{}\", 0, t, t],\n [\"gpt-4o\", \"openai\", \"gpt-4o\", \"{}\", 0, t, t],\n [\"github-copilot\", \"github-copilot\", \"gpt-4o\", \"{}\", 0, t, t],\n\n ];\n for (const s of seeds) insert.run(...s);\n}\n","// One-time, idempotent migration that rewrites legacy plaintext values\n// in the four secret-bearing surfaces with `enc:v1:` envelopes\n// (ADR-0005). Safe to run on every boot — already-encrypted rows are\n// detected by the prefix and skipped.\n\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { encrypt, isEncrypted } from \"./envelope\";\nimport { SENSITIVE_MEMORY_NAMESPACES } from \"./sensitive\";\n\ninterface MemoryStoreRow { namespace: string; key: string; value: string }\ninterface ModelConfigRow { name: string; params: string }\ninterface McpServerRow { name: string; spec: string }\n\nexport function runCryptoMigration(db: DatabaseSync): void {\n let touched = 0;\n\n // 1) memory_store rows in sensitive namespaces.\n const nsList = [...SENSITIVE_MEMORY_NAMESPACES];\n const placeholders = nsList.map(() => \"?\").join(\",\");\n const memoryRows = db\n .prepare(`SELECT namespace, key, value FROM memory_store WHERE namespace IN (${placeholders})`)\n .all(...nsList) as unknown as MemoryStoreRow[];\n const memUpdate = db.prepare(\n \"UPDATE memory_store SET value=?, updated_at=? WHERE namespace=? AND key=?\",\n );\n const now = new Date().toISOString();\n for (const row of memoryRows) {\n if (isEncrypted(row.value)) continue;\n memUpdate.run(encrypt(row.value), now, row.namespace, row.key);\n touched++;\n }\n\n // 2) model_configs.params — every row.\n const modelRows = db\n .prepare(\"SELECT name, params FROM model_configs\")\n .all() as unknown as ModelConfigRow[];\n const modelUpdate = db.prepare(\n \"UPDATE model_configs SET params=?, updated_at=? WHERE name=?\",\n );\n for (const row of modelRows) {\n if (isEncrypted(row.params)) continue;\n modelUpdate.run(encrypt(row.params), now, row.name);\n touched++;\n }\n\n // 3) mcp_servers.spec — every row.\n const mcpRows = db\n .prepare(\"SELECT name, spec FROM mcp_servers\")\n .all() as unknown as McpServerRow[];\n const mcpUpdate = db.prepare(\n \"UPDATE mcp_servers SET spec=?, updated_at=? WHERE name=?\",\n );\n for (const row of mcpRows) {\n if (isEncrypted(row.spec)) continue;\n mcpUpdate.run(encrypt(row.spec), now, row.name);\n touched++;\n }\n\n if (touched > 0) {\n console.info(`[jarela] encrypted ${touched} legacy plaintext secret row(s) at rest`);\n }\n}\n","import { DatabaseSync } from \"node:sqlite\";\nimport { join } from \"node:path\";\nimport { runMigrations } from \"./migrations\";\nimport { getDataDir } from \"./data-dir\";\nimport { initMasterKey } from \"@/lib/crypto/master-key\";\nimport { runCryptoMigration } from \"@/lib/crypto/migrate\";\nimport { applyProxyConfigFromDb } from \"@/lib/proxy/dispatcher\"; // env-var dispatcher applied at module load; DB layer applied below\nimport { runEnvSyncOnce } from \"@/lib/env/sync\";\n\nexport const DB_PATH = join(getDataDir(), \"jarela.db\");\n\nlet _db: DatabaseSync | null = null;\n\nexport function getDb(): DatabaseSync {\n if (!_db) {\n // Bootstrap the at-rest encryption master key (ADR-0005) before any\n // store touches the DB. initMasterKey is synchronous and idempotent.\n const { source } = initMasterKey(getDataDir());\n if (source === \"keyfile\") {\n console.warn(\n \"[jarela] using keyfile fallback for at-rest encryption — keychain \" +\n \"access failed. The master key lives next to the DB; protect the \" +\n \"data directory accordingly. See ADR-0005.\",\n );\n }\n const db = new DatabaseSync(DB_PATH);\n db.exec(\"PRAGMA journal_mode = WAL\");\n db.exec(\"PRAGMA foreign_keys = ON\");\n runMigrations(db);\n // One-time encryption migration: rewrites legacy plaintext rows in\n // the four secret-bearing surfaces with enc:v1: envelopes. Idempotent.\n runCryptoMigration(db);\n _db = db; // only assign after migrations succeed\n // Layer DB-backed proxy config on top of the env-var dispatcher\n // (ADR-0009). Fire-and-forget — keeps getDb() synchronous so existing\n // call sites stay unchanged. Errors are logged but don't break boot;\n // worst case we fall back to direct connection.\n applyProxyConfigFromDb().catch((err) =>\n console.warn(\"[jarela/proxy] applyProxyConfigFromDb failed at boot:\", err),\n );\n // Pull rc-defined credential env vars into the encrypted integration\n // store so installed launchers (LaunchAgent / systemd-user) — which\n // never source the user's shell rc — pick up tokens automatically\n // and survive rotation. Best-effort; never blocks boot.\n runEnvSyncOnce().then((r) => {\n if (r && r.applied_count > 0) {\n console.log(\n `[jarela/env-sync] applied ${r.applied_count} field(s) from ${r.discovered.source}`,\n );\n }\n });\n }\n return _db;\n}\n\n// Close the SQLite handle so WAL is checkpointed and the lock is released\n// before the process exits. Called from the graceful-shutdown path. Safe\n// to call when the DB was never opened (no-op). Best-effort: WAL files\n// stay valid even on hard kills because SQLite is crash-resilient, but\n// a clean close means no stale -shm/-wal sidecars and a faster next boot.\nexport function closeDb(): void {\n if (!_db) return;\n const db = _db;\n _db = null;\n try {\n // PRAGMA optimize is cheap (<1ms typically) and lets SQLite run any\n // pending analyze work it would otherwise defer; safe on shutdown.\n db.exec(\"PRAGMA optimize\");\n } catch { /* not fatal — proceed with close */ }\n try {\n db.close();\n } catch (err) {\n console.warn(\"[jarela] closeDb: close failed:\", err);\n }\n}\n","import { getDb } from \"@/lib/db\";\n\nconst now = () => new Date().toISOString();\n\nconst NS = \"app-settings\";\nconst EMBEDDING_MODEL_KEY = \"embedding_model_config\";\n\nexport function getEmbeddingModelConfigName(): string | null {\n const row = getDb()\n .prepare(\"SELECT value FROM memory_store WHERE namespace=? AND key=?\")\n .get(NS, EMBEDDING_MODEL_KEY) as { value?: string } | undefined;\n const raw = row?.value;\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as unknown;\n return typeof parsed === \"string\" && parsed.trim() ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function setEmbeddingModelConfigName(name: string | null): string | null {\n if (!name) {\n getDb().prepare(\"DELETE FROM memory_store WHERE namespace=? AND key=?\").run(NS, EMBEDDING_MODEL_KEY);\n return null;\n }\n const existing = getDb()\n .prepare(\"SELECT created_at FROM memory_store WHERE namespace=? AND key=?\")\n .get(NS, EMBEDDING_MODEL_KEY) as { created_at?: string } | undefined;\n const t = now();\n const created = existing?.created_at ?? t;\n getDb()\n .prepare(\n \"INSERT OR REPLACE INTO memory_store (namespace,key,value,created_at,updated_at,embedding) VALUES (?,?,?,?,?,NULL)\",\n )\n .run(NS, EMBEDDING_MODEL_KEY, JSON.stringify(name), created, t);\n return name;\n}\n","// AES-256-GCM envelope for at-rest secret storage (ADR-0005).\n//\n// Wire format: `enc:v1:<base64url(iv ‖ ciphertext ‖ tag)>`\n// - iv: 12 bytes (random per value)\n// - ciphertext: variable\n// - tag: 16 bytes (GCM auth tag)\n//\n// The `enc:v1:` prefix is the on-disk marker for \"this value is encrypted\n// under the current scheme\". `decryptIfNeeded` returns plaintext for\n// either prefixed or legacy unprefixed values, so a partially-migrated\n// DB keeps working.\n\nimport { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\nimport { getMasterKey } from \"./master-key\";\n\nconst PREFIX = \"enc:v1:\";\nconst IV_LEN = 12;\nconst TAG_LEN = 16;\n\nexport function isEncrypted(value: string): boolean {\n return value.startsWith(PREFIX);\n}\n\nexport function encrypt(plaintext: string): string {\n const key = getMasterKey();\n const iv = randomBytes(IV_LEN);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n const ct = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n const tag = cipher.getAuthTag();\n return PREFIX + Buffer.concat([iv, ct, tag]).toString(\"base64url\");\n}\n\nexport function decrypt(envelope: string): string {\n if (!isEncrypted(envelope)) {\n throw new Error(\"decrypt() called on non-encrypted value\");\n }\n const buf = Buffer.from(envelope.slice(PREFIX.length), \"base64url\");\n if (buf.length < IV_LEN + TAG_LEN) {\n throw new Error(`encrypted payload too short: ${buf.length} bytes`);\n }\n const iv = buf.subarray(0, IV_LEN);\n const tag = buf.subarray(buf.length - TAG_LEN);\n const ct = buf.subarray(IV_LEN, buf.length - TAG_LEN);\n const key = getMasterKey();\n const decipher = createDecipheriv(\"aes-256-gcm\", key, iv);\n decipher.setAuthTag(tag);\n const pt = Buffer.concat([decipher.update(ct), decipher.final()]);\n return pt.toString(\"utf8\");\n}\n\n// Idempotent read-side helper. Plaintext (legacy) passes through; an\n// encrypted value is decrypted; an unparseable encrypted value throws.\nexport function decryptIfNeeded(value: string): string {\n return isEncrypted(value) ? decrypt(value) : value;\n}\n\n// Idempotent write-side helper. An already-encrypted value passes\n// through unchanged, which keeps the eager migration safe to re-run.\nexport function encryptIfNeeded(value: string): string {\n return isEncrypted(value) ? value : encrypt(value);\n}\n","import { getProvider } from \"@/lib/providers\";\nimport { getModelConfig, getDefaultModelConfig, getModelParams, listModelConfigs, type ModelConfigRow } from \"@/lib/stores/model-config\";\nimport { getEmbeddingModelConfigName } from \"@/lib/stores/app-settings\";\nimport { getDb } from \"@/lib/db\";\nimport { SENSITIVE_MEMORY_NAMESPACES } from \"@/lib/crypto/sensitive\";\nimport type { ProviderParams } from \"@/lib/providers/types\";\n\n// Sensitive namespaces (ADR-0005) are never surfaced via recall: their\n// values are encrypted at rest, and credentials should not reach agent\n// context via semantic search regardless.\nconst EXCLUDED_NS = [...SENSITIVE_MEMORY_NAMESPACES];\nconst EXCLUDED_NS_PLACEHOLDERS = EXCLUDED_NS.map(() => \"?\").join(\",\");\n\n// Embedding model resolution:\n// 1. EMBEDDING_MODEL_CONFIG env var → name of a row in model_configs\n// 2. Else: same provider as the default chat model + a sane default model_id\n// (text-embedding-3-small for OpenAI-compatible providers).\n// Embedding generation is best-effort: any failure returns null and the caller\n// falls back to substring search.\nasync function resolveEmbeddingClient(): Promise<{\n provider: ReturnType<typeof getProvider>;\n modelId: string;\n params: ProviderParams;\n} | null> {\n function fromConfig(cfg: ModelConfigRow | null): {\n provider: ReturnType<typeof getProvider>;\n modelId: string;\n params: ProviderParams;\n } | null {\n if (!cfg) return null;\n const params: ProviderParams = getModelParams(cfg);\n const provider = getProvider(cfg.provider);\n if (!provider.embed) return null;\n // Default to a small embedding model for the OpenAI-compatible providers if\n // the chat model_id was used (e.g. \"gpt-4o\", \"claude-...\"). Override via\n // params.embedding_model_id.\n const overridden = (params as Record<string, unknown>).embedding_model_id;\n const modelId = typeof overridden === \"string\" && overridden\n ? overridden\n : isChatModelId(cfg.model_id)\n ? \"text-embedding-3-small\"\n : cfg.model_id;\n return { provider, modelId, params };\n }\n\n const explicitName = process.env.EMBEDDING_MODEL_CONFIG;\n // 1) explicit embedding model name (if provided).\n if (explicitName) {\n const explicit = fromConfig(getModelConfig(explicitName));\n if (explicit) return explicit;\n }\n\n // 2) persisted app-level embedding model selection.\n const configuredName = getEmbeddingModelConfigName();\n if (configuredName) {\n const configured = fromConfig(getModelConfig(configuredName));\n if (configured) return configured;\n }\n\n // 3) default chat model if it also supports embeddings.\n const fromDefault = fromConfig(getDefaultModelConfig());\n if (fromDefault) return fromDefault;\n\n // 4) installation-safe fallback: any configured model with embed support.\n // This avoids \"silent 0 embeddings forever\" when default chat provider\n // (e.g. github-copilot) has no embed API but another model is configured.\n const configs = listModelConfigs();\n for (const cfg of configs) {\n if (explicitName && cfg.name === explicitName) continue;\n const candidate = fromConfig(cfg);\n if (candidate) return candidate;\n }\n return null;\n}\n\nfunction isChatModelId(id: string): boolean {\n return /^(gpt-|claude-|deepseek-chat|deepseek-reasoner)/.test(id);\n}\n\nexport async function embed(texts: string[]): Promise<number[][] | null> {\n if (texts.length === 0) return [];\n const client = await resolveEmbeddingClient();\n if (!client) return null;\n try {\n return await client.provider.embed!(client.modelId, texts, client.params);\n } catch (err) {\n console.warn(\"[embeddings] failed:\", err instanceof Error ? err.message : String(err));\n return null;\n }\n}\n\nexport async function embedOne(text: string): Promise<number[] | null> {\n const out = await embed([text]);\n return out?.[0] ?? null;\n}\n\n// HTTP status / error message → \"should we retry?\"\n// 429 = rate limit, 5xx = transient server, plus a small set of node fetch\n// codes that show up under load. Anything else is a real config / input\n// problem that retrying won't fix.\nconst TRANSIENT_RE = /\\b(429|5\\d\\d|ECONNRESET|ETIMEDOUT|EAI_AGAIN|UND_ERR_(SOCKET|CONNECT_TIMEOUT)|fetch failed)\\b/;\nfunction isTransient(err: unknown): boolean {\n return TRANSIENT_RE.test(err instanceof Error ? err.message : String(err));\n}\n\nasync function callEmbedWithRetry(\n client: { provider: ReturnType<typeof getProvider>; modelId: string; params: ProviderParams },\n texts: string[],\n): Promise<number[][]> {\n // 250ms → 1s → 4s. Three attempts is enough to ride through a brief\n // rate-limit blip without dragging out a whole reindex run.\n const backoffs = [250, 1000, 4000];\n let lastErr: unknown;\n for (let attempt = 0; attempt <= backoffs.length; attempt++) {\n try {\n return await client.provider.embed!(client.modelId, texts, client.params);\n } catch (err) {\n lastErr = err;\n if (attempt >= backoffs.length || !isTransient(err)) break;\n await new Promise((r) => setTimeout(r, backoffs[attempt]));\n }\n }\n throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));\n}\n\nexport interface EmbedBestEffortResult {\n /** One slot per input text. `null` means embedding failed for that input. */\n vectors: (number[] | null)[];\n /** First error message seen, useful for surfacing on the source row. */\n error: string | null;\n /** Count of inputs that didn't get a vector. */\n failed: number;\n}\n\n/**\n * Like `embed()` but resilient: retries transient errors (429/5xx) with\n * exponential backoff, then on persistent failure splits the batch in half\n * and recurses, so one bad input doesn't lose embeddings for every other\n * chunk in the same document.\n *\n * Returns per-input results so the caller can persist whichever vectors\n * came back and report an aggregate count of failures up to the source\n * row instead of swallowing the error.\n */\nexport async function embedBestEffort(texts: string[]): Promise<EmbedBestEffortResult> {\n if (texts.length === 0) return { vectors: [], error: null, failed: 0 };\n const client = await resolveEmbeddingClient();\n if (!client) {\n return {\n vectors: texts.map(() => null),\n error: \"no embedding provider configured\",\n failed: texts.length,\n };\n }\n return embedBestEffortInternal(client, texts);\n}\n\nasync function embedBestEffortInternal(\n client: { provider: ReturnType<typeof getProvider>; modelId: string; params: ProviderParams },\n texts: string[],\n): Promise<EmbedBestEffortResult> {\n try {\n const vectors = await callEmbedWithRetry(client, texts);\n if (vectors.length === texts.length) return { vectors, error: null, failed: 0 };\n // Provider returned a short array — pad with nulls so indices line up.\n const padded: (number[] | null)[] = texts.map((_, i) => vectors[i] ?? null);\n const failed = padded.filter((v) => v === null).length;\n return {\n vectors: padded,\n error: `embedding provider returned ${vectors.length}/${texts.length} vectors`,\n failed,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (texts.length === 1) {\n console.warn(\"[embeddings] failed:\", msg);\n return { vectors: [null], error: msg, failed: 1 };\n }\n // Halve and recurse: a single oversized input shouldn't poison its\n // batchmates. The two halves run sequentially because the typical\n // failure (rate limit) doesn't get better by parallelising.\n const mid = Math.floor(texts.length / 2);\n const left = await embedBestEffortInternal(client, texts.slice(0, mid));\n const right = await embedBestEffortInternal(client, texts.slice(mid));\n return {\n vectors: [...left.vectors, ...right.vectors],\n error: left.error ?? right.error,\n failed: left.failed + right.failed,\n };\n }\n}\n\nexport function cosine(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length === 0) return 0;\n let dot = 0, na = 0, nb = 0;\n for (let i = 0; i < a.length; i++) {\n dot += a[i] * b[i];\n na += a[i] * a[i];\n nb += b[i] * b[i];\n }\n const denom = Math.sqrt(na) * Math.sqrt(nb);\n return denom === 0 ? 0 : dot / denom;\n}\n\nexport interface RecalledMemory {\n source: \"memory\" | \"message\";\n namespace?: string;\n key?: string;\n thread_id?: string;\n role?: string;\n content: string;\n score: number;\n created_at: string;\n}\n\n// Cross-source recall: compares the query embedding against every memory entry\n// and chat message that has an embedding. Returns top-k by cosine. Falls back\n// to a recent-rows substring scan for entries that don't have an embedding yet\n// (write-then-immediate-query case where the async embed hasn't landed).\nexport async function recall(query: string, limit = 5): Promise<RecalledMemory[]> {\n const qVec = await embedOne(query);\n const db = getDb();\n const scored: RecalledMemory[] = [];\n\n // ── semantic pass ─────────────────────────────────────────────────────────\n if (qVec) {\n const memRows = db.prepare(\n // Exclude sensitive namespaces (ADR-0005) — encrypted blobs would\n // surface as enc:v1:… strings and credentials should never reach\n // the agent context via recall regardless.\n `SELECT namespace, key, value, embedding, created_at FROM memory_store\n WHERE embedding IS NOT NULL AND namespace NOT IN (${EXCLUDED_NS_PLACEHOLDERS})`,\n ).all(...EXCLUDED_NS) as Array<{ namespace: string; key: string; value: string; embedding: string; created_at: string }>;\n\n const msgRows = db.prepare(\n \"SELECT thread_id, role, content, embedding, created_at FROM messages WHERE embedding IS NOT NULL\",\n ).all() as Array<{ thread_id: string; role: string; content: string; embedding: string; created_at: string }>;\n\n for (const r of memRows) {\n const v = parseEmbedding(r.embedding);\n if (!v) continue;\n scored.push({\n source: \"memory\", namespace: r.namespace, key: r.key,\n content: r.value, score: cosine(qVec, v), created_at: r.created_at,\n });\n }\n for (const r of msgRows) {\n const v = parseEmbedding(r.embedding);\n if (!v) continue;\n scored.push({\n source: \"message\", thread_id: r.thread_id, role: r.role,\n content: r.content, score: cosine(qVec, v), created_at: r.created_at,\n });\n }\n }\n\n // ── unembedded fallback: keyword overlap on rows still pending embedding ─\n // This catches the write-then-immediately-query case where async embed\n // hasn't completed. Score is capped below the embedding floor so a real\n // semantic match always wins.\n const tokens = tokenize(query);\n if (tokens.length > 0) {\n const recentMem = db.prepare(\n `SELECT namespace, key, value, created_at FROM memory_store\n WHERE embedding IS NULL AND namespace NOT IN (${EXCLUDED_NS_PLACEHOLDERS})\n ORDER BY updated_at DESC LIMIT 50`,\n ).all(...EXCLUDED_NS) as Array<{ namespace: string; key: string; value: string; created_at: string }>;\n const recentMsg = db.prepare(\n \"SELECT thread_id, role, content, created_at FROM messages WHERE embedding IS NULL ORDER BY created_at DESC LIMIT 50\",\n ).all() as Array<{ thread_id: string; role: string; content: string; created_at: string }>;\n\n for (const r of recentMem) {\n const score = keywordOverlap(tokens, r.value);\n if (score > 0) {\n scored.push({ source: \"memory\", namespace: r.namespace, key: r.key, content: r.value, score: 0.26 + score * 0.1, created_at: r.created_at });\n }\n }\n for (const r of recentMsg) {\n const score = keywordOverlap(tokens, r.content);\n if (score > 0) {\n scored.push({ source: \"message\", thread_id: r.thread_id, role: r.role, content: r.content, score: 0.26 + score * 0.1, created_at: r.created_at });\n }\n }\n }\n\n // Dedup by a short content prefix. When several entries share the same prefix\n // (e.g. multiple revisions of the same fact: \"My codename for X is...\"),\n // keep the most recently updated one rather than the highest-scoring one —\n // semantically they're \"the same fact\" and the user wants the latest version.\n const groups = new Map<string, RecalledMemory>();\n for (const s of scored) {\n if (s.score <= 0.25) continue;\n const key = `${s.source}:${normalizeForDedup(s.content)}`;\n const existing = groups.get(key);\n if (!existing) {\n groups.set(key, s);\n } else if (s.created_at > existing.created_at) {\n // Keep the newer one but propagate the highest score we've seen for the group\n // so it doesn't lose ranking against stale duplicates.\n groups.set(key, { ...s, score: Math.max(s.score, existing.score) });\n }\n }\n return Array.from(groups.values())\n .sort((a, b) => b.score - a.score)\n .slice(0, limit);\n}\n\nfunction normalizeForDedup(text: string): string {\n // First 80 chars after collapsing whitespace — long enough to distinguish\n // different topics but short enough that \"My X for Y is FOO\" and\n // \"My X for Y is BAR\" collapse into the same group.\n return text.replace(/\\s+/g, \" \").trim().toLowerCase().slice(0, 80);\n}\n\nconst STOP_WORDS = new Set([\n \"the\", \"a\", \"an\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\", \"of\", \"to\", \"in\",\n \"on\", \"at\", \"by\", \"for\", \"with\", \"about\", \"as\", \"what\", \"which\", \"who\", \"whose\", \"why\",\n \"how\", \"do\", \"does\", \"did\", \"i\", \"me\", \"my\", \"you\", \"your\", \"it\", \"its\", \"this\", \"that\",\n \"and\", \"or\", \"but\", \"if\", \"then\", \"than\", \"so\", \"have\", \"has\", \"had\", \"can\", \"will\",\n]);\n\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9_-]+/)\n .filter((w) => w.length >= 3 && !STOP_WORDS.has(w));\n}\n\nfunction keywordOverlap(queryTokens: string[], text: string): number {\n const textLower = text.toLowerCase();\n let hits = 0;\n for (const t of queryTokens) {\n if (textLower.includes(t)) hits++;\n }\n return queryTokens.length === 0 ? 0 : hits / queryTokens.length;\n}\n\nfunction parseEmbedding(raw: string): number[] | null {\n try {\n const arr = JSON.parse(raw) as unknown;\n return Array.isArray(arr) && arr.every((n) => typeof n === \"number\") ? (arr as number[]) : null;\n } catch {\n return null;\n }\n}\n","// Mapping from \"standard\" environment variable names to integration store\n// fields. Used by the env-sync feature (lib/env/sync.ts) so common\n// rc-defined credentials (GITHUB_TOKEN, ATLASSIAN_API_TOKEN, …) populate\n// the encrypted DB automatically and survive rotation without the user\n// re-typing them in the Integrations panel.\n//\n// `ENV_ALLOWLIST` is the static, code-owned default. Users can extend any\n// row's `envVars` list at runtime via the allowlist overrides API\n// (`POST /api/v1/env-sync/allowlist`) — see ADR-0034. They cannot point a\n// new env var at a *new* (integration, field): the target side is fixed\n// here so we never write rc values into a row that has no schema.\n//\n// Adding a new mapping is one line. The integration name MUST exist in\n// `INTEGRATIONS` (lib/stores/integrations.ts) and the field key MUST\n// match — there is a build-time check in scripts/check-env-allowlist.mjs\n// that fails the lint step otherwise.\n\nimport { getMemory, listMemory, putMemory, deleteMemory } from \"@/lib/stores/memory\";\nimport { INTEGRATIONS, getIntegrationRaw, isKnownIntegration, type IntegrationName } from \"@/lib/stores/integrations\";\n\nconst OVERRIDES_NS = \"env_allowlist_overrides\";\n\nexport interface EnvFieldMapping {\n /**\n * Env var names in priority order. The first one that is present and\n * non-empty wins. Lets us support both vendor-canonical names and the\n * older aliases users tend to have in their dotfiles.\n */\n envVars: string[];\n integration: IntegrationName;\n field: string;\n}\n\nexport const ENV_ALLOWLIST: readonly EnvFieldMapping[] = [\n // Anthropic (Claude) — primary LLM provider\n { envVars: [\"ANTHROPIC_API_KEY\"], integration: \"anthropic\", field: \"api_key\" },\n\n // GitHub — used by github_* tools (ADR-0015)\n { envVars: [\"GITHUB_TOKEN\", \"GH_TOKEN\"], integration: \"github\", field: \"token\" },\n\n // Atlassian — Jira + Confluence\n { envVars: [\"ATLASSIAN_URL\", \"JIRA_URL\"], integration: \"atlassian\", field: \"url\" },\n { envVars: [\"ATLASSIAN_EMAIL\", \"JIRA_EMAIL\"], integration: \"atlassian\", field: \"email\" },\n { envVars: [\"ATLASSIAN_API_TOKEN\", \"JIRA_API_TOKEN\", \"JIRA_TOKEN\"], integration: \"atlassian\", field: \"api_token\" },\n\n // Google AI (Gemini / Imagen) — used by generate_image\n { envVars: [\"GOOGLE_API_KEY\", \"GEMINI_API_KEY\"], integration: \"google\", field: \"api_key\" },\n];\n\n// ── User overrides ───────────────────────────────────────────────────────────\n// Stored as `memory_store` rows in namespace `\"env_allowlist_overrides\"`.\n// Key is `\"<integration>:<field>\"`, value is `{ envVars: string[] }`. The\n// listed names are *additional* aliases — defaults always remain so a\n// user who renames their dotfile var doesn't lose the canonical fallback.\n\nconst OVERRIDE_KEY = (integration: string, field: string): string => `${integration}:${field}`;\n\ninterface StoredOverride { envVars: string[] }\n\nfunction parseOverride(raw: string): string[] {\n try {\n const parsed = JSON.parse(raw) as StoredOverride;\n if (parsed && Array.isArray(parsed.envVars)) {\n return parsed.envVars.filter((v) => typeof v === \"string\" && v.trim().length > 0);\n }\n } catch { /* fall through */ }\n return [];\n}\n\n/** Read every (integration, field) override the user has saved. */\nexport function listOverrides(): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const row of listMemory(OVERRIDES_NS, undefined, 200)) {\n out[row.key] = parseOverride(row.value);\n }\n return out;\n}\n\n/** Read one override; returns the empty list when none is stored. */\nexport function getOverride(integration: string, field: string): string[] {\n const row = getMemory(OVERRIDES_NS, OVERRIDE_KEY(integration, field));\n return row ? parseOverride(row.value) : [];\n}\n\n/**\n * Persist an override. Validates that the (integration, field) pair points\n * at an existing schema entry — env-var renames cannot create new targets.\n * Names are uppercased and de-duplicated; defaults are stripped from the\n * stored payload so a future schema change to canonical names doesn't\n * leave dead duplicates behind.\n */\nexport function setOverride(integration: string, field: string, envVars: string[]):\n | { ok: true; envVars: string[] }\n | { ok: false; error: string }\n{\n if (!isKnownIntegration(integration)) {\n return { ok: false, error: `unknown integration \"${integration}\"` };\n }\n const def = INTEGRATIONS[integration];\n if (!def.fields.some((f) => f.key === field)) {\n return { ok: false, error: `unknown field \"${field}\" on integration \"${integration}\"` };\n }\n const defaults = defaultAliasesFor(integration, field);\n const cleaned: string[] = [];\n const seen = new Set<string>(defaults);\n for (const raw of envVars) {\n if (typeof raw !== \"string\") continue;\n const name = raw.trim().toUpperCase();\n if (!name) continue;\n if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) {\n return { ok: false, error: `\"${raw}\" is not a valid env var name` };\n }\n if (seen.has(name)) continue;\n seen.add(name);\n cleaned.push(name);\n }\n if (cleaned.length === 0) {\n deleteMemory(OVERRIDES_NS, OVERRIDE_KEY(integration, field));\n return { ok: true, envVars: [] };\n }\n putMemory(OVERRIDES_NS, OVERRIDE_KEY(integration, field), { envVars: cleaned } satisfies StoredOverride);\n return { ok: true, envVars: cleaned };\n}\n\n/** Drop the override row for one (integration, field). */\nexport function deleteOverride(integration: string, field: string): boolean {\n return deleteMemory(OVERRIDES_NS, OVERRIDE_KEY(integration, field));\n}\n\nfunction defaultAliasesFor(integration: string, field: string): string[] {\n const m = ENV_ALLOWLIST.find((m) => m.integration === integration && m.field === field);\n return m ? [...m.envVars] : [];\n}\n\n// ── Effective allowlist ──────────────────────────────────────────────────────\n\n/**\n * `ENV_ALLOWLIST` merged with stored overrides. Default aliases come first\n * so they keep their priority during sync; user-added aliases are appended\n * after them. The shape is identical to `ENV_ALLOWLIST` so call sites can\n * iterate either one — only `runSync` and `getAllEnvVarNames` need the\n * effective view today.\n */\nexport function getEffectiveAllowlist(): EnvFieldMapping[] {\n const overrides = listOverrides();\n return ENV_ALLOWLIST.map((m) => {\n const extra = overrides[OVERRIDE_KEY(m.integration, m.field)] ?? [];\n if (extra.length === 0) return { ...m, envVars: [...m.envVars] };\n const merged = [...m.envVars];\n const seen = new Set(merged);\n for (const name of extra) {\n if (!seen.has(name)) {\n merged.push(name);\n seen.add(name);\n }\n }\n return { ...m, envVars: merged };\n });\n}\n\n/** Flat list of every env var name we look at — defaults + user overrides. */\nexport function getAllEnvVarNames(): string[] {\n const set = new Set<string>();\n for (const m of getEffectiveAllowlist()) for (const n of m.envVars) set.add(n);\n return [...set];\n}\n\n/**\n * Render the encrypted integration store back into a `Record<envVarName, value>`\n * so subprocesses (MCP children, `local_exec` shells) can read credentials\n * even when they were never exported in the launching shell — e.g. when\n * Jarela is installed as a service. For each `(integration, field)` row in\n * the effective allowlist that has a stored value, every alias name (default\n * + user-added override) is set to that value. The first alias to be\n * inserted wins if two different rows would somehow collide.\n */\nexport function getInjectedSubprocessEnv(): Record<string, string> {\n const out: Record<string, string> = {};\n for (const m of getEffectiveAllowlist()) {\n const value = getIntegrationRaw(m.integration)?.[m.field];\n if (!value) continue;\n for (const name of m.envVars) {\n if (!(name in out)) out[name] = value;\n }\n }\n return out;\n}\n","// Cross-platform discovery of \"shell-defined\" environment variables.\n//\n// The problem: Jarela installed as a macOS LaunchAgent or a Linux systemd\n// user unit doesn't run inside a login shell, so it never sees vars\n// defined in `.zshrc`/`.bashrc`. Windows is the opposite — User-scope\n// vars set via the Settings UI/registry ARE inherited by every process,\n// but vars set only inside a PowerShell `$PROFILE` are not.\n//\n// Strategy:\n// - macOS / Linux: spawn `$SHELL -ic '<print-allowlisted>'`. Sourcing\n// the rc file is the whole point of the `-i` flag. Output is\n// framed with a unique sentinel so user rc echo doesn't poison the\n// parser.\n// - Windows: read the User-scope environment block via\n// `[Environment]::GetEnvironmentVariable($name, 'User')`. This hits\n// the registry directly — no rc-equivalent to source.\n//\n// Always falls back gracefully to whatever is already in `process.env`.\n// Hard 4 s timeout per probe so a hung shell can't stall startup.\n\nimport { spawn } from \"node:child_process\";\nimport { platform } from \"node:os\";\n\nexport type DiscoverySource =\n | \"process\"\n | \"shell-rc\"\n | \"windows-registry\"\n | \"unavailable\";\n\nexport interface DiscoveredEnv {\n values: Record<string, string>;\n source: DiscoverySource;\n /** Path to the shell that ran (unix), or \"powershell\" on Windows. */\n shell: string | null;\n warnings: string[];\n /** Probe wall-time in ms — useful for telemetry / debugging. */\n elapsed_ms: number;\n}\n\nconst TIMEOUT_MS = 4000;\nconst SENTINEL_OPEN = \"__JARELA_ENV_BEGIN__\";\nconst SENTINEL_CLOSE = \"__JARELA_ENV_END__\";\n\n/**\n * Discover values for the given allowlist of env-var names. Always\n * returns; never throws. On platforms or shells we can't probe, falls\n * back to `process.env`.\n */\nexport async function discoverEnvVars(allowlist: readonly string[]): Promise<DiscoveredEnv> {\n const t0 = Date.now();\n const warnings: string[] = [];\n\n // Baseline: whatever the running process already has. On Windows this\n // already includes registry User vars. In dev mode (`npm run dev` from\n // a terminal) it includes the parent shell's exports.\n const fromProcess: Record<string, string> = {};\n for (const name of allowlist) {\n const v = process.env[name];\n if (v && v.trim()) fromProcess[name] = v.trim();\n }\n\n if (platform() === \"win32\") {\n const reg = await queryWindowsUserEnv(allowlist).catch((e: unknown): null => {\n warnings.push(`windows registry probe failed: ${String(e)}`);\n return null;\n });\n if (reg) {\n // Registry wins over process.env: the registry is the *current*\n // truth, while process.env is frozen at process-spawn time. This\n // is what makes rotation pickup work after the user updates a\n // var in the Settings UI without restarting the app.\n return {\n values: { ...fromProcess, ...reg },\n source: \"windows-registry\",\n shell: \"powershell\",\n warnings,\n elapsed_ms: Date.now() - t0,\n };\n }\n return {\n values: fromProcess,\n source: \"process\",\n shell: null,\n warnings,\n elapsed_ms: Date.now() - t0,\n };\n }\n\n // macOS / Linux\n const shell = process.env.SHELL || \"/bin/sh\";\n const fromShell = await queryUnixShellEnv(shell, allowlist).catch((e: unknown): null => {\n warnings.push(`shell rc probe (${shell}) failed: ${String(e)}`);\n return null;\n });\n if (fromShell) {\n return {\n values: { ...fromProcess, ...fromShell },\n source: \"shell-rc\",\n shell,\n warnings,\n elapsed_ms: Date.now() - t0,\n };\n }\n return {\n values: fromProcess,\n source: \"process\",\n shell,\n warnings,\n elapsed_ms: Date.now() - t0,\n };\n}\n\nfunction queryUnixShellEnv(shell: string, allowlist: readonly string[]): Promise<Record<string, string>> {\n return new Promise((resolve, reject) => {\n // Frame each var with sentinels so any noise the user's rc prints\n // (oh-my-zsh banners, version-manager init logs, etc.) gets\n // skipped by the parser. Single-quoted names are JS-side string\n // constants, double-quoted \"$VAR\" lets the shell expand.\n const lines = allowlist\n .map(\n (n) =>\n `printf '${SENTINEL_OPEN}%s=%s${SENTINEL_CLOSE}\\\\n' '${n}' \"$${n}\"`,\n )\n .join(\"; \");\n // Suppress prompts and history side-effects. Pipe stderr to /dev/null\n // — we don't care about rc-emitted warnings.\n const child = spawn(shell, [\"-ic\", lines], {\n env: { ...process.env, PS1: \"\", PROMPT: \"\", HISTFILE: \"/dev/null\" },\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n let stdout = \"\";\n const t = setTimeout(() => {\n child.kill(\"SIGKILL\");\n reject(new Error(\"timeout\"));\n }, TIMEOUT_MS);\n child.stdout.on(\"data\", (b: Buffer) => {\n stdout += b.toString();\n });\n child.on(\"close\", (code: number | null) => {\n clearTimeout(t);\n if (code !== 0 && code !== null) {\n // Some shells return non-zero from `-ic` if rc has any failing\n // command, but our printfs still ran first — try parsing anyway.\n // Only reject if we got nothing usable.\n const parsed = parseSentinelStream(stdout, allowlist);\n if (Object.keys(parsed).length === 0) {\n return reject(new Error(`shell exited ${code} with no parseable output`));\n }\n return resolve(parsed);\n }\n resolve(parseSentinelStream(stdout, allowlist));\n });\n child.on(\"error\", (e: Error) => {\n clearTimeout(t);\n reject(e);\n });\n });\n}\n\nasync function queryWindowsUserEnv(allowlist: readonly string[]): Promise<Record<string, string>> {\n // Try modern PowerShell 7+ (pwsh) first, then fall back to the always-\n // present Windows PowerShell 5.1 (powershell.exe). pwsh defaults to\n // UTF-8 stdout; powershell.exe 5.1 defaults to UTF-16, so we force\n // UTF-8 inside the script either way.\n try {\n return await runWindowsProbe(\"pwsh.exe\", allowlist);\n } catch {\n return await runWindowsProbe(\"powershell.exe\", allowlist);\n }\n}\n\nfunction runWindowsProbe(exe: string, allowlist: readonly string[]): Promise<Record<string, string>> {\n return new Promise((resolve, reject) => {\n const namesArr = allowlist.map((n) => `'${n.replace(/'/g, \"''\")}'`).join(\",\");\n // Force UTF-8 stdout — Windows PowerShell 5.1 emits UTF-16 LE by\n // default, which would garble the sentinel parser. The\n // `[Console]::OutputEncoding` line is a no-op on pwsh 7+ but\n // critical on legacy powershell.exe.\n const script =\n `[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ` +\n `$names = @(${namesArr}); ` +\n `foreach ($n in $names) { ` +\n ` $v = [Environment]::GetEnvironmentVariable($n, 'User'); ` +\n ` if ($v) { Write-Output ('${SENTINEL_OPEN}' + $n + '=' + $v + '${SENTINEL_CLOSE}') } ` +\n `}`;\n const child = spawn(\n exe,\n [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-Command\", script],\n { stdio: [\"ignore\", \"pipe\", \"ignore\"], windowsHide: true },\n );\n let stdout = \"\";\n const t = setTimeout(() => {\n child.kill(\"SIGKILL\");\n reject(new Error(\"timeout\"));\n }, TIMEOUT_MS);\n child.stdout.on(\"data\", (b: Buffer) => {\n stdout += b.toString(\"utf8\");\n });\n child.on(\"close\", (code: number | null) => {\n clearTimeout(t);\n if (code !== 0 && code !== null) return reject(new Error(`${exe} exited ${code}`));\n resolve(parseSentinelStream(stdout, allowlist));\n });\n child.on(\"error\", (e: Error) => {\n clearTimeout(t);\n reject(e);\n });\n });\n}\n\n/**\n * Pull `__OPEN__NAME=VALUE__CLOSE__` segments out of a stream, ignoring\n * everything else. Tolerates rc-line noise and partial reads.\n */\nfunction parseSentinelStream(stream: string, allowlist: readonly string[]): Record<string, string> {\n const allow = new Set(allowlist);\n const out: Record<string, string> = {};\n // Non-greedy, case-sensitive, multi-line capable. Use `split` so we\n // don't depend on regex flags that some Node versions surface oddly.\n const parts = stream.split(SENTINEL_OPEN);\n for (let i = 1; i < parts.length; i += 1) {\n const seg = parts[i];\n const end = seg.indexOf(SENTINEL_CLOSE);\n if (end < 0) continue;\n const body = seg.slice(0, end);\n const eq = body.indexOf(\"=\");\n if (eq <= 0) continue;\n const name = body.slice(0, eq);\n const value = body.slice(eq + 1).trim();\n if (allow.has(name) && value) out[name] = value;\n }\n return out;\n}\n","// Env-sync orchestrator. Reads \"standard\" credential env vars from the\n// user's shell rc (or Windows User registry), writes them into the\n// encrypted integration store, and tracks per-field provenance so user\n// edits in the Integrations panel are never overwritten.\n//\n// Conflict rule: \"panel-wins-once-touched\". A field whose meta source\n// is `\"user\"` is skipped on every sync; one whose source is `\"rc\"` (or\n// absent) gets the rc value written through. This is what makes\n// rotation flow through automatically — the user updates `.zshrc`, the\n// next sync picks it up, the encrypted DB row updates, and the\n// existing env-then-store fallback in `lib/tools/atlassian.ts` /\n// `lib/tools/github.ts` reads the fresh value on the next tool call.\n//\n// Triggered:\n// - Once per process from `lib/db/index.ts` after DB init (silent,\n// fire-and-forget).\n// - On demand via POST /api/v1/env-sync (returns a SyncResult so the\n// UI can show what happened).\n\nimport { getEffectiveAllowlist, getAllEnvVarNames, type EnvFieldMapping } from \"./allowlist\";\nimport { discoverEnvVars, type DiscoveredEnv } from \"./discover\";\nimport {\n INTEGRATIONS,\n getIntegrationRaw,\n isKnownIntegration,\n type IntegrationName,\n} from \"@/lib/stores/integrations\";\nimport { getIntegrationMeta, setFieldSources, type FieldSource } from \"@/lib/stores/integration_meta\";\nimport { putMemory } from \"@/lib/stores/memory\";\n\nconst INTEGRATIONS_NS = \"integrations\";\n\nexport type SyncAction =\n | \"would-write\" // candidate is eligible, will (or did) overwrite\n | \"skipped-user\" // user has touched this field — leave it alone\n | \"skipped-equal\" // rc value matches what's already stored\n | \"skipped-empty\" // env var was set but empty after trim\n | \"absent\"; // env var not set in any allowlist alias\n\nexport interface SyncCandidate {\n /** Which env var name actually held the value (first present alias). */\n envVar: string | null;\n integration: string;\n field: string;\n /** Current meta source for this field — what's in the DB right now. */\n current_source: FieldSource | \"absent\";\n current_value_present: boolean;\n /** Masked preview of the rc value (full value for non-secret fields). */\n rc_value_preview: string | null;\n action: SyncAction;\n}\n\nexport interface SyncResult {\n discovered: DiscoveredEnv;\n candidates: SyncCandidate[];\n /** Subset of `candidates` where action === \"would-write\" and apply=true. */\n applied_count: number;\n ts: string;\n}\n\n/** Public — non-mutating; lets the UI show what *would* happen. */\nexport async function previewEnvSync(): Promise<SyncResult> {\n return runSync(false);\n}\n\n/** Public — mutates the DB (writes \"rc\"-sourced fields). */\nexport async function applyEnvSync(): Promise<SyncResult> {\n return runSync(true);\n}\n\n// Module-level guard so we run at most once per process from the\n// fire-and-forget startup hook. The on-demand API endpoint bypasses\n// this and re-runs every call.\nlet _bootRanPromise: Promise<SyncResult> | null = null;\n\n/**\n * Idempotent boot-time apply. First call kicks off; subsequent calls\n * within the same process return the same promise. Errors are\n * swallowed (logged) — env-sync is best-effort, never blocks startup.\n */\nexport function runEnvSyncOnce(): Promise<SyncResult | null> {\n if (_bootRanPromise) return _bootRanPromise.catch(() => null);\n _bootRanPromise = applyEnvSync();\n return _bootRanPromise.catch((err) => {\n console.warn(\"[jarela/env-sync] boot apply failed:\", err);\n return null;\n });\n}\n\nasync function runSync(apply: boolean): Promise<SyncResult> {\n const discovered = await discoverEnvVars(getAllEnvVarNames());\n const ts = new Date().toISOString();\n const candidates: SyncCandidate[] = [];\n\n // Group writes by integration so we issue one putMemory per row.\n const writesByIntegration = new Map<string, Record<string, string>>();\n const metaUpdates: Array<{ name: string; field: string; source: FieldSource }> = [];\n\n for (const m of getEffectiveAllowlist()) {\n if (!isKnownIntegration(m.integration)) continue; // allowlist drift; ignore\n const cand = evaluateCandidate(m, discovered.values);\n candidates.push(cand);\n\n if (apply && cand.action === \"would-write\") {\n const existing = getIntegrationRaw(m.integration) ?? {};\n const w = writesByIntegration.get(m.integration) ?? { ...existing };\n const value = pickEnvValue(m, discovered.values);\n if (value !== null) w[m.field] = value;\n writesByIntegration.set(m.integration, w);\n metaUpdates.push({ name: m.integration, field: m.field, source: \"rc\" });\n }\n }\n\n let applied_count = 0;\n if (apply && writesByIntegration.size > 0) {\n for (const [name, fields] of writesByIntegration) {\n putMemory(INTEGRATIONS_NS, name, fields);\n }\n setFieldSources(metaUpdates, ts);\n applied_count = metaUpdates.length;\n }\n\n return { discovered, candidates, applied_count, ts };\n}\n\nfunction evaluateCandidate(\n m: EnvFieldMapping,\n values: Record<string, string>,\n): SyncCandidate {\n const envVar = m.envVars.find((n) => values[n]) ?? null;\n const rcValue = envVar ? values[envVar] : null;\n const meta = getIntegrationMeta(m.integration);\n const sourceFlag = meta.source[m.field];\n const existing = getIntegrationRaw(m.integration);\n const currentValue = existing?.[m.field] ?? null;\n const currentSource: SyncCandidate[\"current_source\"] = sourceFlag ?? \"absent\";\n const isSecret = isFieldSecret(m.integration, m.field);\n\n let action: SyncAction;\n if (envVar === null || rcValue === null) {\n action = \"absent\";\n } else if (sourceFlag === \"user\") {\n action = \"skipped-user\";\n } else if (!rcValue.trim()) {\n action = \"skipped-empty\";\n } else if (currentValue === rcValue) {\n action = \"skipped-equal\";\n } else {\n action = \"would-write\";\n }\n\n return {\n envVar,\n integration: m.integration,\n field: m.field,\n current_source: currentSource,\n current_value_present: !!currentValue,\n rc_value_preview: rcValue ? maskValue(rcValue, isSecret) : null,\n action,\n };\n}\n\nfunction pickEnvValue(m: EnvFieldMapping, values: Record<string, string>): string | null {\n for (const n of m.envVars) {\n const v = values[n];\n if (v && v.trim()) return v.trim();\n }\n return null;\n}\n\nfunction isFieldSecret(integration: IntegrationName, field: string): boolean {\n const def = INTEGRATIONS[integration];\n return def.fields.find((f) => f.key === field)?.secret ?? true;\n}\n\nfunction maskValue(value: string, isSecret: boolean): string {\n if (!isSecret) return value;\n if (value.length <= 6) return \"***\";\n return value.slice(0, 4) + \"…\" + value.slice(-2);\n}\n","// Sensitive namespaces in `memory_store` whose `value` column holds\n// secret material that must be encrypted at rest (ADR-0005).\n//\n// Centralised here so stores and the migration agree on the same list.\n\nexport const SENSITIVE_MEMORY_NAMESPACES: ReadonlySet<string> = new Set([\n \"integrations\", // Atlassian / Gmail OAuth / Gemini keys\n \"github-copilot-auth\", // GitHub Copilot device-flow OAuth token\n \"tool-secrets\", // Secrets for external tools (ADR-0023)\n]);\n\nexport function isSensitiveMemoryNamespace(ns: string): boolean {\n return SENSITIVE_MEMORY_NAMESPACES.has(ns);\n}\n","// Resolves the Jarela data directory and performs one-time migrations:\n//\n// 1. Legacy LangGUI layout (~/.langgui with langgui.db) — rebrand\n// migration: rename the dir + the DB files.\n// 2. On Windows, ~/.jarela → %LOCALAPPDATA%\\Jarela (ADR-0006) to escape\n// OneDrive-synced user-profile paths.\n//\n// No backward-compat for env vars is retained at the code level; both\n// migrations are best-effort renames on first launch against a populated\n// machine so existing users keep their data.\n\nimport { existsSync, mkdirSync, renameSync, readdirSync, rmdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nlet cached: string | null = null;\n\nfunction expandHome(p: string): string {\n return p.startsWith(\"~\") ? p.replace(/^~/, homedir()) : p;\n}\n\n// A dir \"has DB\" iff it contains jarela.db OR langgui.db. We treat the\n// presence of a DB as the signal that the dir holds real user state;\n// otherwise it may just be a vestigial launcher working dir\n// (e.g. %LOCALAPPDATA%\\Jarela created by installed-launcher.vbs with\n// only files/ and logs/ inside).\nfunction hasDb(dir: string): boolean {\n if (!existsSync(dir)) return false;\n try {\n return readdirSync(dir).some((n) => n === \"jarela.db\" || n === \"langgui.db\");\n } catch {\n return false;\n }\n}\n\nfunction migrateLegacyDir(legacyDir: string, newDir: string): void {\n if (!existsSync(legacyDir)) return;\n if (hasDb(newDir)) return; // new dir already has user state — never overwrite.\n\n mkdirSync(newDir, { recursive: true });\n\n // Move contents item-by-item so we can merge into a partially-existing\n // newDir (e.g. one containing only logs/ from a prior launcher run).\n // Skips items that already exist on the destination side.\n let entries: string[] = [];\n try { entries = readdirSync(legacyDir); } catch { entries = []; }\n\n let moved = 0;\n for (const name of entries) {\n const from = join(legacyDir, name);\n const to = join(newDir, name);\n if (existsSync(to)) continue;\n try {\n renameSync(from, to);\n moved++;\n } catch (err) {\n // EXDEV: cross-volume rename. EPERM/EBUSY: locked by another\n // process. Non-fatal: skip this item and continue with the rest.\n console.warn(\n `[jarela] could not move ${from} -> ${to}: ${(err as Error).message}`,\n );\n }\n }\n\n // Rename DB files: langgui.db -> jarela.db (and any -wal / -shm sidecars).\n let postEntries: string[] = [];\n try { postEntries = readdirSync(newDir); } catch { postEntries = []; }\n for (const name of postEntries) {\n if (!name.startsWith(\"langgui.db\")) continue;\n const suffix = name.slice(\"langgui.db\".length); // \"\", \"-wal\", \"-shm\", \"-journal\"\n const from = join(newDir, name);\n const to = join(newDir, `jarela.db${suffix}`);\n if (existsSync(to)) continue;\n try { renameSync(from, to); } catch { /* leave as-is; DB layer recreates */ }\n }\n\n // Best-effort cleanup of an emptied legacy dir. If anything remained\n // (locked files, dotfiles we declined to move) leave the dir in place.\n try {\n if (readdirSync(legacyDir).length === 0) {\n rmdirSync(legacyDir);\n }\n } catch { /* */ }\n\n if (moved > 0) {\n console.info(`[jarela] migrated ${moved} entries from ${legacyDir} -> ${newDir}`);\n }\n}\n\nexport function getDataDir(): string {\n if (cached) return cached;\n\n const envDir = process.env.JARELA_DB_DIR;\n const newDir = envDir ? expandHome(envDir) : defaultDataDir();\n\n // Only run automatic migrations for the default location; if the user\n // customized JARELA_DB_DIR they're explicitly opting out.\n if (!envDir) {\n // Chain order matters: rebrand first so a ~/.langgui from the old\n // build lands at ~/.jarela, then the Windows-only move lifts that to\n // %LOCALAPPDATA%\\Jarela in the same boot.\n migrateLegacyDir(join(homedir(), \".langgui\"), join(homedir(), \".jarela\"));\n if (process.platform === \"win32\" && newDir !== join(homedir(), \".jarela\")) {\n migrateLegacyDir(join(homedir(), \".jarela\"), newDir);\n }\n }\n\n mkdirSync(newDir, { recursive: true });\n cached = newDir;\n return newDir;\n}\n\nfunction defaultDataDir(): string {\n if (process.platform === \"win32\") {\n const local = process.env.LOCALAPPDATA ?? join(homedir(), \"AppData\", \"Local\");\n return join(local, \"Jarela\");\n }\n return join(homedir(), \".jarela\");\n}\n","// macOS keychain → PEM bundle export (ADR-0020).\n//\n// macOS hosts behind a TLS-intercepting corporate proxy receive the\n// internal root (used by the proxy to re-sign outbound TLS) via MDM or\n// manual install, which lands it in the System and Login keychains. We\n// extract those certs to a single\n// PEM file under the Jarela data dir, then point both undici's\n// `requestTls.ca` (live) and the launchd plist's `NODE_EXTRA_CA_CERTS`\n// (next restart) at it. End result: one source of truth (the OS), one\n// destination (~/.jarela/system-ca.pem), zero manual paste.\n//\n// Sibling to `parseScutilProxy()` in dispatcher.ts — both turn an OS-level\n// settings surface into something the dispatcher can consume.\n\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync, writeFileSync, chmodSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { getDataDir } from \"@/lib/db/data-dir\";\n\nexport interface KeychainExtractResult {\n pemPath: string; // absolute path to the written bundle\n certCount: number; // unique BEGIN CERTIFICATE blocks\n source: \"macos-keychain\";\n keychains: string[]; // which keychains contributed\n}\n\nconst KEYCHAINS_TO_TRY = [\n \"/Library/Keychains/System.keychain\",\n \"/System/Library/Keychains/SystemRootCertificates.keychain\",\n // login.keychain-db lives under each user's home; resolved at runtime.\n];\n\nconst PEM_BLOCK_RE = /-----BEGIN CERTIFICATE-----[\\s\\S]+?-----END CERTIFICATE-----/g;\n\n// Exported for unit testing — the bare parser side, no fs / spawn.\n// Returns deduped PEM blocks in first-seen order so callers can attribute\n// \"this cert came from system\" vs \"from login\".\nexport function parseSecurityFindCertificate(stdout: string): string[] {\n const seen = new Set<string>();\n const blocks: string[] = [];\n const matches = stdout.match(PEM_BLOCK_RE) ?? [];\n for (const raw of matches) {\n // Normalise line endings so a CR-different copy of the same cert\n // doesn't slip past the dedupe.\n const normalised = raw.replace(/\\r\\n/g, \"\\n\").trim();\n if (seen.has(normalised)) continue;\n seen.add(normalised);\n blocks.push(normalised);\n }\n return blocks;\n}\n\n// Extract all certificates from the user's macOS trust stores into a\n// single PEM bundle at <dataDir>/system-ca.pem. Returns the path + count.\n//\n// On non-darwin platforms returns { error } — callers should treat this\n// as \"no system trust available, proceed without an injected bundle\".\nexport function extractSystemKeychainCAs(): KeychainExtractResult | { error: string } {\n if (process.platform !== \"darwin\") {\n return { error: \"system trust extraction is macOS-only in v1\" };\n }\n\n const candidates = [...KEYCHAINS_TO_TRY, join(homedir(), \"Library/Keychains/login.keychain-db\")];\n const used: string[] = [];\n const allPem: string[] = [];\n\n for (const kc of candidates) {\n if (!existsSync(kc)) continue;\n try {\n // -a = all matches, -p = output PEM. The path positional arg\n // restricts the search to this keychain. Fixed argv (no shell)\n // — safe even though no part of this is user-controlled.\n const out = execFileSync(\n \"/usr/bin/security\",\n [\"find-certificate\", \"-a\", \"-p\", kc],\n { encoding: \"utf8\", maxBuffer: 16 * 1024 * 1024 },\n );\n const blocks = parseSecurityFindCertificate(out);\n if (blocks.length > 0) {\n used.push(kc);\n allPem.push(...blocks);\n }\n } catch (err) {\n // Empty keychain or permission refusal — skip and continue.\n // We still want partial extraction (system but not login, etc.)\n // to succeed.\n console.warn(`[jarela/keychain] could not read ${kc}: ${(err as Error).message}`);\n }\n }\n\n // Dedupe across keychains: the same root commonly appears in System\n // and SystemRootCertificates.\n const deduped = parseSecurityFindCertificate(allPem.join(\"\\n\"));\n\n if (deduped.length === 0) {\n return { error: \"no certificates extracted from any keychain (security find-certificate returned empty)\" };\n }\n\n const pemPath = join(getDataDir(), \"system-ca.pem\");\n const body =\n `# Jarela system trust bundle — generated from macOS keychains.\\n` +\n `# Source keychains: ${used.join(\", \")}\\n` +\n `# ${deduped.length} unique certificates. Regenerate via the Proxy panel\\n` +\n `# \"Refresh trust store\" button, or by re-running 'jarela install-service'.\\n\\n` +\n deduped.join(\"\\n\") +\n \"\\n\";\n writeFileSync(pemPath, body, \"utf8\");\n // Trust bundle is not secret but is user-scoped state; 0600 keeps it\n // tidy alongside the SQLite file's permissions.\n try { chmodSync(pemPath, 0o600); } catch { /* best-effort */ }\n\n return {\n pemPath,\n certCount: deduped.length,\n source: \"macos-keychain\",\n keychains: used,\n };\n}\n","// HTTP proxy dispatcher (ADR-0009).\n//\n// Routes every undici-backed `fetch` in the server through an HTTP proxy\n// when one is configured, so corporate-network installs reach LLM\n// providers, MCP servers, and integration APIs.\n//\n// Two configuration sources, in priority order:\n// 1. process.env.HTTP_PROXY / HTTPS_PROXY / NO_PROXY (and their\n// lowercase aliases). Captured at process start so a later DB\n// change cannot accidentally override an explicit env override.\n// 2. proxy_config row in SQLite. Read after DB init via\n// applyProxyConfigFromDb(); re-applied from the settings save\n// handler so changes take effect without a server restart.\n//\n// All paths funnel through `setGlobalDispatcher` so existing call sites\n// (providers, tools, MCP, embeddings) inherit the dispatcher at fetch\n// time. SDK clients are constructed per-call inside provider methods so\n// the next outbound request after a swap picks up the new proxy\n// immediately (see ADR-0009 \"Live-swap caveats\" for the two narrow\n// exceptions: in-flight long-lived streams and child-process MCP\n// servers).\n\nimport { exec } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { promisify } from \"node:util\";\nimport {\n Agent,\n EnvHttpProxyAgent,\n ProxyAgent,\n getGlobalDispatcher,\n setGlobalDispatcher,\n type Dispatcher,\n} from \"undici\";\nimport { getProxyConfigRaw, type ProxyConfigRaw, type ProxyScheme } from \"@/lib/stores/proxy-config\";\nimport { extractSystemKeychainCAs } from \"@/lib/proxy/keychain\";\n\nconst execAsync = promisify(exec);\n\n// Snapshot of HTTP proxy env vars at module load. If the user set them\n// before launch (terminal session, plist EnvironmentVariables, …) we\n// honor that and ignore the DB config. This preserves the documented\n// override path: env > DB.\nconst ENV_HAD_PROXY_AT_BOOT = !!(\n process.env.HTTP_PROXY ||\n process.env.HTTPS_PROXY ||\n process.env.http_proxy ||\n process.env.https_proxy\n);\n\nlet baselineDispatcher: Dispatcher | null = null;\nlet envInstalled = false;\n\n// ---------------------------------------------------------------------\n// Synchronous boot-time setup\n// ---------------------------------------------------------------------\n// Runs at module import (before DB init). Installs the env-var-based\n// dispatcher synchronously so any keychain / migration path that does\n// outbound HTTP from boot can use the proxy. The DB-based layer applies\n// later via applyProxyConfigFromDb().\nexport function ensureProxyDispatcher(): void {\n if (envInstalled) return;\n envInstalled = true;\n // Capture whatever undici initialized as the default so we can revert\n // to it when the user picks `mode = off` and there are no env vars.\n baselineDispatcher = getGlobalDispatcher();\n if (ENV_HAD_PROXY_AT_BOOT) {\n setGlobalDispatcher(new EnvHttpProxyAgent());\n }\n}\n\nensureProxyDispatcher();\n\n// ---------------------------------------------------------------------\n// Async DB-backed apply\n// ---------------------------------------------------------------------\n\nexport interface ApplyResult {\n source: \"env\" | \"manual\" | \"system\" | \"off\";\n proxyUrl: string | null;\n note?: string;\n // ADR-0020: system mode also auto-extracts the macOS keychain trust\n // store into a managed PEM file. Surfaced so the UI can show\n // \"System trust: 187 certs from ~/.jarela/system-ca.pem\".\n caBundlePath?: string;\n caBundleCertCount?: number;\n caBundleSource?: \"macos-keychain\";\n}\n\n// Reads the DB row and reconciles with env vars. Idempotent and safe to\n// call after every settings save. Returns a small descriptor that the\n// settings save handler can echo back to the UI.\nexport async function applyProxyConfigFromDb(): Promise<ApplyResult> {\n if (ENV_HAD_PROXY_AT_BOOT) {\n return {\n source: \"env\",\n proxyUrl: null,\n note: \"Honoring HTTPS_PROXY env var; in-app proxy config is ignored while it is set.\",\n };\n }\n\n let cfg: ProxyConfigRaw | null = null;\n try {\n cfg = getProxyConfigRaw();\n } catch (err) {\n // Migration ordering safety net: if proxy_config table doesn't exist\n // yet (older DB about to be migrated), fall back to no-proxy.\n console.warn(\"[jarela/proxy] could not read proxy_config:\", err);\n }\n\n if (!cfg || cfg.mode === \"off\") {\n resetToBaseline();\n return { source: \"off\", proxyUrl: null };\n }\n\n if (cfg.mode === \"manual\") {\n if (!cfg.host || !cfg.port) {\n resetToBaseline();\n return { source: \"off\", proxyUrl: null, note: \"manual mode missing host/port; reverted to no proxy\" };\n }\n const url = buildProxyUrl(cfg.scheme, cfg.host, cfg.port, cfg.username, cfg.password);\n installProxy(url, cfg.no_proxy, cfg.ca_bundle);\n return { source: \"manual\", proxyUrl: redactAuth(url) };\n }\n\n if (cfg.mode === \"system\") {\n // ADR-0020: in `system` mode the OS is the source of truth for both\n // proxy URL (System Preferences → Network → Proxies, via scutil) AND\n // trust store (System + Login keychains, via `security`). Extract\n // the keychain bundle every apply so MDM-pushed cert rotations land\n // without manual intervention.\n const trust = extractSystemKeychainCAs();\n let caBundleText: string | null = cfg.ca_bundle; // user-pasted override, if any\n let caBundlePath: string | undefined;\n let caBundleCertCount: number | undefined;\n let caBundleSource: \"macos-keychain\" | undefined;\n if (!(\"error\" in trust)) {\n try {\n caBundleText = readFileSync(trust.pemPath, \"utf8\");\n caBundlePath = trust.pemPath;\n caBundleCertCount = trust.certCount;\n caBundleSource = trust.source;\n } catch (err) {\n console.warn(\"[jarela/proxy] could not read extracted keychain bundle:\", err);\n }\n } else {\n // Non-fatal: fall back to whatever the user pasted into the UI,\n // or to no bundle if they didn't.\n console.info(`[jarela/proxy] keychain extraction skipped: ${trust.error}`);\n }\n\n const detected = await detectSystemProxy();\n if (!detected) {\n // No HTTPS proxy at the OS level (common when macOS uses a PAC URL\n // — scutil reports ProxyAutoConfigEnable=1 but HTTPSEnable=0 — or\n // when an on-host steering agent like Zscaler/Netskope handles\n // egress transparently). If we extracted a keychain bundle, apply\n // it to a direct-egress dispatcher so TLS interception by the\n // on-host agent still validates against the corporate root.\n if (caBundleText) {\n installDirectWithCa(caBundleText);\n return {\n source: \"off\",\n proxyUrl: null,\n note: caBundleSource\n ? `scutil --proxy reported no HTTPS proxy (likely PAC or on-host agent); applied ${caBundleCertCount} keychain CAs to direct-egress TLS so on-host MITM validates.`\n : \"scutil --proxy reported no HTTPS proxy; using direct connection\",\n caBundlePath,\n caBundleCertCount,\n caBundleSource,\n };\n }\n resetToBaseline();\n return {\n source: \"off\",\n proxyUrl: null,\n note:\n process.platform === \"darwin\"\n ? \"scutil --proxy reported no HTTPS proxy; using direct connection\"\n : \"system mode is macOS-only in v1; using direct connection\",\n caBundlePath,\n caBundleCertCount,\n caBundleSource,\n };\n }\n // scutil only reports host/port — the proxy hop is plain http.\n const url = buildProxyUrl(\"http\", detected.host, detected.port, null, null);\n installProxy(url, cfg.no_proxy, caBundleText);\n return {\n source: \"system\",\n proxyUrl: redactAuth(url),\n note: caBundleSource\n ? `Imported ${caBundleCertCount} CAs from macOS keychain → ${caBundlePath}. Restart the service for non-undici code paths to pick up the new trust store.`\n : undefined,\n caBundlePath,\n caBundleCertCount,\n caBundleSource,\n };\n }\n\n resetToBaseline();\n return { source: \"off\", proxyUrl: null };\n}\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nfunction buildProxyUrl(\n scheme: ProxyScheme,\n host: string,\n port: number,\n username: string | null,\n password: string | null,\n): string {\n const auth = username\n ? `${encodeURIComponent(username)}${password ? `:${encodeURIComponent(password)}` : \"\"}@`\n : \"\";\n return `${scheme}://${auth}${host}:${port}`;\n}\n\nfunction installProxy(url: string, noProxy: string | null, caBundle: string | null): void {\n // Set process.env so EnvHttpProxyAgent honors NO_PROXY semantics\n // (per-host bypass) without us reimplementing the matching logic.\n // We still treat the boot-time env snapshot as authoritative for the\n // \"env beats DB\" rule — this mutation only happens after we've\n // confirmed the user did NOT set HTTP_PROXY at launch.\n process.env.HTTP_PROXY = url;\n process.env.HTTPS_PROXY = url;\n if (noProxy && noProxy.trim().length > 0) {\n process.env.NO_PROXY = noProxy.trim();\n } else {\n delete process.env.NO_PROXY;\n }\n // ADR-0012: when the user pasted a corporate root CA, inject it on\n // both TLS legs — the proxy hop (proxyTls) for https-scheme proxies\n // signed by the corporate root, and the upstream tunnel (requestTls)\n // for proxies that MITM outbound HTTPS with the same internal CA.\n // Same blob is correct: the corporate trust chain typically signs\n // both ends.\n const opts = caBundle\n ? { requestTls: { ca: caBundle }, proxyTls: { ca: caBundle } }\n : {};\n setGlobalDispatcher(new EnvHttpProxyAgent(opts));\n}\n\nfunction resetToBaseline(): void {\n if (ENV_HAD_PROXY_AT_BOOT) return; // never tear down a user-set env proxy\n delete process.env.HTTP_PROXY;\n delete process.env.HTTPS_PROXY;\n delete process.env.NO_PROXY;\n if (baselineDispatcher) setGlobalDispatcher(baselineDispatcher);\n}\n\n// ADR-0020 follow-up: install a direct-egress dispatcher whose TLS trust\n// store includes the supplied CA bundle. Used when the OS reports no\n// HTTPS proxy (e.g. macOS PAC, or no proxy at all) but on-host agents\n// (Zscaler ZIA, Netskope SteeringAgent, Cisco Umbrella, GlobalProtect)\n// still intercept and re-sign outbound TLS with an internal root.\n// Without this, `mode=system` extracts a useful bundle but never applies\n// it to direct-egress code paths and the user gets\n// UNABLE_TO_GET_ISSUER_CERT_LOCALLY despite a green \"242 certs\" status.\nfunction installDirectWithCa(caBundle: string): void {\n // Clear proxy env so EnvHttpProxyAgent isn't re-summoned by some other\n // import path; we want unambiguous direct egress with custom trust.\n delete process.env.HTTP_PROXY;\n delete process.env.HTTPS_PROXY;\n delete process.env.NO_PROXY;\n setGlobalDispatcher(new Agent({ connect: { ca: caBundle } }));\n}\n\nfunction redactAuth(url: string): string {\n try {\n const u = new URL(url);\n if (u.password) u.password = \"***\";\n return u.toString();\n } catch {\n return url;\n }\n}\n\n// ---------------------------------------------------------------------\n// macOS scutil --proxy parser\n// ---------------------------------------------------------------------\n// Output is a heredoc-style block of `key : value` lines, one section\n// per network service. We only care about the HTTPS bag.\n\ninterface DetectedProxy {\n host: string;\n port: number;\n}\n\nasync function detectSystemProxy(): Promise<DetectedProxy | null> {\n if (process.platform !== \"darwin\") return null;\n try {\n const { stdout } = await execAsync(\"scutil --proxy\", { timeout: 3_000 });\n return parseScutilProxy(stdout);\n } catch (err) {\n console.warn(\"[jarela/proxy] scutil --proxy failed:\", err);\n return null;\n }\n}\n\n// Exported for unit-test use. Parses the relevant fields out of\n// `scutil --proxy` stdout. Returns null when HTTPSEnable is 0 or the\n// host/port pair is missing.\nexport function parseScutilProxy(output: string): DetectedProxy | null {\n const fields = new Map<string, string>();\n for (const raw of output.split(\"\\n\")) {\n const line = raw.trim();\n const m = /^([A-Za-z0-9]+)\\s*:\\s*(.+?)\\s*$/.exec(line);\n if (!m) continue;\n // Only the first occurrence of each key is meaningful — later\n // sections (FTP, SOCKS, …) reuse some names.\n if (!fields.has(m[1])) fields.set(m[1], m[2]);\n }\n if (fields.get(\"HTTPSEnable\") !== \"1\") return null;\n const host = fields.get(\"HTTPSProxy\");\n const portStr = fields.get(\"HTTPSPort\");\n if (!host || !portStr) return null;\n const port = Number.parseInt(portStr, 10);\n if (!Number.isFinite(port) || port <= 0 || port > 65535) return null;\n return { host, port };\n}\n\n// Test-only / diagnostics export: was an env-var proxy set at boot?\nexport function envProxyWasSetAtBoot(): boolean {\n return ENV_HAD_PROXY_AT_BOOT;\n}\n","export type MbtiType =\n | \"INTJ\" | \"INTP\" | \"ENTJ\" | \"ENTP\"\n | \"INFJ\" | \"INFP\" | \"ENFJ\" | \"ENFP\"\n | \"ISTJ\" | \"ISFJ\" | \"ESTJ\" | \"ESFJ\"\n | \"ISTP\" | \"ISFP\" | \"ESTP\" | \"ESFP\";\n\nexport interface MbtiPreset {\n label: string;\n strength: number;\n empathy: number;\n expressiveness: number;\n verbosity: number;\n}\n\n// Presets are intentionally conservative: they shape tone while leaving\n// truthfulness and execution behavior to core agent policies.\nexport const MBTI_PRESETS: Record<MbtiType, MbtiPreset> = {\n INTJ: { label: \"Architect\", strength: 55, empathy: 35, expressiveness: 30, verbosity: 45 },\n INTP: { label: \"Logician\", strength: 50, empathy: 35, expressiveness: 30, verbosity: 55 },\n ENTJ: { label: \"Commander\", strength: 65, empathy: 30, expressiveness: 45, verbosity: 40 },\n ENTP: { label: \"Debater\", strength: 60, empathy: 40, expressiveness: 60, verbosity: 50 },\n\n INFJ: { label: \"Advocate\", strength: 55, empathy: 75, expressiveness: 50, verbosity: 55 },\n INFP: { label: \"Mediator\", strength: 50, empathy: 80, expressiveness: 55, verbosity: 60 },\n ENFJ: { label: \"Protagonist\", strength: 65, empathy: 80, expressiveness: 70, verbosity: 55 },\n ENFP: { label: \"Campaigner\", strength: 60, empathy: 75, expressiveness: 75, verbosity: 60 },\n\n ISTJ: { label: \"Logistician\", strength: 50, empathy: 30, expressiveness: 25, verbosity: 40 },\n ISFJ: { label: \"Defender\", strength: 50, empathy: 70, expressiveness: 40, verbosity: 50 },\n ESTJ: { label: \"Executive\", strength: 60, empathy: 35, expressiveness: 45, verbosity: 40 },\n ESFJ: { label: \"Consul\", strength: 60, empathy: 80, expressiveness: 65, verbosity: 50 },\n\n ISTP: { label: \"Virtuoso\", strength: 50, empathy: 30, expressiveness: 30, verbosity: 35 },\n ISFP: { label: \"Adventurer\", strength: 50, empathy: 65, expressiveness: 55, verbosity: 45 },\n ESTP: { label: \"Entrepreneur\", strength: 60, empathy: 40, expressiveness: 70, verbosity: 40 },\n ESFP: { label: \"Entertainer\", strength: 60, empathy: 70, expressiveness: 80, verbosity: 50 },\n};\n\nexport const MBTI_TYPES: MbtiType[] = Object.keys(MBTI_PRESETS) as MbtiType[];\n","import OpenAI from \"openai\";\nimport type { ContentPart } from \"@/lib/tools/types\";\nimport type {\n ModelProvider,\n ProviderMessage,\n ProviderParams,\n ProviderStreamResult,\n ProviderStreamEvent,\n InvokeMessage,\n InvokeResult,\n OpenAITool,\n} from \"./types\";\n\nfunction pickOpenAICompatOptions(params: ProviderParams): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const p = params as Record<string, unknown>;\n const keys = [\n \"top_p\",\n \"presence_penalty\",\n \"frequency_penalty\",\n \"stop\",\n \"response_format\",\n \"logprobs\",\n \"top_logprobs\",\n \"reasoning_effort\",\n \"thinking\",\n \"stream_options\",\n \"user\",\n \"user_id\",\n ];\n for (const k of keys) {\n if (p[k] !== undefined) out[k] = p[k];\n }\n return out;\n}\n\nfunction makeClient(\n params: ProviderParams,\n baseURL?: string,\n extraHeaders?: Record<string, string>,\n): OpenAI {\n return new OpenAI({\n apiKey: params.api_key ?? process.env.OPENAI_API_KEY,\n baseURL: params.base_url ?? baseURL,\n defaultHeaders: { ...params.extra_headers, ...extraHeaders },\n });\n}\n\n// Convert ContentPart[] to OpenAI multipart content\nfunction toOpenAIContent(\n content: string | ContentPart[],\n): string | OpenAI.Chat.ChatCompletionContentPart[] {\n if (typeof content === \"string\") return content;\n return content.map((part): OpenAI.Chat.ChatCompletionContentPart => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n if (part.type === \"image\") {\n return {\n type: \"image_url\",\n image_url: { url: `data:${part.media_type};base64,${part.data}` },\n };\n }\n // Files rendered as text for OpenAI\n return { type: \"text\", text: `[File: ${(part as ContentPart & { type: \"file\" }).name}]\\n${part.data}` };\n });\n}\n\nfunction toOpenAIMessages(\n messages: InvokeMessage[],\n): OpenAI.Chat.ChatCompletionMessageParam[] {\n return messages.map((m) => {\n if (m.role === \"tool\") {\n return { role: \"tool\", tool_call_id: m.tool_call_id!, content: String(m.content) };\n }\n if (m.role === \"assistant\") {\n const msg: OpenAI.Chat.ChatCompletionAssistantMessageParam & { reasoning_content?: string } = {\n role: \"assistant\",\n content: typeof m.content === \"string\" ? m.content : null,\n tool_calls: m.tool_calls as OpenAI.Chat.ChatCompletionMessageToolCall[] | undefined,\n };\n // DeepSeek's reasoning models reject follow-up requests that omit the\n // assistant's prior reasoning_content. The OpenAI SDK's type doesn't\n // know about this field, but the underlying HTTP body forwards it.\n if (m.reasoning_content) msg.reasoning_content = m.reasoning_content;\n return msg as OpenAI.Chat.ChatCompletionAssistantMessageParam;\n }\n return {\n role: m.role as \"system\" | \"user\",\n content: toOpenAIContent(m.content),\n } as OpenAI.Chat.ChatCompletionMessageParam;\n });\n}\n\n// Re-export so other OpenAI-compatible providers (github-copilot, etc.) can\n// share the same ContentPart -> wire-format conversion instead of casting\n// raw InvokeMessage shapes that the OpenAI SDK then rejects for images/files.\nexport { toOpenAIContent, toOpenAIMessages };\n\ntype OpenAIStreamDelta = {\n content?: string | null;\n reasoning_content?: string | null;\n tool_calls?: Array<{ index?: number; id?: string; function?: { name?: string; arguments?: string } }>;\n};\n\ntype OpenAIStreamChoice = {\n delta?: OpenAIStreamDelta;\n finish_reason?: string | null;\n};\n\ntype OpenAIInvokeChoice = {\n message?: {\n content?: string | null;\n tool_calls?: Array<{ type?: string; id?: string; function?: { name?: string; arguments?: string } }>;\n };\n finish_reason?: string | null;\n};\n\nfunction parseStopReason(reason: string | null | undefined): InvokeResult[\"stop_reason\"] {\n if (reason === \"tool_calls\") return \"tool_use\";\n if (reason === \"length\") return \"length\";\n return \"stop\";\n}\n\nexport function parseOpenAIInvokeChoice(choice: OpenAIInvokeChoice): InvokeResult {\n return {\n text: choice.message?.content ?? null,\n tool_calls: (choice.message?.tool_calls ?? []).flatMap((tc) => {\n if (tc?.type !== \"function\" || !tc.function?.name) return [];\n return [{\n id: tc.id ?? \"\",\n name: tc.function.name,\n arguments: (() => {\n try {\n return JSON.parse(tc.function.arguments ?? \"{}\") as Record<string, unknown>;\n } catch {\n return {};\n }\n })(),\n }];\n }),\n stop_reason: parseStopReason(choice.finish_reason),\n };\n}\n\nexport async function* streamOpenAIEvents(\n stream: AsyncIterable<{\n choices?: OpenAIStreamChoice[];\n usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null;\n }>,\n): AsyncIterable<ProviderStreamEvent> {\n for await (const chunk of stream) {\n if (chunk.usage) {\n yield {\n type: \"usage\",\n input_tokens: chunk.usage.prompt_tokens,\n output_tokens: chunk.usage.completion_tokens,\n total_tokens: chunk.usage.total_tokens,\n };\n }\n const choice = chunk.choices?.[0];\n if (!choice) continue;\n const delta = choice.delta;\n if (!delta) continue;\n if (delta.content) yield { type: \"text\", delta: delta.content };\n if (typeof delta.reasoning_content === \"string\" && delta.reasoning_content) {\n yield { type: \"thinking\", delta: delta.reasoning_content };\n }\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n yield {\n type: \"tool_call_chunk\",\n index: tc.index ?? 0,\n id: tc.id,\n name: tc.function?.name,\n args_delta: tc.function?.arguments,\n };\n }\n }\n if (choice.finish_reason) {\n yield { type: \"stop\", reason: parseStopReason(choice.finish_reason) };\n }\n }\n}\n\nasync function streamOpenAIText(\n stream: AsyncIterable<{ choices?: Array<{ delta?: { content?: string | null } }> }>,\n): Promise<ProviderStreamResult> {\n return {\n stream: (async function* () {\n for await (const chunk of stream) {\n const delta = chunk.choices?.[0]?.delta?.content;\n if (delta) yield delta;\n }\n })(),\n };\n}\n\nfunction ollamaOriginFromParams(params: ProviderParams): string | null {\n const raw = typeof params.base_url === \"string\" ? params.base_url : \"\";\n if (!raw) return null;\n try {\n const u = new URL(raw);\n const isLocal = u.hostname === \"localhost\" || u.hostname === \"127.0.0.1\";\n const isOllamaPort = u.port === \"11434\";\n if (!isLocal || !isOllamaPort) return null;\n return `${u.protocol}//${u.host}`;\n } catch {\n return null;\n }\n}\n\nasync function tryPullOllamaModel(model_id: string, params: ProviderParams): Promise<boolean> {\n const origin = ollamaOriginFromParams(params);\n if (!origin) return false;\n try {\n const res = await fetch(`${origin}/api/pull`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ name: model_id, stream: false }),\n });\n return res.ok;\n } catch {\n return false;\n }\n}\n\nfunction isModelNotFoundError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err);\n return /\\b404\\b|model.*not found|unsupported.*embed/i.test(msg);\n}\n\nexport const openaiProvider: ModelProvider = {\n name: \"openai\",\n\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n const client = makeClient(params);\n const mapped = messages.map((m): InvokeMessage => ({\n role: m.role,\n content: m.content,\n }));\n const stream = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(mapped),\n stream: true,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickOpenAICompatOptions(params) as Record<string, unknown>),\n });\n return streamOpenAIText(stream);\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n const client = makeClient(params);\n const resp = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(messages),\n tools: tools as OpenAI.Chat.ChatCompletionTool[],\n tool_choice: \"auto\",\n stream: false,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickOpenAICompatOptions(params) as Record<string, unknown>),\n });\n return parseOpenAIInvokeChoice(resp.choices[0] as OpenAIInvokeChoice);\n },\n\n streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n return openaiStreamInvoke(makeClient(params), model_id, messages, params, tools);\n },\n\n async embed(model_id, inputs, params): Promise<number[][]> {\n return openaiEmbed(makeClient(params), model_id, inputs, params);\n },\n};\n\nasync function openaiEmbed(\n client: OpenAI,\n model_id: string,\n inputs: string[],\n params: ProviderParams,\n): Promise<number[][]> {\n if (inputs.length === 0) return [];\n try {\n const resp = await client.embeddings.create({ model: model_id, input: inputs });\n return resp.data.map((d) => d.embedding);\n } catch (err) {\n // Self-host ergonomics: when pointed at local Ollama and the embedding\n // model isn't present yet, pull it on-demand and retry once.\n if (isModelNotFoundError(err) && await tryPullOllamaModel(model_id, params)) {\n const resp = await client.embeddings.create({ model: model_id, input: inputs });\n return resp.data.map((d) => d.embedding);\n }\n throw err;\n }\n}\n\nasync function* openaiStreamInvoke(\n client: OpenAI,\n model_id: string,\n messages: InvokeMessage[],\n params: ProviderParams,\n tools: OpenAITool[],\n): AsyncIterable<ProviderStreamEvent> {\n const compatOptions = pickOpenAICompatOptions(params) as Record<string, unknown>;\n const body: OpenAI.Chat.ChatCompletionCreateParamsStreaming = {\n model: model_id,\n messages: toOpenAIMessages(messages),\n stream: true,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...compatOptions,\n stream_options: { include_usage: true, ...(compatOptions.stream_options as object | undefined) },\n };\n if (tools.length > 0) {\n body.tools = tools as OpenAI.Chat.ChatCompletionTool[];\n body.tool_choice = \"auto\";\n }\n const stream = await client.chat.completions.create(body);\n yield* streamOpenAIEvents(\n stream as AsyncIterable<{\n choices?: OpenAIStreamChoice[];\n usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null;\n }>,\n );\n}\n\nexport function makeOpenAICompatProvider(\n providerName: string,\n defaultBaseURL: string,\n fixedHeaders: Record<string, string>,\n): ModelProvider {\n return {\n name: providerName,\n\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n const client = makeClient(params, defaultBaseURL, fixedHeaders);\n const mapped = messages.map((m): InvokeMessage => ({\n role: m.role,\n content: m.content,\n }));\n const stream = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(mapped),\n stream: true,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickOpenAICompatOptions(params) as Record<string, unknown>),\n });\n return streamOpenAIText(stream);\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n const client = makeClient(params, defaultBaseURL, fixedHeaders);\n const resp = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(messages),\n tools: tools as OpenAI.Chat.ChatCompletionTool[],\n tool_choice: \"auto\",\n stream: false,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickOpenAICompatOptions(params) as Record<string, unknown>),\n });\n return parseOpenAIInvokeChoice(resp.choices[0] as OpenAIInvokeChoice);\n },\n\n streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n return openaiStreamInvoke(makeClient(params, defaultBaseURL, fixedHeaders), model_id, messages, params, tools);\n },\n\n async embed(model_id, inputs, params): Promise<number[][]> {\n return openaiEmbed(makeClient(params, defaultBaseURL, fixedHeaders), model_id, inputs, params);\n },\n };\n}\n\n\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport type { ContentPart } from \"@/lib/tools/types\";\nimport { getIntegrationRaw } from \"@/lib/stores/integrations\";\nimport type {\n ModelProvider,\n ProviderMessage,\n ProviderParams,\n ProviderStreamResult,\n ProviderStreamEvent,\n InvokeMessage,\n InvokeResult,\n OpenAITool,\n} from \"./types\";\n\n// Resolves the API key in fallback order:\n// 1. params.api_key — explicit per-call override\n// 2. integration store — value put there by the user (UI) or env-sync (rc)\n// 3. process.env.ANTHROPIC_API_KEY — last-resort process inheritance\nfunction resolveApiKey(params: ProviderParams): string | undefined {\n return params.api_key ?? getIntegrationRaw(\"anthropic\")?.api_key ?? process.env.ANTHROPIC_API_KEY;\n}\n\nfunction pickAnthropicOptions(params: ProviderParams): Record<string, unknown> {\n const p = params as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n const keys = [\n \"temperature\",\n \"top_p\",\n \"top_k\",\n \"stop_sequences\",\n \"metadata\",\n \"tool_choice\",\n \"service_tier\",\n ];\n for (const k of keys) {\n if (p[k] !== undefined) out[k] = p[k];\n }\n return out;\n}\n\nfunction appendServerTools(\n anthropicTools: Anthropic.Tool[],\n params: ProviderParams,\n): Anthropic.Tool[] {\n const native = (params as Record<string, unknown>).anthropic_server_tools;\n if (!Array.isArray(native)) return anthropicTools;\n const merged = [...anthropicTools];\n for (const t of native) {\n if (t && typeof t === \"object\") {\n merged.push(t as Anthropic.Tool);\n }\n }\n return merged;\n}\n\n// Anthropic prompt-caching breakpoints. Within a multi-tool ReAct turn the\n// system prompt + tools are stable across every LLM call, and tool_results\n// only grow at the tail — exactly the prefix Anthropic's ephemeral cache is\n// built for. We mark three breakpoints (system, last tool, last tool_result)\n// so calls 2..N read the prefix at ~10% the input rate. The prefix below the\n// minimum cacheable size is silently ignored by the API at no extra cost,\n// so it is safe to mark unconditionally.\nconst EPHEMERAL: Anthropic.CacheControlEphemeral = { type: \"ephemeral\" };\n\nexport function withSystemCacheControl(text: string): Anthropic.TextBlockParam[] | undefined {\n if (!text) return undefined;\n return [{ type: \"text\", text, cache_control: EPHEMERAL }];\n}\n\nexport function withToolsCacheControl(tools: Anthropic.Tool[]): Anthropic.Tool[] {\n if (tools.length === 0) return tools;\n const last = tools[tools.length - 1];\n return [...tools.slice(0, -1), { ...last, cache_control: EPHEMERAL }];\n}\n\nexport function withLastToolResultCacheControl(\n messages: Anthropic.MessageParam[],\n): Anthropic.MessageParam[] {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i];\n if (typeof m.content === \"string\") continue;\n const blocks = m.content;\n for (let j = blocks.length - 1; j >= 0; j--) {\n const b = blocks[j];\n if (b.type === \"tool_result\") {\n const newBlocks = [...blocks];\n newBlocks[j] = { ...b, cache_control: EPHEMERAL };\n const next = [...messages];\n next[i] = { ...m, content: newBlocks };\n return next;\n }\n }\n }\n return messages;\n}\n\ninterface AnthropicMessageStartEvent {\n type: \"message_start\";\n message: { usage?: Anthropic.Usage };\n}\ninterface AnthropicMessageDeltaEvent {\n type: \"message_delta\";\n usage?: Anthropic.MessageDeltaUsage;\n}\n\nfunction usageEventFromStart(usage: Anthropic.Usage | undefined): ProviderStreamEvent | null {\n if (!usage) return null;\n return {\n type: \"usage\",\n input_tokens: usage.input_tokens ?? 0,\n output_tokens: usage.output_tokens ?? 0,\n cache_creation_input_tokens: usage.cache_creation_input_tokens ?? 0,\n cache_read_input_tokens: usage.cache_read_input_tokens ?? 0,\n };\n}\n\nfunction usageEventFromDelta(usage: Anthropic.MessageDeltaUsage | undefined): ProviderStreamEvent | null {\n if (!usage) return null;\n // message_delta only carries the *final* output_tokens; input/cache fields\n // are already accounted for from message_start. Emitting just the output\n // delta here keeps the agent loop's running total accurate without\n // double-counting cache reads.\n return {\n type: \"usage\",\n input_tokens: 0,\n output_tokens: usage.output_tokens ?? 0,\n };\n}\n\nexport const anthropicProvider: ModelProvider = {\n name: \"anthropic\",\n\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n const client = new Anthropic({\n apiKey: resolveApiKey(params),\n baseURL: params.base_url,\n defaultHeaders: params.extra_headers,\n });\n\n const systemMsg = messages.find((m) => m.role === \"system\");\n const systemText = typeof systemMsg?.content === \"string\"\n ? systemMsg.content\n : (systemMsg?.content ?? [])\n .filter((p): p is ContentPart & { type: \"text\" } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\\n\");\n const userMessages = messages\n .filter((m) => m.role !== \"system\")\n .map((m): Anthropic.MessageParam => ({\n role: (m.role === \"assistant\" ? \"assistant\" : \"user\"),\n content: toAnthropicContent(m.content),\n }));\n\n const stream = await client.messages.stream({\n model: model_id,\n max_tokens: params.max_tokens ?? 4096,\n system: withSystemCacheControl(systemText),\n messages: userMessages,\n });\n\n return {\n stream: (async function* () {\n for await (const event of stream) {\n if (event.type === \"content_block_delta\" && event.delta.type === \"text_delta\") {\n yield event.delta.text;\n }\n }\n })(),\n };\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n const client = new Anthropic({\n apiKey: resolveApiKey(params),\n baseURL: params.base_url,\n defaultHeaders: params.extra_headers,\n });\n\n const systemMsg = messages.find((m) => m.role === \"system\");\n const systemText = typeof systemMsg?.content === \"string\" ? systemMsg.content : \"\";\n const msgList = withLastToolResultCacheControl(\n toAnthropicMessages(messages.filter((m) => m.role !== \"system\")),\n );\n const anthropicTools = withToolsCacheControl(\n appendServerTools(toAnthropicTools(tools), params),\n );\n\n const resp = await client.messages.create({\n model: model_id,\n max_tokens: params.max_tokens ?? 4096,\n system: withSystemCacheControl(systemText),\n messages: msgList,\n tools: anthropicTools,\n ...(params.thinking ? { thinking: params.thinking } : {}),\n ...(pickAnthropicOptions(params) as Record<string, unknown>),\n });\n\n const textContent = resp.content\n .filter((b): b is Anthropic.TextBlock => b.type === \"text\")\n .map((b) => b.text)\n .join(\"\");\n\n const toolCalls = resp.content\n .filter((b): b is Anthropic.ToolUseBlock => b.type === \"tool_use\")\n .map((b) => ({ id: b.id, name: b.name, arguments: b.input as Record<string, unknown> }));\n\n return {\n text: textContent || null,\n tool_calls: toolCalls,\n stop_reason: resp.stop_reason === \"tool_use\" ? \"tool_use\" : \"stop\",\n };\n },\n\n streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n return (async function* () {\n const client = new Anthropic({\n apiKey: resolveApiKey(params),\n baseURL: params.base_url,\n defaultHeaders: params.extra_headers,\n });\n\n const systemMsg = messages.find((m) => m.role === \"system\");\n const systemText = typeof systemMsg?.content === \"string\" ? systemMsg.content : \"\";\n const msgList = withLastToolResultCacheControl(\n toAnthropicMessages(messages.filter((m) => m.role !== \"system\")),\n );\n const anthropicTools = withToolsCacheControl(\n appendServerTools(toAnthropicTools(tools), params),\n );\n\n const body: Anthropic.Messages.MessageStreamParams = {\n model: model_id,\n max_tokens: params.max_tokens ?? 4096,\n messages: msgList,\n ...(pickAnthropicOptions(params) as Record<string, unknown>),\n };\n const systemParam = withSystemCacheControl(systemText);\n if (systemParam) body.system = systemParam;\n if (anthropicTools.length > 0) body.tools = anthropicTools;\n if (params.thinking) {\n (body as unknown as Record<string, unknown>).thinking = params.thinking;\n }\n if (params.temperature !== undefined) body.temperature = params.temperature;\n\n const stream = client.messages.stream(body);\n const blockType = new Map<number, \"text\" | \"thinking\" | \"tool_use\">();\n\n for await (const event of stream) {\n if (event.type === \"message_start\") {\n const ev = event as unknown as AnthropicMessageStartEvent;\n const u = usageEventFromStart(ev.message?.usage);\n if (u) yield u;\n continue;\n }\n if (event.type === \"content_block_start\") {\n const cb = event.content_block;\n if (cb.type === \"tool_use\") {\n blockType.set(event.index, \"tool_use\");\n yield { type: \"tool_call_chunk\", index: event.index, id: cb.id, name: cb.name };\n } else if (cb.type === \"thinking\") {\n blockType.set(event.index, \"thinking\");\n } else if (cb.type === \"text\") {\n blockType.set(event.index, \"text\");\n }\n } else if (event.type === \"content_block_delta\") {\n const d = event.delta as { type: string; text?: string; thinking?: string; partial_json?: string };\n if (d.type === \"text_delta\" && d.text) {\n yield { type: \"text\", delta: d.text };\n } else if (d.type === \"thinking_delta\" && d.thinking) {\n yield { type: \"thinking\", delta: d.thinking };\n } else if (d.type === \"input_json_delta\" && d.partial_json !== undefined) {\n yield { type: \"tool_call_chunk\", index: event.index, args_delta: d.partial_json };\n }\n } else if (event.type === \"message_delta\") {\n const delta = event as unknown as AnthropicMessageDeltaEvent;\n const u = usageEventFromDelta(delta.usage);\n if (u) yield u;\n if (event.delta?.stop_reason) {\n const reason = event.delta.stop_reason;\n yield { type: \"stop\", reason: reason === \"tool_use\" ? \"tool_use\" : reason === \"max_tokens\" ? \"length\" : \"stop\" };\n }\n }\n }\n })();\n },\n};\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nexport function toAnthropicContent(\n content: string | ContentPart[],\n): Anthropic.MessageParam[\"content\"] {\n if (typeof content === \"string\") return content;\n return content.flatMap((part): Anthropic.ContentBlockParam[] => {\n if (part.type === \"text\") {\n return [{ type: \"text\", text: part.text }];\n }\n if (part.type === \"image\") {\n const mt = part.media_type as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\";\n return [{ type: \"image\", source: { type: \"base64\", media_type: mt, data: part.data } }];\n }\n if (part.type === \"file\") {\n if (part.media_type === \"application/pdf\") {\n return [\n {\n type: \"document\",\n source: { type: \"base64\", media_type: \"application/pdf\", data: part.data },\n title: part.name,\n } as unknown as Anthropic.ContentBlockParam,\n ];\n }\n return [{ type: \"text\", text: `[File: ${part.name}]\\n${part.data}` }];\n }\n return [];\n });\n}\n\nfunction toAnthropicMessages(messages: InvokeMessage[]): Anthropic.MessageParam[] {\n const result: Anthropic.MessageParam[] = [];\n for (const m of messages) {\n if (m.role === \"tool\") {\n result.push({\n role: \"user\",\n content: [{ type: \"tool_result\", tool_use_id: m.tool_call_id!, content: String(m.content) }],\n });\n } else if (m.role === \"assistant\" && m.tool_calls?.length) {\n const blocks: Anthropic.ContentBlockParam[] = [];\n if (m.content) blocks.push({ type: \"text\", text: String(m.content) });\n for (const tc of m.tool_calls) {\n blocks.push({\n type: \"tool_use\",\n id: tc.id,\n name: tc.function?.name ?? \"\",\n input: (() => {\n try {\n return JSON.parse(tc.function?.arguments ?? \"{}\");\n } catch {\n return {};\n }\n })(),\n });\n }\n result.push({ role: \"assistant\", content: blocks });\n } else {\n result.push({\n role: m.role as \"user\" | \"assistant\",\n content: toAnthropicContent(m.content),\n });\n }\n }\n return result;\n}\n\nfunction toAnthropicTools(tools: OpenAITool[]): Anthropic.Tool[] {\n return tools.flatMap((t) => {\n if (!t.function?.name) return [];\n return [{ name: t.function.name, description: t.function.description, input_schema: t.function.parameters as Anthropic.Tool.InputSchema }];\n });\n}\n\n// ── Plain-text helper for streaming path (no tool calls) ────────────────────\n\nexport function providerMessagesFromHistory(\n messages: Array<{ role: \"user\" | \"assistant\"; content: string | ContentPart[] }>,\n): ProviderMessage[] {\n return messages.map((m) => ({\n role: m.role,\n content: typeof m.content === \"string\"\n ? m.content\n : m.content.filter((p): p is ContentPart & { type: \"text\" } => p.type === \"text\").map((p) => p.text).join(\"\\n\"),\n }));\n}\n","import OpenAI from \"openai\";\nimport type {\n ModelProvider,\n ProviderParams,\n ProviderStreamResult,\n ProviderStreamEvent,\n InvokeResult,\n} from \"./types\";\nimport { getStoredOAuthToken } from \"./github-copilot-auth\";\nimport { parseOpenAIInvokeChoice, streamOpenAIEvents, toOpenAIMessages } from \"./openai\";\n\nfunction pickGitHubCompatOptions(params: ProviderParams): Record<string, unknown> {\n const p = params as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n const keys = [\n \"top_p\",\n \"presence_penalty\",\n \"frequency_penalty\",\n \"stop\",\n \"response_format\",\n \"logprobs\",\n \"top_logprobs\",\n \"reasoning_effort\",\n \"thinking\",\n \"stream_options\",\n \"user\",\n \"user_id\",\n ];\n for (const k of keys) {\n if (p[k] !== undefined) out[k] = p[k];\n }\n return out;\n}\n\ninterface SessionToken {\n token: string;\n expiresAt: number;\n}\n\nconst tokenCache = new Map<string, SessionToken>();\n\nfunction isLikelyGitHubPat(token: string): boolean {\n return token.startsWith(\"ghp_\") || token.startsWith(\"github_pat_\") || token.startsWith(\"gho_\");\n}\n\nasync function getCopilotToken(pat: string): Promise<string> {\n if (!pat) throw new Error(\"GitHub Copilot: no API key configured for token exchange.\");\n const cached = tokenCache.get(pat);\n if (cached && cached.expiresAt - Date.now() > 60_000) return cached.token;\n\n const res = await fetch(\"https://api.github.com/copilot_internal/v2/token\", {\n headers: {\n Authorization: `token ${pat}`,\n \"User-Agent\": \"Jarela/1.0\",\n },\n });\n\n if (!res.ok) {\n const body = await res.text().catch(() => res.statusText);\n if (res.status === 401) {\n throw new Error(\n `GitHub Copilot: token exchange failed (401). ` +\n `Ensure your PAT has the \"copilot\" scope and that you have an active Copilot subscription. ` +\n `Details: ${body}`,\n );\n }\n if (res.status === 404) {\n throw new Error(\n \"GitHub Copilot token exchange endpoint was not found for this credential. \" +\n \"Personal Access Tokens are not accepted directly by Copilot chat. \" +\n \"Use a Copilot session token in params.copilot_session_token, or a credential that supports token exchange.\",\n );\n }\n throw new Error(`GitHub Copilot: token exchange failed (${res.status}): ${body}`);\n }\n\n const json = await res.json() as { token: string; expires_at: string };\n if (!json.token) throw new Error(\"GitHub Copilot: token exchange returned no token\");\n\n const expiresAt = json.expires_at ? new Date(json.expires_at).getTime() : Date.now() + 28 * 60_000;\n tokenCache.set(pat, { token: json.token, expiresAt });\n return json.token;\n}\n\nconst FIXED_HEADERS = {\n \"Editor-Version\": \"vscode/1.85.0\",\n \"Copilot-Integration-Id\": \"vscode-chat\",\n \"openai-intent\": \"conversation-ai\",\n // Required by the Copilot proxy to accept image_url content parts. Without\n // this header the upstream models silently drop attached images (or 400).\n \"Copilot-Vision-Request\": \"true\",\n};\n\nasync function resolvedClient(params: ProviderParams): Promise<OpenAI> {\n const apiKey = (params.api_key as string | undefined) ?? \"\";\n const explicitSessionToken = (params.copilot_session_token as string | undefined)?.trim();\n\n // Highest priority: an explicit pre-exchanged Copilot session token.\n if (explicitSessionToken && explicitSessionToken.length > 0) {\n return new OpenAI({\n apiKey: explicitSessionToken,\n baseURL: params.base_url ?? \"https://api.githubcopilot.com\",\n defaultHeaders: { ...FIXED_HEADERS, ...params.extra_headers },\n });\n }\n\n // Next: a device-flow OAuth token persisted by the in-app sign-in. This is\n // exchangeable for a Copilot session token, so we get full model context.\n const oauthToken = getStoredOAuthToken();\n if (oauthToken) {\n const token = await getCopilotToken(oauthToken);\n return new OpenAI({\n apiKey: token,\n baseURL: params.base_url ?? \"https://api.githubcopilot.com\",\n defaultHeaders: { ...FIXED_HEADERS, ...params.extra_headers },\n });\n }\n\n // Fallback: a raw PAT. PATs can't be exchanged for Copilot tokens, so they\n // route to the GitHub Models REST API (which enforces tight per-request\n // token caps, e.g. 8000 for gpt-4o). Users who want larger contexts should\n // sign in via the device flow instead.\n if (apiKey && isLikelyGitHubPat(apiKey)) {\n return new OpenAI({\n apiKey,\n baseURL: params.base_url ?? \"https://models.github.ai/inference\",\n defaultHeaders: {\n Accept: \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2026-03-10\",\n ...params.extra_headers,\n },\n });\n }\n\n // Otherwise, treat the credential as an OAuth-capable token and exchange.\n if (!apiKey) {\n throw new Error(\n \"GitHub Copilot: not signed in. Use the in-app device-flow login, or set api_key / copilot_session_token.\",\n );\n }\n const token = await getCopilotToken(apiKey);\n return new OpenAI({\n apiKey: token,\n baseURL: params.base_url ?? \"https://api.githubcopilot.com\",\n defaultHeaders: { ...FIXED_HEADERS, ...params.extra_headers },\n });\n}\n\nexport const githubCopilotProvider: ModelProvider = {\n name: \"github-copilot\",\n\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n const client = await resolvedClient(params);\n const stream = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(messages),\n stream: true,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickGitHubCompatOptions(params) as Record<string, unknown>),\n });\n return {\n stream: (async function* () {\n for await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta?.content;\n if (delta) yield delta;\n }\n })(),\n };\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n const client = await resolvedClient(params);\n const resp = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(messages),\n tools: tools as OpenAI.Chat.ChatCompletionTool[],\n tool_choice: \"auto\",\n stream: false,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...(pickGitHubCompatOptions(params) as Record<string, unknown>),\n });\n return parseOpenAIInvokeChoice(resp.choices[0]);\n },\n\n async *streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n const client = await resolvedClient(params);\n const compat = pickGitHubCompatOptions(params) as Record<string, unknown>;\n const stream = await client.chat.completions.create({\n model: model_id,\n messages: toOpenAIMessages(messages),\n tools: tools as OpenAI.Chat.ChatCompletionTool[],\n tool_choice: \"auto\",\n stream: true,\n temperature: params.temperature,\n max_tokens: params.max_tokens,\n ...compat,\n stream_options: { include_usage: true, ...(compat.stream_options as object | undefined) },\n });\n\n yield* streamOpenAIEvents(\n stream as AsyncIterable<{\n choices?: Array<{\n delta?: {\n content?: string | null;\n reasoning_content?: string | null;\n tool_calls?: Array<{ index?: number; id?: string; function?: { name?: string; arguments?: string } }>;\n };\n finish_reason?: string | null;\n }>;\n usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null;\n }>,\n );\n },\n\n async embed(model_id, inputs, params): Promise<number[][]> {\n if (inputs.length === 0) return [];\n const client = await resolvedClient(params);\n const resp = await client.embeddings.create({\n model: model_id,\n input: inputs,\n });\n return resp.data.map((d) => d.embedding);\n },\n};\n","import { makeOpenAICompatProvider } from \"./openai\";\n\n// DeepSeek API is OpenAI-compatible. Reasoning models (deepseek-reasoner, etc.)\n// emit `reasoning_content` in delta chunks — handled by the shared OpenAI stream parser.\n// Auth: set params.api_key to your DeepSeek API key.\nexport const deepseekProvider = makeOpenAICompatProvider(\n \"deepseek\",\n \"https://api.deepseek.com\",\n {},\n);\n","import type { ProviderStreamEvent } from \"./types\";\n\n// Reads `data: ...` lines from an SSE response body.\nexport async function* readSSELines(body: ReadableStream<Uint8Array>): AsyncIterable<string> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n for (const line of lines) {\n if (line.startsWith(\"data: \")) yield line.slice(6).trim();\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n// Parses an Anthropic SSE stream into ProviderStreamEvents.\n// Tracks per-block-index type so deltas route to the right event.\nexport async function* parseAnthropicStream(\n body: ReadableStream<Uint8Array>,\n): AsyncIterable<ProviderStreamEvent> {\n const blockType = new Map<number, \"text\" | \"thinking\" | \"tool_use\">();\n\n for await (const line of readSSELines(body)) {\n if (!line || line === \"[DONE]\") continue;\n let event: AnthropicStreamEvent;\n try { event = JSON.parse(line) as AnthropicStreamEvent; } catch { continue; }\n\n if (event.type === \"content_block_start\" && event.content_block) {\n const cb = event.content_block;\n if (cb.type === \"tool_use\") {\n blockType.set(event.index, \"tool_use\");\n yield { type: \"tool_call_chunk\", index: event.index, id: cb.id, name: cb.name };\n } else if (cb.type === \"thinking\") {\n blockType.set(event.index, \"thinking\");\n } else {\n blockType.set(event.index, \"text\");\n }\n } else if (event.type === \"content_block_delta\" && event.delta) {\n const d = event.delta;\n if (d.type === \"text_delta\" && d.text) {\n yield { type: \"text\", delta: d.text };\n } else if (d.type === \"thinking_delta\" && d.thinking) {\n yield { type: \"thinking\", delta: d.thinking };\n } else if (d.type === \"input_json_delta\" && d.partial_json !== undefined) {\n yield { type: \"tool_call_chunk\", index: event.index, args_delta: d.partial_json };\n }\n } else if (event.type === \"message_delta\" && event.delta?.stop_reason) {\n const reason = event.delta.stop_reason;\n yield { type: \"stop\", reason: reason === \"tool_use\" ? \"tool_use\" : reason === \"max_tokens\" ? \"length\" : \"stop\" };\n }\n }\n}\n\ninterface AnthropicStreamEvent {\n type: string;\n index: number;\n content_block?: { type: string; id?: string; name?: string };\n delta?: {\n type?: string;\n text?: string;\n thinking?: string;\n partial_json?: string;\n stop_reason?: string;\n };\n}\n\n// Parses an OpenAI-style SSE stream (chat.completions with stream:true) into ProviderStreamEvents.\n// Handles delta.content (text), delta.reasoning_content (DeepSeek thinking), delta.tool_calls fragments.\nexport async function* parseOpenAIStream(\n body: ReadableStream<Uint8Array>,\n): AsyncIterable<ProviderStreamEvent> {\n for await (const line of readSSELines(body)) {\n if (!line || line === \"[DONE]\") continue;\n let event: OpenAIStreamEvent;\n try { event = JSON.parse(line) as OpenAIStreamEvent; } catch { continue; }\n\n const choice = event.choices?.[0];\n if (!choice) continue;\n const delta = choice.delta;\n\n if (delta?.content) {\n yield { type: \"text\", delta: delta.content };\n }\n if (typeof delta?.reasoning_content === \"string\" && delta.reasoning_content) {\n yield { type: \"thinking\", delta: delta.reasoning_content };\n }\n if (delta?.tool_calls) {\n for (const tc of delta.tool_calls) {\n const idx = tc.index ?? 0;\n yield {\n type: \"tool_call_chunk\",\n index: idx,\n id: tc.id,\n name: tc.function?.name,\n args_delta: tc.function?.arguments,\n };\n }\n }\n if (choice.finish_reason) {\n const fr = choice.finish_reason;\n yield { type: \"stop\", reason: fr === \"tool_calls\" ? \"tool_use\" : fr === \"length\" ? \"length\" : \"stop\" };\n }\n }\n}\n\ninterface OpenAIStreamEvent {\n choices?: Array<{\n index?: number;\n delta?: {\n content?: string | null;\n reasoning_content?: string | null;\n tool_calls?: Array<{\n index?: number;\n id?: string;\n function?: { name?: string; arguments?: string };\n }>;\n };\n finish_reason?: string | null;\n }>;\n}\n","import { makeOpenAICompatProvider } from \"./openai\";\nimport { readSSELines } from \"./streaming\";\nimport type { ContentPart, InvokeMessage, InvokeResult, OpenAITool } from \"@/lib/tools/types\";\nimport type { ModelProvider, ProviderMessage, ProviderParams, ProviderStreamEvent, ProviderStreamResult } from \"./types\";\n\n// Google Gemini via its OpenAI-compatible endpoint.\n// Auth: set params.api_key to your Google AI Studio API key.\n// Models: gemini-2.0-flash, gemini-2.5-pro, gemini-1.5-flash, etc.\nconst geminiCompat = makeOpenAICompatProvider(\n \"gemini\",\n \"https://generativelanguage.googleapis.com/v1beta/openai/\",\n {},\n);\n\ntype GeminiPart =\n | { text: string }\n | { inlineData: { mimeType: string; data: string } }\n | { functionCall: { name: string; args?: Record<string, unknown> } }\n | { functionResponse: { name: string; response: Record<string, unknown> } };\n\nfunction isCompatMode(params: ProviderParams): boolean {\n return (params as Record<string, unknown>).gemini_use_openai_compat === true;\n}\n\nfunction nativeBaseUrl(params: ProviderParams): string {\n const raw = (params as Record<string, unknown>).gemini_native_base_url;\n if (typeof raw === \"string\" && raw.trim()) return raw.trim().replace(/\\/+$/, \"\");\n return \"https://generativelanguage.googleapis.com/v1beta\";\n}\n\nfunction geminiApiKey(params: ProviderParams): string {\n const key = typeof params.api_key === \"string\" ? params.api_key : process.env.GEMINI_API_KEY;\n if (!key) throw new Error(\"Gemini: no api_key configured\");\n return key;\n}\n\nfunction contentToGeminiParts(content: string | ContentPart[]): GeminiPart[] {\n if (typeof content === \"string\") return [{ text: content }];\n const parts: GeminiPart[] = [];\n for (const p of content) {\n if (p.type === \"text\") {\n parts.push({ text: p.text });\n continue;\n }\n if (p.type === \"image\") {\n parts.push({ inlineData: { mimeType: p.media_type, data: p.data } });\n continue;\n }\n // Files map to inlineData when possible; otherwise tool-agnostic text fallback.\n if (p.type === \"file\") {\n if (p.media_type && p.data) {\n parts.push({ inlineData: { mimeType: p.media_type, data: p.data } });\n } else {\n parts.push({ text: `[File: ${p.name}]` });\n }\n }\n }\n return parts.length > 0 ? parts : [{ text: \"\" }];\n}\n\nfunction parseJsonObject(v: string | undefined): Record<string, unknown> {\n if (!v) return {};\n try {\n const parsed = JSON.parse(v);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : { value: parsed };\n } catch {\n return {};\n }\n}\n\nfunction providerMessagesToGemini(messages: ProviderMessage[]): {\n systemInstruction?: { parts: GeminiPart[] };\n contents: Array<{ role: \"user\" | \"model\"; parts: GeminiPart[] }>;\n} {\n const system = messages.find((m) => m.role === \"system\");\n const contents = messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({\n role: (m.role === \"assistant\" ? \"model\" : \"user\") as \"user\" | \"model\",\n parts: contentToGeminiParts(m.content),\n }));\n return {\n systemInstruction: system ? { parts: contentToGeminiParts(system.content) } : undefined,\n contents,\n };\n}\n\nfunction invokeMessagesToGemini(messages: InvokeMessage[]): {\n systemInstruction?: { parts: GeminiPart[] };\n contents: Array<{ role: \"user\" | \"model\"; parts: GeminiPart[] }>;\n} {\n const toolNameById = new Map<string, string>();\n const contents: Array<{ role: \"user\" | \"model\"; parts: GeminiPart[] }> = [];\n let systemInstruction: { parts: GeminiPart[] } | undefined;\n\n for (const m of messages) {\n if (m.role === \"system\") {\n const text = typeof m.content === \"string\" ? m.content : contentToGeminiParts(m.content)\n .flatMap((p) => (\"text\" in p ? [p.text] : []))\n .join(\"\\n\");\n if (text.trim()) systemInstruction = { parts: [{ text }] };\n continue;\n }\n\n if (m.role === \"assistant\") {\n const parts = contentToGeminiParts(m.content);\n for (const tc of m.tool_calls ?? []) {\n const name = tc.function?.name ?? \"tool\";\n if (tc.id) toolNameById.set(tc.id, name);\n parts.push({ functionCall: { name, args: parseJsonObject(tc.function?.arguments) } });\n }\n contents.push({ role: \"model\", parts });\n continue;\n }\n\n if (m.role === \"tool\") {\n const name = m.tool_call_id ? toolNameById.get(m.tool_call_id) ?? \"tool\" : \"tool\";\n const raw = typeof m.content === \"string\" ? m.content : \"\";\n const response = parseJsonObject(raw);\n if (Object.keys(response).length === 0 && raw) response.content = raw;\n contents.push({\n role: \"user\",\n parts: [{ functionResponse: { name, response } }],\n });\n continue;\n }\n\n contents.push({ role: \"user\", parts: contentToGeminiParts(m.content) });\n }\n\n return { systemInstruction, contents };\n}\n\nfunction toGeminiTools(tools: OpenAITool[], params: ProviderParams): unknown[] | undefined {\n const out: unknown[] = [];\n if (tools.length > 0) {\n out.push({\n functionDeclarations: tools\n .filter((t) => t.function?.name)\n .map((t) => ({\n name: t.function.name,\n description: t.function.description ?? \"\",\n parameters: t.function.parameters,\n })),\n });\n }\n const builtins = (params as Record<string, unknown>).gemini_builtin_tools;\n if (Array.isArray(builtins)) {\n for (const t of builtins) {\n if (t && typeof t === \"object\") out.push(t);\n }\n }\n return out.length > 0 ? out : undefined;\n}\n\nfunction toGenerationConfig(params: ProviderParams): Record<string, unknown> | undefined {\n const p = params as Record<string, unknown>;\n const base: Record<string, unknown> = {};\n if (params.temperature !== undefined) base.temperature = params.temperature;\n if (params.max_tokens !== undefined) base.maxOutputTokens = params.max_tokens;\n if (p.top_p !== undefined) base.topP = p.top_p;\n if (p.top_k !== undefined) base.topK = p.top_k;\n if (Array.isArray(p.stop)) base.stopSequences = p.stop;\n const rf = p.response_format as Record<string, unknown> | undefined;\n if (rf?.type === \"json_object\") {\n base.responseMimeType = \"application/json\";\n }\n if (typeof p.gemini_response_mime_type === \"string\") {\n base.responseMimeType = p.gemini_response_mime_type;\n }\n if (p.gemini_response_schema && typeof p.gemini_response_schema === \"object\") {\n base.responseSchema = p.gemini_response_schema;\n if (!base.responseMimeType) base.responseMimeType = \"application/json\";\n }\n if (p.gemini_thinking_config && typeof p.gemini_thinking_config === \"object\") {\n base.thinkingConfig = p.gemini_thinking_config;\n }\n const merged = p.gemini_generation_config && typeof p.gemini_generation_config === \"object\"\n ? { ...base, ...(p.gemini_generation_config as Record<string, unknown>) }\n : base;\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\nasync function geminiNativeGenerate(\n model_id: string,\n body: Record<string, unknown>,\n params: ProviderParams,\n): Promise<Record<string, unknown>> {\n const apiKey = geminiApiKey(params);\n const res = await fetch(\n `${nativeBaseUrl(params)}/models/${encodeURIComponent(model_id)}:generateContent?key=${encodeURIComponent(apiKey)}`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n );\n if (!res.ok) {\n const msg = await res.text().catch(() => res.statusText);\n throw new Error(`Gemini generateContent error: ${res.status} ${msg}`);\n }\n return await res.json() as Record<string, unknown>;\n}\n\nfunction mapGeminiStopReason(reason: string | undefined): \"stop\" | \"tool_use\" | \"length\" {\n if (reason === \"MAX_TOKENS\") return \"length\";\n return \"stop\";\n}\n\nfunction extractGeminiInvokeResult(data: Record<string, unknown>): InvokeResult {\n const candidates = (data.candidates as Array<Record<string, unknown>> | undefined) ?? [];\n const first = candidates[0] ?? {};\n const content = (first.content as Record<string, unknown> | undefined) ?? {};\n const parts = (content.parts as Array<Record<string, unknown>> | undefined) ?? [];\n\n let text = \"\";\n const tool_calls: InvokeResult[\"tool_calls\"] = [];\n for (const part of parts) {\n if (typeof part.text === \"string\") text += part.text;\n if (part.functionCall && typeof part.functionCall === \"object\") {\n const fc = part.functionCall as Record<string, unknown>;\n const name = typeof fc.name === \"string\" ? fc.name : \"tool\";\n const args = fc.args && typeof fc.args === \"object\" ? fc.args as Record<string, unknown> : {};\n tool_calls.push({\n id: typeof fc.id === \"string\" ? fc.id : `call_${tool_calls.length + 1}`,\n name,\n arguments: args,\n });\n }\n }\n\n const finishReason = typeof first.finishReason === \"string\" ? first.finishReason : undefined;\n return {\n text: text || null,\n tool_calls,\n stop_reason: tool_calls.length > 0 ? \"tool_use\" : mapGeminiStopReason(finishReason),\n };\n}\n\nasync function* geminiNativeStreamInvoke(\n model_id: string,\n messages: InvokeMessage[],\n params: ProviderParams,\n tools: OpenAITool[],\n): AsyncIterable<ProviderStreamEvent> {\n const { systemInstruction, contents } = invokeMessagesToGemini(messages);\n const body: Record<string, unknown> = {\n contents,\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(toGeminiTools(tools, params) ? { tools: toGeminiTools(tools, params) } : {}),\n ...(toGenerationConfig(params) ? { generationConfig: toGenerationConfig(params) } : {}),\n };\n const p = params as Record<string, unknown>;\n if (p.gemini_tool_config && typeof p.gemini_tool_config === \"object\") body.toolConfig = p.gemini_tool_config;\n if (Array.isArray(p.gemini_safety_settings)) body.safetySettings = p.gemini_safety_settings;\n\n const apiKey = geminiApiKey(params);\n const res = await fetch(\n `${nativeBaseUrl(params)}/models/${encodeURIComponent(model_id)}:streamGenerateContent?alt=sse&key=${encodeURIComponent(apiKey)}`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n );\n if (!res.ok || !res.body) {\n const msg = await res.text().catch(() => res.statusText);\n throw new Error(`Gemini streamGenerateContent error: ${res.status} ${msg}`);\n }\n\n for await (const line of readSSELines(res.body)) {\n if (!line || line === \"[DONE]\") continue;\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue;\n }\n const candidates = (data.candidates as Array<Record<string, unknown>> | undefined) ?? [];\n const first = candidates[0] ?? {};\n const content = (first.content as Record<string, unknown> | undefined) ?? {};\n const parts = (content.parts as Array<Record<string, unknown>> | undefined) ?? [];\n for (const part of parts) {\n const isThought = part.thought === true;\n if (typeof part.text === \"string\" && part.text) {\n if (isThought) {\n yield { type: \"thinking\", delta: part.text };\n } else {\n yield { type: \"text\", delta: part.text };\n }\n }\n if (part.functionCall && typeof part.functionCall === \"object\") {\n const fc = part.functionCall as Record<string, unknown>;\n const name = typeof fc.name === \"string\" ? fc.name : \"tool\";\n const args = fc.args && typeof fc.args === \"object\" ? fc.args as Record<string, unknown> : {};\n yield {\n type: \"tool_call_chunk\",\n index: 0,\n id: typeof fc.id === \"string\" ? fc.id : undefined,\n name,\n args_delta: JSON.stringify(args),\n };\n }\n }\n if (typeof first.finishReason === \"string\") {\n yield { type: \"stop\", reason: mapGeminiStopReason(first.finishReason) };\n }\n }\n}\n\nasync function geminiNativeInvoke(\n model_id: string,\n messages: InvokeMessage[],\n params: ProviderParams,\n tools: OpenAITool[],\n): Promise<InvokeResult> {\n const { systemInstruction, contents } = invokeMessagesToGemini(messages);\n const body: Record<string, unknown> = {\n contents,\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(toGeminiTools(tools, params) ? { tools: toGeminiTools(tools, params) } : {}),\n ...(toGenerationConfig(params) ? { generationConfig: toGenerationConfig(params) } : {}),\n };\n const p = params as Record<string, unknown>;\n if (p.gemini_tool_config && typeof p.gemini_tool_config === \"object\") body.toolConfig = p.gemini_tool_config;\n if (Array.isArray(p.gemini_safety_settings)) body.safetySettings = p.gemini_safety_settings;\n const data = await geminiNativeGenerate(model_id, body, params);\n return extractGeminiInvokeResult(data);\n}\n\nasync function geminiNativeChat(\n model_id: string,\n messages: ProviderMessage[],\n params: ProviderParams,\n): Promise<ProviderStreamResult> {\n const { systemInstruction, contents } = providerMessagesToGemini(messages);\n const body: Record<string, unknown> = {\n contents,\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(toGenerationConfig(params) ? { generationConfig: toGenerationConfig(params) } : {}),\n };\n const p = params as Record<string, unknown>;\n if (Array.isArray(p.gemini_safety_settings)) body.safetySettings = p.gemini_safety_settings;\n\n const apiKey = geminiApiKey(params);\n const res = await fetch(\n `${nativeBaseUrl(params)}/models/${encodeURIComponent(model_id)}:streamGenerateContent?alt=sse&key=${encodeURIComponent(apiKey)}`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n );\n if (!res.ok || !res.body) {\n const msg = await res.text().catch(() => res.statusText);\n throw new Error(`Gemini chat stream error: ${res.status} ${msg}`);\n }\n\n return {\n stream: (async function* () {\n for await (const line of readSSELines(res.body!)) {\n if (!line || line === \"[DONE]\") continue;\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue;\n }\n const candidates = (data.candidates as Array<Record<string, unknown>> | undefined) ?? [];\n const first = candidates[0] ?? {};\n const content = (first.content as Record<string, unknown> | undefined) ?? {};\n const parts = (content.parts as Array<Record<string, unknown>> | undefined) ?? [];\n for (const part of parts) {\n if (typeof part.text === \"string\" && part.text && part.thought !== true) {\n yield part.text;\n }\n }\n }\n })(),\n };\n}\n\nfunction resolveGeminiEmbeddingModel(model_id: string, params: ProviderParams): string {\n const overridden = (params as Record<string, unknown>).embedding_model_id;\n if (typeof overridden === \"string\" && overridden.trim()) return overridden.trim();\n // When chat model ids (gemini-*) are passed into embed(), switch to a\n // dedicated embedding model by default.\n if (/^gemini-/i.test(model_id)) return \"text-embedding-004\";\n return model_id;\n}\n\nasync function geminiEmbed(model_id: string, inputs: string[], params: ProviderParams): Promise<number[][]> {\n if (inputs.length === 0) return [];\n const apiKey = typeof params.api_key === \"string\" ? params.api_key : process.env.GEMINI_API_KEY;\n if (!apiKey) throw new Error(\"Gemini: no api_key configured\");\n\n const model = resolveGeminiEmbeddingModel(model_id, params);\n const body = {\n requests: inputs.map((text) => ({\n model: `models/${model}`,\n content: { parts: [{ text }] },\n })),\n };\n\n const res = await fetch(\n `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:batchEmbedContents?key=${encodeURIComponent(apiKey)}`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n );\n if (!res.ok) {\n const msg = await res.text().catch(() => res.statusText);\n throw new Error(`Gemini embeddings error: ${res.status} ${msg}`);\n }\n const data = await res.json() as {\n embeddings?: Array<{ values?: number[] }>;\n error?: { message?: string };\n };\n if (data.error?.message) throw new Error(data.error.message);\n const vectors = (data.embeddings ?? []).map((e) => e.values ?? []);\n if (vectors.length !== inputs.length) {\n throw new Error(`Gemini embeddings returned ${vectors.length}/${inputs.length} vectors`);\n }\n return vectors;\n}\n\nexport const geminiProvider: ModelProvider = {\n ...geminiCompat,\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n if (isCompatMode(params)) return geminiCompat.chat(model_id, messages, params);\n try {\n return await geminiNativeChat(model_id, messages, params);\n } catch {\n return geminiCompat.chat(model_id, messages, params);\n }\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n if (isCompatMode(params)) {\n if (!geminiCompat.invoke) throw new Error(\"Gemini compat provider has no invoke() implementation\");\n return geminiCompat.invoke(model_id, messages, params, tools);\n }\n try {\n return await geminiNativeInvoke(model_id, messages, params, tools);\n } catch {\n if (!geminiCompat.invoke) throw new Error(\"Gemini compat provider has no invoke() implementation\");\n return geminiCompat.invoke(model_id, messages, params, tools);\n }\n },\n\n streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n if (isCompatMode(params)) {\n if (!geminiCompat.streamInvoke) throw new Error(\"Gemini compat provider has no streamInvoke() implementation\");\n return geminiCompat.streamInvoke(model_id, messages, params, tools);\n }\n return (async function* (): AsyncIterable<ProviderStreamEvent> {\n try {\n yield* geminiNativeStreamInvoke(model_id, messages, params, tools);\n } catch {\n if (!geminiCompat.streamInvoke) throw new Error(\"Gemini compat provider has no streamInvoke() implementation\");\n yield* geminiCompat.streamInvoke(model_id, messages, params, tools);\n }\n })();\n },\n\n async embed(model_id, inputs, params): Promise<number[][]> {\n return geminiEmbed(model_id, inputs, params);\n },\n};\n","/**\n * Bridge provider: wraps any LangChain `BaseChatModel` so that Jarela's\n * `ModelProvider` interface can surface the entire LangChain ecosystem of\n * model integrations (Gemini, Bedrock, Cohere, Ollama-native, etc.) without\n * us writing a custom adapter for each one.\n *\n * Config (params on a `model_configs` row with `provider: \"langchain\"`):\n * - lc_class: required. The exported class name to instantiate\n * (e.g. \"ChatGoogleGenerativeAI\", \"ChatCohere\").\n * - All other params are forwarded to the class constructor as-is, so any\n * vendor-specific option (apiKey, region, projectId, ...) \"just works\".\n *\n * Adding a new LangChain integration:\n * 1. `npm install @langchain/<vendor>`\n * 2. Add a case to the `loadLangChainModel` switch below.\n * 3. Create a model_config: provider=\"langchain\", model_id=\"<vendor's model id>\",\n * params={ lc_class: \"ChatXxx\", apiKey: \"...\" }.\n *\n * Why a switch instead of dynamic import(\"@langchain/\" + vendor)? Next.js\n * bundles server code at build time; dynamic specifiers can't be statically\n * traced and the package wouldn't end up in the bundle. A small switch keeps\n * the bundling explicit and the dependency footprint visible.\n */\nimport { AIMessage, AIMessageChunk, HumanMessage, SystemMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { Runnable } from \"@langchain/core/runnables\";\nimport type {\n ModelProvider,\n ProviderMessage,\n ProviderParams,\n ProviderStreamResult,\n ProviderStreamEvent,\n InvokeMessage,\n InvokeResult,\n OpenAITool,\n} from \"./types\";\n\n// ── Module-cached model instances ────────────────────────────────────────────\n// LangChain model classes are usually cheap to construct, but caching keeps\n// the proxy/HTTP-client setup amortized across requests.\nconst cache = new Map<string, BaseChatModel>();\nfunction cacheKey(model_id: string, params: ProviderParams): string {\n return `${params.lc_class}:${model_id}:${JSON.stringify({ ...params, lc_class: undefined })}`;\n}\n\nasync function loadLangChainModel(model_id: string, params: ProviderParams): Promise<BaseChatModel> {\n const k = cacheKey(model_id, params);\n const hit = cache.get(k);\n if (hit) return hit;\n\n const cls = params.lc_class as string | undefined;\n if (!cls) throw new Error(`langchain provider: params.lc_class is required (e.g. \"ChatGoogleGenerativeAI\")`);\n\n // Strip our control fields from the args we pass to the class constructor.\n const { lc_class: _ignore1, lc_module: _ignore2, ...ctorArgs } = params as Record<string, unknown>;\n void _ignore1; void _ignore2;\n // Convention: if the user puts `model_id` on the config row, forward it as\n // `model` to the class (LangChain's standard option name).\n const args: Record<string, unknown> = { ...ctorArgs, model: model_id };\n\n let model: BaseChatModel;\n switch (cls) {\n case \"ChatGoogleGenerativeAI\": {\n const { ChatGoogleGenerativeAI } = await import(\"@langchain/google-genai\");\n model = new ChatGoogleGenerativeAI(args as unknown as ConstructorParameters<typeof ChatGoogleGenerativeAI>[0]);\n break;\n }\n case \"ChatCohere\": {\n const { ChatCohere } = await import(\"@langchain/cohere\");\n model = new ChatCohere(args as unknown as ConstructorParameters<typeof ChatCohere>[0]);\n break;\n }\n case \"ChatDeepSeek\": {\n const { ChatDeepSeek } = await import(\"@langchain/deepseek\");\n model = new ChatDeepSeek(args as unknown as ConstructorParameters<typeof ChatDeepSeek>[0]);\n break;\n }\n default:\n throw new Error(\n `langchain provider: unknown lc_class \"${cls}\". ` +\n `Supported: ChatGoogleGenerativeAI, ChatCohere, ChatDeepSeek. ` +\n `To add another, install @langchain/<vendor> and extend lib/providers/langchain.ts.`\n );\n }\n cache.set(k, model);\n return model;\n}\n\n// ── Message conversion ──────────────────────────────────────────────────────\nfunction toLCMessages(messages: ProviderMessage[]): BaseMessage[] {\n return messages.map((m) => {\n if (m.role === \"system\") return new SystemMessage(m.content);\n if (m.role === \"assistant\") return new AIMessage(m.content);\n return new HumanMessage(m.content);\n });\n}\n\nfunction toLCInvokeMessages(messages: InvokeMessage[]): BaseMessage[] {\n return messages.map((m) => {\n if (m.role === \"system\") return new SystemMessage(typeof m.content === \"string\" ? m.content : \"\");\n if (m.role === \"tool\") {\n return new ToolMessage({\n content: typeof m.content === \"string\" ? m.content : JSON.stringify(m.content),\n tool_call_id: m.tool_call_id ?? \"\",\n });\n }\n if (m.role === \"assistant\") {\n const ai = new AIMessage({\n content: typeof m.content === \"string\" ? m.content : \"\",\n tool_calls: m.tool_calls?.map((tc) => ({\n id: tc.id,\n name: tc.function?.name ?? \"\",\n args: (() => { try { return JSON.parse(tc.function?.arguments ?? \"{}\"); } catch { return {}; } })(),\n type: \"tool_call\" as const,\n })) ?? [],\n });\n return ai;\n }\n return new HumanMessage(typeof m.content === \"string\" ? m.content : \"\");\n });\n}\n\nfunction toLCTools(tools: OpenAITool[]): Array<{ name: string; description: string; schema: unknown }> {\n return tools.flatMap((t) => {\n if (!t.function?.name) return [];\n return [{\n name: t.function.name,\n description: t.function.description ?? \"\",\n schema: t.function.parameters,\n }];\n });\n}\n\n// ── ModelProvider methods ───────────────────────────────────────────────────\nexport const langchainProvider: ModelProvider = {\n name: \"langchain\",\n\n async chat(model_id, messages, params): Promise<ProviderStreamResult> {\n const model = await loadLangChainModel(model_id, params);\n const stream = await model.stream(toLCMessages(messages));\n return {\n stream: (async function* () {\n for await (const chunk of stream) {\n if (typeof chunk.content === \"string\" && chunk.content) yield chunk.content;\n }\n })(),\n };\n },\n\n async invoke(model_id, messages, params, tools): Promise<InvokeResult> {\n const model = await loadLangChainModel(model_id, params);\n const bound: Runnable = tools.length > 0 && (model as { bindTools?: unknown }).bindTools\n ? (model as unknown as { bindTools: (t: unknown) => Runnable }).bindTools(toLCTools(tools))\n : model;\n const result = await bound.invoke(toLCInvokeMessages(messages)) as AIMessage;\n\n const text = typeof result.content === \"string\" ? result.content : extractText(result.content);\n const toolCalls = (result.tool_calls ?? []).map((tc) => ({\n id: tc.id ?? \"\",\n name: tc.name ?? \"\",\n arguments: (tc.args ?? {}) as Record<string, unknown>,\n }));\n return {\n text: text || null,\n tool_calls: toolCalls,\n stop_reason: toolCalls.length > 0 ? \"tool_use\" : \"stop\",\n };\n },\n\n streamInvoke(model_id, messages, params, tools): AsyncIterable<ProviderStreamEvent> {\n return (async function* () {\n const model = await loadLangChainModel(model_id, params);\n const bound: Runnable = tools.length > 0 && (model as { bindTools?: unknown }).bindTools\n ? (model as unknown as { bindTools: (t: unknown) => Runnable }).bindTools(toLCTools(tools))\n : model;\n\n const stream = await bound.stream(toLCInvokeMessages(messages)) as AsyncIterable<AIMessageChunk>;\n\n // Track which tool_call_chunk indices we've already announced an id for —\n // some providers send id once at start, others repeat it on every chunk.\n for await (const chunk of stream) {\n if (typeof chunk.content === \"string\" && chunk.content) {\n yield { type: \"text\", delta: chunk.content };\n } else if (Array.isArray(chunk.content)) {\n // Multi-modal content blocks (Gemini): pull text out, drop the rest.\n for (const block of chunk.content) {\n if (typeof block === \"object\" && block && \"type\" in block && block.type === \"text\" && \"text\" in block) {\n yield { type: \"text\", delta: String(block.text) };\n }\n }\n }\n const reasoning = chunk.additional_kwargs?.reasoning_content;\n if (typeof reasoning === \"string\" && reasoning) {\n yield { type: \"thinking\", delta: reasoning };\n }\n for (const tcc of chunk.tool_call_chunks ?? []) {\n yield {\n type: \"tool_call_chunk\",\n index: tcc.index ?? 0,\n id: tcc.id,\n name: tcc.name,\n args_delta: tcc.args,\n };\n }\n }\n })();\n },\n\n // Embeddings: LangChain has separate `Embeddings` classes per vendor and the\n // mapping isn't 1:1 with chat-model classes. Skipping here — recall falls\n // back to its substring path for langchain-provided models, which is fine.\n};\n\nfunction extractText(content: unknown): string {\n if (Array.isArray(content)) {\n return content\n .filter((b) => typeof b === \"object\" && b && (b as { type?: string }).type === \"text\")\n .map((b) => String((b as { text?: string }).text ?? \"\"))\n .join(\"\");\n }\n return \"\";\n}\n","// Mock/dummy model provider for tests, demos, and offline development.\n//\n// Behaviour is scripted via directives embedded in the *last user message*:\n//\n// MOCK:reply=Hello world // stream back exactly \"Hello world\"\n// MOCK:echo // echo the user message verbatim\n// MOCK:tool=web_search:{\"q\":\"x\"} // emit one tool_call (id=mock-1, args = JSON)\n// MOCK:think=reasoning here // emit a thinking delta before text\n// MOCK:slow=50 // sleep 50ms between word chunks\n// MOCK:error=overloaded // throw \"overloaded\"\n// MOCK:stop=length // override stop_reason (default \"stop\")\n//\n// Multiple directives may appear on separate lines; everything else in the\n// message is treated as plain context.\n//\n// Default behaviour (no directives): streams back \"Hello from the mock\n// provider. You said: <last user message>\".\n//\n// Registration is gated by JARELA_ENABLE_MOCK_PROVIDER=1 in index.ts so the\n// provider can't be accidentally enabled in production.\n\nimport { createHash } from \"node:crypto\";\nimport type {\n ModelProvider,\n ProviderMessage,\n ProviderParams,\n ProviderStreamResult,\n ProviderStreamEvent,\n InvokeMessage,\n InvokeResult,\n OpenAITool,\n} from \"./types\";\n\nconst DEFAULT_REPLY = \"Hello from the mock provider. You said: \";\nconst EMBED_DIM = 384;\n\nexport type MockDirectives = {\n reply?: string;\n echo?: boolean;\n tool?: { name: string; args: Record<string, unknown> };\n think?: string;\n slowMs?: number;\n error?: string;\n stopReason?: \"stop\" | \"tool_use\" | \"length\";\n};\n\n/** Parse `MOCK:<key>[=<value>]` directives out of a message string. Exported\n * for unit tests. */\nexport function parseMockDirectives(text: string): MockDirectives {\n const out: MockDirectives = {};\n for (const line of text.split(/\\r?\\n/)) {\n const m = /^\\s*MOCK:([a-zA-Z]+)(?:=(.*))?\\s*$/.exec(line);\n if (!m) continue;\n const key = m[1].toLowerCase();\n const value = m[2] ?? \"\";\n switch (key) {\n case \"reply\":\n out.reply = value;\n break;\n case \"echo\":\n out.echo = true;\n break;\n case \"tool\": {\n // tool=<name>[:<json-args>]\n const colon = value.indexOf(\":\");\n if (colon === -1) {\n out.tool = { name: value, args: {} };\n } else {\n const name = value.slice(0, colon);\n const argsRaw = value.slice(colon + 1);\n let args: Record<string, unknown> = {};\n try { args = JSON.parse(argsRaw) as Record<string, unknown>; } catch { /* leave empty */ }\n out.tool = { name, args };\n }\n break;\n }\n case \"think\":\n out.think = value;\n break;\n case \"slow\": {\n const n = Number(value);\n if (Number.isFinite(n) && n >= 0) out.slowMs = n;\n break;\n }\n case \"error\":\n out.error = value || \"mock error\";\n break;\n case \"stop\":\n if (value === \"stop\" || value === \"tool_use\" || value === \"length\") out.stopReason = value;\n break;\n }\n }\n return out;\n}\n\nfunction lastUserText(messages: { role: string; content: unknown }[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i];\n if (m.role !== \"user\") continue;\n if (typeof m.content === \"string\") return m.content;\n if (Array.isArray(m.content)) {\n const parts = m.content as { type: string; text?: string }[];\n return parts.filter((p) => p.type === \"text\").map((p) => p.text ?? \"\").join(\"\\n\");\n }\n return \"\";\n }\n return \"\";\n}\n\nfunction pickReply(directives: MockDirectives, userText: string): string {\n if (directives.reply !== undefined) return directives.reply;\n if (directives.echo) return userText;\n return DEFAULT_REPLY + userText;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction tokenize(text: string): string[] {\n // Split into whitespace-preserving chunks so the streaming feels real and\n // round-trips through the UI's incremental rendering.\n return text.match(/\\S+\\s*|\\s+/g) ?? (text ? [text] : []);\n}\n\nasync function* streamText(text: string, slowMs?: number): AsyncIterable<string> {\n for (const chunk of tokenize(text)) {\n if (slowMs) await sleep(slowMs);\n yield chunk;\n }\n}\n\nexport const mockProvider: ModelProvider = {\n name: \"mock\",\n\n async chat(_model_id, messages, _params: ProviderParams): Promise<ProviderStreamResult> {\n const userText = lastUserText(messages as ProviderMessage[]);\n const directives = parseMockDirectives(userText);\n if (directives.error) throw new Error(directives.error);\n const reply = pickReply(directives, userText);\n return {\n stream: streamText(reply, directives.slowMs),\n };\n },\n\n async invoke(_model_id, messages, _params, _tools: OpenAITool[]): Promise<InvokeResult> {\n const userText = lastUserText(messages as InvokeMessage[]);\n const directives = parseMockDirectives(userText);\n if (directives.error) throw new Error(directives.error);\n\n if (directives.tool) {\n return {\n text: null,\n tool_calls: [{\n id: \"mock-1\",\n name: directives.tool.name,\n arguments: directives.tool.args,\n }],\n stop_reason: \"tool_use\",\n };\n }\n return {\n text: pickReply(directives, userText),\n tool_calls: [],\n stop_reason: directives.stopReason ?? \"stop\",\n };\n },\n\n async *streamInvoke(\n _model_id,\n messages,\n _params,\n _tools: OpenAITool[],\n ): AsyncIterable<ProviderStreamEvent> {\n const userText = lastUserText(messages as InvokeMessage[]);\n const directives = parseMockDirectives(userText);\n if (directives.error) throw new Error(directives.error);\n\n if (directives.think) {\n for (const chunk of tokenize(directives.think)) {\n if (directives.slowMs) await sleep(directives.slowMs);\n yield { type: \"thinking\", delta: chunk };\n }\n }\n\n if (directives.tool) {\n const argsJson = JSON.stringify(directives.tool.args);\n yield { type: \"tool_call_chunk\", index: 0, id: \"mock-1\", name: directives.tool.name };\n yield { type: \"tool_call_chunk\", index: 0, args_delta: argsJson };\n yield { type: \"stop\", reason: \"tool_use\" };\n return;\n }\n\n const reply = pickReply(directives, userText);\n for (const chunk of tokenize(reply)) {\n if (directives.slowMs) await sleep(directives.slowMs);\n yield { type: \"text\", delta: chunk };\n }\n yield { type: \"stop\", reason: directives.stopReason ?? \"stop\" };\n },\n\n async embed(_model_id, inputs, _params): Promise<number[][]> {\n // Deterministic per-input vector seeded by sha256 of the input. Same\n // input always produces the same vector so semantic-recall tests can\n // assert stable rankings.\n return inputs.map((input) => {\n const hash = createHash(\"sha256\").update(input).digest();\n const vec = new Array<number>(EMBED_DIM);\n for (let i = 0; i < EMBED_DIM; i++) {\n // Repeat the 32-byte digest to fill EMBED_DIM. Map [0,255] -> [-1,1].\n vec[i] = (hash[i % hash.length] / 127.5) - 1;\n }\n // L2-normalise so cosine == dot product.\n let norm = 0;\n for (const x of vec) norm += x * x;\n norm = Math.sqrt(norm) || 1;\n for (let i = 0; i < EMBED_DIM; i++) vec[i] /= norm;\n return vec;\n });\n },\n};\n","import type { ModelProvider } from \"./types\";\nimport { openaiProvider } from \"./openai\";\nimport { anthropicProvider } from \"./anthropic\";\nimport { githubCopilotProvider } from \"./github-copilot\";\nimport { deepseekProvider } from \"./deepseek\";\nimport { geminiProvider } from \"./gemini\";\nimport { langchainProvider } from \"./langchain\";\nimport { mockProvider } from \"./mock\";\nimport { loadExternalProviders } from \"./external\";\n\nconst BUILTINS: Record<string, ModelProvider> = {\n openai: openaiProvider,\n anthropic: anthropicProvider,\n \"github-copilot\": githubCopilotProvider,\n deepseek: deepseekProvider,\n gemini: geminiProvider,\n langchain: langchainProvider,\n};\n\n// The mock provider is opt-in via env so production deployments never\n// expose it as a selectable backend. Tests / offline dev set the flag.\nfunction isMockEnabled(): boolean {\n return process.env.JARELA_ENABLE_MOCK_PROVIDER === \"1\";\n}\n\nexport const BUILTIN_PROVIDER_NAMES: ReadonlySet<string> = new Set([\n ...Object.keys(BUILTINS),\n \"mock\",\n]);\n\n// Recompute on every call so external providers dropped into ~/.jarela/providers/\n// are picked up without a process restart. loadExternalProviders cache-busts\n// require() per file, so edits are reflected immediately too.\nfunction getProviders(): Record<string, ModelProvider> {\n const base: Record<string, ModelProvider> = { ...BUILTINS };\n if (isMockEnabled()) base.mock = mockProvider;\n return { ...base, ...loadExternalProviders(BUILTIN_PROVIDER_NAMES) };\n}\n\nexport function listProviderNames(): string[] {\n return Object.keys(getProviders()).sort((a, b) => a.localeCompare(b));\n}\n\nexport function getProvider(name: string): ModelProvider {\n const all = getProviders();\n const p = all[name];\n if (!p) throw new Error(`Unknown provider: \"${name}\". Available: ${Object.keys(all).join(\", \")}`);\n return p;\n}\n\nexport { type ModelProvider };\nexport type { ProviderMessage, ProviderParams, ProviderStreamResult } from \"./types\";\n","// Master key management for at-rest encryption (ADR-0005).\n//\n// The key is a 32-byte value used by lib/crypto/envelope.ts for AES-256-GCM.\n// Primary storage is the host OS keychain via @napi-rs/keyring (its\n// keytar-compatible shim). We bootstrap synchronously by spawning a\n// one-shot child Node process so the rest of the codebase keeps its\n// synchronous store API.\n//\n// Fallback (when keychain access fails — headless Linux, locked Mac\n// keychain, missing keyring native binary): a 0600-permissioned file at\n// ${dataDir}/.secret-key. Same threat model as today's plaintext DB for\n// adversaries with filesystem read, but uniform so the encrypt/decrypt\n// code path stays single-shape.\n\nimport { execFileSync } from \"node:child_process\";\nimport {\n chmodSync,\n existsSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { randomBytes } from \"node:crypto\";\nimport { join } from \"node:path\";\n\nconst KEYCHAIN_SERVICE = \"jarela\";\nconst KEYCHAIN_ACCOUNT = \"master-key.v1\";\nconst KEYFILE_NAME = \".secret-key\";\n\nexport type MasterKeySource = \"keychain\" | \"keyfile\";\n\nlet _key: Buffer | null = null;\nlet _source: MasterKeySource | null = null;\n\n// Synchronously read or generate the master key. Idempotent; only does\n// real work on first call. Returns where the key ended up living so\n// callers can warn the user about the keyfile fallback.\n//\n// Resolution order:\n// 1. If ${dataDir}/.secret-key exists, use it. The keyfile is\n// authoritative once present: the on-disk rows were encrypted\n// with that key, and silently switching to a different key\n// source would orphan them. To migrate to the keychain, decrypt\n// with the keyfile + re-encrypt + delete the keyfile (see\n// scripts/rekey-to-keychain.mjs — TODO).\n// 2. Otherwise try the OS keychain via keytar (child process).\n// 3. Otherwise generate a fresh keyfile and warn the user.\nexport function initMasterKey(dataDir: string): { source: MasterKeySource } {\n if (_key && _source) return { source: _source };\n\n const path = join(dataDir, KEYFILE_NAME);\n\n // 1) Existing keyfile — authoritative.\n if (existsSync(path)) {\n _key = readFileSync(path);\n if (_key.length !== 32) throw new Error(`keyfile wrong length: ${_key.length}`);\n _source = \"keyfile\";\n return { source: \"keyfile\" };\n }\n\n // 2) Try keychain via a one-shot child process so we can stay sync.\n try {\n const keyB64 = loadOrCreateViaKeychain();\n _key = Buffer.from(keyB64, \"base64\");\n if (_key.length !== 32) throw new Error(`keychain key wrong length: ${_key.length}`);\n _source = \"keychain\";\n return { source: \"keychain\" };\n } catch (err) {\n console.warn(\n `[jarela] keychain unavailable, falling back to keyfile: ${(err as Error).message}`,\n );\n }\n\n // 3) Fallback: generate a fresh keyfile.\n _key = randomBytes(32);\n writeFileSync(path, _key, { mode: 0o600 });\n try { chmodSync(path, 0o600); } catch { /* */ }\n\n _source = \"keyfile\";\n return { source: \"keyfile\" };\n}\n\nexport function getMasterKey(): Buffer {\n if (!_key) {\n throw new Error(\n \"master key not initialized — initMasterKey() must run before any encrypted store access\",\n );\n }\n return _key;\n}\n\nexport function getMasterKeySource(): MasterKeySource | null {\n return _source;\n}\n\n// Spawn a child Node process that talks to the OS keyring and prints the\n// base64 key on stdout. Either reads the existing entry or generates a\n// new one and stores it. Synchronous from the caller's perspective.\nfunction loadOrCreateViaKeychain(): string {\n const script = `\n const keytar = require('@napi-rs/keyring/keytar');\n const { randomBytes } = require('crypto');\n (async () => {\n const SERVICE = ${JSON.stringify(KEYCHAIN_SERVICE)};\n const ACCOUNT = ${JSON.stringify(KEYCHAIN_ACCOUNT)};\n let v = await keytar.getPassword(SERVICE, ACCOUNT);\n if (!v) {\n v = randomBytes(32).toString('base64');\n await keytar.setPassword(SERVICE, ACCOUNT, v);\n }\n process.stdout.write(v);\n })().catch((e) => {\n process.stderr.write(String(e && e.message ? e.message : e));\n process.exit(1);\n });\n `;\n const out = execFileSync(process.execPath, [\"-e\", script], {\n encoding: \"utf8\",\n cwd: process.cwd(),\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n // Cap at 10s in case keytar hangs (e.g. macOS prompt with no user).\n timeout: 10_000,\n });\n return out.trim();\n}\n","// Thin wrapper over memory_store for integration credentials. The data lives\n// under namespace=\"integrations\", key=<integration name>, value=<JSON>. We\n// reuse memory_store so the existing Atlassian tool's fallback resolution\n// path \"just works\" without a second source of truth.\n//\n// Secret fields are echoed back to clients as a fixed sentinel string so\n// nothing sensitive ends up in the UI / network logs / browser inspector.\n\nimport { getMemory, putMemory, deleteMemory, listMemory } from \"@/lib/stores/memory\";\nimport { getIntegrationMeta, markFieldsAsUserTouched } from \"@/lib/stores/integration_meta\";\n\nexport const SECRET_MASK = \"********\";\nconst NAMESPACE = \"integrations\";\n\n// Persona-filter category. Mirrors the category enum in\n// lib/integrations/manifest.ts so we can drive the Credentials panel\n// off the same vocabulary the agent uses when explaining setup.\n// llm - LLM provider keys (Google, OpenAI, …)\n// mail - inbox + draft tools (Gmail, Outlook)\n// calendar - calendar event tools\n// issue-tracker - Jira / Jira Align / etc.\n// chat - messaging bridges (future)\n// infrastructure - GitHub / cloud / k8s / …\n// other - everything else\nexport type IntegrationCategory =\n | \"llm\"\n | \"mail\"\n | \"calendar\"\n | \"issue-tracker\"\n | \"chat\"\n | \"infrastructure\"\n | \"other\";\n\n// Per-integration shape. Adding a new integration means:\n// 1. Add an entry here naming its fields and which are secrets.\n// 2. The Atlassian tool (or a future tool) reads via getIntegration().\nexport const INTEGRATIONS = {\n anthropic: {\n label: \"Anthropic (Claude)\",\n category: \"llm\" as IntegrationCategory,\n description: \"Used by Claude-family chat models. Get a key at console.anthropic.com → API keys.\",\n fields: [\n { key: \"api_key\", label: \"API key\", placeholder: \"sk-ant-…\", secret: true, required: true },\n ],\n },\n atlassian: {\n label: \"Atlassian (Jira + Confluence)\",\n category: \"issue-tracker\" as IntegrationCategory,\n description: \"Used by jira_* and confluence_* tools. Get an API token at id.atlassian.com → Security → API tokens.\",\n fields: [\n { key: \"url\", label: \"Site URL\", placeholder: \"https://your-team.atlassian.net\", secret: false, required: true },\n { key: \"email\", label: \"Account email\", placeholder: \"you@company.com\", secret: false, required: true },\n { key: \"api_token\", label: \"API token\", placeholder: \"ATATT3xFfGF0…\", secret: true, required: true },\n ],\n },\n jira_align: {\n label: \"Jira Align\",\n category: \"issue-tracker\" as IntegrationCategory,\n description:\n \"Used by jira_align_* tools (read/search/walk hierarchy, create/update/transition/delete \" +\n \"work items, comment). Generate an API token in Jira Align under Settings → Personal \" +\n \"Access Tokens. Different surface from Jira Cloud — this is the portfolio-level product.\",\n fields: [\n { key: \"url\", label: \"Instance URL\", placeholder: \"https://your-company.jiraalign.com\", secret: false, required: true },\n { key: \"api_token\", label: \"API token\", placeholder: \"eyJ…\", secret: true, required: true },\n ],\n },\n google: {\n label: \"Google AI (Gemini + Imagen)\",\n category: \"llm\" as IntegrationCategory,\n description: \"Used by the generate_image tool (Gemini / Imagen). Get a key at aistudio.google.com → API keys.\",\n fields: [\n { key: \"api_key\", label: \"API key\", placeholder: \"AIza…\", secret: true, required: true },\n ],\n },\n gmail: {\n label: \"Gmail + Calendar\",\n category: \"mail\" as IntegrationCategory,\n description:\n \"Used by the gmail_* and calendar_* tools (search/read/draft/label/archive mail; \" +\n \"list/create/update/delete calendar events). Drafts only \\u2014 this integration \" +\n \"intentionally cannot send mail. See the Setup guide below for how to create the \" +\n \"OAuth client. Existing connections must reconnect to grant the new Calendar scope.\",\n fields: [\n { key: \"client_id\", label: \"OAuth client ID\", placeholder: \"<id>.apps.googleusercontent.com\", secret: false, required: true },\n { key: \"client_secret\", label: \"OAuth client secret\", placeholder: \"GOCSPX-…\", secret: true, required: true },\n { key: \"refresh_token\", label: \"Refresh token\", placeholder: \"1//0…\", secret: true, required: true },\n ],\n }, github: {\n label: \"GitHub\",\n category: \"infrastructure\" as IntegrationCategory,\n description:\n \"Used by github_* tools (search/read/create/comment on issues + PRs, list PRs, get repo info). \" +\n \"Create a Personal Access Token at github.com/settings/tokens. Scopes: `repo` (private repos) or \" +\n \"`public_repo` (public only); add `read:org` if you target org repos.\",\n fields: [\n { key: \"token\", label: \"Personal Access Token\", placeholder: \"ghp_… or github_pat_…\", secret: true, required: true },\n ],\n },\n outlook: {\n label: \"Outlook + Calendar\",\n category: \"mail\" as IntegrationCategory,\n description:\n \"Used by the outlook_* and outlook_calendar_* tools (search/read/draft/move/trash mail; \" +\n \"list/create/update/delete calendar events). Drafts only — this integration intentionally \" +\n \"cannot send mail. Requires an Azure app registration. See the Setup guide below.\",\n fields: [\n { key: \"client_id\", label: \"Application (client) ID\", placeholder: \"00000000-0000-0000-0000-000000000000\", secret: false, required: true },\n { key: \"client_secret\", label: \"Client secret value\", placeholder: \"abc~…\", secret: true, required: true },\n { key: \"refresh_token\", label: \"Refresh token\", placeholder: \"0.AXoA…\", secret: true, required: true },\n ],\n },} as const;\n\nexport type IntegrationName = keyof typeof INTEGRATIONS;\n\nexport function isKnownIntegration(name: string): name is IntegrationName {\n return Object.prototype.hasOwnProperty.call(INTEGRATIONS, name);\n}\n\nexport interface IntegrationStatus {\n name: string;\n configured: boolean;\n values: Record<string, string>; // secrets masked\n updated_at: string | null;\n /**\n * Per-field provenance. `\"rc\"` = pulled from a shell rc / Windows\n * registry env var by the env-syncer. `\"user\"` = the user typed it\n * into the panel. Absent fields haven't been seen by either path.\n * Drives the \"from your shell\" badge in the IntegrationsPanel.\n */\n source?: Record<string, \"rc\" | \"user\">;\n /** Last successful rc-sync write time, ISO. Null until the first sync. */\n rc_synced_at?: string | null;\n}\n\nexport function listIntegrations(): IntegrationStatus[] {\n const rows = listMemory(NAMESPACE, undefined, 100);\n const byKey = new Map(rows.map((r) => [r.key, r]));\n return Object.keys(INTEGRATIONS).map((name) => {\n const row = byKey.get(name);\n const meta = getIntegrationMeta(name);\n if (!row) {\n return {\n name,\n configured: false,\n values: {},\n updated_at: null,\n source: meta.source,\n rc_synced_at: meta.rc_synced_at,\n };\n }\n return {\n name,\n configured: true,\n values: maskSecrets(name as IntegrationName, parseValue(row.value)),\n updated_at: row.updated_at,\n source: meta.source,\n rc_synced_at: meta.rc_synced_at,\n };\n });\n}\n\nexport function getIntegrationStatus(name: string): IntegrationStatus | null {\n if (!isKnownIntegration(name)) return null;\n const row = getMemory(NAMESPACE, name);\n const meta = getIntegrationMeta(name);\n if (!row) {\n return {\n name,\n configured: false,\n values: {},\n updated_at: null,\n source: meta.source,\n rc_synced_at: meta.rc_synced_at,\n };\n }\n return {\n name,\n configured: true,\n values: maskSecrets(name, parseValue(row.value)),\n updated_at: row.updated_at,\n source: meta.source,\n rc_synced_at: meta.rc_synced_at,\n };\n}\n\n// Internal: server-side resolution that returns RAW secrets. Only callable\n// from server code (the integration tools).\nexport function getIntegrationRaw(name: string): Record<string, string> | null {\n const row = getMemory(NAMESPACE, name);\n if (!row) return null;\n return parseValue(row.value);\n}\n\n// Save credentials. Any field whose value matches SECRET_MASK is preserved\n// from the existing record (so unchanged secret fields don't get blanked\n// when the UI sends back the masked form).\nexport function saveIntegration(name: string, incoming: Record<string, string>): IntegrationStatus | { error: string } {\n if (!isKnownIntegration(name)) return { error: `unknown integration \"${name}\"` };\n const def = INTEGRATIONS[name];\n const existing = getIntegrationRaw(name) ?? {};\n const merged: Record<string, string> = {};\n // Track which fields the user actually changed (vs preserved via SECRET_MASK).\n // Only changed fields flip source to \"user\" — if they re-saved without\n // touching the secret, it stays whatever it was (rc or user).\n const touched: string[] = [];\n for (const f of def.fields) {\n const v = incoming[f.key];\n if (v === undefined) {\n if (existing[f.key]) merged[f.key] = existing[f.key];\n else if (f.required) return { error: `missing required field \"${f.key}\"` };\n continue;\n }\n if (f.secret && v === SECRET_MASK) {\n // UI returned masked sentinel — keep existing secret untouched.\n if (existing[f.key]) merged[f.key] = existing[f.key];\n else if (f.required) return { error: `missing required secret \"${f.key}\"` };\n } else {\n if (f.required && !v.trim()) return { error: `\"${f.key}\" cannot be empty` };\n merged[f.key] = v;\n if (existing[f.key] !== v) touched.push(f.key);\n }\n }\n putMemory(NAMESPACE, name, merged);\n if (touched.length > 0) markFieldsAsUserTouched(name, touched);\n return getIntegrationStatus(name)!;\n}\n\nexport function deleteIntegration(name: string): boolean {\n if (!isKnownIntegration(name)) return false;\n return deleteMemory(NAMESPACE, name);\n}\n\nfunction parseValue(raw: string): Record<string, string> {\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (parsed && typeof parsed === \"object\") {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof v === \"string\") out[k] = v;\n }\n return out;\n }\n } catch { /* */ }\n return {};\n}\n\nfunction maskSecrets(name: IntegrationName, values: Record<string, string>): Record<string, string> {\n const out: Record<string, string> = {};\n for (const f of INTEGRATIONS[name].fields) {\n const v = values[f.key];\n if (v === undefined) continue;\n out[f.key] = f.secret ? SECRET_MASK : v;\n }\n return out;\n}\n","import { getDb } from \"@/lib/db\";\nimport { encrypt, decryptIfNeeded } from \"@/lib/crypto/envelope\";\nimport type { ProviderParams } from \"@/lib/providers/types\";\n\nconst now = () => new Date().toISOString();\n\nexport interface ModelConfigRow {\n name: string; provider: string; model_id: string;\n params: string; is_default: number;\n created_at: string; updated_at: string;\n}\n\n// `params` holds the provider API key alongside hyperparameters and is\n// stored encrypted at rest (ADR-0005). Decrypt before returning rows.\nfunction decryptRow<T extends { params: string }>(row: T): T {\n return { ...row, params: decryptIfNeeded(row.params) };\n}\n\nexport function listModelConfigs(): ModelConfigRow[] {\n const rows = getDb()\n .prepare(\"SELECT * FROM model_configs ORDER BY is_default DESC, name ASC\")\n .all() as unknown as ModelConfigRow[];\n return rows.map(decryptRow);\n}\n\nexport function getModelConfig(name: string): ModelConfigRow | null {\n const row = (getDb().prepare(\"SELECT * FROM model_configs WHERE name=?\").get(name) as unknown as ModelConfigRow) ?? null;\n return row ? decryptRow(row) : null;\n}\n\nexport function getDefaultModelConfig(): ModelConfigRow | null {\n const row = (getDb().prepare(\"SELECT * FROM model_configs WHERE is_default=1 LIMIT 1\").get() as unknown as ModelConfigRow) ?? null;\n return row ? decryptRow(row) : null;\n}\n\nexport function upsertModelConfig(\n name: string, provider: string, model_id: string,\n params: Record<string, unknown>, is_default: boolean\n): ModelConfigRow {\n const t = now();\n const existing = getModelConfig(name);\n const created_at = existing?.created_at ?? t;\n const db = getDb();\n if (is_default) db.prepare(\"UPDATE model_configs SET is_default=0\").run();\n db.prepare(\n \"INSERT OR REPLACE INTO model_configs (name,provider,model_id,params,is_default,created_at,updated_at) VALUES (?,?,?,?,?,?,?)\"\n ).run(name, provider, model_id, encrypt(JSON.stringify(params)), is_default ? 1 : 0, created_at, t);\n return getModelConfig(name)!;\n}\n\nexport function deleteModelConfig(name: string): boolean {\n return (getDb().prepare(\"DELETE FROM model_configs WHERE name=?\").run(name) as { changes: number }).changes > 0;\n}\n\n/**\n * Decode the JSON-encoded provider params (api_key, model overrides, etc.).\n * Returns an empty object on NULL/blank/malformed JSON. Callers that\n * previously did `JSON.parse(cfg.params)` inline should switch to this\n * getter so the serialization contract stays owned by this store.\n */\nexport function getModelParams(cfg: Pick<ModelConfigRow, \"params\"> | null | undefined): ProviderParams {\n if (!cfg?.params) return {};\n try {\n const parsed = JSON.parse(cfg.params);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as ProviderParams;\n }\n return {};\n } catch {\n return {};\n }\n}\n","import { getDb } from \"@/lib/db\";\nimport { embedOne } from \"@/lib/embeddings\";\nimport { encrypt, decryptIfNeeded } from \"@/lib/crypto/envelope\";\nimport { isSensitiveMemoryNamespace } from \"@/lib/crypto/sensitive\";\n\nconst now = () => new Date().toISOString();\n\n// Explicit column list for memory reads — omits `embedding` (~20KB of\n// JSON-encoded float[] per row), which only the embeddings module reads.\n// Avoids dragging it through the listMemory / getMemory result set.\nconst MEM_COLS_SQL = \"SELECT namespace, key, value, created_at, updated_at FROM memory_store\";\n\n// Decrypt rows in sensitive namespaces before handing them back to\n// callers. Non-sensitive namespaces pass through untouched (their values\n// are not encrypted at rest, by design — see ADR-0005).\nfunction decryptRow(row: MemoryRow): MemoryRow {\n if (!isSensitiveMemoryNamespace(row.namespace)) return row;\n return { ...row, value: decryptIfNeeded(row.value) };\n}\n\n// Fire-and-forget: compute and persist an embedding without blocking the write.\n// Failures (no embed provider, network down) are logged in embeddings/index.ts\n// and the row simply stays without an embedding — recall falls back to substring.\nfunction asyncEmbed(text: string, persist: (vec: number[]) => void): void {\n embedOne(text).then((vec) => { if (vec) persist(vec); }).catch(() => { /* already logged */ });\n}\n\nexport interface MemoryRow {\n namespace: string; key: string; value: string;\n created_at: string; updated_at: string;\n}\n\nexport function listMemory(namespace?: string, search?: string, limit = 50): MemoryRow[] {\n let sql = MEM_COLS_SQL + \" WHERE 1=1\";\n const params: (string | number)[] = [];\n if (namespace) { sql += \" AND namespace=?\"; params.push(namespace); }\n if (search) { sql += \" AND (key LIKE ? OR value LIKE ?)\"; params.push(`%${search}%`, `%${search}%`); }\n sql += \" ORDER BY updated_at DESC LIMIT ?\";\n params.push(limit);\n const rows = getDb().prepare(sql).all(...params) as unknown as MemoryRow[];\n // P2.7: when the caller pinned the namespace and it isn't in the\n // sensitive set, every row's value is plaintext anyway — skip the\n // per-row decryptRow allocation. The unfiltered case still has to\n // check each row since namespaces vary.\n if (namespace && !isSensitiveMemoryNamespace(namespace)) return rows;\n return rows.map(decryptRow);\n}\n\nexport function getMemory(namespace: string, key: string): MemoryRow | null {\n const row = (getDb().prepare(MEM_COLS_SQL + \" WHERE namespace=? AND key=?\").get(namespace, key) as unknown as MemoryRow) ?? null;\n return row ? decryptRow(row) : null;\n}\n\nexport function putMemory(namespace: string, key: string, value: unknown): MemoryRow {\n const t = now();\n // Only the original created_at is needed to preserve insertion time on\n // upsert; reading the full row would force an unnecessary AES-GCM\n // decrypt of an existing sensitive value just to discard it.\n const existing = getDb()\n .prepare(\"SELECT created_at FROM memory_store WHERE namespace=? AND key=?\")\n .get(namespace, key) as { created_at?: string } | undefined;\n const created_at = existing?.created_at ?? t;\n const json = JSON.stringify(value);\n // Encrypt the value column at rest for sensitive namespaces (ADR-0005).\n // Embeddings (below) keep using the plaintext text so semantic recall\n // still works for non-sensitive namespaces; sensitive namespaces are\n // not the kind of content we expect semantic recall against anyway.\n const stored = isSensitiveMemoryNamespace(namespace) ? encrypt(json) : json;\n getDb()\n .prepare(\"INSERT OR REPLACE INTO memory_store (namespace,key,value,created_at,updated_at,embedding) VALUES (?,?,?,?,?,NULL)\")\n .run(namespace, key, stored, created_at, t);\n // Embed the value text (not the JSON wrapping) so recall matches the semantic content.\n const text = typeof value === \"string\" ? value : json;\n asyncEmbed(`${namespace}/${key}: ${text}`, (vec) => {\n getDb()\n .prepare(\"UPDATE memory_store SET embedding=? WHERE namespace=? AND key=?\")\n .run(JSON.stringify(vec), namespace, key);\n });\n return { namespace, key, value: json, created_at, updated_at: t };\n}\n\nexport function deleteMemory(namespace: string, key: string): boolean {\n return (getDb().prepare(\"DELETE FROM memory_store WHERE namespace=? AND key=?\").run(namespace, key) as { changes: number }).changes > 0;\n}\n","import { join } from \"node:path\";\nimport { existsSync, readdirSync, statSync } from \"node:fs\";\nimport type { ModelProvider } from \"./types\";\nimport { getDataDir } from \"@/lib/db/data-dir\";\n\nexport const PROVIDERS_DIR = join(getDataDir(), \"providers\");\n\nexport interface ExtensionLoadError {\n file: string;\n error: string;\n}\n\nexport interface ExternalProvidersResult {\n providers: Record<string, ModelProvider>;\n files: Map<string, string>;\n errors: ExtensionLoadError[];\n}\n\nfunction isValid(p: unknown): p is ModelProvider {\n if (!p || typeof p !== \"object\") return false;\n const o = p as Record<string, unknown>;\n return typeof o.name === \"string\" && typeof o.chat === \"function\";\n}\n\nexport function loadExternalProvidersDetailed(\n builtins: ReadonlySet<string>,\n): ExternalProvidersResult {\n const providers: Record<string, ModelProvider> = {};\n const files = new Map<string, string>();\n const errors: ExtensionLoadError[] = [];\n if (!existsSync(PROVIDERS_DIR)) return { providers, files, errors };\n\n // Reach for node:module via process.getBuiltinModule so webpack cannot\n // see the dependency and tree-shake it. With a normal `import { createRequire }\n // from \"node:module\"`, Next/webpack drops the call entirely (the result is\n // judged side-effect-free), leaving the require binding undefined at runtime.\n // process.getBuiltinModule is a Node 22+ API that bypasses both the module\n // graph and webpack's static analysis. Anchor to a real on-disk path — not\n // import.meta.url, which is rewritten to a virtual chunk URL that would\n // route absolute requires back through webpack's resolver.\n const { createRequire } = (\n process as unknown as { getBuiltinModule: (id: string) => typeof import(\"node:module\") }\n ).getBuiltinModule(\"node:module\");\n const req = createRequire(join(PROVIDERS_DIR, \"_anchor\"));\n\n let entries: string[];\n try {\n entries = readdirSync(PROVIDERS_DIR);\n } catch {\n return { providers, files, errors };\n }\n\n for (const entry of entries) {\n if (!/\\.(c?js|ts)$/i.test(entry)) continue;\n const path = join(PROVIDERS_DIR, entry);\n try {\n if (!statSync(path).isFile()) continue;\n } catch {\n continue;\n }\n\n let mod: unknown;\n try {\n delete req.cache[req.resolve(path)];\n mod = req(path);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n errors.push({ file: entry, error: message });\n console.error(`[providers] failed to load ${entry}:`, err);\n continue;\n }\n\n const candidate =\n (mod as { default?: unknown })?.default ?? (mod as unknown);\n if (!isValid(candidate)) {\n const msg = \"does not export a valid ModelProvider (need { name, chat })\";\n errors.push({ file: entry, error: msg });\n console.error(`[providers] ${entry} ${msg}`);\n continue;\n }\n\n const name = candidate.name;\n if (builtins.has(name)) {\n const msg = `name \"${name}\" collides with a built-in provider — built-in takes precedence`;\n errors.push({ file: entry, error: msg });\n console.warn(`[providers] external ${entry}: ${msg}`);\n continue;\n }\n if (providers[name]) {\n const msg = `duplicate external provider \"${name}\"`;\n errors.push({ file: entry, error: msg });\n console.warn(`[providers] ${entry}: ${msg}`);\n continue;\n }\n providers[name] = candidate;\n files.set(name, entry);\n }\n\n return { providers, files, errors };\n}\n\n// Convenience for callers that only need the provider map (the existing\n// pattern in lib/providers/index.ts).\nexport function loadExternalProviders(\n builtins: ReadonlySet<string>,\n): Record<string, ModelProvider> {\n return loadExternalProvidersDetailed(builtins).providers;\n}\n","// GitHub Copilot device-flow login. Lets users sign in with their Copilot\n// subscription instead of pasting a PAT (which can't be exchanged for a\n// Copilot session token and gets rate-limited on the Models REST API).\n//\n// Flow (RFC 8628):\n// 1. POST github.com/login/device/code with the VS Code Copilot client_id.\n// 2. Show the user_code + verification_uri so the user can approve.\n// 3. Poll github.com/login/oauth/access_token until success/expiry.\n// 4. Persist the resulting OAuth access token (gho_...) in memory_store.\n// 5. At request time, exchange that OAuth token for a Copilot session token\n// via api.github.com/copilot_internal/v2/token (already implemented in\n// github-copilot.ts).\n\nimport { getMemory, putMemory, deleteMemory } from \"@/lib/stores/memory\";\n\n// Public client ID used by the official VS Code GitHub Copilot extension.\n// Same value is hard-coded into many open-source Copilot clients.\nconst COPILOT_CLIENT_ID = \"Iv1.b507a08c87ecfe98\";\nconst SCOPE = \"read:user\";\n\nconst NAMESPACE = \"github-copilot-auth\";\nconst KEY_OAUTH = \"oauth_token\";\n\nexport interface DeviceCodeResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n expires_in: number;\n interval: number;\n}\n\nexport interface PollResult {\n status: \"pending\" | \"success\" | \"slow_down\" | \"expired\" | \"denied\" | \"error\";\n access_token?: string;\n error?: string;\n}\n\nexport async function startDeviceFlow(): Promise<DeviceCodeResponse> {\n const res = await fetch(\"https://github.com/login/device/code\", {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"Jarela/1.0\",\n },\n body: JSON.stringify({ client_id: COPILOT_CLIENT_ID, scope: SCOPE }),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => res.statusText);\n throw new Error(`GitHub device code request failed (${res.status}): ${body}`);\n }\n const json = await res.json() as DeviceCodeResponse;\n if (!json.device_code || !json.user_code) {\n throw new Error(\"GitHub device code response missing required fields\");\n }\n return json;\n}\n\nexport async function pollDeviceFlow(device_code: string): Promise<PollResult> {\n const res = await fetch(\"https://github.com/login/oauth/access_token\", {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"Jarela/1.0\",\n },\n body: JSON.stringify({\n client_id: COPILOT_CLIENT_ID,\n device_code,\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n }),\n });\n if (!res.ok) {\n return { status: \"error\", error: `HTTP ${res.status}` };\n }\n const json = await res.json() as {\n access_token?: string;\n error?: string;\n error_description?: string;\n };\n if (json.access_token) {\n storeOAuthToken(json.access_token);\n return { status: \"success\", access_token: json.access_token };\n }\n switch (json.error) {\n case \"authorization_pending\": return { status: \"pending\" };\n case \"slow_down\": return { status: \"slow_down\" };\n case \"expired_token\": return { status: \"expired\" };\n case \"access_denied\": return { status: \"denied\" };\n default: return { status: \"error\", error: json.error_description || json.error || \"unknown\" };\n }\n}\n\nexport function storeOAuthToken(token: string): void {\n putMemory(NAMESPACE, KEY_OAUTH, { token, stored_at: new Date().toISOString() });\n}\n\nexport function getStoredOAuthToken(): string | null {\n const row = getMemory(NAMESPACE, KEY_OAUTH);\n if (!row) return null;\n try {\n const parsed = JSON.parse(row.value) as { token?: string };\n return parsed.token ?? null;\n } catch {\n return null;\n }\n}\n\nexport function clearStoredOAuthToken(): boolean {\n return deleteMemory(NAMESPACE, KEY_OAUTH);\n}\n\nexport function getAuthStatus(): { signed_in: boolean; stored_at: string | null } {\n const row = getMemory(NAMESPACE, KEY_OAUTH);\n if (!row) return { signed_in: false, stored_at: null };\n try {\n const parsed = JSON.parse(row.value) as { stored_at?: string };\n return { signed_in: true, stored_at: parsed.stored_at ?? row.updated_at };\n } catch {\n return { signed_in: true, stored_at: row.updated_at };\n }\n}\n","// Per-field metadata for integration credentials. Sits beside the\n// integration values (lib/stores/integrations.ts) and tracks where each\n// field's value came from — `\"rc\"` means env-sync wrote it, `\"user\"`\n// means the user typed it into the Integrations panel.\n//\n// The env-syncer (lib/env/sync.ts) only overwrites fields whose source\n// is `\"rc\"` (or absent). The moment a user edits the field in the panel\n// the source flips to `\"user\"` and the syncer leaves it alone — this is\n// the \"panel-wins-once-touched\" conflict rule.\n//\n// Stored in its own memory_store namespace `integration_meta`. Not\n// encrypted — the metadata itself contains no secrets, just provenance\n// flags + a sync timestamp.\n\nimport { getMemory, putMemory } from \"@/lib/stores/memory\";\n\nconst NAMESPACE = \"integration_meta\";\n\nexport type FieldSource = \"rc\" | \"user\";\n\nexport interface IntegrationMeta {\n /** Source flag per field key (e.g. `{ token: \"rc\" }`). */\n source: Record<string, FieldSource>;\n /** ISO timestamp of the last successful rc sync that wrote this row. */\n rc_synced_at: string | null;\n}\n\nconst EMPTY: IntegrationMeta = { source: {}, rc_synced_at: null };\n\nexport function getIntegrationMeta(name: string): IntegrationMeta {\n const row = getMemory(NAMESPACE, name);\n if (!row) return { ...EMPTY, source: {} };\n try {\n const parsed = JSON.parse(row.value) as Partial<IntegrationMeta> | null;\n return {\n source: (parsed?.source && typeof parsed.source === \"object\") ? parsed.source as Record<string, FieldSource> : {},\n rc_synced_at: parsed?.rc_synced_at ?? null,\n };\n } catch {\n return { ...EMPTY, source: {} };\n }\n}\n\n/**\n * Update many fields across many integrations in one pass. Keeps DB\n * writes proportional to changed integrations, not changed fields.\n */\nexport function setFieldSources(\n updates: Array<{ name: string; field: string; source: FieldSource }>,\n rcSyncedAt?: string,\n): void {\n if (updates.length === 0) return;\n const byName = new Map<string, IntegrationMeta>();\n for (const u of updates) {\n let m = byName.get(u.name);\n if (!m) {\n m = getIntegrationMeta(u.name);\n byName.set(u.name, m);\n }\n m.source[u.field] = u.source;\n if (rcSyncedAt && u.source === \"rc\") m.rc_synced_at = rcSyncedAt;\n }\n for (const [name, meta] of byName) putMemory(NAMESPACE, name, meta);\n}\n\n/** Convenience for the common \"user just edited these fields\" case. */\nexport function markFieldsAsUserTouched(name: string, fields: string[]): void {\n if (fields.length === 0) return;\n setFieldSources(fields.map((f) => ({ name, field: f, source: \"user\" })));\n}\n","// Proxy configuration store (ADR-0009, extended ADR-0012).\n//\n// Single-row table proxy_config. Non-secret columns are plaintext for\n// diagnostics; only `password` is wrapped through lib/crypto/envelope.ts\n// so the on-disk DB cannot reveal the proxy credential. `ca_bundle` is\n// a PEM (public cert) so it stays plaintext as well.\n//\n// Two read shapes:\n// - getProxyConfigStatus(): UI shape — password masked as SECRET_MASK\n// - getProxyConfigRaw(): server-only — returns the real password\n// so lib/proxy/dispatcher.ts can build a\n// ProxyAgent\n//\n// The save handler accepts SECRET_MASK as the sentinel for \"keep\n// existing password\" so the UI can echo back the masked form without\n// blanking the secret.\n\nimport { getDb } from \"@/lib/db\";\nimport { decryptIfNeeded, encrypt } from \"@/lib/crypto/envelope\";\nimport { SECRET_MASK } from \"@/lib/stores/integrations\";\n\nexport type ProxyMode = \"off\" | \"manual\" | \"system\";\nexport type ProxyScheme = \"http\" | \"https\";\n\nexport interface ProxyConfigStatus {\n mode: ProxyMode;\n scheme: ProxyScheme;\n host: string | null;\n port: number | null;\n username: string | null;\n password: string | null; // SECRET_MASK when set, null when unset\n no_proxy: string | null;\n ca_bundle: string | null; // PEM, plaintext\n updated_at: string | null;\n}\n\nexport interface ProxyConfigRaw {\n mode: ProxyMode;\n scheme: ProxyScheme;\n host: string | null;\n port: number | null;\n username: string | null;\n password: string | null; // plaintext\n no_proxy: string | null;\n ca_bundle: string | null;\n updated_at: string;\n}\n\nexport interface ProxyConfigInput {\n mode: ProxyMode;\n scheme?: ProxyScheme;\n host?: string | null;\n port?: number | null;\n username?: string | null;\n password?: string | null;\n no_proxy?: string | null;\n ca_bundle?: string | null;\n}\n\ninterface Row {\n mode: string;\n scheme: string | null;\n host: string | null;\n port: number | null;\n username: string | null;\n password: string | null;\n no_proxy: string | null;\n ca_bundle: string | null;\n updated_at: string;\n}\n\nconst DEFAULT_STATUS: ProxyConfigStatus = {\n mode: \"off\",\n scheme: \"http\",\n host: null,\n port: null,\n username: null,\n password: null,\n no_proxy: null,\n ca_bundle: null,\n updated_at: null,\n};\n\nexport function getProxyConfigStatus(): ProxyConfigStatus {\n const row = readRow();\n if (!row) return DEFAULT_STATUS;\n return {\n mode: normaliseMode(row.mode),\n scheme: normaliseScheme(row.scheme),\n host: row.host,\n port: row.port,\n username: row.username,\n password: row.password ? SECRET_MASK : null,\n no_proxy: row.no_proxy,\n ca_bundle: row.ca_bundle,\n updated_at: row.updated_at,\n };\n}\n\n// Server-only. Decrypts the password envelope. Never expose this to the\n// API surface — the dispatcher and any future test endpoint are the only\n// legitimate callers.\nexport function getProxyConfigRaw(): ProxyConfigRaw | null {\n const row = readRow();\n if (!row) return null;\n return {\n mode: normaliseMode(row.mode),\n scheme: normaliseScheme(row.scheme),\n host: row.host,\n port: row.port,\n username: row.username,\n password: row.password ? decryptIfNeeded(row.password) : null,\n no_proxy: row.no_proxy,\n ca_bundle: row.ca_bundle,\n updated_at: row.updated_at,\n };\n}\n\nexport function saveProxyConfig(input: ProxyConfigInput): ProxyConfigStatus | { error: string } {\n if (!isValidMode(input.mode)) return { error: `invalid mode \"${input.mode}\"` };\n\n const scheme: ProxyScheme = input.scheme === \"https\" ? \"https\" : \"http\";\n\n // Manual mode requires host + port. system / off don't.\n if (input.mode === \"manual\") {\n if (!input.host || !input.host.trim()) return { error: \"host is required in manual mode\" };\n if (input.port == null || !Number.isFinite(input.port) || input.port <= 0 || input.port > 65535) {\n return { error: \"port must be between 1 and 65535\" };\n }\n }\n\n // CA bundle: empty/null clears; non-empty must look like PEM.\n let storedCaBundle: string | null = null;\n if (input.ca_bundle != null && input.ca_bundle.trim().length > 0) {\n if (!input.ca_bundle.includes(\"-----BEGIN CERTIFICATE-----\")) {\n return { error: \"ca_bundle must be PEM (no BEGIN CERTIFICATE block found)\" };\n }\n storedCaBundle = input.ca_bundle;\n }\n\n // Preserve existing password when the UI echoes back the masked sentinel.\n const existing = readRow();\n let storedPassword: string | null = null;\n if (input.password === SECRET_MASK) {\n storedPassword = existing?.password ?? null;\n } else if (input.password && input.password.length > 0) {\n storedPassword = encrypt(input.password);\n } else {\n storedPassword = null;\n }\n\n const now = new Date().toISOString();\n const db = getDb();\n db.prepare(\n `INSERT INTO proxy_config (id, mode, scheme, host, port, username, password, no_proxy, ca_bundle, updated_at)\n VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n mode = excluded.mode,\n scheme = excluded.scheme,\n host = excluded.host,\n port = excluded.port,\n username = excluded.username,\n password = excluded.password,\n no_proxy = excluded.no_proxy,\n ca_bundle = excluded.ca_bundle,\n updated_at = excluded.updated_at`,\n ).run(\n input.mode,\n scheme,\n nullable(input.host),\n input.port ?? null,\n nullable(input.username),\n storedPassword,\n nullable(input.no_proxy),\n storedCaBundle,\n now,\n );\n\n return getProxyConfigStatus();\n}\n\nexport function deleteProxyConfig(): boolean {\n const db = getDb();\n const r = db.prepare(\"DELETE FROM proxy_config WHERE id = 1\").run();\n return r.changes > 0;\n}\n\nfunction readRow(): Row | null {\n const db = getDb();\n const r = db\n .prepare(\n \"SELECT mode, scheme, host, port, username, password, no_proxy, ca_bundle, updated_at FROM proxy_config WHERE id = 1\",\n )\n .get() as Row | undefined;\n return r ?? null;\n}\n\nfunction isValidMode(m: string): m is ProxyMode {\n return m === \"off\" || m === \"manual\" || m === \"system\";\n}\n\nfunction normaliseMode(m: string): ProxyMode {\n return isValidMode(m) ? m : \"off\";\n}\n\nfunction normaliseScheme(s: string | null | undefined): ProxyScheme {\n return s === \"https\" ? \"https\" : \"http\";\n}\n\nfunction nullable(v: string | null | undefined): string | null {\n if (v == null) return null;\n const trimmed = v.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n"],"names":["MBTI_PRESETS","now","Date","toISOString","runMigrations","db","exec","ensureBridgeRouteColumns","ensureAgentConfigColumns","ensureTaskAssignmentColumns","ensureEmbeddingColumns","ensureUserProfileLocationColumns","ensureProxyConfigSchemeAndCaBundle","ensureThreadsAgentIdUnique","ensureMessagesCategoryColumn","ensureMessagesMetadataColumn","ensureScheduledTasksSilentColumn","ensureAgentDisplayFiltersColumn","ensureDocumentSourceRemoteColumns","ensureWatchersReactionPromptColumn","ensureWatchersReactionKindColumns","ensureScheduledTasksReactionKindColumns","ensureMessageUsageTable","ensureMessageUsageTierColumns","ensureMessageUsageCacheColumns","ensureThreadContextPinColumns","ensureThreadChannelSummariesTable","seedModelConfigs","seedAgentConfigs","memCols","prepare","all","Set","map","c","name","has","msgColSet","cols","names","some","idx","get","agentCols","count","n","reanchorOrphanThreads","t","insert","p","BASE_AGENT_PROFILES","preset","mbti","run","id","icon","identity","instructions","JSON","stringify","tools","is_default","never_reply","adaptive","strength","empathy","expressiveness","verbosity","seeds","s","encrypt","isEncrypted","SENSITIVE_MEMORY_NAMESPACES","runCryptoMigration","touched","nsList","placeholders","join","memoryRows","memUpdate","row","value","namespace","key","modelRows","modelUpdate","params","mcpRows","mcpUpdate","spec","console","info","DatabaseSync","getDataDir","initMasterKey","applyProxyConfigFromDb","runEnvSyncOnce","DB_PATH","_db","getDb","source","warn","catch","err","then","r","applied_count","log","discovered","closeDb","close","NS","EMBEDDING_MODEL_KEY","getEmbeddingModelConfigName","raw","parsed","parse","trim","setEmbeddingModelConfigName","existing","created","created_at","createCipheriv","createDecipheriv","randomBytes","getMasterKey","PREFIX","IV_LEN","TAG_LEN","startsWith","plaintext","iv","cipher","ct","Buffer","concat","update","final","tag","getAuthTag","toString","decrypt","envelope","Error","buf","from","slice","length","subarray","decipher","setAuthTag","pt","decryptIfNeeded","encryptIfNeeded","getProvider","getModelConfig","getDefaultModelConfig","getModelParams","listModelConfigs","EXCLUDED_NS","EXCLUDED_NS_PLACEHOLDERS","resolveEmbeddingClient","fromConfig","cfg","provider","embed","overridden","embedding_model_id","modelId","isChatModelId","model_id","explicitName","process","env","EMBEDDING_MODEL_CONFIG","explicit","configuredName","configured","fromDefault","configs","candidate","test","texts","client","message","String","embedOne","text","out","TRANSIENT_RE","isTransient","callEmbedWithRetry","backoffs","lastErr","attempt","Promise","setTimeout","embedBestEffort","vectors","error","failed","embedBestEffortInternal","padded","_","i","filter","v","msg","mid","Math","floor","left","right","cosine","a","b","dot","na","nb","denom","sqrt","recall","query","limit","qVec","scored","memRows","msgRows","parseEmbedding","embedding","push","content","score","thread_id","role","tokens","tokenize","recentMem","recentMsg","keywordOverlap","groups","Map","normalizeForDedup","set","max","Array","values","sort","replace","toLowerCase","STOP_WORDS","split","w","queryTokens","textLower","hits","includes","arr","isArray","every","getMemory","listMemory","putMemory","deleteMemory","INTEGRATIONS","getIntegrationRaw","isKnownIntegration","OVERRIDES_NS","ENV_ALLOWLIST","envVars","integration","field","OVERRIDE_KEY","parseOverride","listOverrides","undefined","getOverride","setOverride","ok","def","fields","f","defaults","defaultAliasesFor","cleaned","seen","toUpperCase","add","deleteOverride","m","find","getEffectiveAllowlist","overrides","extra","merged","getAllEnvVarNames","getInjectedSubprocessEnv","spawn","platform","TIMEOUT_MS","SENTINEL_OPEN","SENTINEL_CLOSE","discoverEnvVars","allowlist","t0","warnings","fromProcess","reg","queryWindowsUserEnv","e","shell","elapsed_ms","SHELL","fromShell","queryUnixShellEnv","resolve","reject","lines","child","PS1","PROMPT","HISTFILE","stdio","stdout","kill","on","code","clearTimeout","parseSentinelStream","Object","keys","runWindowsProbe","exe","namesArr","script","windowsHide","stream","allow","parts","seg","end","indexOf","body","eq","getIntegrationMeta","setFieldSources","INTEGRATIONS_NS","previewEnvSync","runSync","applyEnvSync","_bootRanPromise","apply","ts","candidates","writesByIntegration","metaUpdates","cand","evaluateCandidate","action","pickEnvValue","size","envVar","rcValue","meta","sourceFlag","currentValue","currentSource","isSecret","isFieldSecret","current_source","current_value_present","rc_value_preview","maskValue","secret","isSensitiveMemoryNamespace","ns","existsSync","mkdirSync","renameSync","readdirSync","rmdirSync","homedir","cached","expandHome","hasDb","dir","migrateLegacyDir","legacyDir","newDir","recursive","entries","moved","to","postEntries","suffix","envDir","JARELA_DB_DIR","defaultDataDir","local","LOCALAPPDATA","execFileSync","writeFileSync","chmodSync","KEYCHAINS_TO_TRY","PEM_BLOCK_RE","parseSecurityFindCertificate","blocks","matches","match","normalised","extractSystemKeychainCAs","used","allPem","kc","encoding","maxBuffer","deduped","pemPath","certCount","keychains","readFileSync","promisify","Agent","EnvHttpProxyAgent","getGlobalDispatcher","setGlobalDispatcher","getProxyConfigRaw","execAsync","ENV_HAD_PROXY_AT_BOOT","HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy","baselineDispatcher","envInstalled","ensureProxyDispatcher","proxyUrl","note","mode","resetToBaseline","host","port","url","buildProxyUrl","scheme","username","password","installProxy","no_proxy","ca_bundle","redactAuth","trust","caBundleText","caBundlePath","caBundleCertCount","caBundleSource","detected","detectSystemProxy","installDirectWithCa","auth","encodeURIComponent","noProxy","caBundle","NO_PROXY","opts","requestTls","ca","proxyTls","connect","u","URL","timeout","parseScutilProxy","output","line","portStr","Number","parseInt","isFinite","envProxyWasSetAtBoot","INTJ","label","INTP","ENTJ","ENTP","INFJ","INFP","ENFJ","ENFP","ISTJ","ISFJ","ESTJ","ESFJ","ISTP","ISFP","ESTP","ESFP","MBTI_TYPES","OpenAI","pickOpenAICompatOptions","k","makeClient","baseURL","extraHeaders","apiKey","api_key","OPENAI_API_KEY","base_url","defaultHeaders","extra_headers","toOpenAIContent","part","type","image_url","media_type","data","toOpenAIMessages","messages","tool_call_id","tool_calls","reasoning_content","parseStopReason","reason","parseOpenAIInvokeChoice","choice","flatMap","tc","function","arguments","stop_reason","finish_reason","streamOpenAIEvents","chunk","usage","input_tokens","prompt_tokens","output_tokens","completion_tokens","total_tokens","choices","delta","index","args_delta","streamOpenAIText","ollamaOriginFromParams","isLocal","hostname","isOllamaPort","protocol","tryPullOllamaModel","origin","res","fetch","method","headers","isModelNotFoundError","openaiProvider","chat","mapped","completions","create","model","temperature","max_tokens","invoke","resp","tool_choice","streamInvoke","openaiStreamInvoke","inputs","openaiEmbed","embeddings","input","d","compatOptions","stream_options","include_usage","makeOpenAICompatProvider","providerName","defaultBaseURL","fixedHeaders","Anthropic","resolveApiKey","ANTHROPIC_API_KEY","pickAnthropicOptions","appendServerTools","anthropicTools","native","anthropic_server_tools","EPHEMERAL","withSystemCacheControl","cache_control","withToolsCacheControl","last","withLastToolResultCacheControl","j","newBlocks","next","usageEventFromStart","cache_creation_input_tokens","cache_read_input_tokens","usageEventFromDelta","anthropicProvider","systemMsg","systemText","userMessages","toAnthropicContent","system","event","msgList","toAnthropicMessages","toAnthropicTools","thinking","textContent","toolCalls","systemParam","blockType","ev","cb","content_block","partial_json","mt","title","result","tool_use_id","description","input_schema","parameters","providerMessagesFromHistory","getStoredOAuthToken","pickGitHubCompatOptions","tokenCache","isLikelyGitHubPat","token","getCopilotToken","pat","expiresAt","Authorization","statusText","status","json","expires_at","getTime","FIXED_HEADERS","resolvedClient","explicitSessionToken","copilot_session_token","oauthToken","Accept","githubCopilotProvider","compat","deepseekProvider","readSSELines","reader","getReader","decoder","TextDecoder","buffer","done","read","decode","pop","releaseLock","parseAnthropicStream","parseOpenAIStream","fr","geminiCompat","isCompatMode","gemini_use_openai_compat","nativeBaseUrl","gemini_native_base_url","geminiApiKey","GEMINI_API_KEY","contentToGeminiParts","inlineData","mimeType","parseJsonObject","providerMessagesToGemini","contents","systemInstruction","invokeMessagesToGemini","toolNameById","functionCall","args","response","functionResponse","toGeminiTools","functionDeclarations","builtins","gemini_builtin_tools","toGenerationConfig","base","maxOutputTokens","top_p","topP","top_k","topK","stop","stopSequences","rf","response_format","responseMimeType","gemini_response_mime_type","gemini_response_schema","responseSchema","gemini_thinking_config","thinkingConfig","gemini_generation_config","geminiNativeGenerate","mapGeminiStopReason","extractGeminiInvokeResult","first","fc","finishReason","geminiNativeStreamInvoke","generationConfig","gemini_tool_config","toolConfig","gemini_safety_settings","safetySettings","isThought","thought","geminiNativeInvoke","geminiNativeChat","resolveGeminiEmbeddingModel","geminiEmbed","requests","geminiProvider","AIMessage","HumanMessage","SystemMessage","ToolMessage","cache","cacheKey","lc_class","loadLangChainModel","hit","cls","_ignore1","lc_module","_ignore2","ctorArgs","ChatGoogleGenerativeAI","ChatCohere","ChatDeepSeek","toLCMessages","toLCInvokeMessages","ai","toLCTools","schema","langchainProvider","bound","bindTools","extractText","block","reasoning","additional_kwargs","tcc","tool_call_chunks","createHash","DEFAULT_REPLY","EMBED_DIM","parseMockDirectives","reply","echo","colon","tool","argsRaw","think","slowMs","stopReason","lastUserText","pickReply","directives","userText","sleep","ms","streamText","mockProvider","_model_id","_params","_tools","argsJson","hash","digest","vec","norm","x","loadExternalProviders","BUILTINS","openai","anthropic","deepseek","gemini","langchain","isMockEnabled","JARELA_ENABLE_MOCK_PROVIDER","BUILTIN_PROVIDER_NAMES","getProviders","mock","listProviderNames","localeCompare","KEYCHAIN_SERVICE","KEYCHAIN_ACCOUNT","KEYFILE_NAME","_key","_source","dataDir","path","keyB64","loadOrCreateViaKeychain","getMasterKeySource","execPath","cwd","markFieldsAsUserTouched","SECRET_MASK","NAMESPACE","category","placeholder","required","atlassian","jira_align","google","gmail","github","outlook","prototype","hasOwnProperty","call","listIntegrations","rows","byKey","updated_at","rc_synced_at","maskSecrets","parseValue","getIntegrationStatus","saveIntegration","incoming","deleteIntegration","decryptRow","upsertModelConfig","deleteModelConfig","changes","MEM_COLS_SQL","asyncEmbed","persist","search","sql","stored","statSync","PROVIDERS_DIR","isValid","o","loadExternalProvidersDetailed","providers","files","errors","createRequire","getBuiltinModule","req","entry","isFile","mod","file","default","COPILOT_CLIENT_ID","SCOPE","KEY_OAUTH","startDeviceFlow","client_id","scope","device_code","user_code","pollDeviceFlow","grant_type","access_token","storeOAuthToken","error_description","stored_at","clearStoredOAuthToken","getAuthStatus","signed_in","EMPTY","updates","rcSyncedAt","byName","DEFAULT_STATUS","getProxyConfigStatus","readRow","normaliseMode","normaliseScheme","saveProxyConfig","isValidMode","storedCaBundle","storedPassword","nullable","deleteProxyConfig","trimmed"],"sourceRoot":"","ignoreList":[]}