@causyne/agent 1.20.124 → 1.20.127

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 (235) hide show
  1. package/bin/causyne.js +1 -1
  2. package/package.json +4 -4
  3. package/src/acp/protocol.ts +19 -1
  4. package/src/acp/server.js +282 -8
  5. package/src/acp/server.ts +284 -8
  6. package/src/agent/abortableDelay.js +2 -2
  7. package/src/agent/abortableDelay.ts +2 -2
  8. package/src/agent/errorClassifier.js +9 -1
  9. package/src/agent/errorClassifier.ts +8 -1
  10. package/src/agentLoop.js +83 -27
  11. package/src/agentLoop.ts +92 -26
  12. package/src/approvalPolicy.js +34 -10
  13. package/src/approvalPolicy.ts +42 -11
  14. package/src/browser/causyneBrowser.js +30 -3
  15. package/src/browser/causyneBrowser.ts +33 -3
  16. package/src/browser/urlPolicy.js +14 -1
  17. package/src/browser/urlPolicy.ts +12 -1
  18. package/src/cliMode.js +21 -9
  19. package/src/cliMode.ts +20 -8
  20. package/src/commands.js +188 -32
  21. package/src/commands.ts +209 -32
  22. package/src/config.js +19 -4
  23. package/src/config.ts +18 -4
  24. package/src/core/contextCompactor.js +54 -7
  25. package/src/core/contextCompactor.ts +63 -7
  26. package/src/core/goalLoop.js +257 -0
  27. package/src/core/goalLoop.ts +310 -0
  28. package/src/entrypoint.js +135 -3
  29. package/src/entrypoint.ts +136 -3
  30. package/src/game/causyneCoreBridge.js +686 -0
  31. package/src/game/causyneCoreBridge.ts +702 -0
  32. package/src/game/gameLauncher.js +287 -0
  33. package/src/game/gameLauncher.ts +352 -0
  34. package/src/game/gameProvisioner.js +425 -0
  35. package/src/game/gameProvisioner.ts +488 -0
  36. package/src/headlessCli.js +19 -12
  37. package/src/headlessCli.ts +22 -8
  38. package/src/infra/atomicWriter.js +40 -4
  39. package/src/infra/atomicWriter.ts +36 -4
  40. package/src/launchIntent.js +73 -3
  41. package/src/launchIntent.ts +76 -3
  42. package/src/lsp/lspClient.js +83 -12
  43. package/src/lsp/lspClient.ts +75 -12
  44. package/src/mcp/mcpRegistry.js +75 -8
  45. package/src/mcp/mcpRegistry.ts +70 -7
  46. package/src/memory/contextBudget.js +2 -0
  47. package/src/memory/contextBudget.ts +1 -0
  48. package/src/modelVariants.js +45 -0
  49. package/src/modelVariants.ts +54 -0
  50. package/src/outputRecovery.js +3 -2
  51. package/src/outputRecovery.ts +4 -2
  52. package/src/permissionPresets.js +327 -0
  53. package/src/permissionPresets.ts +361 -0
  54. package/src/providers/antigravity.js +62 -9
  55. package/src/providers/antigravity.ts +73 -9
  56. package/src/providers/byokHttp.js +7 -1
  57. package/src/providers/byokHttp.ts +6 -1
  58. package/src/providers/byokStream.js +21 -8
  59. package/src/providers/byokStream.ts +17 -7
  60. package/src/providers/dashscope-byok.js +21 -5
  61. package/src/providers/dashscope-byok.ts +29 -11
  62. package/src/providers/moonshot.js +26 -7
  63. package/src/providers/moonshot.ts +34 -13
  64. package/src/providers/muse.js +6 -0
  65. package/src/providers/muse.ts +8 -0
  66. package/src/providers/ollama.js +39 -7
  67. package/src/providers/ollama.ts +36 -7
  68. package/src/providers/openai-compatible.js +16 -3
  69. package/src/providers/openai-compatible.ts +13 -3
  70. package/src/providers/openai.js +62 -4
  71. package/src/providers/openai.ts +50 -4
  72. package/src/providers/openrouter.js +19 -4
  73. package/src/providers/openrouter.ts +21 -4
  74. package/src/providers/qwen-byok.js +21 -5
  75. package/src/providers/qwen-byok.ts +29 -11
  76. package/src/providers/xai.js +26 -10
  77. package/src/providers/xai.ts +34 -16
  78. package/src/reporting.js +4 -2
  79. package/src/reporting.ts +4 -2
  80. package/src/sandbox.js +34 -0
  81. package/src/sandbox.ts +43 -0
  82. package/src/scheduler/scheduler.js +372 -0
  83. package/src/scheduler/scheduler.ts +433 -0
  84. package/src/sessionSearchIndex.js +267 -0
  85. package/src/sessionSearchIndex.ts +311 -0
  86. package/src/skillsManager.js +2 -3
  87. package/src/skillsManager.ts +2 -3
  88. package/src/toolPacks.js +6 -0
  89. package/src/toolPacks.ts +6 -0
  90. package/src/tools/applyPatch.js +1 -1
  91. package/src/tools/applyPatch.ts +1 -1
  92. package/src/tools/generateMediaViaApi.js +4 -3
  93. package/src/tools/generateMediaViaApi.ts +4 -3
  94. package/src/tools/nativeEngine.js +2 -2
  95. package/src/tools/nativeEngine.ts +2 -2
  96. package/src/tools/openSourceToolProvisioner.js +2 -2
  97. package/src/tools/openSourceToolProvisioner.ts +2 -2
  98. package/src/tools/payloadSanitizer.js +0 -1
  99. package/src/tools/payloadSanitizer.ts +0 -1
  100. package/src/tools/pdfReader.js +122 -20
  101. package/src/tools/pdfReader.ts +111 -20
  102. package/src/tools/presentDeliverable.js +103 -0
  103. package/src/tools/presentDeliverable.ts +127 -0
  104. package/src/tools/ptcRuntime.js +444 -0
  105. package/src/tools/ptcRuntime.ts +490 -0
  106. package/src/tools/ptyTerminal.js +1096 -0
  107. package/src/tools/ptyTerminal.ts +1231 -0
  108. package/src/tools/registry.js +21 -12
  109. package/src/tools/registry.ts +21 -12
  110. package/src/tools/toolOutputStore.js +26 -4
  111. package/src/tools/toolOutputStore.ts +22 -4
  112. package/src/tools/webFetch.js +158 -11
  113. package/src/tools/webFetch.ts +145 -11
  114. package/src/tools/webSearch.js +123 -36
  115. package/src/tools/webSearch.ts +124 -33
  116. package/src/tui/banner.js +5 -1
  117. package/src/tui/banner.ts +6 -1
  118. package/src/tui/chatRenderer.js +1 -2
  119. package/src/tui/chatRenderer.ts +1 -2
  120. package/src/tui/completion.js +1 -0
  121. package/src/tui/completion.ts +1 -0
  122. package/src/tui/composerControls.js +111 -27
  123. package/src/tui/composerControls.ts +124 -28
  124. package/src/tui/dialogs.js +3 -16
  125. package/src/tui/dialogs.ts +3 -16
  126. package/src/tui/home.js +1 -0
  127. package/src/tui/home.ts +1 -0
  128. package/src/tui/invocation.js +1 -2
  129. package/src/tui/invocation.ts +1 -2
  130. package/src/tui/modelPicker.js +22 -12
  131. package/src/tui/modelPicker.ts +22 -12
  132. package/src/tui/overlay.js +2 -5
  133. package/src/tui/overlay.ts +2 -5
  134. package/src/tui/prompt.js +6 -4
  135. package/src/tui/prompt.ts +6 -4
  136. package/src/tui/selectList.js +4 -12
  137. package/src/tui/selectList.ts +4 -12
  138. package/src/tui/setup.js +22 -9
  139. package/src/tui/setup.ts +26 -9
  140. package/src/tui/statusLine.ts +2 -0
  141. package/src/web/client/browserPanel.js +702 -0
  142. package/src/web/client/browserPanel.ts +663 -0
  143. package/src/web/client/chatStream.js +309 -0
  144. package/src/web/client/chatStream.ts +289 -0
  145. package/src/web/client/cliPanel.js +165 -0
  146. package/src/web/client/cliPanel.ts +171 -0
  147. package/src/web/client/composer.js +204 -0
  148. package/src/web/client/composer.ts +209 -0
  149. package/src/web/client/diffPanel.js +176 -0
  150. package/src/web/client/diffPanel.ts +203 -0
  151. package/src/web/client/dom.js +220 -0
  152. package/src/web/client/dom.ts +221 -0
  153. package/src/web/client/filesAndCanvas.js +231 -0
  154. package/src/web/client/filesAndCanvas.ts +238 -0
  155. package/src/web/client/gameLauncherUi.js +78 -0
  156. package/src/web/client/gameLauncherUi.ts +78 -0
  157. package/src/web/client/main.js +301 -0
  158. package/src/web/client/main.ts +368 -0
  159. package/src/web/client/markdown.js +364 -0
  160. package/src/web/client/markdown.ts +373 -0
  161. package/src/web/client/modelPicker.js +455 -0
  162. package/src/web/client/modelPicker.ts +451 -0
  163. package/src/web/client/permissionPresetsUi.js +307 -0
  164. package/src/web/client/permissionPresetsUi.ts +333 -0
  165. package/src/web/client/sessions.js +353 -0
  166. package/src/web/client/sessions.ts +372 -0
  167. package/src/web/client/settingsModal.js +191 -0
  168. package/src/web/client/settingsModal.ts +176 -0
  169. package/src/web/client/state.js +250 -0
  170. package/src/web/client/state.ts +233 -0
  171. package/src/web/client/streamSmoother.js +127 -0
  172. package/src/web/client/streamSmoother.ts +119 -0
  173. package/src/web/client/studioLayout.js +54 -0
  174. package/src/web/client/studioLayout.ts +60 -0
  175. package/src/web/client/studioShell.js +327 -0
  176. package/src/web/client/studioShell.ts +340 -0
  177. package/src/web/client/studioStart.js +77 -0
  178. package/src/web/client/studioStart.ts +89 -0
  179. package/src/web/client/terminalPanel.js +357 -0
  180. package/src/web/client/terminalPanel.ts +345 -0
  181. package/src/web/client/turnView.js +934 -0
  182. package/src/web/client/turnView.ts +981 -0
  183. package/src/web/client/types.js +1 -0
  184. package/src/web/client/types.ts +319 -0
  185. package/src/web/client/validators.js +106 -0
  186. package/src/web/client/validators.ts +96 -0
  187. package/src/web/server/activeRuns.js +152 -0
  188. package/src/web/server/activeRuns.ts +171 -0
  189. package/src/web/server/routesBrowser.js +355 -0
  190. package/src/web/server/routesBrowser.ts +386 -0
  191. package/src/web/server/routesChat.js +304 -0
  192. package/src/web/server/routesChat.ts +347 -0
  193. package/src/web/server/routesCore.js +472 -0
  194. package/src/web/server/routesCore.ts +522 -0
  195. package/src/web/server/routesTerminal.js +162 -0
  196. package/src/web/server/routesTerminal.ts +182 -0
  197. package/src/web/server/routesWorkspace.js +510 -0
  198. package/src/web/server/routesWorkspace.ts +546 -0
  199. package/src/web/server/security.js +98 -0
  200. package/src/web/server/security.ts +108 -0
  201. package/src/web/server/sessionTranscript.js +586 -0
  202. package/src/web/server/sessionTranscript.ts +566 -0
  203. package/src/web/server/staticAssets.js +80 -0
  204. package/src/web/server/staticAssets.ts +91 -0
  205. package/src/web/server/types.js +1 -0
  206. package/src/web/server/types.ts +135 -0
  207. package/src/web/server/workspaceFiles.js +368 -0
  208. package/src/web/server/workspaceFiles.ts +363 -0
  209. package/src/web/skybridgeServer.js +76 -2449
  210. package/src/web/skybridgeServer.ts +118 -2600
  211. package/src/web/skybridgeUi.js +16 -450
  212. package/src/web/skybridgeUi.ts +16 -454
  213. package/src/web/styles/agent.css +380 -0
  214. package/src/web/styles/composer.css +193 -0
  215. package/src/web/styles/overlays.css +436 -0
  216. package/src/web/styles/shell.css +387 -0
  217. package/src/web/styles/studio.css +723 -0
  218. package/src/web/styles/thread.css +221 -0
  219. package/src/web/styles/tokens.css +94 -0
  220. package/src/web/ui/brandMark.js +73 -0
  221. package/src/web/ui/brandMark.ts +82 -0
  222. package/src/web/ui/modalsTemplate.js +139 -0
  223. package/src/web/ui/modalsTemplate.ts +139 -0
  224. package/src/web/ui/sidebarTemplate.js +63 -0
  225. package/src/web/ui/sidebarTemplate.ts +64 -0
  226. package/src/web/ui/studioTemplate.js +258 -0
  227. package/src/web/ui/studioTemplate.ts +258 -0
  228. package/src/web/ui/workspaceTemplate.js +72 -0
  229. package/src/web/ui/workspaceTemplate.ts +73 -0
  230. package/src/worktreeManager.js +16 -1
  231. package/src/worktreeManager.ts +22 -1
  232. package/src/web/skybridgeClientScript.js +0 -3951
  233. package/src/web/skybridgeClientScript.ts +0 -3952
  234. package/src/web/skybridgeStyles.js +0 -827
  235. package/src/web/skybridgeStyles.ts +0 -828
