@causyne/agent 1.20.124 → 1.20.128

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/bin/causyne.js +1 -1
  2. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  3. package/package.json +6 -4
  4. package/src/acp/protocol.ts +19 -1
  5. package/src/acp/server.js +282 -8
  6. package/src/acp/server.ts +284 -8
  7. package/src/agent/abortableDelay.js +2 -2
  8. package/src/agent/abortableDelay.ts +2 -2
  9. package/src/agent/errorClassifier.js +9 -1
  10. package/src/agent/errorClassifier.ts +8 -1
  11. package/src/agentLoop.js +142 -53
  12. package/src/agentLoop.ts +151 -50
  13. package/src/approvalPolicy.js +34 -10
  14. package/src/approvalPolicy.ts +42 -11
  15. package/src/browser/causyneBrowser.js +61 -3
  16. package/src/browser/causyneBrowser.ts +65 -3
  17. package/src/browser/urlPolicy.js +14 -1
  18. package/src/browser/urlPolicy.ts +12 -1
  19. package/src/cliMode.js +21 -9
  20. package/src/cliMode.ts +20 -8
  21. package/src/commands.js +365 -45
  22. package/src/commands.ts +403 -45
  23. package/src/config.js +19 -4
  24. package/src/config.ts +18 -4
  25. package/src/core/contextCompactor.js +54 -7
  26. package/src/core/contextCompactor.ts +63 -7
  27. package/src/core/goalLoop.js +257 -0
  28. package/src/core/goalLoop.ts +310 -0
  29. package/src/entrypoint.js +135 -3
  30. package/src/entrypoint.ts +136 -3
  31. package/src/game/causyneCoreBridge.js +686 -0
  32. package/src/game/causyneCoreBridge.ts +702 -0
  33. package/src/game/gameLauncher.js +287 -0
  34. package/src/game/gameLauncher.ts +352 -0
  35. package/src/game/gameProvisioner.js +425 -0
  36. package/src/game/gameProvisioner.ts +488 -0
  37. package/src/headlessCli.js +19 -12
  38. package/src/headlessCli.ts +22 -8
  39. package/src/infra/atomicWriter.js +40 -4
  40. package/src/infra/atomicWriter.ts +36 -4
  41. package/src/launchIntent.js +73 -3
  42. package/src/launchIntent.ts +76 -3
  43. package/src/lsp/lspClient.js +83 -12
  44. package/src/lsp/lspClient.ts +75 -12
  45. package/src/mcp/mcpRegistry.js +75 -8
  46. package/src/mcp/mcpRegistry.ts +70 -7
  47. package/src/memory/contextBudget.js +2 -0
  48. package/src/memory/contextBudget.ts +1 -0
  49. package/src/memory/episodicStore.js +40 -0
  50. package/src/memory/episodicStore.ts +46 -0
  51. package/src/memory.js +67 -0
  52. package/src/memory.ts +65 -0
  53. package/src/modelVariants.js +45 -0
  54. package/src/modelVariants.ts +54 -0
  55. package/src/outputRecovery.js +3 -2
  56. package/src/outputRecovery.ts +4 -2
  57. package/src/permissionPresets.js +327 -0
  58. package/src/permissionPresets.ts +361 -0
  59. package/src/personalization.js +365 -0
  60. package/src/personalization.ts +471 -0
  61. package/src/projectInstructions.js +30 -10
  62. package/src/projectInstructions.ts +31 -12
  63. package/src/providers/acp.js +3 -2
  64. package/src/providers/acp.ts +3 -2
  65. package/src/providers/antigravity.js +64 -9
  66. package/src/providers/antigravity.ts +75 -9
  67. package/src/providers/byokHttp.js +7 -1
  68. package/src/providers/byokHttp.ts +6 -1
  69. package/src/providers/byokStream.js +21 -8
  70. package/src/providers/byokStream.ts +17 -7
  71. package/src/providers/dashscope-byok.js +21 -5
  72. package/src/providers/dashscope-byok.ts +29 -11
  73. package/src/providers/moonshot.js +26 -7
  74. package/src/providers/moonshot.ts +34 -13
  75. package/src/providers/muse.js +6 -0
  76. package/src/providers/muse.ts +8 -0
  77. package/src/providers/ollama.js +39 -7
  78. package/src/providers/ollama.ts +36 -7
  79. package/src/providers/openai-compatible.js +16 -3
  80. package/src/providers/openai-compatible.ts +13 -3
  81. package/src/providers/openai.js +62 -4
  82. package/src/providers/openai.ts +50 -4
  83. package/src/providers/openrouter.js +19 -4
  84. package/src/providers/openrouter.ts +21 -4
  85. package/src/providers/qwen-byok.js +21 -5
  86. package/src/providers/qwen-byok.ts +29 -11
  87. package/src/providers/xai.js +26 -10
  88. package/src/providers/xai.ts +34 -16
  89. package/src/reporting.js +4 -2
  90. package/src/reporting.ts +4 -2
  91. package/src/sandbox.js +34 -0
  92. package/src/sandbox.ts +43 -0
  93. package/src/scheduler/scheduler.js +372 -0
  94. package/src/scheduler/scheduler.ts +433 -0
  95. package/src/sessionSearchIndex.js +267 -0
  96. package/src/sessionSearchIndex.ts +311 -0
  97. package/src/skillsManager.js +2 -3
  98. package/src/skillsManager.ts +2 -3
  99. package/src/toolPacks.js +6 -0
  100. package/src/toolPacks.ts +6 -0
  101. package/src/tools/applyPatch.js +1 -1
  102. package/src/tools/applyPatch.ts +1 -1
  103. package/src/tools/generateMediaViaApi.js +4 -3
  104. package/src/tools/generateMediaViaApi.ts +4 -3
  105. package/src/tools/memoryWrite.js +15 -1
  106. package/src/tools/memoryWrite.ts +16 -1
  107. package/src/tools/nativeEngine.js +2 -2
  108. package/src/tools/nativeEngine.ts +2 -2
  109. package/src/tools/openSourceToolProvisioner.js +2 -2
  110. package/src/tools/openSourceToolProvisioner.ts +2 -2
  111. package/src/tools/osSandbox.js +1 -1
  112. package/src/tools/osSandbox.ts +1 -1
  113. package/src/tools/payloadSanitizer.js +0 -1
  114. package/src/tools/payloadSanitizer.ts +0 -1
  115. package/src/tools/pdfReader.js +122 -20
  116. package/src/tools/pdfReader.ts +111 -20
  117. package/src/tools/presentDeliverable.js +103 -0
  118. package/src/tools/presentDeliverable.ts +127 -0
  119. package/src/tools/ptcRuntime.js +444 -0
  120. package/src/tools/ptcRuntime.ts +490 -0
  121. package/src/tools/ptyTerminal.js +1108 -0
  122. package/src/tools/ptyTerminal.ts +1245 -0
  123. package/src/tools/registry.js +21 -12
  124. package/src/tools/registry.ts +21 -12
  125. package/src/tools/toolOutputStore.js +26 -4
  126. package/src/tools/toolOutputStore.ts +22 -4
  127. package/src/tools/webFetch.js +158 -11
  128. package/src/tools/webFetch.ts +145 -11
  129. package/src/tools/webSearch.js +123 -36
  130. package/src/tools/webSearch.ts +124 -33
  131. package/src/tui/banner.js +5 -1
  132. package/src/tui/banner.ts +6 -1
  133. package/src/tui/chatRenderer.js +1 -2
  134. package/src/tui/chatRenderer.ts +1 -2
  135. package/src/tui/completion.js +1 -0
  136. package/src/tui/completion.ts +1 -0
  137. package/src/tui/composerControls.js +111 -27
  138. package/src/tui/composerControls.ts +124 -28
  139. package/src/tui/dialogs.js +3 -16
  140. package/src/tui/dialogs.ts +3 -16
  141. package/src/tui/home.js +1 -0
  142. package/src/tui/home.ts +1 -0
  143. package/src/tui/invocation.js +1 -2
  144. package/src/tui/invocation.ts +1 -2
  145. package/src/tui/modelPicker.js +22 -12
  146. package/src/tui/modelPicker.ts +22 -12
  147. package/src/tui/overlay.js +2 -5
  148. package/src/tui/overlay.ts +2 -5
  149. package/src/tui/prompt.js +6 -4
  150. package/src/tui/prompt.ts +6 -4
  151. package/src/tui/selectList.js +4 -12
  152. package/src/tui/selectList.ts +4 -12
  153. package/src/tui/setup.js +22 -9
  154. package/src/tui/setup.ts +26 -9
  155. package/src/tui/statusLine.ts +2 -0
  156. package/src/web/client/browserPanel.js +905 -0
  157. package/src/web/client/browserPanel.ts +872 -0
  158. package/src/web/client/chatStream.js +321 -0
  159. package/src/web/client/chatStream.ts +297 -0
  160. package/src/web/client/cliPanel.js +165 -0
  161. package/src/web/client/cliPanel.ts +171 -0
  162. package/src/web/client/composer.js +204 -0
  163. package/src/web/client/composer.ts +209 -0
  164. package/src/web/client/diffPanel.js +176 -0
  165. package/src/web/client/diffPanel.ts +203 -0
  166. package/src/web/client/dom.js +271 -0
  167. package/src/web/client/dom.ts +272 -0
  168. package/src/web/client/filesAndCanvas.js +233 -0
  169. package/src/web/client/filesAndCanvas.ts +240 -0
  170. package/src/web/client/gameLauncherUi.js +78 -0
  171. package/src/web/client/gameLauncherUi.ts +78 -0
  172. package/src/web/client/main.js +316 -0
  173. package/src/web/client/main.ts +391 -0
  174. package/src/web/client/markdown.js +364 -0
  175. package/src/web/client/markdown.ts +373 -0
  176. package/src/web/client/modelPicker.js +455 -0
  177. package/src/web/client/modelPicker.ts +451 -0
  178. package/src/web/client/permissionPresetsUi.js +307 -0
  179. package/src/web/client/permissionPresetsUi.ts +333 -0
  180. package/src/web/client/sessions.js +353 -0
  181. package/src/web/client/sessions.ts +372 -0
  182. package/src/web/client/settingsModal.js +824 -0
  183. package/src/web/client/settingsModal.ts +959 -0
  184. package/src/web/client/state.js +280 -0
  185. package/src/web/client/state.ts +259 -0
  186. package/src/web/client/streamSmoother.js +127 -0
  187. package/src/web/client/streamSmoother.ts +119 -0
  188. package/src/web/client/studioLayout.js +89 -0
  189. package/src/web/client/studioLayout.ts +103 -0
  190. package/src/web/client/studioShell.js +660 -0
  191. package/src/web/client/studioShell.ts +672 -0
  192. package/src/web/client/studioStart.js +77 -0
  193. package/src/web/client/studioStart.ts +89 -0
  194. package/src/web/client/terminalPanel.js +606 -0
  195. package/src/web/client/terminalPanel.ts +632 -0
  196. package/src/web/client/terminalTheme.js +249 -0
  197. package/src/web/client/terminalTheme.ts +258 -0
  198. package/src/web/client/turnView.js +934 -0
  199. package/src/web/client/turnView.ts +981 -0
  200. package/src/web/client/types.js +1 -0
  201. package/src/web/client/types.ts +322 -0
  202. package/src/web/client/validators.js +147 -0
  203. package/src/web/client/validators.ts +140 -0
  204. package/src/web/server/activeRuns.js +152 -0
  205. package/src/web/server/activeRuns.ts +171 -0
  206. package/src/web/server/routesBrowser.js +409 -0
  207. package/src/web/server/routesBrowser.ts +435 -0
  208. package/src/web/server/routesChat.js +304 -0
  209. package/src/web/server/routesChat.ts +347 -0
  210. package/src/web/server/routesCore.js +472 -0
  211. package/src/web/server/routesCore.ts +522 -0
  212. package/src/web/server/routesSettings.js +344 -0
  213. package/src/web/server/routesSettings.ts +397 -0
  214. package/src/web/server/routesTerminal.js +162 -0
  215. package/src/web/server/routesTerminal.ts +182 -0
  216. package/src/web/server/routesWorkspace.js +510 -0
  217. package/src/web/server/routesWorkspace.ts +546 -0
  218. package/src/web/server/security.js +98 -0
  219. package/src/web/server/security.ts +108 -0
  220. package/src/web/server/sessionTranscript.js +586 -0
  221. package/src/web/server/sessionTranscript.ts +566 -0
  222. package/src/web/server/staticAssets.js +104 -0
  223. package/src/web/server/staticAssets.ts +116 -0
  224. package/src/web/server/types.js +1 -0
  225. package/src/web/server/types.ts +135 -0
  226. package/src/web/server/workspaceFiles.js +368 -0
  227. package/src/web/server/workspaceFiles.ts +363 -0
  228. package/src/web/skybridgeServer.js +78 -2448
  229. package/src/web/skybridgeServer.ts +120 -2600
  230. package/src/web/skybridgeUi.js +20 -450
  231. package/src/web/skybridgeUi.ts +24 -455
  232. package/src/web/styles/agent.css +380 -0
  233. package/src/web/styles/composer.css +193 -0
  234. package/src/web/styles/overlays.css +935 -0
  235. package/src/web/styles/shell.css +387 -0
  236. package/src/web/styles/studio.css +951 -0
  237. package/src/web/styles/thread.css +221 -0
  238. package/src/web/styles/tokens.css +94 -0
  239. package/src/web/ui/brandMark.js +73 -0
  240. package/src/web/ui/brandMark.ts +82 -0
  241. package/src/web/ui/modalsTemplate.js +388 -0
  242. package/src/web/ui/modalsTemplate.ts +388 -0
  243. package/src/web/ui/sidebarTemplate.js +63 -0
  244. package/src/web/ui/sidebarTemplate.ts +64 -0
  245. package/src/web/ui/studioTemplate.js +256 -0
  246. package/src/web/ui/studioTemplate.ts +256 -0
  247. package/src/web/ui/workspaceTemplate.js +72 -0
  248. package/src/web/ui/workspaceTemplate.ts +73 -0
  249. package/src/worktreeManager.js +16 -1
  250. package/src/worktreeManager.ts +22 -1
  251. package/src/web/skybridgeClientScript.js +0 -3951
  252. package/src/web/skybridgeClientScript.ts +0 -3952
  253. package/src/web/skybridgeStyles.js +0 -827
  254. package/src/web/skybridgeStyles.ts +0 -828
