@causyne/agent 1.20.124 → 1.20.128

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 (254) hide show
  1. package/bin/causyne.js +1 -1
  2. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  3. package/package.json +6 -4
  4. package/src/acp/protocol.ts +19 -1
  5. package/src/acp/server.js +282 -8
  6. package/src/acp/server.ts +284 -8
  7. package/src/agent/abortableDelay.js +2 -2
  8. package/src/agent/abortableDelay.ts +2 -2
  9. package/src/agent/errorClassifier.js +9 -1
  10. package/src/agent/errorClassifier.ts +8 -1
  11. package/src/agentLoop.js +142 -53
  12. package/src/agentLoop.ts +151 -50
  13. package/src/approvalPolicy.js +34 -10
  14. package/src/approvalPolicy.ts +42 -11
  15. package/src/browser/causyneBrowser.js +61 -3
  16. package/src/browser/causyneBrowser.ts +65 -3
  17. package/src/browser/urlPolicy.js +14 -1
  18. package/src/browser/urlPolicy.ts +12 -1
  19. package/src/cliMode.js +21 -9
  20. package/src/cliMode.ts +20 -8
  21. package/src/commands.js +365 -45
  22. package/src/commands.ts +403 -45
  23. package/src/config.js +19 -4
  24. package/src/config.ts +18 -4
  25. package/src/core/contextCompactor.js +54 -7
  26. package/src/core/contextCompactor.ts +63 -7
  27. package/src/core/goalLoop.js +257 -0
  28. package/src/core/goalLoop.ts +310 -0
  29. package/src/entrypoint.js +135 -3
  30. package/src/entrypoint.ts +136 -3
  31. package/src/game/causyneCoreBridge.js +686 -0
  32. package/src/game/causyneCoreBridge.ts +702 -0
  33. package/src/game/gameLauncher.js +287 -0
  34. package/src/game/gameLauncher.ts +352 -0
  35. package/src/game/gameProvisioner.js +425 -0
  36. package/src/game/gameProvisioner.ts +488 -0
  37. package/src/headlessCli.js +19 -12
  38. package/src/headlessCli.ts +22 -8
  39. package/src/infra/atomicWriter.js +40 -4
  40. package/src/infra/atomicWriter.ts +36 -4
  41. package/src/launchIntent.js +73 -3
  42. package/src/launchIntent.ts +76 -3
  43. package/src/lsp/lspClient.js +83 -12
  44. package/src/lsp/lspClient.ts +75 -12
  45. package/src/mcp/mcpRegistry.js +75 -8
  46. package/src/mcp/mcpRegistry.ts +70 -7
  47. package/src/memory/contextBudget.js +2 -0
  48. package/src/memory/contextBudget.ts +1 -0
  49. package/src/memory/episodicStore.js +40 -0
  50. package/src/memory/episodicStore.ts +46 -0
  51. package/src/memory.js +67 -0
  52. package/src/memory.ts +65 -0
  53. package/src/modelVariants.js +45 -0
  54. package/src/modelVariants.ts +54 -0
  55. package/src/outputRecovery.js +3 -2
  56. package/src/outputRecovery.ts +4 -2
  57. package/src/permissionPresets.js +327 -0
  58. package/src/permissionPresets.ts +361 -0
  59. package/src/personalization.js +365 -0
  60. package/src/personalization.ts +471 -0
  61. package/src/projectInstructions.js +30 -10
  62. package/src/projectInstructions.ts +31 -12
  63. package/src/providers/acp.js +3 -2
  64. package/src/providers/acp.ts +3 -2
  65. package/src/providers/antigravity.js +64 -9
  66. package/src/providers/antigravity.ts +75 -9
  67. package/src/providers/byokHttp.js +7 -1
  68. package/src/providers/byokHttp.ts +6 -1
  69. package/src/providers/byokStream.js +21 -8
  70. package/src/providers/byokStream.ts +17 -7
  71. package/src/providers/dashscope-byok.js +21 -5
  72. package/src/providers/dashscope-byok.ts +29 -11
  73. package/src/providers/moonshot.js +26 -7
  74. package/src/providers/moonshot.ts +34 -13
  75. package/src/providers/muse.js +6 -0
  76. package/src/providers/muse.ts +8 -0
  77. package/src/providers/ollama.js +39 -7
  78. package/src/providers/ollama.ts +36 -7
  79. package/src/providers/openai-compatible.js +16 -3
  80. package/src/providers/openai-compatible.ts +13 -3
  81. package/src/providers/openai.js +62 -4
  82. package/src/providers/openai.ts +50 -4
  83. package/src/providers/openrouter.js +19 -4
  84. package/src/providers/openrouter.ts +21 -4
  85. package/src/providers/qwen-byok.js +21 -5
  86. package/src/providers/qwen-byok.ts +29 -11
  87. package/src/providers/xai.js +26 -10
  88. package/src/providers/xai.ts +34 -16
  89. package/src/reporting.js +4 -2
  90. package/src/reporting.ts +4 -2
  91. package/src/sandbox.js +34 -0
  92. package/src/sandbox.ts +43 -0
  93. package/src/scheduler/scheduler.js +372 -0
  94. package/src/scheduler/scheduler.ts +433 -0
  95. package/src/sessionSearchIndex.js +267 -0
  96. package/src/sessionSearchIndex.ts +311 -0
  97. package/src/skillsManager.js +2 -3
  98. package/src/skillsManager.ts +2 -3
  99. package/src/toolPacks.js +6 -0
  100. package/src/toolPacks.ts +6 -0
  101. package/src/tools/applyPatch.js +1 -1
  102. package/src/tools/applyPatch.ts +1 -1
  103. package/src/tools/generateMediaViaApi.js +4 -3
  104. package/src/tools/generateMediaViaApi.ts +4 -3
  105. package/src/tools/memoryWrite.js +15 -1
  106. package/src/tools/memoryWrite.ts +16 -1
  107. package/src/tools/nativeEngine.js +2 -2
  108. package/src/tools/nativeEngine.ts +2 -2
  109. package/src/tools/openSourceToolProvisioner.js +2 -2
  110. package/src/tools/openSourceToolProvisioner.ts +2 -2
  111. package/src/tools/osSandbox.js +1 -1
  112. package/src/tools/osSandbox.ts +1 -1
  113. package/src/tools/payloadSanitizer.js +0 -1
  114. package/src/tools/payloadSanitizer.ts +0 -1
  115. package/src/tools/pdfReader.js +122 -20
  116. package/src/tools/pdfReader.ts +111 -20
  117. package/src/tools/presentDeliverable.js +103 -0
  118. package/src/tools/presentDeliverable.ts +127 -0
  119. package/src/tools/ptcRuntime.js +444 -0
  120. package/src/tools/ptcRuntime.ts +490 -0
  121. package/src/tools/ptyTerminal.js +1108 -0
  122. package/src/tools/ptyTerminal.ts +1245 -0
  123. package/src/tools/registry.js +21 -12
  124. package/src/tools/registry.ts +21 -12
  125. package/src/tools/toolOutputStore.js +26 -4
  126. package/src/tools/toolOutputStore.ts +22 -4
  127. package/src/tools/webFetch.js +158 -11
  128. package/src/tools/webFetch.ts +145 -11
  129. package/src/tools/webSearch.js +123 -36
  130. package/src/tools/webSearch.ts +124 -33
  131. package/src/tui/banner.js +5 -1
  132. package/src/tui/banner.ts +6 -1
  133. package/src/tui/chatRenderer.js +1 -2
  134. package/src/tui/chatRenderer.ts +1 -2
  135. package/src/tui/completion.js +1 -0
  136. package/src/tui/completion.ts +1 -0
  137. package/src/tui/composerControls.js +111 -27
  138. package/src/tui/composerControls.ts +124 -28
  139. package/src/tui/dialogs.js +3 -16
  140. package/src/tui/dialogs.ts +3 -16
  141. package/src/tui/home.js +1 -0
  142. package/src/tui/home.ts +1 -0
  143. package/src/tui/invocation.js +1 -2
  144. package/src/tui/invocation.ts +1 -2
  145. package/src/tui/modelPicker.js +22 -12
  146. package/src/tui/modelPicker.ts +22 -12
  147. package/src/tui/overlay.js +2 -5
  148. package/src/tui/overlay.ts +2 -5
  149. package/src/tui/prompt.js +6 -4
  150. package/src/tui/prompt.ts +6 -4
  151. package/src/tui/selectList.js +4 -12
  152. package/src/tui/selectList.ts +4 -12
  153. package/src/tui/setup.js +22 -9
  154. package/src/tui/setup.ts +26 -9
  155. package/src/tui/statusLine.ts +2 -0
  156. package/src/web/client/browserPanel.js +905 -0
  157. package/src/web/client/browserPanel.ts +872 -0
  158. package/src/web/client/chatStream.js +321 -0
  159. package/src/web/client/chatStream.ts +297 -0
  160. package/src/web/client/cliPanel.js +165 -0
  161. package/src/web/client/cliPanel.ts +171 -0
  162. package/src/web/client/composer.js +204 -0
  163. package/src/web/client/composer.ts +209 -0
  164. package/src/web/client/diffPanel.js +176 -0
  165. package/src/web/client/diffPanel.ts +203 -0
  166. package/src/web/client/dom.js +271 -0
  167. package/src/web/client/dom.ts +272 -0
  168. package/src/web/client/filesAndCanvas.js +233 -0
  169. package/src/web/client/filesAndCanvas.ts +240 -0
  170. package/src/web/client/gameLauncherUi.js +78 -0
  171. package/src/web/client/gameLauncherUi.ts +78 -0
  172. package/src/web/client/main.js +316 -0
  173. package/src/web/client/main.ts +391 -0
  174. package/src/web/client/markdown.js +364 -0
  175. package/src/web/client/markdown.ts +373 -0
  176. package/src/web/client/modelPicker.js +455 -0
  177. package/src/web/client/modelPicker.ts +451 -0
  178. package/src/web/client/permissionPresetsUi.js +307 -0
  179. package/src/web/client/permissionPresetsUi.ts +333 -0
  180. package/src/web/client/sessions.js +353 -0
  181. package/src/web/client/sessions.ts +372 -0
  182. package/src/web/client/settingsModal.js +824 -0
  183. package/src/web/client/settingsModal.ts +959 -0
  184. package/src/web/client/state.js +280 -0
  185. package/src/web/client/state.ts +259 -0
  186. package/src/web/client/streamSmoother.js +127 -0
  187. package/src/web/client/streamSmoother.ts +119 -0
  188. package/src/web/client/studioLayout.js +89 -0
  189. package/src/web/client/studioLayout.ts +103 -0
  190. package/src/web/client/studioShell.js +660 -0
  191. package/src/web/client/studioShell.ts +672 -0
  192. package/src/web/client/studioStart.js +77 -0
  193. package/src/web/client/studioStart.ts +89 -0
  194. package/src/web/client/terminalPanel.js +606 -0
  195. package/src/web/client/terminalPanel.ts +632 -0
  196. package/src/web/client/terminalTheme.js +249 -0
  197. package/src/web/client/terminalTheme.ts +258 -0
  198. package/src/web/client/turnView.js +934 -0
  199. package/src/web/client/turnView.ts +981 -0
  200. package/src/web/client/types.js +1 -0
  201. package/src/web/client/types.ts +322 -0
  202. package/src/web/client/validators.js +147 -0
  203. package/src/web/client/validators.ts +140 -0
  204. package/src/web/server/activeRuns.js +152 -0
  205. package/src/web/server/activeRuns.ts +171 -0
  206. package/src/web/server/routesBrowser.js +409 -0
  207. package/src/web/server/routesBrowser.ts +435 -0
  208. package/src/web/server/routesChat.js +304 -0
  209. package/src/web/server/routesChat.ts +347 -0
  210. package/src/web/server/routesCore.js +472 -0
  211. package/src/web/server/routesCore.ts +522 -0
  212. package/src/web/server/routesSettings.js +344 -0
  213. package/src/web/server/routesSettings.ts +397 -0
  214. package/src/web/server/routesTerminal.js +162 -0
  215. package/src/web/server/routesTerminal.ts +182 -0
  216. package/src/web/server/routesWorkspace.js +510 -0
  217. package/src/web/server/routesWorkspace.ts +546 -0
  218. package/src/web/server/security.js +98 -0
  219. package/src/web/server/security.ts +108 -0
  220. package/src/web/server/sessionTranscript.js +586 -0
  221. package/src/web/server/sessionTranscript.ts +566 -0
  222. package/src/web/server/staticAssets.js +104 -0
  223. package/src/web/server/staticAssets.ts +116 -0
  224. package/src/web/server/types.js +1 -0
  225. package/src/web/server/types.ts +135 -0
  226. package/src/web/server/workspaceFiles.js +368 -0
  227. package/src/web/server/workspaceFiles.ts +363 -0
  228. package/src/web/skybridgeServer.js +78 -2448
  229. package/src/web/skybridgeServer.ts +120 -2600
  230. package/src/web/skybridgeUi.js +20 -450
  231. package/src/web/skybridgeUi.ts +24 -455
  232. package/src/web/styles/agent.css +380 -0
  233. package/src/web/styles/composer.css +193 -0
  234. package/src/web/styles/overlays.css +935 -0
  235. package/src/web/styles/shell.css +387 -0
  236. package/src/web/styles/studio.css +951 -0
  237. package/src/web/styles/thread.css +221 -0
  238. package/src/web/styles/tokens.css +94 -0
  239. package/src/web/ui/brandMark.js +73 -0
  240. package/src/web/ui/brandMark.ts +82 -0
  241. package/src/web/ui/modalsTemplate.js +388 -0
  242. package/src/web/ui/modalsTemplate.ts +388 -0
  243. package/src/web/ui/sidebarTemplate.js +63 -0
  244. package/src/web/ui/sidebarTemplate.ts +64 -0
  245. package/src/web/ui/studioTemplate.js +256 -0
  246. package/src/web/ui/studioTemplate.ts +256 -0
  247. package/src/web/ui/workspaceTemplate.js +72 -0
  248. package/src/web/ui/workspaceTemplate.ts +73 -0
  249. package/src/worktreeManager.js +16 -1
  250. package/src/worktreeManager.ts +22 -1
  251. package/src/web/skybridgeClientScript.js +0 -3951
  252. package/src/web/skybridgeClientScript.ts +0 -3952
  253. package/src/web/skybridgeStyles.js +0 -827
  254. package/src/web/skybridgeStyles.ts +0 -828
