@causyne/agent 1.20.127 → 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 (69) hide show
  1. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  2. package/package.json +3 -1
  3. package/src/agentLoop.js +59 -26
  4. package/src/agentLoop.ts +59 -24
  5. package/src/browser/causyneBrowser.js +31 -0
  6. package/src/browser/causyneBrowser.ts +32 -0
  7. package/src/commands.js +177 -13
  8. package/src/commands.ts +194 -13
  9. package/src/memory/episodicStore.js +40 -0
  10. package/src/memory/episodicStore.ts +46 -0
  11. package/src/memory.js +67 -0
  12. package/src/memory.ts +65 -0
  13. package/src/personalization.js +365 -0
  14. package/src/personalization.ts +471 -0
  15. package/src/projectInstructions.js +30 -10
  16. package/src/projectInstructions.ts +31 -12
  17. package/src/providers/acp.js +3 -2
  18. package/src/providers/acp.ts +3 -2
  19. package/src/providers/antigravity.js +2 -0
  20. package/src/providers/antigravity.ts +2 -0
  21. package/src/tools/memoryWrite.js +15 -1
  22. package/src/tools/memoryWrite.ts +16 -1
  23. package/src/tools/osSandbox.js +1 -1
  24. package/src/tools/osSandbox.ts +1 -1
  25. package/src/tools/ptyTerminal.js +17 -5
  26. package/src/tools/ptyTerminal.ts +19 -5
  27. package/src/web/client/browserPanel.js +234 -31
  28. package/src/web/client/browserPanel.ts +240 -31
  29. package/src/web/client/chatStream.js +19 -7
  30. package/src/web/client/chatStream.ts +17 -9
  31. package/src/web/client/cliPanel.js +3 -3
  32. package/src/web/client/cliPanel.ts +3 -3
  33. package/src/web/client/dom.js +53 -2
  34. package/src/web/client/dom.ts +54 -3
  35. package/src/web/client/filesAndCanvas.js +3 -1
  36. package/src/web/client/filesAndCanvas.ts +3 -1
  37. package/src/web/client/main.js +28 -13
  38. package/src/web/client/main.ts +35 -12
  39. package/src/web/client/settingsModal.js +641 -8
  40. package/src/web/client/settingsModal.ts +791 -8
  41. package/src/web/client/state.js +31 -1
  42. package/src/web/client/state.ts +27 -1
  43. package/src/web/client/studioLayout.js +39 -4
  44. package/src/web/client/studioLayout.ts +47 -4
  45. package/src/web/client/studioShell.js +370 -37
  46. package/src/web/client/studioShell.ts +368 -36
  47. package/src/web/client/terminalPanel.js +378 -129
  48. package/src/web/client/terminalPanel.ts +394 -107
  49. package/src/web/client/terminalTheme.js +249 -0
  50. package/src/web/client/terminalTheme.ts +258 -0
  51. package/src/web/client/types.ts +3 -0
  52. package/src/web/client/validators.js +51 -10
  53. package/src/web/client/validators.ts +54 -10
  54. package/src/web/server/routesBrowser.js +64 -10
  55. package/src/web/server/routesBrowser.ts +62 -13
  56. package/src/web/server/routesSettings.js +344 -0
  57. package/src/web/server/routesSettings.ts +397 -0
  58. package/src/web/server/staticAssets.js +24 -0
  59. package/src/web/server/staticAssets.ts +25 -0
  60. package/src/web/skybridgeServer.js +3 -0
  61. package/src/web/skybridgeServer.ts +2 -0
  62. package/src/web/skybridgeUi.js +5 -1
  63. package/src/web/skybridgeUi.ts +8 -1
  64. package/src/web/styles/overlays.css +499 -0
  65. package/src/web/styles/studio.css +274 -46
  66. package/src/web/ui/modalsTemplate.js +320 -71
  67. package/src/web/ui/modalsTemplate.ts +320 -71
  68. package/src/web/ui/studioTemplate.js +19 -21
  69. package/src/web/ui/studioTemplate.ts +19 -21
@@ -1,13 +1,580 @@
1
1
  import { dom } from './dom.js';
2
- import { apiUrl, applyTheme, authHeaders } from './state.js';
2
+ import { apiUrl, applyAutoScrollPref, applyDensity, applyTheme, authHeaders, isAutoScrollEnabled } from './state.js';
3
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
+ };
4
15
  let callbacks = {
5
16
  loadHealth: async () => { },
6
17
  loadModels: async () => { }
7
18
  };