@@ -0,0 +1,176 @@
1
+ import { dom } from './dom.js';
2
+ import { apiUrl, applyTheme, authHeaders } from './state.js';
3
+ import { isSafeBillingUrl } from './validators.js';
4
+
5
+ interface LicenseStatusPayload {
6
+ entitlement?: string;
7
+ plan?: string;
8
+ paidUntil?: string | null;
9
+ dailySeconds?: number | null;
10
+ remainingSeconds?: number | null;
11
+ recoveryCode?: string | null;
12
+ supportMessage?: string;
13
+ error?: string;
14
+ }
15
+
16
+ export interface SettingsModalCallbacks {
17
+ loadHealth(): Promise<void>;
18
+ loadModels(mode?: string): Promise<void>;
19
+ }
20
+
21
+ let callbacks: SettingsModalCallbacks = {
22
+ loadHealth: async () => {},
23
+ loadModels: async () => {}
24
+ };
25
+
26
+ export function configureSettingsModalCallbacks(cbs: SettingsModalCallbacks): void {
27
+ callbacks = cbs;
28
+ }
29
+
30
+ export async function loadDoctorReport(): Promise<void> {
31
+ dom.doctorPre.textContent = 'Loading redacted diagnostics...';
32
+ const res = await fetch(apiUrl('/api/doctor/report'), { headers: authHeaders() });
33
+ if (!res.ok) { dom.doctorPre.textContent = 'Unable to load diagnostics.'; return; }
34
+ const data = await res.json() as { report?: string };
35
+ dom.doctorPre.textContent = data.report || 'No diagnostics available.';
36
+ }
37
+
38
+ export async function loadLicenseStatus(forceLive: boolean): Promise<void> {
39
+ if (!dom.licenseSummaryEl) return;
40
+ dom.licenseSummaryEl.textContent = 'Checking plan status...';
41
+ const qs = forceLive ? '?live=1' : '';
42
+ const res = await fetch(apiUrl(`/api/license/status${qs}`), { headers: authHeaders() }).catch(() => null);
43
+ if (!res) { dom.licenseSummaryEl.textContent = 'Could not load plan status.'; return; }
44
+ const data = await res.json().catch(() => null) as LicenseStatusPayload | null;
45
+ if (!res.ok || !data) {
46
+ dom.licenseSummaryEl.textContent = (data && data.error) || 'Licensing service offline.';
47
+ return;
48
+ }
49
+ const isPro = data.entitlement === 'pro' && Boolean(data.paidUntil);
50
+ if (dom.licenseBadgeEl) {
51
+ dom.licenseBadgeEl.textContent = isPro ? (`Pro · ${data.plan || 'active'}`) : 'Free · 6h/day';
52
+ dom.licenseBadgeEl.classList.toggle('is-pro', isPro);
53
+ }
54
+ if (dom.licensePortalBtn) dom.licensePortalBtn.style.display = isPro ? 'inline-flex' : 'none';
55
+ if (isPro) {
56
+ const untilStr = String(data.paidUntil).slice(0, 10);
57
+ dom.licenseSummaryEl.textContent = `Unlimited daily execution · Paid through ${untilStr}`;
58
+ if (dom.licenseMeterWrap) dom.licenseMeterWrap.style.display = 'none';
59
+ if (dom.licenseSupportNote) {
60
+ dom.licenseSupportNote.textContent = data.recoveryCode
61
+ ? `Thank you for supporting Causyne! Save your multi-device recovery code: ${data.recoveryCode}`
62
+ : 'Thank you for supporting independent Causyne development and community maintenance.';
63
+ }
64
+ } else {
65
+ const daySec = Number(data.dailySeconds || 21600);
66
+ const remSec = typeof data.remainingSeconds === 'number' ? Math.max(0, data.remainingSeconds) : daySec;
67
+ const remMin = Math.floor(remSec / 60);
68
+ const dayMin = Math.floor(daySec / 60);
69
+ const pct = daySec > 0 ? Math.max(0, Math.min(100, Math.round((remSec / daySec) * 100))) : 100;
70
+ dom.licenseSummaryEl.textContent = `${remMin} of ${dayMin} free active minutes remaining today (resets 00:00 UTC)`;
71
+ if (dom.licenseMeterWrap) dom.licenseMeterWrap.style.display = 'block';
72
+ if (dom.licenseMeterFill) dom.licenseMeterFill.style.width = `${pct}%`;
73
+ if (dom.licenseSupportNote) {
74
+ dom.licenseSupportNote.textContent = remSec <= 0 && data.supportMessage
75
+ ? data.supportMessage
76
+ : '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.';
77
+ }
78
+ }
79
+ }
80
+
81
+ async function startLicenseCheckout(): Promise<void> {
82
+ if (!dom.licensePlanSelect || !dom.licenseStatusMsg) return;
83
+ const plan = dom.licensePlanSelect.value || 'monthly';
84
+ dom.licenseStatusMsg.textContent = 'Opening secure Paddle checkout...';
85
+ const res = await fetch(apiUrl('/api/license/checkout'), {
86
+ method: 'POST',
87
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
88
+ body: JSON.stringify({ plan })
89
+ }).catch(() => null);
90
+ if (!res) { dom.licenseStatusMsg.textContent = 'Could not reach checkout service.'; return; }
91
+ const data = await res.json().catch(() => ({ error: 'Checkout error' })) as { url?: string; error?: string };
92
+ if (!res.ok || !data.url || !isSafeBillingUrl(data.url)) {
93
+ dom.licenseStatusMsg.textContent = data.error || 'Checkout unavailable right now. Visit causyne.com/pricing.html.';
94
+ return;
95
+ }
96
+ window.open(data.url, '_blank', 'noopener,noreferrer');
97
+ dom.licenseStatusMsg.textContent = 'Paddle checkout opened in a new tab. Click Refresh after payment completes.';
98
+ }
99
+
100
+ async function claimLicenseRecovery(): Promise<void> {
101
+ if (!dom.licenseRecoveryInput || !dom.licenseStatusMsg) return;
102
+ const code = (dom.licenseRecoveryInput.value || '').trim();
103
+ if (!code) { dom.licenseStatusMsg.textContent = 'Enter your CSYN-XXXX-XXXX-XXXX-XXXX recovery code first.'; return; }
104
+ dom.licenseStatusMsg.textContent = 'Linking license...';
105
+ const res = await fetch(apiUrl('/api/license/recover'), {
106
+ method: 'POST',
107
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
108
+ body: JSON.stringify({ recoveryCode: code })
109
+ }).catch(() => null);
110
+ if (!res) { dom.licenseStatusMsg.textContent = 'Could not reach licensing service.'; return; }
111
+ const data = await res.json().catch(() => ({ error: 'Recovery failed' })) as { error?: string };
112
+ if (!res.ok) { dom.licenseStatusMsg.textContent = data.error || 'Could not link recovery code.'; return; }
113
+ dom.licenseRecoveryInput.value = '';
114
+ dom.licenseStatusMsg.textContent = 'Causyne Pro linked to this device!';
115
+ void loadLicenseStatus(true);
116
+ }
117
+
118
+ async function openBillingPortal(): Promise<void> {
119
+ if (!dom.licenseStatusMsg) return;
120
+ dom.licenseStatusMsg.textContent = 'Opening Paddle billing portal...';
121
+ const res = await fetch(apiUrl('/api/license/portal'), {
122
+ method: 'POST',
123
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
124
+ body: '{}'
125
+ }).catch(() => null);
126
+ if (!res) { dom.licenseStatusMsg.textContent = 'Could not open billing portal.'; return; }
127
+ const data = await res.json().catch(() => ({ error: 'Portal unavailable' })) as { url?: string; error?: string };
128
+ if (!res.ok || !data.url || !isSafeBillingUrl(data.url)) {
129
+ dom.licenseStatusMsg.textContent = data.error || 'Billing portal unavailable.';
130
+ return;
131
+ }
132
+ window.open(data.url, '_blank', 'noopener,noreferrer');
133
+ dom.licenseStatusMsg.textContent = 'Paddle billing portal opened in a new tab.';
134
+ }
135
+
136
+ async function saveVaultApiKey(): Promise<void> {
137
+ const provider = dom.vaultProviderSelect.value;
138
+ const apiKey = (dom.vaultKeyInput.value || '').trim();
139
+ if (!apiKey) { dom.vaultStatusEl.textContent = 'Enter an API key first.'; return; }
140
+ dom.vaultStatusEl.textContent = 'Saving...';
141
+ const res = await fetch(apiUrl('/api/config/key'), {
142
+ method: 'POST',
143
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
144
+ body: JSON.stringify({ provider, apiKey, activate: true })
145
+ }).catch(() => null);
146
+ dom.vaultKeyInput.value = '';
147
+ if (!res || !res.ok) { dom.vaultStatusEl.textContent = 'Could not save key.'; return; }
148
+ const data = await res.json() as { provider?: string };
149
+ dom.vaultStatusEl.textContent = `Saved for ${data.provider || provider}.`;
150
+ void callbacks.loadHealth();
151
+ void callbacks.loadModels();
152
+ }
153
+
154
+ export function openSettingsModal(): void {
155
+ dom.settingsModal.classList.add('open');
156
+ void loadLicenseStatus(false);
157
+ void loadDoctorReport();
158
+ }
159
+
160
+ export function bindSettingsModalEvents(): void {
161
+ dom.navSettingsBtn.addEventListener('click', openSettingsModal);
162
+ dom.settingsCloseBtn.addEventListener('click', () => dom.settingsModal.classList.remove('open'));
163
+ dom.settingsModal.addEventListener('click', (e) => {
164
+ if (e.target === dom.settingsModal) dom.settingsModal.classList.remove('open');
165
+ });
166
+ dom.themeToggleBtn.addEventListener('click', () => {
167
+ const cur = document.documentElement.getAttribute('data-theme') || 'dark';
168
+ applyTheme(cur === 'light' ? 'dark' : 'light');
169
+ });
170
+ dom.doctorLoadBtn.addEventListener('click', () => { void loadDoctorReport(); });
171
+ dom.vaultSaveBtn.addEventListener('click', () => { void saveVaultApiKey(); });
172
+ if (dom.licenseUpgradeBtn) dom.licenseUpgradeBtn.addEventListener('click', () => { void startLicenseCheckout(); });
173
+ if (dom.licensePortalBtn) dom.licensePortalBtn.addEventListener('click', () => { void openBillingPortal(); });
174
+ if (dom.licenseRefreshBtn) dom.licenseRefreshBtn.addEventListener('click', () => { void loadLicenseStatus(true); });
175
+ if (dom.licenseRecoverBtn) dom.licenseRecoverBtn.addEventListener('click', () => { void claimLicenseRecovery(); });
176
+ }
@@ -0,0 +1,250 @@
1
+ import { dom, maybeById } from './dom.js';
2
+ export const DRAFT_KEY = 'causyne/web/composerDraft/v1';
3
+ export const THEME_KEY = 'causyne/web/theme/v1';
4
+ export const PERMISSION_PRESET_KEY = 'causyne/web/permissionPreset/v1';
5
+ export const LEGACY_MODE_KEY = 'causyne/web/autonomyMode/v1';
6
+ export const STUDIO_WIDTH_KEY = 'causyne/web/studioWidth/v1';
7
+ export const DEFAULT_STUDIO_W = 480;
8
+ const hashParams = new URLSearchParams((window.location.hash || '').replace(/^#/, ''));
9
+ export const TOKEN_STORE_KEY = `causyne/web/token:${window.location.origin}`;
10
+ let sessionToken = hashParams.get('token') || '';
11
+ if (sessionToken) {
12
+ try {
13
+ window.sessionStorage.setItem(TOKEN_STORE_KEY, sessionToken);
14
+ }
15
+ catch { /* ignore */ }
16
+ try {
17
+ window.history.replaceState(null, '', window.location.pathname + window.location.search);
18
+ }
19
+ catch { /* ignore */ }
20
+ }
21
+ else {
22
+ try {
23
+ sessionToken = window.sessionStorage.getItem(TOKEN_STORE_KEY) || '';
24
+ }
25
+ catch { /* ignore */ }
26
+ }
27
+ let apiBase = '';
28
+ try {
29
+ const qs = new URLSearchParams(window.location.search || '');
30
+ const bridge = (qs.get('bridge') || '').trim();
31
+ if (bridge) {
32
+ const parsed = new URL(bridge);
33
+ const host = parsed.hostname.toLowerCase();
34
+ if (parsed.protocol === 'http:' && (host === '127.0.0.1' || host === 'localhost')) {
35
+ apiBase = parsed.origin;
36
+ }
37
+ }
38
+ }
39
+ catch {
40
+ // Ignore invalid bridge parameter.
41
+ }
42
+ export function apiUrl(p) {
43
+ return apiBase + p;
44
+ }
45
+ export function authHeaders(extra) {
46
+ return Object.assign({ Authorization: `Bearer ${sessionToken}` }, extra || {});
47
+ }
48
+ export const state = {
49
+ sessionId: null,
50
+ sessions: [],
51
+ models: null,
52
+ modelTab: null,
53
+ modelQuery: '',
54
+ modelExpandedPeers: new Set(),
55
+ modelSelectedIndex: 0,
56
+ modelRefreshing: false,
57
+ modelLiveHydrated: false,
58
+ modelNotice: '',
59
+ activeProvider: 'unconfigured',
60
+ activeModel: 'default',
61
+ permissionPreset: 'workspace-write',
62
+ defaultPermissionPreset: 'workspace-write',
63
+ workspaceRoot: '',
64
+ lastScrollTop: 0,
65
+ attachments: [],
66
+ currentDir: '',
67
+ parentDir: '',
68
+ studioTab: 'start',
69
+ studioSplit: false,
70
+ studioSecondaryTab: 'terminal',
71
+ studioExpanded: false,
72
+ studioWidth: DEFAULT_STUDIO_W,
73
+ terminalSessions: [],
74
+ activeTerminalId: null,
75
+ availableShells: [],
76
+ canvasPreviewMode: false,
77
+ canvasDirty: false,
78
+ artifactVersions: new Map(),
79
+ sessionWorkspaces: new Map(),
80
+ sessionSwitchSeq: 0,
81
+ usageTokens: 0,
82
+ diffScope: 'session',
83
+ browserEngine: 'agent',
84
+ browserMode: 'empty',
85
+ browserUrl: '',
86
+ browserSrcdoc: '',
87
+ browserViewport: 'desktop',
88
+ liveBrowserActive: false,
89
+ liveBrowserVisible: false,
90
+ liveBrowserRuntime: null,
91
+ liveBrowserPref: 'auto',
92
+ liveStreamMode: 'idle',
93
+ liveStreamAbort: null,
94
+ liveStreamConnected: false,
95
+ liveFps: 0,
96
+ pointerDragging: false,
97
+ liveBrowserWidth: 1280,
98
+ liveBrowserHeight: 800,
99
+ controlOwner: 'human',
100
+ cliCommands: [],
101
+ mentionMode: 'file',
102
+ mentionItems: [],
103
+ mentionIndex: 0,
104
+ mentionStart: -1,
105
+ diffStaged: false,
106
+ isComposing: false,
107
+ stickToBottom: true,
108
+ activeController: null,
109
+ activeTurn: null,
110
+ activePrompt: '',
111
+ gameStatus: null,
112
+ gameLaunching: false
113
+ };
114
+ export function setLiveness(active, label) {
115
+ const isActive = Boolean(active);
116
+ dom.livenessPill.classList.toggle('active', isActive);
117
+ dom.appEl.classList.toggle('is-processing', isActive);
118
+ if (label)
119
+ dom.livenessText.textContent = label;
120
+ if (state.activeTurn && typeof state.activeTurn.setActivity === 'function') {
121
+ state.activeTurn.setActivity(isActive, label || 'Thinking...');
122
+ }
123
+ }
124
+ export function applyTheme(theme) {
125
+ const next = theme === 'light' ? 'light' : 'dark';
126
+ document.documentElement.setAttribute('data-theme', next);
127
+ if (dom.themeToggleBtn)
128
+ dom.themeToggleBtn.textContent = next === 'light' ? 'Dark' : 'Light';
129
+ try {
130
+ window.localStorage.setItem(THEME_KEY, next);
131
+ }
132
+ catch { /* ignore */ }
133
+ }
134
+ export function clampStudioWidth(raw) {
135
+ const n = Number(raw);
136
+ const sidebarW = dom.appEl.classList.contains('sidebar-collapsed') || window.innerWidth <= 960 ? 0 : 256;
137
+ const minW = 320;
138
+ const maxByChat = Math.max(minW, window.innerWidth - sidebarW - 360);
139
+ const maxW = Math.max(minW, Math.min(Math.floor(window.innerWidth * 0.72), maxByChat));
140
+ const base = Number.isFinite(n) && n > 0 ? Math.round(n) : DEFAULT_STUDIO_W;
141
+ return Math.max(minW, Math.min(maxW, base));
142
+ }
143
+ export function syncExpandedStudioWidth() {
144
+ const sidebarW = dom.appEl.classList.contains('sidebar-collapsed') || window.innerWidth <= 960 ? 0 : 256;
145
+ const available = Math.max(360, window.innerWidth - sidebarW - 380);
146
+ const expandedW = Math.min(1040, Math.max(360, available));
147
+ document.documentElement.style.setProperty('--studio-expanded-w', `${expandedW}px`);
148
+ }
149
+ export function applyStudioWidth(px, persist) {
150
+ const clamped = clampStudioWidth(px);
151
+ state.studioWidth = clamped;
152
+ document.documentElement.style.setProperty('--studio-w', `${clamped}px`);
153
+ syncExpandedStudioWidth();
154
+ if (dom.studioRoot) {
155
+ dom.studioRoot.style.flexBasis = '';
156
+ dom.studioRoot.style.width = '';
157
+ }
158
+ if (persist) {
159
+ try {
160
+ window.localStorage.setItem(STUDIO_WIDTH_KEY, String(clamped));
161
+ }
162
+ catch { /* ignore */ }
163
+ }
164
+ }
165
+ export function setStageMode(hasMessages) {
166
+ dom.stageEl.classList.toggle('is-empty', !hasMessages);
167
+ dom.stageEl.classList.toggle('has-messages', hasMessages);
168
+ }
169
+ export function updateComposerMetrics() {
170
+ dom.promptInput.style.height = 'auto';
171
+ const nextH = Math.min(200, Math.max(26, dom.promptInput.scrollHeight));
172
+ dom.promptInput.style.height = `${nextH}px`;
173
+ const hasText = Boolean((dom.promptInput.value || '').trim());
174
+ const streaming = state.activeController !== null;
175
+ dom.sendBtn.classList.toggle('ready', !streaming && hasText);
176
+ dom.sendBtn.classList.toggle('stopping', streaming);
177
+ dom.sendBtn.setAttribute('aria-label', streaming ? 'Stop response' : 'Send message');
178
+ const iconSend = maybeById('icon-send');
179
+ const iconStop = maybeById('icon-stop');
180
+ if (iconSend)
181
+ iconSend.style.display = streaming ? 'none' : 'block';
182
+ if (iconStop)
183
+ iconStop.style.display = streaming ? 'block' : 'none';
184
+ try {
185
+ if (dom.promptInput.value)
186
+ window.localStorage.setItem(DRAFT_KEY, dom.promptInput.value);
187
+ else
188
+ window.localStorage.removeItem(DRAFT_KEY);
189
+ }
190
+ catch { /* ignore */ }
191
+ }
192
+ export function scrollToBottom(force, smooth = false) {
193
+ if (!dom.threadWrapEl)
194
+ return;
195
+ if (force || state.stickToBottom) {
196
+ if (smooth && typeof dom.threadWrapEl.scrollTo === 'function') {
197
+ dom.threadWrapEl.scrollTo({ top: dom.threadWrapEl.scrollHeight, behavior: 'smooth' });
198
+ }
199
+ else {
200
+ dom.threadWrapEl.scrollTop = dom.threadWrapEl.scrollHeight;
201
+ }
202
+ state.lastScrollTop = dom.threadWrapEl.scrollTop;
203
+ state.stickToBottom = true;
204
+ dom.scrollBottomBtn.classList.remove('visible');
205
+ }
206
+ }
207
+ export function syncUsagePill(tokens) {
208
+ state.usageTokens = Number(tokens) > 0 ? Number(tokens) : 0;
209
+ if (dom.usagePill) {
210
+ if (state.usageTokens > 0) {
211
+ dom.usagePill.textContent = `${state.usageTokens.toLocaleString()} tok`;
212
+ dom.usagePill.classList.add('visible');
213
+ }
214
+ else {
215
+ dom.usagePill.textContent = '';
216
+ dom.usagePill.classList.remove('visible');
217
+ }
218
+ }
219
+ }
220
+ export function restorePersistedPreferences() {
221
+ try {
222
+ const savedTheme = window.localStorage.getItem(THEME_KEY);
223
+ if (savedTheme === 'light' || savedTheme === 'dark')
224
+ applyTheme(savedTheme);
225
+ const savedPreset = window.localStorage.getItem(PERMISSION_PRESET_KEY);
226
+ if (savedPreset === 'read-only' || savedPreset === 'workspace-write' || savedPreset === 'danger-full-access') {
227
+ state.permissionPreset = savedPreset;
228
+ state.defaultPermissionPreset = savedPreset;
229
+ }
230
+ else {
231
+ const legacyMode = window.localStorage.getItem(LEGACY_MODE_KEY);
232
+ if (legacyMode === 'A')
233
+ state.permissionPreset = 'read-only';
234
+ else if (legacyMode === 'C')
235
+ state.permissionPreset = 'danger-full-access';
236
+ else if (legacyMode === 'B')
237
+ state.permissionPreset = 'workspace-write';
238
+ state.defaultPermissionPreset = state.permissionPreset;
239
+ }
240
+ const savedDraft = window.localStorage.getItem(DRAFT_KEY);
241
+ if (savedDraft)
242
+ dom.promptInput.value = savedDraft;
243
+ const savedW = window.localStorage.getItem(STUDIO_WIDTH_KEY);
244
+ if (savedW)
245
+ applyStudioWidth(savedW, false);
246
+ }
247
+ catch { /* ignore */ }
248
+ if (window.innerWidth <= 960)
249
+ dom.appEl.classList.add('sidebar-collapsed');
250
+ }
@@ -0,0 +1,233 @@
1
+ import { dom, maybeById } from './dom.js';
2
+ import type { AppState } from './types.js';
3
+
4
+ export const DRAFT_KEY = 'causyne/web/composerDraft/v1';
5
+ export const THEME_KEY = 'causyne/web/theme/v1';
6
+ export const PERMISSION_PRESET_KEY = 'causyne/web/permissionPreset/v1';
7
+ export const LEGACY_MODE_KEY = 'causyne/web/autonomyMode/v1';
8
+ export const STUDIO_WIDTH_KEY = 'causyne/web/studioWidth/v1';
9
+ export const DEFAULT_STUDIO_W = 480;
10
+
11
+ const hashParams = new URLSearchParams((window.location.hash || '').replace(/^#/, ''));
12
+ export const TOKEN_STORE_KEY = `causyne/web/token:${window.location.origin}`;
13
+
14
+ let sessionToken = hashParams.get('token') || '';
15
+ if (sessionToken) {
16
+ try { window.sessionStorage.setItem(TOKEN_STORE_KEY, sessionToken); } catch { /* ignore */ }
17
+ try { window.history.replaceState(null, '', window.location.pathname + window.location.search); } catch { /* ignore */ }
18
+ } else {
19
+ try { sessionToken = window.sessionStorage.getItem(TOKEN_STORE_KEY) || ''; } catch { /* ignore */ }
20
+ }
21
+
22
+ let apiBase = '';
23
+ try {
24
+ const qs = new URLSearchParams(window.location.search || '');
25
+ const bridge = (qs.get('bridge') || '').trim();
26
+ if (bridge) {
27
+ const parsed = new URL(bridge);
28
+ const host = parsed.hostname.toLowerCase();
29
+ if (parsed.protocol === 'http:' && (host === '127.0.0.1' || host === 'localhost')) {
30
+ apiBase = parsed.origin;
31
+ }
32
+ }
33
+ } catch {
34
+ // Ignore invalid bridge parameter.
35
+ }
36
+
37
+ export function apiUrl(p: string): string {
38
+ return apiBase + p;
39
+ }
40
+
41
+ export function authHeaders(extra?: Record<string, string>): Record<string, string> {
42
+ return Object.assign({ Authorization: `Bearer ${sessionToken}` }, extra || {});
43
+ }
44
+
45
+ export const state: AppState = {
46
+ sessionId: null,
47
+ sessions: [],
48
+ models: null,
49
+ modelTab: null,
50
+ modelQuery: '',
51
+ modelExpandedPeers: new Set<string>(),
52
+ modelSelectedIndex: 0,
53
+ modelRefreshing: false,
54
+ modelLiveHydrated: false,
55
+ modelNotice: '',
56
+ activeProvider: 'unconfigured',
57
+ activeModel: 'default',
58
+ permissionPreset: 'workspace-write',
59
+ defaultPermissionPreset: 'workspace-write',
60
+ workspaceRoot: '',
61
+ lastScrollTop: 0,
62
+ attachments: [],
63
+ currentDir: '',
64
+ parentDir: '',
65
+ studioTab: 'start',
66
+ studioSplit: false,
67
+ studioSecondaryTab: 'terminal',
68
+ studioExpanded: false,
69
+ studioWidth: DEFAULT_STUDIO_W,
70
+ terminalSessions: [],
71
+ activeTerminalId: null,
72
+ availableShells: [],
73
+ canvasPreviewMode: false,
74
+ canvasDirty: false,
75
+ artifactVersions: new Map(),
76
+ sessionWorkspaces: new Map(),
77
+ sessionSwitchSeq: 0,
78
+ usageTokens: 0,
79
+ diffScope: 'session',
80
+ browserEngine: 'agent',
81
+ browserMode: 'empty',
82
+ browserUrl: '',
83
+ browserSrcdoc: '',
84
+ browserViewport: 'desktop',
85
+ liveBrowserActive: false,
86
+ liveBrowserVisible: false,
87
+ liveBrowserRuntime: null,
88
+ liveBrowserPref: 'auto',
89
+ liveStreamMode: 'idle',
90
+ liveStreamAbort: null,
91
+ liveStreamConnected: false,
92
+ liveFps: 0,
93
+ pointerDragging: false,
94
+ liveBrowserWidth: 1280,
95
+ liveBrowserHeight: 800,
96
+ controlOwner: 'human',
97
+ cliCommands: [],
98
+ mentionMode: 'file',
99
+ mentionItems: [],
100
+ mentionIndex: 0,
101
+ mentionStart: -1,
102
+ diffStaged: false,
103
+ isComposing: false,
104
+ stickToBottom: true,
105
+ activeController: null,
106
+ activeTurn: null,
107
+ activePrompt: '',
108
+ gameStatus: null,
109
+ gameLaunching: false
110
+ };
111
+
112
+ export function setLiveness(active: boolean, label: string): void {
113
+ const isActive = Boolean(active);
114
+ dom.livenessPill.classList.toggle('active', isActive);
115
+ dom.appEl.classList.toggle('is-processing', isActive);
116
+ if (label) dom.livenessText.textContent = label;
117
+ if (state.activeTurn && typeof state.activeTurn.setActivity === 'function') {
118
+ state.activeTurn.setActivity(isActive, label || 'Thinking...');
119
+ }
120
+ }
121
+
122
+ export function applyTheme(theme: string): void {
123
+ const next = theme === 'light' ? 'light' : 'dark';
124
+ document.documentElement.setAttribute('data-theme', next);
125
+ if (dom.themeToggleBtn) dom.themeToggleBtn.textContent = next === 'light' ? 'Dark' : 'Light';
126
+ try { window.localStorage.setItem(THEME_KEY, next); } catch { /* ignore */ }
127
+ }
128
+
129
+ export function clampStudioWidth(raw: unknown): number {
130
+ const n = Number(raw);
131
+ const sidebarW = dom.appEl.classList.contains('sidebar-collapsed') || window.innerWidth <= 960 ? 0 : 256;
132
+ const minW = 320;
133
+ const maxByChat = Math.max(minW, window.innerWidth - sidebarW - 360);
134
+ const maxW = Math.max(minW, Math.min(Math.floor(window.innerWidth * 0.72), maxByChat));
135
+ const base = Number.isFinite(n) && n > 0 ? Math.round(n) : DEFAULT_STUDIO_W;
136
+ return Math.max(minW, Math.min(maxW, base));
137
+ }
138
+
139
+ export function syncExpandedStudioWidth(): void {
140
+ const sidebarW = dom.appEl.classList.contains('sidebar-collapsed') || window.innerWidth <= 960 ? 0 : 256;
141
+ const available = Math.max(360, window.innerWidth - sidebarW - 380);
142
+ const expandedW = Math.min(1040, Math.max(360, available));
143
+ document.documentElement.style.setProperty('--studio-expanded-w', `${expandedW}px`);
144
+ }
145
+
146
+ export function applyStudioWidth(px: number | string, persist: boolean): void {
147
+ const clamped = clampStudioWidth(px);
148
+ state.studioWidth = clamped;
149
+ document.documentElement.style.setProperty('--studio-w', `${clamped}px`);
150
+ syncExpandedStudioWidth();
151
+ if (dom.studioRoot) {
152
+ dom.studioRoot.style.flexBasis = '';
153
+ dom.studioRoot.style.width = '';
154
+ }
155
+ if (persist) {
156
+ try { window.localStorage.setItem(STUDIO_WIDTH_KEY, String(clamped)); } catch { /* ignore */ }
157
+ }
158
+ }
159
+
160
+ export function setStageMode(hasMessages: boolean): void {
161
+ dom.stageEl.classList.toggle('is-empty', !hasMessages);
162
+ dom.stageEl.classList.toggle('has-messages', hasMessages);
163
+ }
164
+
165
+ export function updateComposerMetrics(): void {
166
+ dom.promptInput.style.height = 'auto';
167
+ const nextH = Math.min(200, Math.max(26, dom.promptInput.scrollHeight));
168
+ dom.promptInput.style.height = `${nextH}px`;
169
+ const hasText = Boolean((dom.promptInput.value || '').trim());
170
+ const streaming = state.activeController !== null;
171
+ dom.sendBtn.classList.toggle('ready', !streaming && hasText);
172
+ dom.sendBtn.classList.toggle('stopping', streaming);
173
+ dom.sendBtn.setAttribute('aria-label', streaming ? 'Stop response' : 'Send message');
174
+ const iconSend = maybeById('icon-send');
175
+ const iconStop = maybeById('icon-stop');
176
+ if (iconSend) iconSend.style.display = streaming ? 'none' : 'block';
177
+ if (iconStop) iconStop.style.display = streaming ? 'block' : 'none';
178
+ try {
179
+ if (dom.promptInput.value) window.localStorage.setItem(DRAFT_KEY, dom.promptInput.value);
180
+ else window.localStorage.removeItem(DRAFT_KEY);
181
+ } catch { /* ignore */ }
182
+ }
183
+
184
+ export function scrollToBottom(force: boolean, smooth = false): void {
185
+ if (!dom.threadWrapEl) return;
186
+ if (force || state.stickToBottom) {
187
+ if (smooth && typeof dom.threadWrapEl.scrollTo === 'function') {
188
+ dom.threadWrapEl.scrollTo({ top: dom.threadWrapEl.scrollHeight, behavior: 'smooth' });
189
+ } else {
190
+ dom.threadWrapEl.scrollTop = dom.threadWrapEl.scrollHeight;
191
+ }
192
+ state.lastScrollTop = dom.threadWrapEl.scrollTop;
193
+ state.stickToBottom = true;
194
+ dom.scrollBottomBtn.classList.remove('visible');
195
+ }
196
+ }
197
+
198
+ export function syncUsagePill(tokens: number): void {
199
+ state.usageTokens = Number(tokens) > 0 ? Number(tokens) : 0;
200
+ if (dom.usagePill) {
201
+ if (state.usageTokens > 0) {
202
+ dom.usagePill.textContent = `${state.usageTokens.toLocaleString()} tok`;
203
+ dom.usagePill.classList.add('visible');
204
+ } else {
205
+ dom.usagePill.textContent = '';
206
+ dom.usagePill.classList.remove('visible');
207
+ }
208
+ }
209
+ }
210
+
211
+ export function restorePersistedPreferences(): void {
212
+ try {
213
+ const savedTheme = window.localStorage.getItem(THEME_KEY);
214
+ if (savedTheme === 'light' || savedTheme === 'dark') applyTheme(savedTheme);
215
+ const savedPreset = window.localStorage.getItem(PERMISSION_PRESET_KEY);
216
+ if (savedPreset === 'read-only' || savedPreset === 'workspace-write' || savedPreset === 'danger-full-access') {
217
+ state.permissionPreset = savedPreset;
218
+ state.defaultPermissionPreset = savedPreset;
219
+ } else {
220
+ const legacyMode = window.localStorage.getItem(LEGACY_MODE_KEY);
221
+ if (legacyMode === 'A') state.permissionPreset = 'read-only';
222
+ else if (legacyMode === 'C') state.permissionPreset = 'danger-full-access';
223
+ else if (legacyMode === 'B') state.permissionPreset = 'workspace-write';
224
+ state.defaultPermissionPreset = state.permissionPreset;
225
+ }
226
+ const savedDraft = window.localStorage.getItem(DRAFT_KEY);
227
+ if (savedDraft) dom.promptInput.value = savedDraft;
228
+ const savedW = window.localStorage.getItem(STUDIO_WIDTH_KEY);
229
+ if (savedW) applyStudioWidth(savedW, false);
230
+ } catch { /* ignore */ }
231
+
232
+ if (window.innerWidth <= 960) dom.appEl.classList.add('sidebar-collapsed');
233
+ }