@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,472 @@
1
+ import path from 'node:path';
2
+ import { applyProviderOverrides, loadConfig, resolveProviderApiKey, saveConfig } from '../../config.js';
3
+ import { detectZeroCostProviders } from '../../zeroCostRouting.js';
4
+ import { DEFAULT_MODEL_BY_PROVIDER, MODEL_CATALOGUE } from '../../modelCatalogue.js';
5
+ import { getAvailableProvidersOverview, resolveAvailableProvidersOverview } from '../../dynamicCatalogue.js';
6
+ import { reconcileConfigVariant } from '../../modelVariants.js';
7
+ import { buildModelPickerItems } from '../../tui/modelPicker.js';
8
+ import { getGameStudioStatus, launchGameStudio, stopGameStudio } from '../../game/gameLauncher.js';
9
+ import { installGameStudio, locateGameStudio } from '../../game/gameProvisioner.js';
10
+ import { disconnectOpenRouter } from '../../auth/openrouterAuth.js';
11
+ import { auditLog } from '../../auditLog.js';
12
+ import { formatRedactedProviderErrorReport } from '../../providers/byokHttp.js';
13
+ import { formatByokProbeReport, runZeroSpendByokProbe } from '../../verification/byokSmokeProbe.js';
14
+ import { DAILY_LIMIT_SUPPORT_MESSAGE, EntitlementAccessError, EntitlementClient } from '../../licensing/entitlements.js';
15
+ import { LICENSE_ENFORCEMENT_ENABLED, isValidLicensePlan } from '../../licensing/policy.js';
16
+ import { PERMISSION_PRESET_CATALOG, getDefaultPermissionPreset, getSessionPermissionPreset, normalizePermissionPreset, presetToAutonomyMode, setDefaultPermissionPreset, setSessionPermissionPreset } from '../../permissionPresets.js';
17
+ import { SAFE_MODEL_RE, SAFE_PROVIDER_RE, SAFE_SESSION_ID_RE, readJsonBody, sendJson } from './security.js';
18
+ const PROVIDER_KEY_FOR_CATALOG_LABEL = {
19
+ 'DeepSeek': 'deepseek',
20
+ 'Qwen': 'qwen',
21
+ 'Anthropic': 'anthropic',
22
+ 'OpenAI': 'openai',
23
+ 'Gemini': 'gemini',
24
+ 'Meta (Muse)': 'muse',
25
+ 'Ollama (Local)': 'ollama',
26
+ 'Alibaba (DashScope)': 'dashscope-byok',
27
+ 'Moonshot (Kimi)': 'moonshot',
28
+ 'xAI (Grok)': 'xai',
29
+ 'Google Antigravity': 'antigravity',
30
+ 'Pi (Local Peer)': 'pi',
31
+ 'ACP (Peer Agents)': 'acp',
32
+ 'OpenCode (ACP)': 'acp/opencode',
33
+ 'Claude Code (ACP)': 'acp/claude',
34
+ 'OpenRouter (Free)': 'openrouter',
35
+ 'Groq (Free Tier)': 'groq',
36
+ 'Cerebras (Free Tier)': 'cerebras',
37
+ 'Mistral (Free Tier)': 'mistral'
38
+ };
39
+ export async function handleCoreRoutes(req, res, parsedUrl, ctx) {
40
+ const pathname = parsedUrl.pathname;
41
+ if (req.method === 'GET' && pathname === '/api/health') {
42
+ const config = loadConfig();
43
+ const zeroCost = await detectZeroCostProviders({ config, probeOllama: false });
44
+ const readyZeroCost = zeroCost.filter((z) => z.readiness === 'ready');
45
+ sendJson(res, 200, {
46
+ ok: true,
47
+ version: ctx.version,
48
+ workspaceRoot: ctx.workspaceRoot,
49
+ workspaceName: path.basename(ctx.workspaceRoot),
50
+ provider: config.provider || 'unconfigured',
51
+ model: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default',
52
+ zeroCostReadyCount: readyZeroCost.length,
53
+ zeroCostRoutes: readyZeroCost.map((z) => ({
54
+ id: z.id,
55
+ provider: z.provider,
56
+ model: z.model,
57
+ label: z.label,
58
+ costTier: z.costTier
59
+ })),
60
+ defaultPermissionPreset: getDefaultPermissionPreset(),
61
+ busy: ctx.activeRuns.size > 0
62
+ });
63
+ return true;
64
+ }
65
+ if (req.method === 'GET' && pathname === '/api/permissions') {
66
+ const rawSid = (parsedUrl.searchParams.get('sessionId') || '').trim();
67
+ const sessionId = rawSid && SAFE_SESSION_ID_RE.test(rawSid) ? rawSid : null;
68
+ const defaultPreset = getDefaultPermissionPreset();
69
+ const currentPreset = getSessionPermissionPreset(sessionId);
70
+ sendJson(res, 200, {
71
+ ok: true,
72
+ catalog: PERMISSION_PRESET_CATALOG,
73
+ defaultPreset,
74
+ currentPreset,
75
+ mode: presetToAutonomyMode(currentPreset),
76
+ sessionId
77
+ });
78
+ return true;
79
+ }
80
+ if (req.method === 'POST' && pathname === '/api/permissions') {
81
+ const body = await readJsonBody(req);
82
+ const preset = normalizePermissionPreset(body.preset ?? body.permissionPreset ?? body.mode);
83
+ if (!preset) {
84
+ sendJson(res, 400, { error: 'Valid permission preset (read-only, workspace-write, danger-full-access) is required.' });
85
+ return true;
86
+ }
87
+ const scope = body.scope === 'default' ? 'default' : 'session';
88
+ const rawSid = typeof body.sessionId === 'string' ? body.sessionId.trim() : '';
89
+ const sessionId = rawSid && SAFE_SESSION_ID_RE.test(rawSid) ? rawSid : null;
90
+ if (scope === 'default') {
91
+ setDefaultPermissionPreset(preset);
92
+ }
93
+ else if (sessionId) {
94
+ setSessionPermissionPreset(sessionId, preset);
95
+ }
96
+ else {
97
+ setDefaultPermissionPreset(preset);
98
+ }
99
+ const defaultPreset = getDefaultPermissionPreset();
100
+ const currentPreset = sessionId ? getSessionPermissionPreset(sessionId) : defaultPreset;
101
+ auditLog.log({
102
+ event: 'skybridge_permission_preset_changed',
103
+ scope,
104
+ sessionId: sessionId || undefined,
105
+ preset
106
+ });
107
+ sendJson(res, 200, {
108
+ ok: true,
109
+ scope,
110
+ sessionId,
111
+ currentPreset,
112
+ defaultPreset,
113
+ mode: presetToAutonomyMode(currentPreset)
114
+ });
115
+ return true;
116
+ }
117
+ if (req.method === 'GET' && pathname === '/api/game/status') {
118
+ const located = locateGameStudio();
119
+ const status = getGameStudioStatus();
120
+ sendJson(res, 200, {
121
+ ok: true,
122
+ installed: Boolean(located),
123
+ ...(located ? { source: located.source, version: located.version, ready: located.hasNodeModules && located.hasStudioBuild } : {}),
124
+ ...status
125
+ });
126
+ return true;
127
+ }
128
+ if (req.method === 'POST' && pathname === '/api/game/launch') {
129
+ let body = {};
130
+ try {
131
+ body = await readJsonBody(req);
132
+ }
133
+ catch {
134
+ body = {};
135
+ }
136
+ try {
137
+ const openBrowser = body.openBrowser !== false;
138
+ const launched = await launchGameStudio({ openBrowser, copyToClipboard: false });
139
+ sendJson(res, 200, {
140
+ ok: true,
141
+ url: launched.url,
142
+ origin: launched.origin,
143
+ port: launched.port,
144
+ source: launched.source,
145
+ ...(launched.version ? { version: launched.version } : {}),
146
+ reused: launched.reused,
147
+ openedBrowser: launched.openedBrowser
148
+ });
149
+ }
150
+ catch (err) {
151
+ auditLog.log({
152
+ event: 'skybridge_game_launch_error',
153
+ detail: err instanceof Error ? err.message.slice(0, 300) : 'launch_failed'
154
+ });
155
+ sendJson(res, 400, {
156
+ ok: false,
157
+ error: 'Unable to launch Causyne Game.'
158
+ });
159
+ }
160
+ return true;
161
+ }
162
+ if (req.method === 'POST' && pathname === '/api/game/install') {
163
+ let body = {};
164
+ try {
165
+ body = await readJsonBody(req);
166
+ }
167
+ catch {
168
+ body = {};
169
+ }
170
+ const confirm = body.confirm === true;
171
+ const manifestUrl = typeof body.manifestUrl === 'string' && body.manifestUrl.trim()
172
+ ? body.manifestUrl.trim()
173
+ : undefined;
174
+ const result = await installGameStudio({
175
+ confirm,
176
+ ...(manifestUrl ? { manifestUrl } : {})
177
+ });
178
+ if (!result.success && !result.requiresConsent && result.error) {
179
+ auditLog.log({
180
+ event: 'skybridge_game_install_error',
181
+ detail: String(result.error).slice(0, 300)
182
+ });
183
+ }
184
+ sendJson(res, result.success ? 200 : (result.requiresConsent ? 202 : 400), {
185
+ ok: result.success,
186
+ manifestUrl: result.manifestUrl,
187
+ ...(result.requiresConsent !== undefined ? { requiresConsent: result.requiresConsent } : {}),
188
+ ...(result.installed !== undefined ? { installed: result.installed } : {}),
189
+ ...(result.alreadyInstalled !== undefined ? { alreadyInstalled: result.alreadyInstalled } : {}),
190
+ ...(result.version ? { version: result.version } : {}),
191
+ ...(result.license ? { license: result.license } : {}),
192
+ ...(result.size !== undefined ? { size: result.size } : {}),
193
+ ...(result.path ? { path: result.path } : {}),
194
+ ...(!result.success && !result.requiresConsent
195
+ ? { error: 'Causyne Game installation failed. Check local logs and retry.' }
196
+ : {})
197
+ });
198
+ return true;
199
+ }
200
+ if (req.method === 'POST' && pathname === '/api/game/stop') {
201
+ const stopped = await stopGameStudio();
202
+ sendJson(res, 200, { ok: true, stopped });
203
+ return true;
204
+ }
205
+ if (req.method === 'GET' && pathname === '/api/models') {
206
+ const config = loadConfig();
207
+ const forceRefresh = parsedUrl.searchParams.get('refresh') === '1';
208
+ const allowLive = forceRefresh || parsedUrl.searchParams.get('live') === '1';
209
+ const overview = allowLive
210
+ ? await resolveAvailableProvidersOverview(config, { forceRefresh })
211
+ : getAvailableProvidersOverview(config);
212
+ const activeProviderRaw = String(config.provider || '').toLowerCase().trim();
213
+ const initialTab = activeProviderRaw === 'openrouter'
214
+ ? 'free'
215
+ : (activeProviderRaw === 'antigravity'
216
+ || activeProviderRaw === 'agy'
217
+ || activeProviderRaw === 'pi'
218
+ || activeProviderRaw === 'acp'
219
+ || activeProviderRaw.startsWith('acp/')
220
+ ? 'acp'
221
+ : 'byok');
222
+ const tabs = {
223
+ acp: buildModelPickerItems(config, overview, { tab: 'acp', maxAcpPerPeer: Infinity }),
224
+ byok: buildModelPickerItems(config, overview, { tab: 'byok', maxAcpPerPeer: Infinity }),
225
+ free: buildModelPickerItems(config, overview, { tab: 'free', maxAcpPerPeer: Infinity })
226
+ };
227
+ const zeroCost = await detectZeroCostProviders({ config, probeOllama: false });
228
+ const readySet = new Set(zeroCost.filter((z) => z.readiness === 'ready').map((z) => z.provider));
229
+ const groups = Object.entries(MODEL_CATALOGUE).map(([label, models]) => {
230
+ const providerId = PROVIDER_KEY_FOR_CATALOG_LABEL[label] || label.toLowerCase();
231
+ const hasKey = Boolean(resolveProviderApiKey(config, providerId));
232
+ const isZeroCostReady = readySet.has(providerId);
233
+ return {
234
+ label,
235
+ provider: providerId,
236
+ configured: hasKey || isZeroCostReady,
237
+ zeroCostReady: isZeroCostReady,
238
+ defaultModel: DEFAULT_MODEL_BY_PROVIDER[providerId] || models[0] || '',
239
+ models
240
+ };
241
+ });
242
+ sendJson(res, 200, {
243
+ ok: true,
244
+ activeProvider: config.provider || 'unconfigured',
245
+ activeModel: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || '',
246
+ initialTab,
247
+ tabs,
248
+ overview,
249
+ zeroCost: zeroCost.map((z) => ({
250
+ id: z.id,
251
+ provider: z.provider,
252
+ model: z.model,
253
+ label: z.label,
254
+ costTier: z.costTier,
255
+ readiness: z.readiness
256
+ })),
257
+ groups
258
+ });
259
+ return true;
260
+ }
261
+ if (req.method === 'POST' && pathname === '/api/model') {
262
+ const body = await readJsonBody(req);
263
+ const action = typeof body.action === 'string' ? body.action.trim() : '';
264
+ const provider = typeof body.provider === 'string' ? body.provider.trim() : '';
265
+ const model = typeof body.model === 'string' ? body.model.trim() : '';
266
+ if (action === 'disconnect' && provider === 'openrouter') {
267
+ disconnectOpenRouter();
268
+ const updated = loadConfig();
269
+ auditLog.log({ event: 'skybridge_openrouter_disconnect' });
270
+ sendJson(res, 200, {
271
+ ok: true,
272
+ disconnected: true,
273
+ provider: updated.provider || 'unconfigured',
274
+ model: updated.model || DEFAULT_MODEL_BY_PROVIDER[String(updated.provider || '')] || 'default'
275
+ });
276
+ return true;
277
+ }
278
+ if (!provider || !SAFE_PROVIDER_RE.test(provider)) {
279
+ sendJson(res, 400, { error: 'Valid provider identifier is required.' });
280
+ return true;
281
+ }
282
+ if (model && !SAFE_MODEL_RE.test(model)) {
283
+ sendJson(res, 400, { error: 'Invalid model identifier.' });
284
+ return true;
285
+ }
286
+ const config = loadConfig();
287
+ const resolvedModel = model || DEFAULT_MODEL_BY_PROVIDER[provider] || '';
288
+ applyProviderOverrides(config, provider, resolvedModel);
289
+ reconcileConfigVariant(config);
290
+ saveConfig(config);
291
+ auditLog.log({
292
+ event: 'skybridge_model_switch',
293
+ provider: config.provider,
294
+ model: config.model
295
+ });
296
+ sendJson(res, 200, {
297
+ ok: true,
298
+ provider: config.provider,
299
+ model: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default'
300
+ });
301
+ return true;
302
+ }
303
+ if (req.method === 'GET' && pathname === '/api/doctor/report') {
304
+ const config = loadConfig();
305
+ sendJson(res, 200, {
306
+ ok: true,
307
+ report: formatRedactedProviderErrorReport({
308
+ provider: config.provider,
309
+ model: config.model,
310
+ causyneVersion: ctx.version
311
+ })
312
+ });
313
+ return true;
314
+ }
315
+ if (req.method === 'POST' && pathname === '/api/doctor/probe') {
316
+ const report = await runZeroSpendByokProbe();
317
+ sendJson(res, 200, {
318
+ ok: true,
319
+ report: formatByokProbeReport(report),
320
+ summary: {
321
+ testedCount: report.testedCount,
322
+ passedCount: report.passedCount,
323
+ failedCount: report.failedCount,
324
+ skippedCount: report.skippedCount
325
+ }
326
+ });
327
+ return true;
328
+ }
329
+ if (req.method === 'GET' && pathname === '/api/license/status') {
330
+ const liveRequested = parsedUrl.searchParams.get('live') === '1';
331
+ const hasCustomClient = Boolean(ctx.entitlementClient);
332
+ if (!LICENSE_ENFORCEMENT_ENABLED && !hasCustomClient && !liveRequested) {
333
+ sendJson(res, 200, {
334
+ ok: true,
335
+ enforcementEnabled: false,
336
+ entitlement: 'free',
337
+ plan: 'free',
338
+ paidUntil: null,
339
+ dailySeconds: 21_600,
340
+ remainingSeconds: 21_600,
341
+ resetsAt: null,
342
+ recoveryCode: null,
343
+ supportMessage: DAILY_LIMIT_SUPPORT_MESSAGE
344
+ });
345
+ return true;
346
+ }
347
+ try {
348
+ const client = ctx.entitlementClient ?? new EntitlementClient();
349
+ const data = await client.status();
350
+ sendJson(res, 200, {
351
+ ok: true,
352
+ enforcementEnabled: LICENSE_ENFORCEMENT_ENABLED,
353
+ entitlement: typeof data?.entitlement === 'string' ? data.entitlement : 'free',
354
+ plan: typeof data?.plan === 'string' ? data.plan : 'free',
355
+ status: typeof data?.status === 'string' ? data.status : 'free',
356
+ paidUntil: typeof data?.paidUntil === 'string' ? data.paidUntil : null,
357
+ dailySeconds: typeof data?.dailySeconds === 'number' ? data.dailySeconds : null,
358
+ remainingSeconds: typeof data?.remainingSeconds === 'number' ? data.remainingSeconds : null,
359
+ resetsAt: typeof data?.resetsAt === 'string' ? data.resetsAt : null,
360
+ recoveryCode: typeof data?.recoveryCode === 'string' ? data.recoveryCode : null,
361
+ supportMessage: typeof data?.upgradeMessage === 'string' ? data.upgradeMessage : DAILY_LIMIT_SUPPORT_MESSAGE
362
+ });
363
+ }
364
+ catch (err) {
365
+ const code = err instanceof EntitlementAccessError ? err.code : '';
366
+ const msg = code === 'DAILY_LIMIT_REACHED'
367
+ ? DAILY_LIMIT_SUPPORT_MESSAGE
368
+ : 'Unable to reach licensing service right now.';
369
+ sendJson(res, 503, { ok: false, error: msg, enforcementEnabled: LICENSE_ENFORCEMENT_ENABLED });
370
+ }
371
+ return true;
372
+ }
373
+ if (req.method === 'POST' && pathname === '/api/license/checkout') {
374
+ const body = await readJsonBody(req);
375
+ const plan = typeof body.plan === 'string' ? body.plan.trim() : '';
376
+ if (!isValidLicensePlan(plan)) {
377
+ sendJson(res, 400, { error: 'Unknown Causyne plan.' });
378
+ return true;
379
+ }
380
+ try {
381
+ const client = ctx.entitlementClient ?? new EntitlementClient();
382
+ const result = await client.checkout(plan);
383
+ auditLog.log({ event: 'skybridge_license_checkout', plan });
384
+ sendJson(res, 200, { ok: true, plan, url: result.url });
385
+ }
386
+ catch (err) {
387
+ auditLog.log({
388
+ event: 'skybridge_license_checkout_error',
389
+ detail: err instanceof Error ? err.message.slice(0, 200) : 'checkout_failed'
390
+ });
391
+ sendJson(res, 502, {
392
+ ok: false,
393
+ error: 'Unable to start Paddle checkout right now. Visit https://causyne.com/pricing.html.'
394
+ });
395
+ }
396
+ return true;
397
+ }
398
+ if (req.method === 'POST' && pathname === '/api/license/recover') {
399
+ const body = await readJsonBody(req);
400
+ const code = typeof body.recoveryCode === 'string' ? body.recoveryCode.trim() : '';
401
+ try {
402
+ const client = ctx.entitlementClient ?? new EntitlementClient();
403
+ const result = await client.recover(code);
404
+ auditLog.log({ event: 'skybridge_license_recover', ok: true });
405
+ sendJson(res, 200, {
406
+ ok: true,
407
+ entitlement: result?.entitlement ?? 'pro',
408
+ plan: result?.plan ?? 'monthly',
409
+ paidUntil: result?.paidUntil ?? null
410
+ });
411
+ }
412
+ catch (err) {
413
+ const isInvalidCode = err instanceof EntitlementAccessError && err.code === 'INVALID_RECOVERY_CODE';
414
+ const status = isInvalidCode ? 400 : 404;
415
+ const msg = isInvalidCode
416
+ ? 'Invalid recovery code format.'
417
+ : 'Could not link recovery code.';
418
+ sendJson(res, status, { ok: false, error: msg });
419
+ }
420
+ return true;
421
+ }
422
+ if (req.method === 'POST' && pathname === '/api/license/portal') {
423
+ try {
424
+ const client = ctx.entitlementClient ?? new EntitlementClient();
425
+ const result = await client.portal();
426
+ sendJson(res, 200, { ok: true, url: result.url });
427
+ }
428
+ catch (err) {
429
+ auditLog.log({
430
+ event: 'skybridge_license_portal_error',
431
+ detail: err instanceof Error ? err.message.slice(0, 200) : 'portal_failed'
432
+ });
433
+ sendJson(res, 502, { ok: false, error: 'Billing portal unavailable.' });
434
+ }
435
+ return true;
436
+ }
437
+ if (req.method === 'POST' && pathname === '/api/config/key') {
438
+ const body = await readJsonBody(req);
439
+ const provider = typeof body.provider === 'string' ? body.provider.trim().toLowerCase() : '';
440
+ const apiKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';
441
+ const forbidden = new Set(['__proto__', 'constructor', 'prototype']);
442
+ if (!provider || forbidden.has(provider) || !SAFE_PROVIDER_RE.test(provider)) {
443
+ sendJson(res, 400, { error: 'Valid provider identifier is required.' });
444
+ return true;
445
+ }
446
+ if (!apiKey || apiKey.length < 4 || apiKey.length > 512) {
447
+ sendJson(res, 400, { error: 'API key must be between 4 and 512 characters.' });
448
+ return true;
449
+ }
450
+ const config = loadConfig();
451
+ const existingKeys = config.providerKeys && typeof config.providerKeys === 'object' && !Array.isArray(config.providerKeys)
452
+ ? { ...config.providerKeys }
453
+ : {};
454
+ existingKeys[provider] = apiKey;
455
+ config.providerKeys = existingKeys;
456
+ if (String(config.provider || '').trim().toLowerCase() === provider || body.activate === true) {
457
+ applyProviderOverrides(config, provider, typeof body.model === 'string' ? body.model.trim() : undefined);
458
+ reconcileConfigVariant(config);
459
+ }
460
+ saveConfig(config);
461
+ auditLog.log({ event: 'skybridge_vault_key_saved', provider });
462
+ sendJson(res, 200, {
463
+ ok: true,
464
+ provider,
465
+ configured: true,
466
+ activeProvider: config.provider || 'unconfigured',
467
+ activeModel: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default'
468
+ });
469
+ return true;
470
+ }
471
+ return false;
472
+ }