19
+ let activeSection = 'general';
20
+ let activeScope = 'project';
21
+ let overviewData = null;
22
+ const savedInstructions = { project: '', global: '' };
23
+ const draftInstructions = { project: '', global: '' };
8
24
  export function configureSettingsModalCallbacks(cbs) {
9
25
  callbacks = cbs;
10
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
+ }
11
578
  export async function loadDoctorReport() {
12
579
  dom.doctorPre.textContent = 'Loading redacted diagnostics...';
13
580
  const res = await fetch(apiUrl('/api/doctor/report'), { headers: authHeaders() });
@@ -73,7 +640,7 @@ async function startLicenseCheckout() {
73
640
  if (!dom.licensePlanSelect || !dom.licenseStatusMsg)
74
641
  return;
75
642
  const plan = dom.licensePlanSelect.value || 'monthly';
76
- dom.licenseStatusMsg.textContent = 'Opening secure Paddle checkout...';
643
+ dom.licenseStatusMsg.textContent = 'Opening secure checkout...';
77
644
  const res = await fetch(apiUrl('/api/license/checkout'), {
78
645
  method: 'POST',
79
646
  headers: authHeaders({ 'Content-Type': 'application/json' }),
@@ -89,7 +656,7 @@ async function startLicenseCheckout() {
89
656
  return;
90
657
  }
91
658
  window.open(data.url, '_blank', 'noopener,noreferrer');
92
- dom.licenseStatusMsg.textContent = 'Paddle checkout opened in a new tab. Click Refresh after payment completes.';
659
+ dom.licenseStatusMsg.textContent = 'Checkout opened in a new tab. Click Refresh after payment completes.';
93
660
  }
94
661
  async function claimLicenseRecovery() {
95
662
  if (!dom.licenseRecoveryInput || !dom.licenseStatusMsg)
@@ -121,7 +688,7 @@ async function claimLicenseRecovery() {
121
688
  async function openBillingPortal() {
122
689
  if (!dom.licenseStatusMsg)
123
690
  return;
124
- dom.licenseStatusMsg.textContent = 'Opening Paddle billing portal...';
691
+ dom.licenseStatusMsg.textContent = 'Opening billing portal...';
125
692
  const res = await fetch(apiUrl('/api/license/portal'), {
126
693
  method: 'POST',
127
694
  headers: authHeaders({ 'Content-Type': 'application/json' }),
@@ -137,7 +704,7 @@ async function openBillingPortal() {
137
704
  return;
138
705
  }
139
706
  window.open(data.url, '_blank', 'noopener,noreferrer');
140
- dom.licenseStatusMsg.textContent = 'Paddle billing portal opened in a new tab.';
707
+ dom.licenseStatusMsg.textContent = 'Billing portal opened in a new tab.';
141
708
  }
142
709
  async function saveVaultApiKey() {
143
710
  const provider = dom.vaultProviderSelect.value;
@@ -161,23 +728,89 @@ async function saveVaultApiKey() {
161
728
  dom.vaultStatusEl.textContent = `Saved for ${data.provider || provider}.`;
162
729
  void callbacks.loadHealth();
163
730
  void callbacks.loadModels();
731
+ void loadSettingsOverview();
164
732
  }
165
- export function openSettingsModal() {
733
+ export function openSettingsModal(initialSection) {
166
734
  dom.settingsModal.classList.add('open');
735
+ if (initialSection) {
736
+ selectSettingsSection(initialSection);
737
+ }
738
+ else {
739
+ selectSettingsSection(activeSection);
740
+ }
741
+ void loadSettingsOverview();
167
742
  void loadLicenseStatus(false);
168
- void loadDoctorReport();
169
743
  }
170
744
  export function bindSettingsModalEvents() {
171
- dom.navSettingsBtn.addEventListener('click', openSettingsModal);
745
+ dom.navSettingsBtn.addEventListener('click', () => openSettingsModal());
172
746
  dom.settingsCloseBtn.addEventListener('click', () => dom.settingsModal.classList.remove('open'));
173
747
  dom.settingsModal.addEventListener('click', (e) => {
174
748
  if (e.target === dom.settingsModal)
175
749
  dom.settingsModal.classList.remove('open');
176
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
+ });
177
760
  dom.themeToggleBtn.addEventListener('click', () => {
178
761
  const cur = document.documentElement.getAttribute('data-theme') || 'dark';
179
762
  applyTheme(cur === 'light' ? 'dark' : 'light');
180
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(); });
181
814
  dom.doctorLoadBtn.addEventListener('click', () => { void loadDoctorReport(); });
182
815
  dom.vaultSaveBtn.addEventListener('click', () => { void saveVaultApiKey(); });
183
816
  if (dom.licenseUpgradeBtn)