@@ -0,0 +1,397 @@
1
+ import type http from 'node:http';
2
+ import path from 'node:path';
3
+ import { loadConfig, resolveProviderApiKey, saveConfig } from '../../config.js';
4
+ import { DEFAULT_MODEL_BY_PROVIDER } from '../../modelCatalogue.js';
5
+ import {
6
+ getDefaultPermissionPreset,
7
+ normalizePermissionPreset,
8
+ setDefaultPermissionPreset
9
+ } from '../../permissionPresets.js';
10
+ import { probeOsSandbox, resolveOsSandboxMode } from '../../tools/osSandbox.js';
11
+ import {
12
+ deleteCausyneMemories,
13
+ readPersonalizationOverview,
14
+ saveMemoryPreferences,
15
+ savePersonalizationInstructions,
16
+ type PersonalizationScope
17
+ } from '../../personalization.js';
18
+ import { discoverProjectMcpServers, serverStatus } from '../../mcp/mcpRegistry.js';
19
+ import { disablePlugin, enablePlugin, listPlugins, PLUGIN_ROOT } from '../../plugins/pluginManager.js';
20
+ import { auditLog } from '../../auditLog.js';
21
+ import { readJsonBody, sendJson } from './security.js';
22
+ import type { SkybridgeContext } from './types.js';
23
+
24
+ const VAULT_PROVIDER_IDS = [
25
+ 'deepseek',
26
+ 'qwen',
27
+ 'dashscope-byok',
28
+ 'anthropic',
29
+ 'openai',
30
+ 'gemini',
31
+ 'moonshot',
32
+ 'xai',
33
+ 'openrouter',
34
+ 'groq',
35
+ 'cerebras',
36
+ 'mistral'
37
+ ] as const;
38
+
39
+ const ALLOWED_OS_SANDBOX_MODES = new Set([
40
+ 'off',
41
+ 'workspace-write',
42
+ 'strict',
43
+ 'read-only',
44
+ 'read-only-strict'
45
+ ]);
46
+
47
+ const ALLOWED_EFFORT_LEVELS = new Set(['', 'off', 'low', 'medium', 'high', 'max']);
48
+
49
+ function buildHooksOverview(config: Record<string, unknown>): Array<{
50
+ index: number;
51
+ name: string;
52
+ event: string;
53
+ tools: string[];
54
+ commandPreview: string;
55
+ timeoutMs: number;
56
+ enabled: boolean;
57
+ }> {
58
+ const rawHooks = Array.isArray(config.hooks) ? config.hooks : [];
59
+ const items: Array<{
60
+ index: number;
61
+ name: string;
62
+ event: string;
63
+ tools: string[];
64
+ commandPreview: string;
65
+ timeoutMs: number;
66
+ enabled: boolean;
67
+ }> = [];
68
+ for (let i = 0; i < rawHooks.length && i < 64; i++) {
69
+ const entry = rawHooks[i];
70
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
71
+ const rec = entry as Record<string, unknown>;
72
+ const event = typeof rec.event === 'string' && rec.event.trim() ? rec.event.trim() : 'PreToolUse';
73
+ const tools = Array.isArray(rec.tools)
74
+ ? rec.tools.filter((t): t is string => typeof t === 'string' && t.trim().length > 0)
75
+ : [typeof rec.tool === 'string' && rec.tool.trim() ? rec.tool.trim() : '*'];
76
+ const command = Array.isArray(rec.command)
77
+ ? rec.command.map((c) => String(c)).join(' ')
78
+ : '';
79
+ const name = typeof rec.name === 'string' && rec.name.trim()
80
+ ? rec.name.trim().slice(0, 120)
81
+ : `${event}:${tools[0] || '*'}`;
82
+ const timeoutMs = typeof rec.timeoutMs === 'number' && Number.isFinite(rec.timeoutMs)
83
+ ? Math.max(100, Math.min(10_000, Math.round(rec.timeoutMs)))
84
+ : 5_000;
85
+ items.push({
86
+ index: i,
87
+ name,
88
+ event,
89
+ tools,
90
+ commandPreview: command.slice(0, 180),
91
+ timeoutMs,
92
+ enabled: rec.enabled !== false
93
+ });
94
+ }
95
+ return items;
96
+ }
97
+
98
+ function buildSettingsOverviewPayload(ctx: SkybridgeContext): Record<string, unknown> {
99
+ const config = loadConfig();
100
+ const osSandboxCap = probeOsSandbox();
101
+ const osSandboxResolved = resolveOsSandboxMode(process.env, config.osSandbox);
102
+ const configuredOsSandbox = typeof config.osSandbox === 'string' && ALLOWED_OS_SANDBOX_MODES.has(config.osSandbox.trim().toLowerCase())
103
+ ? config.osSandbox.trim().toLowerCase()
104
+ : 'workspace-write';
105
+
106
+ const rawBudget = config.tokenBudget && typeof config.tokenBudget === 'object' && !Array.isArray(config.tokenBudget)
107
+ ? (config.tokenBudget as Record<string, unknown>)
108
+ : {};
109
+ const tokenBudget = {
110
+ enabled: rawBudget.enabled === true,
111
+ maxTokensPerTask: typeof rawBudget.maxTokensPerTask === 'number' && Number.isFinite(rawBudget.maxTokensPerTask)
112
+ ? Math.max(1000, Math.round(rawBudget.maxTokensPerTask))
113
+ : 150000,
114
+ maxTokensPerDay: typeof rawBudget.maxTokensPerDay === 'number' && Number.isFinite(rawBudget.maxTokensPerDay)
115
+ ? Math.max(1000, Math.round(rawBudget.maxTokensPerDay))
116
+ : 1000000,
117
+ maxCostUsd: typeof rawBudget.maxCostUsd === 'number' && Number.isFinite(rawBudget.maxCostUsd)
118
+ ? Math.max(0.1, Number(rawBudget.maxCostUsd))
119
+ : 5,
120
+ hardStop: rawBudget.hardStop === true
121
+ };
122
+
123
+ const rawCompact = config.contextCompaction && typeof config.contextCompaction === 'object' && !Array.isArray(config.contextCompaction)
124
+ ? (config.contextCompaction as Record<string, unknown>)
125
+ : {};
126
+ const autoCompact = {
127
+ enabled: rawCompact.enabled !== false,
128
+ thresholdPercent: typeof rawCompact.thresholdPercent === 'number' && Number.isFinite(rawCompact.thresholdPercent)
129
+ ? Math.max(40, Math.min(95, Math.round(rawCompact.thresholdPercent)))
130
+ : 78
131
+ };
132
+
133
+ const configuredProviders = VAULT_PROVIDER_IDS.filter((id) => Boolean(resolveProviderApiKey(config, id)));
134
+ const projectMcp = discoverProjectMcpServers(ctx.workspaceRoot);
135
+
136
+ let pluginItems: ReturnType<typeof listPlugins> = [];
137
+ try {
138
+ pluginItems = listPlugins();
139
+ } catch {
140
+ pluginItems = [];
141
+ }
142
+
143
+ return {
144
+ ok: true,
145
+ general: {
146
+ workspaceRoot: ctx.workspaceRoot,
147
+ workspaceName: path.basename(ctx.workspaceRoot),
148
+ version: ctx.version,
149
+ platform: process.platform,
150
+ provider: config.provider || 'unconfigured',
151
+ model: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default'
152
+ },
153
+ configuration: {
154
+ defaultPermissionPreset: getDefaultPermissionPreset(),
155
+ reasoningEffort: typeof config.reasoningEffort === 'string' ? config.reasoningEffort.trim().toLowerCase() : '',
156
+ osSandbox: {
157
+ configuredMode: configuredOsSandbox,
158
+ effectiveMode: osSandboxResolved.mode,
159
+ strict: osSandboxResolved.strict,
160
+ allowNetwork: osSandboxResolved.allowNetwork,
161
+ backend: osSandboxCap.backend,
162
+ available: osSandboxCap.available,
163
+ reason: osSandboxCap.reason
164
+ },
165
+ tokenBudget,
166
+ autoCompact
167
+ },
168
+ personalization: readPersonalizationOverview(ctx.workspaceRoot),
169
+ vault: {
170
+ activeProvider: config.provider || '',
171
+ configuredProviders
172
+ },
173
+ mcp: {
174
+ servers: serverStatus(),
175
+ projectDiscovered: projectMcp.servers.map((srv) => ({
176
+ name: srv.name,
177
+ transport: srv.url ? 'http' : 'stdio',
178
+ target: srv.url ?? [srv.command, ...(srv.args ?? [])].filter(Boolean).join(' ')
179
+ })),
180
+ projectWarnings: projectMcp.warnings,
181
+ projectFile: projectMcp.filePath
182
+ },
183
+ hooks: buildHooksOverview(config),
184
+ plugins: {
185
+ root: PLUGIN_ROOT,
186
+ items: pluginItems
187
+ }
188
+ };
189
+ }
190
+
191
+ function invalidateActiveLoopStaticContexts(ctx: SkybridgeContext): void {
192
+ for (const run of ctx.activeRuns.values()) {
193
+ const loopObj = run.loop as unknown as { staticContext?: unknown };
194
+ if (loopObj && typeof loopObj === 'object' && 'staticContext' in loopObj) {
195
+ loopObj.staticContext = null;
196
+ }
197
+ }
198
+ }
199
+
200
+ export async function handleSettingsRoutes(
201
+ req: http.IncomingMessage,
202
+ res: http.ServerResponse,
203
+ parsedUrl: URL,
204
+ ctx: SkybridgeContext
205
+ ): Promise<boolean> {
206
+ const pathname = parsedUrl.pathname;
207
+
208
+ if (req.method === 'GET' && pathname === '/api/settings/overview') {
209
+ sendJson(res, 200, buildSettingsOverviewPayload(ctx));
210
+ return true;
211
+ }
212
+
213
+ if (req.method === 'POST' && pathname === '/api/settings/configuration') {
214
+ const body = await readJsonBody(req);
215
+ const config = loadConfig();
216
+
217
+ if (body.defaultPermissionPreset !== undefined) {
218
+ const preset = normalizePermissionPreset(body.defaultPermissionPreset);
219
+ if (!preset) {
220
+ sendJson(res, 400, { error: 'Invalid defaultPermissionPreset value.' });
221
+ return true;
222
+ }
223
+ setDefaultPermissionPreset(preset);
224
+ config.defaultPermissionPreset = preset;
225
+ }
226
+
227
+ if (typeof body.osSandbox === 'string') {
228
+ const mode = body.osSandbox.trim().toLowerCase();
229
+ if (!ALLOWED_OS_SANDBOX_MODES.has(mode)) {
230
+ sendJson(res, 400, { error: 'Invalid osSandbox mode.' });
231
+ return true;
232
+ }
233
+ config.osSandbox = mode;
234
+ }
235
+
236
+ if (typeof body.reasoningEffort === 'string') {
237
+ const effort = body.reasoningEffort.trim().toLowerCase();
238
+ if (!ALLOWED_EFFORT_LEVELS.has(effort)) {
239
+ sendJson(res, 400, { error: 'Invalid reasoningEffort level.' });
240
+ return true;
241
+ }
242
+ if (!effort) delete config.reasoningEffort;
243
+ else config.reasoningEffort = effort;
244
+ }
245
+
246
+ if (body.tokenBudget && typeof body.tokenBudget === 'object' && !Array.isArray(body.tokenBudget)) {
247
+ const raw = body.tokenBudget as Record<string, unknown>;
248
+ const prev = config.tokenBudget && typeof config.tokenBudget === 'object'
249
+ ? (config.tokenBudget as Record<string, unknown>)
250
+ : {};
251
+ const nextBudget: Record<string, unknown> = { ...prev };
252
+ if (typeof raw.enabled === 'boolean') nextBudget.enabled = raw.enabled;
253
+ if (typeof raw.hardStop === 'boolean') nextBudget.hardStop = raw.hardStop;
254
+ if (typeof raw.maxTokensPerTask === 'number' && Number.isFinite(raw.maxTokensPerTask)) {
255
+ nextBudget.maxTokensPerTask = Math.max(1000, Math.min(100_000_000, Math.round(raw.maxTokensPerTask)));
256
+ }
257
+ if (typeof raw.maxTokensPerDay === 'number' && Number.isFinite(raw.maxTokensPerDay)) {
258
+ nextBudget.maxTokensPerDay = Math.max(1000, Math.min(1_000_000_000, Math.round(raw.maxTokensPerDay)));
259
+ }
260
+ if (typeof raw.maxCostUsd === 'number' && Number.isFinite(raw.maxCostUsd)) {
261
+ nextBudget.maxCostUsd = Math.max(0.1, Math.min(10_000, Number(raw.maxCostUsd.toFixed(2))));
262
+ }
263
+ config.tokenBudget = nextBudget;
264
+ }
265
+
266
+ if (body.autoCompact && typeof body.autoCompact === 'object' && !Array.isArray(body.autoCompact)) {
267
+ const raw = body.autoCompact as Record<string, unknown>;
268
+ const prev = config.contextCompaction && typeof config.contextCompaction === 'object'
269
+ ? (config.contextCompaction as Record<string, unknown>)
270
+ : {};
271
+ const nextCompact: Record<string, unknown> = { ...prev };
272
+ if (typeof raw.enabled === 'boolean') nextCompact.enabled = raw.enabled;
273
+ if (typeof raw.thresholdPercent === 'number' && Number.isFinite(raw.thresholdPercent)) {
274
+ nextCompact.thresholdPercent = Math.max(40, Math.min(95, Math.round(raw.thresholdPercent)));
275
+ }
276
+ config.contextCompaction = nextCompact;
277
+ }
278
+
279
+ saveConfig(config);
280
+ auditLog.log({ event: 'skybridge_configuration_updated' });
281
+ sendJson(res, 200, buildSettingsOverviewPayload(ctx));
282
+ return true;
283
+ }
284
+
285
+ if (req.method === 'POST' && pathname === '/api/settings/personalization') {
286
+ const body = await readJsonBody(req);
287
+ const scope: PersonalizationScope = body.scope === 'global' ? 'global' : 'project';
288
+
289
+ try {
290
+ if (typeof body.instructions === 'string') {
291
+ savePersonalizationInstructions(ctx.workspaceRoot, scope, body.instructions);
292
+ }
293
+
294
+ const memPatch: { enabled?: boolean | null | undefined; allowToolAssisted?: boolean | null | undefined } = {};
295
+ if (typeof body.memoryEnabled === 'boolean' || body.memoryEnabled === null) {
296
+ memPatch.enabled = body.memoryEnabled;
297
+ }
298
+ if (typeof body.allowToolAssisted === 'boolean' || body.allowToolAssisted === null) {
299
+ memPatch.allowToolAssisted = body.allowToolAssisted;
300
+ }
301
+ if (memPatch.enabled !== undefined || memPatch.allowToolAssisted !== undefined) {
302
+ saveMemoryPreferences(ctx.workspaceRoot, scope, memPatch);
303
+ }
304
+
305
+ invalidateActiveLoopStaticContexts(ctx);
306
+ auditLog.log({
307
+ event: 'skybridge_personalization_updated',
308
+ scope,
309
+ updatedInstructions: typeof body.instructions === 'string',
310
+ updatedMemory: memPatch.enabled !== undefined || memPatch.allowToolAssisted !== undefined
311
+ });
312
+ sendJson(res, 200, {
313
+ ok: true,
314
+ scope,
315
+ personalization: readPersonalizationOverview(ctx.workspaceRoot)
316
+ });
317
+ return true;
318
+ } catch (err: unknown) {
319
+ const rawMsg = err instanceof Error ? err.message : '';
320
+ const safeMsg = rawMsg.includes('exceed maximum size')
321
+ ? 'Personalization instructions exceed the 16 KB limit.'
322
+ : rawMsg.includes('symlink')
323
+ ? 'Refusing to write personalization through a symbolic link.'
324
+ : 'Could not save personalization settings.';
325
+ sendJson(res, 400, { error: safeMsg });
326
+ return true;
327
+ }
328
+ }
329
+
330
+ if (req.method === 'POST' && pathname === '/api/settings/memories/delete') {
331
+ const body = await readJsonBody(req);
332
+ const scope = body.scope === 'all' ? 'all' : 'project';
333
+ const result = deleteCausyneMemories(ctx.workspaceRoot, scope);
334
+ invalidateActiveLoopStaticContexts(ctx);
335
+ auditLog.log({
336
+ event: 'skybridge_memories_deleted',
337
+ scope,
338
+ factsRemoved: result.factsRemoved,
339
+ observationsRemoved: result.observationsRemoved,
340
+ summariesRemoved: result.summariesRemoved
341
+ });
342
+ sendJson(res, 200, {
343
+ ok: true,
344
+ ...result,
345
+ personalization: readPersonalizationOverview(ctx.workspaceRoot)
346
+ });
347
+ return true;
348
+ }
349
+
350
+ if (req.method === 'POST' && pathname === '/api/settings/hooks/toggle') {
351
+ const body = await readJsonBody(req);
352
+ const index = typeof body.index === 'number' && Number.isInteger(body.index) ? body.index : -1;
353
+ const enabled = typeof body.enabled === 'boolean' ? body.enabled : null;
354
+ if (index < 0 || enabled === null) {
355
+ sendJson(res, 400, { error: 'Valid hook index and boolean enabled flag are required.' });
356
+ return true;
357
+ }
358
+ const config = loadConfig();
359
+ if (!Array.isArray(config.hooks) || index >= config.hooks.length) {
360
+ sendJson(res, 404, { error: 'Configured hook entry not found.' });
361
+ return true;
362
+ }
363
+ const target = config.hooks[index];
364
+ if (!target || typeof target !== 'object' || Array.isArray(target)) {
365
+ sendJson(res, 400, { error: 'Hook entry is malformed.' });
366
+ return true;
367
+ }
368
+ (target as Record<string, unknown>).enabled = enabled;
369
+ saveConfig(config);
370
+ auditLog.log({ event: 'skybridge_hook_toggled', index, enabled });
371
+ sendJson(res, 200, { ok: true, hooks: buildHooksOverview(config) });
372
+ return true;
373
+ }
374
+
375
+ if (req.method === 'POST' && pathname === '/api/settings/plugins/toggle') {
376
+ const body = await readJsonBody(req);
377
+ const name = typeof body.name === 'string' ? body.name.trim() : '';
378
+ const enabled = typeof body.enabled === 'boolean' ? body.enabled : null;
379
+ if (!name || enabled === null) {
380
+ sendJson(res, 400, { error: 'Valid plugin name and boolean enabled flag are required.' });
381
+ return true;
382
+ }
383
+ const outcome = enabled ? enablePlugin(name) : disablePlugin(name);
384
+ if (!outcome.ok) {
385
+ sendJson(res, 400, { error: 'Could not update plugin trust state.' });
386
+ return true;
387
+ }
388
+ auditLog.log({ event: 'skybridge_plugin_toggled', name, enabled });
389
+ sendJson(res, 200, {
390
+ ok: true,
391
+ plugins: { root: PLUGIN_ROOT, items: listPlugins() }
392
+ });
393
+ return true;
394
+ }
395
+
396
+ return false;
397
+ }
@@ -0,0 +1,162 @@
1
+ import { auditLog } from '../../auditLog.js';
2
+ import { listAvailableShells, ptyTerminalManager } from '../../tools/ptyTerminal.js';
3
+ import { readJsonBody, sendJson } from './security.js';
4
+ const SAFE_TERMINAL_ID_RE = /^term_[0-9]+_[a-f0-9]{8}$/;
5
+ const ALLOWED_WEB_SIGNALS = new Set(['SIGINT', 'SIGTERM', 'SIGTSTP', 'SIGHUP']);
6
+ function parseTerminalSessionRoute(pathname) {
7
+ if (!pathname.startsWith('/api/terminal/sessions/'))
8
+ return null;
9
+ const raw = pathname.slice('/api/terminal/sessions/'.length);
10
+ if (!raw || raw.includes('/'))
11
+ return null;
12
+ return SAFE_TERMINAL_ID_RE.test(raw) ? raw : null;
13
+ }
14
+ export async function handleTerminalRoutes(req, res, parsedUrl, ctx) {
15
+ const pathname = parsedUrl.pathname;
16
+ const { workspaceRoot } = ctx;
17
+ if (req.method === 'GET' && pathname === '/api/terminal/sessions') {
18
+ sendJson(res, 200, {
19
+ ok: true,
20
+ sessions: ptyTerminalManager.listSessions(workspaceRoot),
21
+ shells: listAvailableShells()
22
+ });
23
+ return true;
24
+ }
25
+ if (req.method === 'POST' && pathname === '/api/terminal/sessions') {
26
+ const body = await readJsonBody(req);
27
+ const shell = typeof body.shell === 'string' ? body.shell.trim() : undefined;
28
+ const name = typeof body.name === 'string' ? body.name.trim() : undefined;
29
+ const cols = typeof body.cols === 'number' ? body.cols : undefined;
30
+ const rows = typeof body.rows === 'number' ? body.rows : undefined;
31
+ const session = ptyTerminalManager.openSession({
32
+ workspaceRoot,
33
+ shell,
34
+ name,
35
+ origin: 'user',
36
+ cols,
37
+ rows
38
+ });
39
+ auditLog.log({
40
+ event: 'skybridge_terminal_open',
41
+ terminalId: session.id,
42
+ shell: session.shellLabel,
43
+ transport: session.transport
44
+ });
45
+ sendJson(res, 201, { ok: true, session });
46
+ return true;
47
+ }
48
+ const deleteId = parseTerminalSessionRoute(pathname);
49
+ if (req.method === 'DELETE' && deleteId) {
50
+ const existing = ptyTerminalManager.getSession(deleteId);
51
+ if (!existing || existing.workspaceRoot !== workspaceRoot) {
52
+ sendJson(res, 404, { error: 'Terminal session not found in this workspace.' });
53
+ return true;
54
+ }
55
+ const closed = ptyTerminalManager.closeSession(deleteId);
56
+ sendJson(res, closed ? 200 : 404, { ok: closed, id: deleteId });
57
+ return true;
58
+ }
59
+ if (req.method === 'GET' && pathname === '/api/terminal/stream') {
60
+ const id = (parsedUrl.searchParams.get('id') || '').trim();
61
+ if (!SAFE_TERMINAL_ID_RE.test(id)) {
62
+ sendJson(res, 400, { error: 'Invalid terminal session id.' });
63
+ return true;
64
+ }
65
+ const existing = ptyTerminalManager.getSession(id);
66
+ if (!existing || existing.workspaceRoot !== workspaceRoot) {
67
+ sendJson(res, 404, { error: 'Terminal session not found in this workspace.' });
68
+ return true;
69
+ }
70
+ res.statusCode = 200;
71
+ res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
72
+ res.setHeader('Transfer-Encoding', 'chunked');
73
+ res.setHeader('Cache-Control', 'no-store');
74
+ res.setHeader('X-Accel-Buffering', 'no');
75
+ const writeLine = (payload) => {
76
+ if (res.writableEnded || res.destroyed)
77
+ return;
78
+ try {
79
+ res.write(`${JSON.stringify(payload)}\n`);
80
+ }
81
+ catch {
82
+ // Stream closed mid-write
83
+ }
84
+ };
85
+ const unsub = ptyTerminalManager.subscribe(id, (ev) => writeLine(ev), true);
86
+ const keepAlive = setInterval(() => {
87
+ writeLine({ type: 'ping', ts: Date.now() });
88
+ }, 15_000);
89
+ keepAlive.unref?.();
90
+ const cleanup = () => {
91
+ clearInterval(keepAlive);
92
+ unsub();
93
+ };
94
+ req.on('close', cleanup);
95
+ res.on('close', cleanup);
96
+ return true;
97
+ }
98
+ if (req.method === 'POST' && pathname === '/api/terminal/input') {
99
+ const body = await readJsonBody(req);
100
+ const id = typeof body.id === 'string' ? body.id.trim() : '';
101
+ if (!SAFE_TERMINAL_ID_RE.test(id)) {
102
+ sendJson(res, 400, { error: 'Invalid terminal session id.' });
103
+ return true;
104
+ }
105
+ const existing = ptyTerminalManager.getSession(id);
106
+ if (!existing || existing.workspaceRoot !== workspaceRoot) {
107
+ sendJson(res, 404, { error: 'Terminal session not found in this workspace.' });
108
+ return true;
109
+ }
110
+ if (typeof body.cols === 'number' && typeof body.rows === 'number') {
111
+ ptyTerminalManager.resizeSession(id, body.cols, body.rows);
112
+ }
113
+ if (typeof body.data === 'string') {
114
+ const result = ptyTerminalManager.writeInput(id, body.data, {
115
+ actor: 'user',
116
+ typed: body.typed !== false
117
+ });
118
+ if (!result.ok) {
119
+ const safeErr = result.code === 'SESSION_EXITED'
120
+ ? 'Terminal session has already exited.'
121
+ : result.code === 'TAKEN_OVER'
122
+ ? 'Terminal session was taken over by the user.'
123
+ : 'Unable to write to terminal session.';
124
+ sendJson(res, 400, { ok: false, error: safeErr, code: result.code });
125
+ return true;
126
+ }
127
+ sendJson(res, 200, { ok: true, control: result.control });
128
+ return true;
129
+ }
130
+ sendJson(res, 200, { ok: true, control: existing.control });
131
+ return true;
132
+ }
133
+ if (req.method === 'POST' && pathname === '/api/terminal/signal') {
134
+ const body = await readJsonBody(req);
135
+ const id = typeof body.id === 'string' ? body.id.trim() : '';
136
+ const sig = typeof body.signal === 'string' ? body.signal.trim().toUpperCase() : '';
137
+ if (!SAFE_TERMINAL_ID_RE.test(id)) {
138
+ sendJson(res, 400, { error: 'Invalid terminal session id.' });
139
+ return true;
140
+ }
141
+ if (!ALLOWED_WEB_SIGNALS.has(sig)) {
142
+ sendJson(res, 400, { error: 'Unsupported terminal signal.' });
143
+ return true;
144
+ }
145
+ const existing = ptyTerminalManager.getSession(id);
146
+ if (!existing || existing.workspaceRoot !== workspaceRoot) {
147
+ sendJson(res, 404, { error: 'Terminal session not found in this workspace.' });
148
+ return true;
149
+ }
150
+ const result = ptyTerminalManager.signalSession(id, sig, 'user');
151
+ const safeErr = result.ok
152
+ ? undefined
153
+ : (result.code === 'SESSION_EXITED'
154
+ ? 'Terminal session has already exited.'
155
+ : result.code === 'SIGNAL_DENIED'
156
+ ? 'Requested signal is not permitted.'
157
+ : 'Unable to signal terminal session.');
158
+ sendJson(res, result.ok ? 200 : 400, { ok: result.ok, ...(safeErr ? { error: safeErr } : {}) });
159
+ return true;
160
+ }
161
+ return false;
162
+ }