@@ -0,0 +1,824 @@
1
+ import { dom } from './dom.js';
2
+ import { apiUrl, applyAutoScrollPref, applyDensity, applyTheme, authHeaders, isAutoScrollEnabled } from './state.js';
3
+ import { isSafeBillingUrl } from './validators.js';
4
+ const SECTION_LABELS = {
5
+ general: 'General',
6
+ configuration: 'Configuration',
7
+ personalization: 'Personalization',
8
+ billing: 'Usage & billing',
9
+ vault: 'API keys',
10
+ mcp: 'MCP servers',
11
+ hooks: 'Hooks',
12
+ plugins: 'Plugins',
13
+ diagnostics: 'Diagnostics'
14
+ };
15
+ let callbacks = {
16
+ loadHealth: async () => { },
17
+ loadModels: async () => { }
18
+ };
19
+ let activeSection = 'general';
20
+ let activeScope = 'project';
21
+ let overviewData = null;
22
+ const savedInstructions = { project: '', global: '' };
23
+ const draftInstructions = { project: '', global: '' };
24
+ export function configureSettingsModalCallbacks(cbs) {
25
+ callbacks = cbs;
26
+ }
27
+ function utf8ByteLength(text) {
28
+ return new TextEncoder().encode(text).length;
29
+ }
30
+ function clearChildren(el) {
31
+ if (!el)
32
+ return;
33
+ while (el.firstChild)
34
+ el.removeChild(el.firstChild);
35
+ }
36
+ function makePill(text, variant) {
37
+ const span = document.createElement('span');
38
+ span.className = variant === 'ok'
39
+ ? 'settings-pill is-ok'
40
+ : variant === 'warn'
41
+ ? 'settings-pill is-warn'
42
+ : 'settings-pill';
43
+ span.textContent = text;
44
+ return span;
45
+ }
46
+ function makeEmptyBox(text) {
47
+ const div = document.createElement('div');
48
+ div.className = 'settings-empty-box';
49
+ div.textContent = text;
50
+ return div;
51
+ }
52
+ function makeSwitchControl(checked, ariaLabel, onChange) {
53
+ const label = document.createElement('label');
54
+ label.className = 'c-switch';
55
+ const input = document.createElement('input');
56
+ input.type = 'checkbox';
57
+ input.checked = checked;
58
+ input.setAttribute('aria-label', ariaLabel);
59
+ input.addEventListener('change', () => onChange(input.checked, input));
60
+ const track = document.createElement('span');
61
+ track.className = 'c-switch-track';
62
+ label.appendChild(input);
63
+ label.appendChild(track);
64
+ return label;
65
+ }
66
+ function syncDeleteConfirmVisibility(confirming) {
67
+ if (dom.personalizationMemoryDeleteBtn)
68
+ dom.personalizationMemoryDeleteBtn.hidden = confirming;
69
+ if (dom.personalizationMemoryConfirmBtn)
70
+ dom.personalizationMemoryConfirmBtn.hidden = !confirming;
71
+ if (dom.personalizationMemoryCancelBtn)
72
+ dom.personalizationMemoryCancelBtn.hidden = !confirming;
73
+ }
74
+ export function selectSettingsSection(section) {
75
+ activeSection = section;
76
+ const navButtons = dom.settingsModal.querySelectorAll('[data-settings-section]');
77
+ navButtons.forEach((btn) => {
78
+ const isMatch = btn.dataset.settingsSection === section;
79
+ btn.classList.toggle('active', isMatch);
80
+ btn.setAttribute('aria-selected', isMatch ? 'true' : 'false');
81
+ });
82
+ const panes = dom.settingsModal.querySelectorAll('[data-settings-pane]');
83
+ panes.forEach((pane) => {
84
+ const isMatch = pane.dataset.settingsPane === section;
85
+ pane.classList.toggle('active', isMatch);
86
+ pane.hidden = !isMatch;
87
+ });
88
+ if (dom.settingsMobileTitle) {
89
+ dom.settingsMobileTitle.textContent = SECTION_LABELS[section] || 'Settings';
90
+ }
91
+ if (section === 'diagnostics') {
92
+ void loadDoctorReport();
93
+ }
94
+ else if (section === 'billing') {
95
+ void loadLicenseStatus(false);
96
+ }
97
+ }
98
+ function updatePersonalizationSaveState() {
99
+ if (!dom.personalizationInstructionsInput || !dom.personalizationSaveBtn)
100
+ return;
101
+ const current = dom.personalizationInstructionsInput.value;
102
+ draftInstructions[activeScope] = current;
103
+ const bytes = utf8ByteLength(current);
104
+ const maxBytes = overviewData?.personalization?.[activeScope]?.maxBytes ?? 16_384;
105
+ if (dom.personalizationByteCount) {
106
+ dom.personalizationByteCount.textContent = `${bytes.toLocaleString()} / ${maxBytes.toLocaleString()} bytes`;
107
+ dom.personalizationByteCount.style.color = bytes > maxBytes ? 'var(--err)' : '';
108
+ }
109
+ const dirty = current !== savedInstructions[activeScope];
110
+ dom.personalizationSaveBtn.disabled = !dirty || bytes > maxBytes;
111
+ }
112
+ function renderPersonalizationView() {
113
+ const p = overviewData?.personalization;
114
+ if (!p)
115
+ return;
116
+ if (dom.settingsPersonalizationDot) {
117
+ dom.settingsPersonalizationDot.hidden = !(p.project.exists && p.project.content.trim().length > 0);
118
+ }
119
+ const isProject = activeScope === 'project';
120
+ dom.personalizationScopeProjectBtn?.classList.toggle('active', isProject);
121
+ dom.personalizationScopeGlobalBtn?.classList.toggle('active', !isProject);
122
+ const doc = isProject ? p.project : p.global;
123
+ if (dom.personalizationDocTitle) {
124
+ dom.personalizationDocTitle.textContent = isProject ? 'Project instructions' : 'Global instructions';
125
+ }
126
+ if (dom.personalizationDocDesc) {
127
+ dom.personalizationDocDesc.textContent = isProject
128
+ ? 'Applies specifically to this project (.causyne/personalization.md) and is treated by Causyne Agent as a high-priority binding contract. Repository rules (CAUSYNE.md, AGENTS.md, .causyne/rules/) also apply.'
129
+ : 'Applies across all projects on this computer (~/.causyne/CAUSYNE.md). Project-specific personalization overrides global defaults when both are set.';
130
+ }
131
+ if (dom.personalizationFilePath) {
132
+ dom.personalizationFilePath.textContent = doc.displayPath;
133
+ }
134
+ if (dom.personalizationInstructionsInput) {
135
+ dom.personalizationInstructionsInput.value = draftInstructions[activeScope];
136
+ }
137
+ updatePersonalizationSaveState();
138
+ clearChildren(dom.personalizationActiveRules);
139
+ if (dom.personalizationActiveRules) {
140
+ if (p.activeRules.length === 0) {
141
+ dom.personalizationActiveRules.appendChild(makePill('No active project rule files yet'));
142
+ }
143
+ else {
144
+ for (const rule of p.activeRules) {
145
+ const chip = makePill(`${rule.scope}: ${rule.label} (${rule.bytes.toLocaleString()} B)`, rule.scope === 'personalization' ? 'ok' : undefined);
146
+ dom.personalizationActiveRules.appendChild(chip);
147
+ }
148
+ }
149
+ }
150
+ const memEnabled = isProject
151
+ ? (typeof p.memory.projectOverrides.enabled === 'boolean' ? p.memory.projectOverrides.enabled : p.memory.globalDefaults.enabled)
152
+ : p.memory.globalDefaults.enabled;
153
+ const memToolAssisted = isProject
154
+ ? (typeof p.memory.projectOverrides.allowToolAssisted === 'boolean' ? p.memory.projectOverrides.allowToolAssisted : p.memory.globalDefaults.allowToolAssisted)
155
+ : p.memory.globalDefaults.allowToolAssisted;
156
+ if (dom.personalizationMemoryEnabled)
157
+ dom.personalizationMemoryEnabled.checked = memEnabled;
158
+ if (dom.personalizationMemoryToolAssisted)
159
+ dom.personalizationMemoryToolAssisted.checked = memToolAssisted;
160
+ if (dom.personalizationMemoryDesc) {
161
+ if (isProject) {
162
+ dom.personalizationMemoryDesc.textContent = p.memory.source === 'project'
163
+ ? 'Using project-specific memory settings for this workspace.'
164
+ : 'Inheriting global memory defaults for this workspace (toggling sets a project override).';
165
+ }
166
+ else {
167
+ dom.personalizationMemoryDesc.textContent = 'Default Causyne memory behavior across all projects on this computer.';
168
+ }
169
+ }
170
+ if (dom.personalizationMemEnableDesc) {
171
+ dom.personalizationMemEnableDesc.textContent = isProject
172
+ ? 'Create memories from chats in this project and use them to personalize future chats'
173
+ : 'Create memories from chats on this computer and use them to personalize future chats';
174
+ }
175
+ if (dom.personalizationMemDeleteDesc) {
176
+ dom.personalizationMemDeleteDesc.textContent = isProject
177
+ ? 'Delete stored Causyne memories for this project'
178
+ : 'Delete all Causyne memories stored across every project on this computer';
179
+ }
180
+ if (dom.personalizationMemoryStats) {
181
+ const s = p.memoryStats;
182
+ dom.personalizationMemoryStats.textContent = isProject
183
+ ? `${s.projectFacts} facts · ${s.projectObservations} observations`
184
+ : `${s.totalFacts} facts · ${s.totalObservations} observations`;
185
+ }
186
+ syncDeleteConfirmVisibility(false);
187
+ }
188
+ function renderConfigurationView() {
189
+ const cfg = overviewData?.configuration;
190
+ if (!cfg)
191
+ return;
192
+ if (dom.settingsPermSelect && cfg.defaultPermissionPreset) {
193
+ dom.settingsPermSelect.value = cfg.defaultPermissionPreset;
194
+ }
195
+ if (dom.settingsOsSandboxSelect && cfg.osSandbox?.configuredMode) {
196
+ dom.settingsOsSandboxSelect.value = cfg.osSandbox.configuredMode;
197
+ }
198
+ if (dom.settingsSandboxBadge && cfg.osSandbox) {
199
+ const sb = cfg.osSandbox;
200
+ const label = sb.available
201
+ ? `${sb.backend === 'seatbelt' ? 'Seatbelt' : sb.backend === 'bubblewrap' ? 'Bubblewrap' : sb.backend} ready`
202
+ : 'Unavailable';
203
+ dom.settingsSandboxBadge.textContent = label;
204
+ dom.settingsSandboxBadge.className = sb.available ? 'settings-pill is-ok' : 'settings-pill is-warn';
205
+ }
206
+ if (dom.settingsSandboxDesc && cfg.osSandbox?.reason) {
207
+ dom.settingsSandboxDesc.textContent = cfg.osSandbox.reason;
208
+ }
209
+ if (dom.settingsEffortSelect) {
210
+ dom.settingsEffortSelect.value = cfg.reasoningEffort || '';
211
+ }
212
+ if (cfg.tokenBudget) {
213
+ if (dom.settingsBudgetEnabled)
214
+ dom.settingsBudgetEnabled.checked = cfg.tokenBudget.enabled === true;
215
+ if (dom.settingsBudgetHardstop)
216
+ dom.settingsBudgetHardstop.checked = cfg.tokenBudget.hardStop === true;
217
+ if (dom.settingsBudgetTask)
218
+ dom.settingsBudgetTask.value = String(cfg.tokenBudget.maxTokensPerTask ?? 150000);
219
+ if (dom.settingsBudgetDay)
220
+ dom.settingsBudgetDay.value = String(cfg.tokenBudget.maxTokensPerDay ?? 1000000);
221
+ if (dom.settingsBudgetCost)
222
+ dom.settingsBudgetCost.value = String(cfg.tokenBudget.maxCostUsd ?? 5);
223
+ }
224
+ if (cfg.autoCompact) {
225
+ if (dom.settingsAutoCompactEnabled)
226
+ dom.settingsAutoCompactEnabled.checked = cfg.autoCompact.enabled !== false;
227
+ if (dom.settingsCompactPct)
228
+ dom.settingsCompactPct.value = String(cfg.autoCompact.thresholdPercent ?? 78);
229
+ }
230
+ }
231
+ function renderVaultConfiguredChips() {
232
+ clearChildren(dom.vaultConfiguredList);
233
+ if (!dom.vaultConfiguredList)
234
+ return;
235
+ const list = overviewData?.vault?.configuredProviders || [];
236
+ if (list.length === 0) {
237
+ dom.vaultConfiguredList.appendChild(makePill('No BYOK provider keys saved yet'));
238
+ return;
239
+ }
240
+ for (const id of list) {
241
+ dom.vaultConfiguredList.appendChild(makePill(id, 'ok'));
242
+ }
243
+ }
244
+ function renderMcpView() {
245
+ clearChildren(dom.settingsMcpList);
246
+ if (!dom.settingsMcpList)
247
+ return;
248
+ const servers = overviewData?.mcp?.servers || [];
249
+ const discovered = overviewData?.mcp?.projectDiscovered || [];
250
+ if (servers.length === 0 && discovered.length === 0) {
251
+ dom.settingsMcpList.appendChild(makeEmptyBox('No MCP servers configured yet. Add servers with `/mcp add` in the CLI or define a workspace `.mcp.json` file.'));
252
+ return;
253
+ }
254
+ for (const srv of servers) {
255
+ const card = document.createElement('div');
256
+ card.className = 'settings-entity-card';
257
+ const main = document.createElement('div');
258
+ main.className = 'settings-entity-main';
259
+ const nameRow = document.createElement('div');
260
+ nameRow.className = 'settings-entity-name';
261
+ nameRow.textContent = srv.name;
262
+ nameRow.appendChild(makePill(srv.transport || 'stdio'));
263
+ const statusText = srv.connected ? `connected · ${(srv.tools || []).length} tools` : (srv.status || 'disconnected');
264
+ nameRow.appendChild(makePill(statusText, srv.connected ? 'ok' : undefined));
265
+ const meta = document.createElement('div');
266
+ meta.className = 'settings-entity-meta';
267
+ meta.textContent = srv.error ? `${srv.target} — ${srv.error}` : (srv.target || 'Configured server');
268
+ main.appendChild(nameRow);
269
+ main.appendChild(meta);
270
+ card.appendChild(main);
271
+ dom.settingsMcpList.appendChild(card);
272
+ }
273
+ for (const srv of discovered) {
274
+ if (servers.some((existing) => existing.name === srv.name))
275
+ continue;
276
+ const card = document.createElement('div');
277
+ card.className = 'settings-entity-card';
278
+ const main = document.createElement('div');
279
+ main.className = 'settings-entity-main';
280
+ const nameRow = document.createElement('div');
281
+ nameRow.className = 'settings-entity-name';
282
+ nameRow.textContent = srv.name;
283
+ nameRow.appendChild(makePill('workspace .mcp.json', 'warn'));
284
+ const meta = document.createElement('div');
285
+ meta.className = 'settings-entity-meta';
286
+ meta.textContent = srv.target || 'Requires trust grant before launch';
287
+ main.appendChild(nameRow);
288
+ main.appendChild(meta);
289
+ card.appendChild(main);
290
+ dom.settingsMcpList.appendChild(card);
291
+ }
292
+ }
293
+ function renderHooksView() {
294
+ clearChildren(dom.settingsHooksList);
295
+ if (!dom.settingsHooksList)
296
+ return;
297
+ const hooks = overviewData?.hooks || [];
298
+ if (hooks.length === 0) {
299
+ dom.settingsHooksList.appendChild(makeEmptyBox('No lifecycle hooks configured. Add `hooks` entries (PreToolUse / PostToolUse) in `~/.causyne/config.json` to inspect or toggle them here.'));
300
+ return;
301
+ }
302
+ for (const hook of hooks) {
303
+ const card = document.createElement('div');
304
+ card.className = 'settings-entity-card';
305
+ const main = document.createElement('div');
306
+ main.className = 'settings-entity-main';
307
+ const nameRow = document.createElement('div');
308
+ nameRow.className = 'settings-entity-name';
309
+ nameRow.textContent = hook.name;
310
+ nameRow.appendChild(makePill(hook.event));
311
+ nameRow.appendChild(makePill(hook.tools.join(', ')));
312
+ const meta = document.createElement('div');
313
+ meta.className = 'settings-entity-meta';
314
+ meta.textContent = hook.commandPreview || `${hook.timeoutMs} ms timeout`;
315
+ main.appendChild(nameRow);
316
+ main.appendChild(meta);
317
+ card.appendChild(main);
318
+ card.appendChild(makeSwitchControl(hook.enabled, `Toggle hook ${hook.name}`, (nextEnabled, inputEl) => {
319
+ void toggleHookEnabled(hook.index, nextEnabled, inputEl);
320
+ }));
321
+ dom.settingsHooksList.appendChild(card);
322
+ }
323
+ }
324
+ function renderPluginsView() {
325
+ if (dom.settingsPluginsRoot && overviewData?.plugins?.root) {
326
+ dom.settingsPluginsRoot.textContent = `Plugin directory: ${overviewData.plugins.root}`;
327
+ }
328
+ clearChildren(dom.settingsPluginsList);
329
+ if (!dom.settingsPluginsList)
330
+ return;
331
+ const items = overviewData?.plugins?.items || [];
332
+ if (items.length === 0) {
333
+ dom.settingsPluginsList.appendChild(makeEmptyBox('No local plugins installed. Place a plugin directory with `plugin.json` in the plugin root and enable trust here or via `/plugins enable <name>`.'));
334
+ return;
335
+ }
336
+ for (const plugin of items) {
337
+ const card = document.createElement('div');
338
+ card.className = 'settings-entity-card';
339
+ const main = document.createElement('div');
340
+ main.className = 'settings-entity-main';
341
+ const nameRow = document.createElement('div');
342
+ nameRow.className = 'settings-entity-name';
343
+ nameRow.textContent = plugin.version ? `${plugin.name} v${plugin.version}` : plugin.name;
344
+ if (plugin.invalid) {
345
+ nameRow.appendChild(makePill('invalid', 'warn'));
346
+ }
347
+ else if (plugin.modified) {
348
+ nameRow.appendChild(makePill('modified · trust revoked', 'warn'));
349
+ }
350
+ else {
351
+ nameRow.appendChild(makePill(plugin.enabled ? 'enabled' : 'disabled', plugin.enabled ? 'ok' : undefined));
352
+ }
353
+ const meta = document.createElement('div');
354
+ meta.className = 'settings-entity-meta';
355
+ const caps = Array.isArray(plugin.capabilities) && plugin.capabilities.length > 0
356
+ ? `Capabilities: ${plugin.capabilities.join(', ')}`
357
+ : 'No extra capabilities';
358
+ meta.textContent = plugin.error || plugin.description || caps;
359
+ main.appendChild(nameRow);
360
+ main.appendChild(meta);
361
+ card.appendChild(main);
362
+ if (!plugin.invalid) {
363
+ card.appendChild(makeSwitchControl(plugin.enabled && !plugin.modified, `Toggle plugin ${plugin.name}`, (nextEnabled, inputEl) => {
364
+ void togglePluginEnabled(plugin.name, nextEnabled, inputEl);
365
+ }));
366
+ }
367
+ dom.settingsPluginsList.appendChild(card);
368
+ }
369
+ }
370
+ function renderGeneralMeta() {
371
+ const gen = overviewData?.general;
372
+ if (dom.settingsCompactToggle) {
373
+ dom.settingsCompactToggle.checked = document.documentElement.getAttribute('data-density') === 'compact';
374
+ }
375
+ if (dom.settingsAutoScrollToggle) {
376
+ dom.settingsAutoScrollToggle.checked = isAutoScrollEnabled();
377
+ }
378
+ if (!gen)
379
+ return;
380
+ if (dom.settingsWsPath && gen.workspaceRoot) {
381
+ dom.settingsWsPath.textContent = gen.workspaceRoot;
382
+ }
383
+ if (dom.settingsRuntimeMeta) {
384
+ dom.settingsRuntimeMeta.textContent = `${gen.provider || 'unconfigured'} · ${gen.model || 'default'} · ${gen.platform || 'local'}`;
385
+ }
386
+ if (dom.settingsVersionPill && gen.version) {
387
+ dom.settingsVersionPill.textContent = `v${gen.version}`;
388
+ }
389
+ }
390
+ export async function loadSettingsOverview() {
391
+ const res = await fetch(apiUrl('/api/settings/overview'), { headers: authHeaders() }).catch(() => null);
392
+ if (!res || !res.ok)
393
+ return;
394
+ const data = await res.json().catch(() => null);
395
+ if (!data)
396
+ return;
397
+ overviewData = data;
398
+ if (data.personalization) {
399
+ savedInstructions.project = data.personalization.project.content;
400
+ savedInstructions.global = data.personalization.global.content;
401
+ draftInstructions.project = data.personalization.project.content;
402
+ draftInstructions.global = data.personalization.global.content;
403
+ }
404
+ renderGeneralMeta();
405
+ renderConfigurationView();
406
+ renderPersonalizationView();
407
+ renderVaultConfiguredChips();
408
+ renderMcpView();
409
+ renderHooksView();
410
+ renderPluginsView();
411
+ }
412
+ async function saveConfigurationSettings() {
413
+ if (dom.settingsConfigStatus)
414
+ dom.settingsConfigStatus.textContent = 'Saving configuration...';
415
+ const payload = {
416
+ defaultPermissionPreset: dom.settingsPermSelect?.value,
417
+ osSandbox: dom.settingsOsSandboxSelect?.value,
418
+ reasoningEffort: dom.settingsEffortSelect?.value ?? '',
419
+ tokenBudget: {
420
+ enabled: Boolean(dom.settingsBudgetEnabled?.checked),
421
+ hardStop: Boolean(dom.settingsBudgetHardstop?.checked),
422
+ maxTokensPerTask: Number(dom.settingsBudgetTask?.value || 150000),
423
+ maxTokensPerDay: Number(dom.settingsBudgetDay?.value || 1000000),
424
+ maxCostUsd: Number(dom.settingsBudgetCost?.value || 5)
425
+ },
426
+ autoCompact: {
427
+ enabled: Boolean(dom.settingsAutoCompactEnabled?.checked),
428
+ thresholdPercent: Number(dom.settingsCompactPct?.value || 78)
429
+ }
430
+ };
431
+ const res = await fetch(apiUrl('/api/settings/configuration'), {
432
+ method: 'POST',
433
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
434
+ body: JSON.stringify(payload)
435
+ }).catch(() => null);
436
+ if (!res || !res.ok) {
437
+ const err = await res?.json().catch(() => ({ error: 'Could not save configuration.' }));
438
+ if (dom.settingsConfigStatus)
439
+ dom.settingsConfigStatus.textContent = err?.error || 'Could not save configuration.';
440
+ return;
441
+ }
442
+ const updated = await res.json().catch(() => null);
443
+ if (updated) {
444
+ overviewData = updated;
445
+ renderConfigurationView();
446
+ }
447
+ if (dom.settingsConfigStatus)
448
+ dom.settingsConfigStatus.textContent = 'Configuration saved.';
449
+ void callbacks.loadHealth();
450
+ }
451
+ async function savePersonalizationText() {
452
+ if (!dom.personalizationInstructionsInput)
453
+ return;
454
+ const content = dom.personalizationInstructionsInput.value;
455
+ if (dom.personalizationStatusMsg)
456
+ dom.personalizationStatusMsg.textContent = 'Saving...';
457
+ const res = await fetch(apiUrl('/api/settings/personalization'), {
458
+ method: 'POST',
459
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
460
+ body: JSON.stringify({ scope: activeScope, instructions: content })
461
+ }).catch(() => null);
462
+ if (!res || !res.ok) {
463
+ const err = await res?.json().catch(() => ({ error: 'Could not save personalization.' }));
464
+ if (dom.personalizationStatusMsg)
465
+ dom.personalizationStatusMsg.textContent = err?.error || 'Could not save personalization.';
466
+ return;
467
+ }
468
+ const data = await res.json().catch(() => null);
469
+ if (data?.personalization && overviewData) {
470
+ overviewData.personalization = data.personalization;
471
+ savedInstructions[activeScope] = data.personalization[activeScope].content;
472
+ draftInstructions[activeScope] = data.personalization[activeScope].content;
473
+ renderPersonalizationView();
474
+ }
475
+ if (dom.personalizationStatusMsg) {
476
+ dom.personalizationStatusMsg.textContent = activeScope === 'project'
477
+ ? 'Saved to .causyne/personalization.md — active immediately for this project.'
478
+ : 'Saved to ~/.causyne/CAUSYNE.md — active across all projects.';
479
+ }
480
+ }
481
+ async function saveMemoryTogglePatch(patch) {
482
+ if (dom.personalizationMemoryStatus)
483
+ dom.personalizationMemoryStatus.textContent = 'Updating memory preference...';
484
+ const res = await fetch(apiUrl('/api/settings/personalization'), {
485
+ method: 'POST',
486
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
487
+ body: JSON.stringify({ scope: activeScope, ...patch })
488
+ }).catch(() => null);
489
+ if (!res || !res.ok) {
490
+ if (dom.personalizationMemoryStatus)
491
+ dom.personalizationMemoryStatus.textContent = 'Could not update memory setting.';
492
+ void loadSettingsOverview();
493
+ return;
494
+ }
495
+ const data = await res.json().catch(() => null);
496
+ if (data?.personalization && overviewData) {
497
+ overviewData.personalization = data.personalization;
498
+ renderPersonalizationView();
499
+ }
500
+ if (dom.personalizationMemoryStatus) {
501
+ dom.personalizationMemoryStatus.textContent = activeScope === 'project'
502
+ ? 'Project memory settings updated.'
503
+ : 'Global memory defaults updated.';
504
+ }
505
+ }
506
+ async function confirmDeleteMemories() {
507
+ const deleteScope = activeScope === 'global' ? 'all' : 'project';
508
+ if (dom.personalizationMemoryStatus)
509
+ dom.personalizationMemoryStatus.textContent = 'Deleting memories...';
510
+ const res = await fetch(apiUrl('/api/settings/memories/delete'), {
511
+ method: 'POST',
512
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
513
+ body: JSON.stringify({ scope: deleteScope })
514
+ }).catch(() => null);
515
+ syncDeleteConfirmVisibility(false);
516
+ if (!res || !res.ok) {
517
+ if (dom.personalizationMemoryStatus)
518
+ dom.personalizationMemoryStatus.textContent = 'Could not delete memories.';
519
+ return;
520
+ }
521
+ const data = await res.json().catch(() => null);
522
+ if (data?.personalization && overviewData) {
523
+ overviewData.personalization = data.personalization;
524
+ renderPersonalizationView();
525
+ }
526
+ if (dom.personalizationMemoryStatus) {
527
+ const f = data?.factsRemoved ?? 0;
528
+ const o = data?.observationsRemoved ?? 0;
529
+ const s = data?.summariesRemoved ?? 0;
530
+ dom.personalizationMemoryStatus.textContent =
531
+ `Deleted ${f} fact${f === 1 ? '' : 's'}, ${o} observation${o === 1 ? '' : 's'}, and ${s} summar${s === 1 ? 'y' : 'ies'}.`;
532
+ }
533
+ }
534
+ async function toggleHookEnabled(index, enabled, inputEl) {
535
+ if (dom.settingsHooksStatus)
536
+ dom.settingsHooksStatus.textContent = 'Updating hook...';
537
+ const res = await fetch(apiUrl('/api/settings/hooks/toggle'), {
538
+ method: 'POST',
539
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
540
+ body: JSON.stringify({ index, enabled })
541
+ }).catch(() => null);
542
+ if (!res || !res.ok) {
543
+ inputEl.checked = !enabled;
544
+ if (dom.settingsHooksStatus)
545
+ dom.settingsHooksStatus.textContent = 'Could not update hook state.';
546
+ return;
547
+ }
548
+ const data = await res.json().catch(() => null);
549
+ if (data?.hooks && overviewData) {
550
+ overviewData.hooks = data.hooks;
551
+ renderHooksView();
552
+ }
553
+ if (dom.settingsHooksStatus)
554
+ dom.settingsHooksStatus.textContent = enabled ? 'Hook enabled.' : 'Hook disabled.';
555
+ }
556
+ async function togglePluginEnabled(name, enabled, inputEl) {
557
+ if (dom.settingsPluginsStatus)
558
+ dom.settingsPluginsStatus.textContent = `${enabled ? 'Enabling' : 'Disabling'} ${name}...`;
559
+ const res = await fetch(apiUrl('/api/settings/plugins/toggle'), {
560
+ method: 'POST',
561
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
562
+ body: JSON.stringify({ name, enabled })
563
+ }).catch(() => null);
564
+ if (!res || !res.ok) {
565
+ inputEl.checked = !enabled;
566
+ if (dom.settingsPluginsStatus)
567
+ dom.settingsPluginsStatus.textContent = `Could not update plugin ${name}.`;
568
+ return;
569
+ }
570
+ const data = await res.json().catch(() => null);
571
+ if (data?.plugins && overviewData) {
572
+ overviewData.plugins = data.plugins;
573
+ renderPluginsView();
574
+ }
575
+ if (dom.settingsPluginsStatus)
576
+ dom.settingsPluginsStatus.textContent = enabled ? `Enabled ${name}.` : `Disabled ${name}.`;
577
+ }
578
+ export async function loadDoctorReport() {
579
+ dom.doctorPre.textContent = 'Loading redacted diagnostics...';
580
+ const res = await fetch(apiUrl('/api/doctor/report'), { headers: authHeaders() });
581
+ if (!res.ok) {
582
+ dom.doctorPre.textContent = 'Unable to load diagnostics.';
583
+ return;
584
+ }
585
+ const data = await res.json();
586
+ dom.doctorPre.textContent = data.report || 'No diagnostics available.';
587
+ }
588
+ export async function loadLicenseStatus(forceLive) {
589
+ if (!dom.licenseSummaryEl)
590
+ return;
591
+ dom.licenseSummaryEl.textContent = 'Checking plan status...';
592
+ const qs = forceLive ? '?live=1' : '';
593
+ const res = await fetch(apiUrl(`/api/license/status${qs}`), { headers: authHeaders() }).catch(() => null);
594
+ if (!res) {
595
+ dom.licenseSummaryEl.textContent = 'Could not load plan status.';
596
+ return;
597
+ }
598
+ const data = await res.json().catch(() => null);
599
+ if (!res.ok || !data) {
600
+ dom.licenseSummaryEl.textContent = (data && data.error) || 'Licensing service offline.';
601
+ return;
602
+ }
603
+ const isPro = data.entitlement === 'pro' && Boolean(data.paidUntil);
604
+ if (dom.licenseBadgeEl) {
605
+ dom.licenseBadgeEl.textContent = isPro ? (`Pro · ${data.plan || 'active'}`) : 'Free · 6h/day';
606
+ dom.licenseBadgeEl.classList.toggle('is-pro', isPro);
607
+ }
608
+ if (dom.licensePortalBtn)
609
+ dom.licensePortalBtn.style.display = isPro ? 'inline-flex' : 'none';
610
+ if (isPro) {
611
+ const untilStr = String(data.paidUntil).slice(0, 10);
612
+ dom.licenseSummaryEl.textContent = `Unlimited daily execution · Paid through ${untilStr}`;
613
+ if (dom.licenseMeterWrap)
614
+ dom.licenseMeterWrap.style.display = 'none';
615
+ if (dom.licenseSupportNote) {
616
+ dom.licenseSupportNote.textContent = data.recoveryCode
617
+ ? `Thank you for supporting Causyne! Save your multi-device recovery code: ${data.recoveryCode}`
618
+ : 'Thank you for supporting independent Causyne development and community maintenance.';
619
+ }
620
+ }
621
+ else {
622
+ const daySec = Number(data.dailySeconds || 21600);
623
+ const remSec = typeof data.remainingSeconds === 'number' ? Math.max(0, data.remainingSeconds) : daySec;
624
+ const remMin = Math.floor(remSec / 60);
625
+ const dayMin = Math.floor(daySec / 60);
626
+ const pct = daySec > 0 ? Math.max(0, Math.min(100, Math.round((remSec / daySec) * 100))) : 100;
627
+ dom.licenseSummaryEl.textContent = `${remMin} of ${dayMin} free active minutes remaining today (resets 00:00 UTC)`;
628
+ if (dom.licenseMeterWrap)
629
+ dom.licenseMeterWrap.style.display = 'block';
630
+ if (dom.licenseMeterFill)
631
+ dom.licenseMeterFill.style.width = `${pct}%`;
632
+ if (dom.licenseSupportNote) {
633
+ dom.licenseSupportNote.textContent = remSec <= 0 && data.supportMessage
634
+ ? data.supportMessage
635
+ : 'Free includes 6 hours/day of active execution. Upgrade to Causyne Pro for unlimited daily usage and to support independent development, ongoing maintenance, and making Causyne Agent better for the entire community. Thank you for your trust and support.';
636
+ }
637
+ }
638
+ }
639
+ async function startLicenseCheckout() {
640
+ if (!dom.licensePlanSelect || !dom.licenseStatusMsg)
641
+ return;
642
+ const plan = dom.licensePlanSelect.value || 'monthly';
643
+ dom.licenseStatusMsg.textContent = 'Opening secure checkout...';
644
+ const res = await fetch(apiUrl('/api/license/checkout'), {
645
+ method: 'POST',
646
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
647
+ body: JSON.stringify({ plan })
648
+ }).catch(() => null);
649
+ if (!res) {
650
+ dom.licenseStatusMsg.textContent = 'Could not reach checkout service.';
651
+ return;
652
+ }
653
+ const data = await res.json().catch(() => ({ error: 'Checkout error' }));
654
+ if (!res.ok || !data.url || !isSafeBillingUrl(data.url)) {
655
+ dom.licenseStatusMsg.textContent = data.error || 'Checkout unavailable right now. Visit causyne.com/pricing.html.';
656
+ return;
657
+ }
658
+ window.open(data.url, '_blank', 'noopener,noreferrer');
659
+ dom.licenseStatusMsg.textContent = 'Checkout opened in a new tab. Click Refresh after payment completes.';
660
+ }
661
+ async function claimLicenseRecovery() {
662
+ if (!dom.licenseRecoveryInput || !dom.licenseStatusMsg)
663
+ return;
664
+ const code = (dom.licenseRecoveryInput.value || '').trim();
665
+ if (!code) {
666
+ dom.licenseStatusMsg.textContent = 'Enter your CSYN-XXXX-XXXX-XXXX-XXXX recovery code first.';
667
+ return;
668
+ }
669
+ dom.licenseStatusMsg.textContent = 'Linking license...';
670
+ const res = await fetch(apiUrl('/api/license/recover'), {
671
+ method: 'POST',
672
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
673
+ body: JSON.stringify({ recoveryCode: code })
674
+ }).catch(() => null);
675
+ if (!res) {
676
+ dom.licenseStatusMsg.textContent = 'Could not reach licensing service.';
677
+ return;
678
+ }
679
+ const data = await res.json().catch(() => ({ error: 'Recovery failed' }));
680
+ if (!res.ok) {
681
+ dom.licenseStatusMsg.textContent = data.error || 'Could not link recovery code.';
682
+ return;
683
+ }
684
+ dom.licenseRecoveryInput.value = '';
685
+ dom.licenseStatusMsg.textContent = 'Causyne Pro linked to this device!';
686
+ void loadLicenseStatus(true);
687
+ }
688
+ async function openBillingPortal() {
689
+ if (!dom.licenseStatusMsg)
690
+ return;
691
+ dom.licenseStatusMsg.textContent = 'Opening billing portal...';
692
+ const res = await fetch(apiUrl('/api/license/portal'), {
693
+ method: 'POST',
694
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
695
+ body: '{}'
696
+ }).catch(() => null);
697
+ if (!res) {
698
+ dom.licenseStatusMsg.textContent = 'Could not open billing portal.';
699
+ return;
700
+ }
701
+ const data = await res.json().catch(() => ({ error: 'Portal unavailable' }));
702
+ if (!res.ok || !data.url || !isSafeBillingUrl(data.url)) {
703
+ dom.licenseStatusMsg.textContent = data.error || 'Billing portal unavailable.';
704
+ return;
705
+ }
706
+ window.open(data.url, '_blank', 'noopener,noreferrer');
707
+ dom.licenseStatusMsg.textContent = 'Billing portal opened in a new tab.';
708
+ }
709
+ async function saveVaultApiKey() {
710
+ const provider = dom.vaultProviderSelect.value;
711
+ const apiKey = (dom.vaultKeyInput.value || '').trim();
712
+ if (!apiKey) {
713
+ dom.vaultStatusEl.textContent = 'Enter an API key first.';
714
+ return;
715
+ }
716
+ dom.vaultStatusEl.textContent = 'Saving...';
717
+ const res = await fetch(apiUrl('/api/config/key'), {
718
+ method: 'POST',
719
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
720
+ body: JSON.stringify({ provider, apiKey, activate: true })
721
+ }).catch(() => null);
722
+ dom.vaultKeyInput.value = '';
723
+ if (!res || !res.ok) {
724
+ dom.vaultStatusEl.textContent = 'Could not save key.';
725
+ return;
726
+ }
727
+ const data = await res.json();
728
+ dom.vaultStatusEl.textContent = `Saved for ${data.provider || provider}.`;
729
+ void callbacks.loadHealth();
730
+ void callbacks.loadModels();
731
+ void loadSettingsOverview();
732
+ }
733
+ export function openSettingsModal(initialSection) {
734
+ dom.settingsModal.classList.add('open');
735
+ if (initialSection) {
736
+ selectSettingsSection(initialSection);
737
+ }
738
+ else {
739
+ selectSettingsSection(activeSection);
740
+ }
741
+ void loadSettingsOverview();
742
+ void loadLicenseStatus(false);
743
+ }
744
+ export function bindSettingsModalEvents() {
745
+ dom.navSettingsBtn.addEventListener('click', () => openSettingsModal());
746
+ dom.settingsCloseBtn.addEventListener('click', () => dom.settingsModal.classList.remove('open'));
747
+ dom.settingsModal.addEventListener('click', (e) => {
748
+ if (e.target === dom.settingsModal)
749
+ dom.settingsModal.classList.remove('open');
750
+ });
751
+ const navButtons = dom.settingsModal.querySelectorAll('[data-settings-section]');
752
+ navButtons.forEach((btn) => {
753
+ btn.addEventListener('click', () => {
754
+ const target = btn.dataset.settingsSection;
755
+ if (target && Object.prototype.hasOwnProperty.call(SECTION_LABELS, target)) {
756
+ selectSettingsSection(target);
757
+ }
758
+ });
759
+ });
760
+ dom.themeToggleBtn.addEventListener('click', () => {
761
+ const cur = document.documentElement.getAttribute('data-theme') || 'dark';
762
+ applyTheme(cur === 'light' ? 'dark' : 'light');
763
+ });
764
+ dom.settingsCompactToggle?.addEventListener('change', () => {
765
+ applyDensity(dom.settingsCompactToggle?.checked ? 'compact' : 'comfortable');
766
+ });
767
+ dom.settingsAutoScrollToggle?.addEventListener('change', () => {
768
+ applyAutoScrollPref(Boolean(dom.settingsAutoScrollToggle?.checked));
769
+ });
770
+ dom.settingsConfigSaveBtn?.addEventListener('click', () => { void saveConfigurationSettings(); });
771
+ dom.personalizationScopeProjectBtn?.addEventListener('click', () => {
772
+ activeScope = 'project';
773
+ if (dom.personalizationStatusMsg)
774
+ dom.personalizationStatusMsg.textContent = '';
775
+ if (dom.personalizationMemoryStatus)
776
+ dom.personalizationMemoryStatus.textContent = '';
777
+ renderPersonalizationView();
778
+ });
779
+ dom.personalizationScopeGlobalBtn?.addEventListener('click', () => {
780
+ activeScope = 'global';
781
+ if (dom.personalizationStatusMsg)
782
+ dom.personalizationStatusMsg.textContent = '';
783
+ if (dom.personalizationMemoryStatus)
784
+ dom.personalizationMemoryStatus.textContent = '';
785
+ renderPersonalizationView();
786
+ });
787
+ dom.personalizationInstructionsInput?.addEventListener('input', () => {
788
+ updatePersonalizationSaveState();
789
+ });
790
+ dom.personalizationInstructionsInput?.addEventListener('keydown', (e) => {
791
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
792
+ e.preventDefault();
793
+ if (!dom.personalizationSaveBtn?.disabled)
794
+ void savePersonalizationText();
795
+ }
796
+ });
797
+ dom.personalizationSaveBtn?.addEventListener('click', () => { void savePersonalizationText(); });
798
+ dom.personalizationMemoryEnabled?.addEventListener('change', () => {
799
+ void saveMemoryTogglePatch({ memoryEnabled: Boolean(dom.personalizationMemoryEnabled?.checked) });
800
+ });
801
+ dom.personalizationMemoryToolAssisted?.addEventListener('change', () => {
802
+ void saveMemoryTogglePatch({ allowToolAssisted: Boolean(dom.personalizationMemoryToolAssisted?.checked) });
803
+ });
804
+ dom.personalizationMemoryDeleteBtn?.addEventListener('click', () => {
805
+ syncDeleteConfirmVisibility(true);
806
+ });
807
+ dom.personalizationMemoryCancelBtn?.addEventListener('click', () => {
808
+ syncDeleteConfirmVisibility(false);
809
+ });
810
+ dom.personalizationMemoryConfirmBtn?.addEventListener('click', () => {
811
+ void confirmDeleteMemories();
812
+ });
813
+ dom.settingsMcpRefreshBtn?.addEventListener('click', () => { void loadSettingsOverview(); });
814
+ dom.doctorLoadBtn.addEventListener('click', () => { void loadDoctorReport(); });
815
+ dom.vaultSaveBtn.addEventListener('click', () => { void saveVaultApiKey(); });
816
+ if (dom.licenseUpgradeBtn)
817
+ dom.licenseUpgradeBtn.addEventListener('click', () => { void startLicenseCheckout(); });
818
+ if (dom.licensePortalBtn)
819
+ dom.licensePortalBtn.addEventListener('click', () => { void openBillingPortal(); });
820
+ if (dom.licenseRefreshBtn)
821
+ dom.licenseRefreshBtn.addEventListener('click', () => { void loadLicenseStatus(true); });
822
+ if (dom.licenseRecoverBtn)
823
+ dom.licenseRecoverBtn.addEventListener('click', () => { void claimLicenseRecovery(); });
824
+ }