@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,304 @@
1
+ import { createSession, getSession, saveSessionMessages } from '../../sessionJournal.js';
2
+ import { auditLog } from '../../auditLog.js';
3
+ import { redactProviderSecrets } from '../../providers/byokHttp.js';
4
+ import { DAILY_LIMIT_SUPPORT_MESSAGE, EntitlementAccessError } from '../../licensing/entitlements.js';
5
+ import { getSessionPermissionPreset, normalizePermissionPreset, presetToAutonomyMode, setSessionPermissionPreset } from '../../permissionPresets.js';
6
+ import { SAFE_MODEL_RE, SAFE_PROVIDER_RE, SAFE_SESSION_ID_RE, readJsonBody, sendJson } from './security.js';
7
+ import { buildWorkspacePromptWithAttachments, workspaceMatchesSession } from './workspaceFiles.js';
8
+ import { MUTATING_FILE_TOOLS } from './sessionTranscript.js';
9
+ export async function handleChatRoutes(req, res, parsedUrl, ctx) {
10
+ const pathname = parsedUrl.pathname;
11
+ const { workspaceRoot } = ctx;
12
+ if (req.method === 'POST' && pathname === '/api/approve') {
13
+ const body = await readJsonBody(req);
14
+ const toolCallId = typeof body.toolCallId === 'string' ? body.toolCallId.trim() : '';
15
+ const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
16
+ ? body.sessionId.trim()
17
+ : '';
18
+ const approved = body.approved === true;
19
+ const remember = body.remember === true;
20
+ const toolName = typeof body.tool === 'string' ? body.tool.trim().slice(0, 80) : '';
21
+ const targetRun = ctx.findActiveRun(sessionId || null);
22
+ if (!toolCallId || !targetRun?.loop.resolveApproval) {
23
+ sendJson(res, 400, { error: 'No active pending approval matches that toolCallId.' });
24
+ return true;
25
+ }
26
+ if (approved && remember && toolName && targetRun.loop.grantAlways) {
27
+ targetRun.loop.grantAlways(toolName);
28
+ auditLog.log({ event: 'skybridge_approval_grant_always', tool: toolName });
29
+ }
30
+ targetRun.status = 'running';
31
+ targetRun.loop.resolveApproval(toolCallId, approved);
32
+ sendJson(res, 200, { ok: true, toolCallId, approved, remembered: Boolean(approved && remember && toolName) });
33
+ return true;
34
+ }
35
+ if (req.method === 'POST' && pathname === '/api/decision') {
36
+ const body = await readJsonBody(req);
37
+ const requestId = typeof body.requestId === 'string' ? body.requestId.trim() : '';
38
+ const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
39
+ ? body.sessionId.trim()
40
+ : '';
41
+ const label = typeof body.label === 'string' ? body.label.trim().slice(0, 400) : '';
42
+ const optionId = typeof body.optionId === 'string' ? body.optionId.trim().slice(0, 120) : null;
43
+ const custom = body.custom === true;
44
+ const targetRun = ctx.findActiveRun(sessionId || null);
45
+ if (!requestId || !targetRun?.loop.resolveDecision) {
46
+ sendJson(res, 400, { error: 'No active pending decision matches that requestId.' });
47
+ return true;
48
+ }
49
+ targetRun.status = 'running';
50
+ targetRun.loop.resolveDecision(requestId, label ? { optionId, label, custom } : null);
51
+ sendJson(res, 200, { ok: true, requestId, label });
52
+ return true;
53
+ }
54
+ if (req.method === 'POST' && pathname === '/api/stop') {
55
+ let stopSessionId = '';
56
+ try {
57
+ const body = await readJsonBody(req);
58
+ if (typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())) {
59
+ stopSessionId = body.sessionId.trim();
60
+ }
61
+ }
62
+ catch {
63
+ // Empty body is valid for /api/stop.
64
+ }
65
+ if (stopSessionId) {
66
+ const run = ctx.activeRuns.get(stopSessionId);
67
+ if (run) {
68
+ run.userStopped = true;
69
+ run.loop.abort?.();
70
+ }
71
+ }
72
+ else {
73
+ for (const run of ctx.activeRuns.values()) {
74
+ run.userStopped = true;
75
+ run.loop.abort?.();
76
+ }
77
+ }
78
+ sendJson(res, 200, { ok: true });
79
+ return true;
80
+ }
81
+ if (req.method === 'POST' && pathname === '/api/chat') {
82
+ const body = await readJsonBody(req);
83
+ const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
84
+ const requestedSessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
85
+ ? body.sessionId.trim()
86
+ : '';
87
+ const explicitPreset = normalizePermissionPreset(body.permissionPreset)
88
+ ?? normalizePermissionPreset(body.mode);
89
+ const resolvedPreset = explicitPreset ?? getSessionPermissionPreset(requestedSessionId || null);
90
+ const mode = presetToAutonomyMode(resolvedPreset);
91
+ const providerOverride = typeof body.provider === 'string' && SAFE_PROVIDER_RE.test(body.provider.trim())
92
+ ? body.provider.trim()
93
+ : undefined;
94
+ const modelOverride = typeof body.model === 'string' && SAFE_MODEL_RE.test(body.model.trim())
95
+ ? body.model.trim()
96
+ : undefined;
97
+ if (!prompt) {
98
+ sendJson(res, 400, { error: 'Prompt text is required.' });
99
+ return true;
100
+ }
101
+ let boundSession = requestedSessionId ? getSession(requestedSessionId) : null;
102
+ if (boundSession && !workspaceMatchesSession(boundSession.workspace, workspaceRoot)) {
103
+ boundSession = null;
104
+ }
105
+ if (!boundSession && !ctx.hasCustomFactory) {
106
+ boundSession = createSession(workspaceRoot, prompt.slice(0, 60), false);
107
+ }
108
+ if (boundSession && explicitPreset) {
109
+ setSessionPermissionPreset(boundSession.id, resolvedPreset);
110
+ }
111
+ const runKey = boundSession?.id || '__ephemeral__';
112
+ const existingRun = ctx.activeRuns.get(runKey);
113
+ if (existingRun && (existingRun.status === 'running' || existingRun.status === 'awaiting_client')) {
114
+ sendJson(res, 409, {
115
+ error: 'This conversation already has a task running. Stop it or wait for completion.'
116
+ });
117
+ return true;
118
+ }
119
+ const { effectivePrompt, attachedPaths } = buildWorkspacePromptWithAttachments(workspaceRoot, prompt, body.attachments);
120
+ const taskId = ctx.nextTaskId();
121
+ let collectedAssistantText = '';
122
+ let runRef = null;
123
+ const emitFrame = (raw) => {
124
+ const clean = raw.replace(/\r?\n/g, ' ');
125
+ try {
126
+ const parsed = JSON.parse(clean);
127
+ if (parsed.type === 'agent_chunk' && typeof parsed.delta === 'string') {
128
+ collectedAssistantText += parsed.delta;
129
+ }
130
+ else if (parsed.type === 'agent_message' && typeof parsed.content === 'string' && !collectedAssistantText) {
131
+ collectedAssistantText = parsed.content;
132
+ }
133
+ if (runRef && (parsed.type === 'approval_request' || parsed.type === 'decision_request')) {
134
+ runRef.status = 'awaiting_client';
135
+ }
136
+ const toolLower = typeof parsed.tool === 'string' ? parsed.tool.toLowerCase() : '';
137
+ const actionLower = typeof parsed.actionName === 'string' ? parsed.actionName.toLowerCase() : '';
138
+ if (boundSession?.id) {
139
+ if (parsed.type === 'code_progress' && typeof parsed.path === 'string') {
140
+ ctx.recordSessionTouchedFile(boundSession.id, parsed.path);
141
+ }
142
+ else if ((parsed.type === 'step_complete' || parsed.type === 'tool_result')
143
+ && MUTATING_FILE_TOOLS.has(toolLower)
144
+ && parsed.args) {
145
+ for (const key of ['path', 'filePath', 'file_path', 'targetFile', 'filename', 'file', 'destination']) {
146
+ ctx.recordSessionTouchedFile(boundSession.id, parsed.args[key]);
147
+ }
148
+ }
149
+ else if (parsed.type === 'notice' && MUTATING_FILE_TOOLS.has(actionLower) && parsed.detail) {
150
+ ctx.recordSessionTouchedFile(boundSession.id, parsed.detail);
151
+ }
152
+ }
153
+ const isBrowserTool = toolLower.includes('browser');
154
+ const isComputerTool = toolLower.includes('computer_use') || toolLower.includes('desktop_act');
155
+ if ((parsed.type === 'step_start' || parsed.type === 'tool_start') && (isBrowserTool || isComputerTool)) {
156
+ if (isBrowserTool)
157
+ ctx.setBrowserControlOwner('agent');
158
+ const detail = isBrowserTool && Array.isArray(parsed.args?.actions) && parsed.args.actions[0]
159
+ ? String(parsed.args.actions[0].type || 'browser.act')
160
+ : String(parsed.args?.action || parsed.tool || '');
161
+ ctx.setBrowserAgentActivity({
162
+ active: true,
163
+ tool: parsed.tool || 'browser.act',
164
+ detail: detail.slice(0, 80),
165
+ updatedAt: Date.now()
166
+ });
167
+ ctx.broadcastBrowserNotice({
168
+ type: 'agent_activity',
169
+ controlOwner: ctx.getBrowserControlOwner(),
170
+ agentActivity: ctx.getBrowserAgentActivity()
171
+ });
172
+ }
173
+ else if ((parsed.type === 'step_complete' || parsed.type === 'step_error' || parsed.type === 'tool_complete')
174
+ && (isBrowserTool || isComputerTool)) {
175
+ ctx.setBrowserAgentActivity({ active: false, tool: '', detail: '', updatedAt: Date.now() });
176
+ ctx.broadcastBrowserNotice({
177
+ type: 'agent_activity',
178
+ controlOwner: ctx.getBrowserControlOwner(),
179
+ agentActivity: ctx.getBrowserAgentActivity()
180
+ });
181
+ }
182
+ }
183
+ catch {
184
+ // pass raw frame through untouched
185
+ }
186
+ if (runRef)
187
+ ctx.pushRunFrame(runRef, clean);
188
+ };
189
+ const wrappedSink = { readyState: 1, send: emitFrame };
190
+ const loop = ctx.loopFactory(wrappedSink, taskId, effectivePrompt, {
191
+ workspaceRoot,
192
+ mode,
193
+ permissionPreset: resolvedPreset,
194
+ sessionId: boundSession?.id,
195
+ provider: providerOverride,
196
+ model: modelOverride
197
+ });
198
+ const run = {
199
+ key: runKey,
200
+ sessionId: boundSession?.id || null,
201
+ taskId,
202
+ prompt,
203
+ startedAt: Date.now(),
204
+ status: 'running',
205
+ userStopped: false,
206
+ loop,
207
+ frames: [],
208
+ bufferedBytes: 0,
209
+ subscribers: new Set(),
210
+ doneSubscribers: new Set()
211
+ };
212
+ runRef = run;
213
+ ctx.activeRuns.set(runKey, run);
214
+ if (boundSession) {
215
+ ctx.pushRunFrame(run, JSON.stringify({
216
+ type: 'session_bound',
217
+ sessionId: boundSession.id,
218
+ title: boundSession.title,
219
+ attachments: attachedPaths
220
+ }));
221
+ }
222
+ ctx.attachRunStream(req, res, run, true);
223
+ void (async () => {
224
+ try {
225
+ await loop.run();
226
+ if (boundSession && ctx.hasCustomFactory && collectedAssistantText.trim()) {
227
+ const latest = getSession(boundSession.id);
228
+ if (latest) {
229
+ const nextMessages = [
230
+ ...latest.messages,
231
+ { role: 'user', content: prompt },
232
+ { role: 'assistant', content: collectedAssistantText.trim() }
233
+ ];
234
+ saveSessionMessages(boundSession.id, nextMessages);
235
+ }
236
+ }
237
+ const refreshed = boundSession ? getSession(boundSession.id) : null;
238
+ if (run.userStopped) {
239
+ run.status = 'stopped';
240
+ ctx.pushRunFrame(run, JSON.stringify({
241
+ type: 'stopped',
242
+ taskId,
243
+ sessionId: boundSession?.id || null,
244
+ title: refreshed?.title || boundSession?.title || null,
245
+ userStopped: true
246
+ }));
247
+ }
248
+ else {
249
+ run.status = 'completed';
250
+ ctx.pushRunFrame(run, JSON.stringify({
251
+ type: 'done',
252
+ taskId,
253
+ sessionId: boundSession?.id || null,
254
+ title: refreshed?.title || boundSession?.title || null
255
+ }));
256
+ }
257
+ }
258
+ catch (err) {
259
+ run.status = run.userStopped ? 'stopped' : 'errored';
260
+ if (run.userStopped) {
261
+ ctx.pushRunFrame(run, JSON.stringify({
262
+ type: 'stopped',
263
+ taskId,
264
+ sessionId: boundSession?.id || null,
265
+ userStopped: true
266
+ }));
267
+ }
268
+ else if (err instanceof EntitlementAccessError && err.code === 'DAILY_LIMIT_REACHED') {
269
+ ctx.pushRunFrame(run, JSON.stringify({
270
+ type: 'error',
271
+ code: 'DAILY_LIMIT_REACHED',
272
+ message: err.message || DAILY_LIMIT_SUPPORT_MESSAGE
273
+ }));
274
+ }
275
+ else {
276
+ auditLog.log({
277
+ event: 'skybridge_chat_error',
278
+ taskId,
279
+ detail: redactProviderSecrets(err instanceof Error ? err.message : String(err)).slice(0, 300)
280
+ });
281
+ ctx.pushRunFrame(run, JSON.stringify({
282
+ type: 'error',
283
+ message: 'Task failed. Inspect local audit log or run `/doctor --report` for sanitized details.'
284
+ }));
285
+ }
286
+ }
287
+ finally {
288
+ for (const doneCb of [...run.doneSubscribers]) {
289
+ try {
290
+ doneCb();
291
+ }
292
+ catch { /* ignore */ }
293
+ }
294
+ run.subscribers.clear();
295
+ run.doneSubscribers.clear();
296
+ if (ctx.activeRuns.get(runKey) === run) {
297
+ ctx.activeRuns.delete(runKey);
298
+ }
299
+ }
300
+ })();
301
+ return true;
302
+ }
303
+ return false;
304
+ }
@@ -0,0 +1,347 @@
1
+ import type http from 'node:http';
2
+ import {
3
+ createSession,
4
+ getSession,
5
+ saveSessionMessages,
6
+ type SessionMessage
7
+ } from '../../sessionJournal.js';
8
+ import { auditLog } from '../../auditLog.js';
9
+ import { redactProviderSecrets } from '../../providers/byokHttp.js';
10
+ import {
11
+ DAILY_LIMIT_SUPPORT_MESSAGE,
12
+ EntitlementAccessError
13
+ } from '../../licensing/entitlements.js';
14
+ import {
15
+ getSessionPermissionPreset,
16
+ normalizePermissionPreset,
17
+ presetToAutonomyMode,
18
+ setSessionPermissionPreset
19
+ } from '../../permissionPresets.js';
20
+ import {
21
+ SAFE_MODEL_RE,
22
+ SAFE_PROVIDER_RE,
23
+ SAFE_SESSION_ID_RE,
24
+ readJsonBody,
25
+ sendJson
26
+ } from './security.js';
27
+ import {
28
+ buildWorkspacePromptWithAttachments,
29
+ workspaceMatchesSession
30
+ } from './workspaceFiles.js';
31
+ import { MUTATING_FILE_TOOLS } from './sessionTranscript.js';
32
+ import type { SessionActiveRun, SkybridgeContext } from './types.js';
33
+
34
+ export async function handleChatRoutes(
35
+ req: http.IncomingMessage,
36
+ res: http.ServerResponse,
37
+ parsedUrl: URL,
38
+ ctx: SkybridgeContext
39
+ ): Promise<boolean> {
40
+ const pathname = parsedUrl.pathname;
41
+ const { workspaceRoot } = ctx;
42
+
43
+ if (req.method === 'POST' && pathname === '/api/approve') {
44
+ const body = await readJsonBody(req);
45
+ const toolCallId = typeof body.toolCallId === 'string' ? body.toolCallId.trim() : '';
46
+ const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
47
+ ? body.sessionId.trim()
48
+ : '';
49
+ const approved = body.approved === true;
50
+ const remember = body.remember === true;
51
+ const toolName = typeof body.tool === 'string' ? body.tool.trim().slice(0, 80) : '';
52
+ const targetRun = ctx.findActiveRun(sessionId || null);
53
+ if (!toolCallId || !targetRun?.loop.resolveApproval) {
54
+ sendJson(res, 400, { error: 'No active pending approval matches that toolCallId.' });
55
+ return true;
56
+ }
57
+ if (approved && remember && toolName && targetRun.loop.grantAlways) {
58
+ targetRun.loop.grantAlways(toolName);
59
+ auditLog.log({ event: 'skybridge_approval_grant_always', tool: toolName });
60
+ }
61
+ targetRun.status = 'running';
62
+ targetRun.loop.resolveApproval(toolCallId, approved);
63
+ sendJson(res, 200, { ok: true, toolCallId, approved, remembered: Boolean(approved && remember && toolName) });
64
+ return true;
65
+ }
66
+
67
+ if (req.method === 'POST' && pathname === '/api/decision') {
68
+ const body = await readJsonBody(req);
69
+ const requestId = typeof body.requestId === 'string' ? body.requestId.trim() : '';
70
+ const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
71
+ ? body.sessionId.trim()
72
+ : '';
73
+ const label = typeof body.label === 'string' ? body.label.trim().slice(0, 400) : '';
74
+ const optionId = typeof body.optionId === 'string' ? body.optionId.trim().slice(0, 120) : null;
75
+ const custom = body.custom === true;
76
+ const targetRun = ctx.findActiveRun(sessionId || null);
77
+ if (!requestId || !targetRun?.loop.resolveDecision) {
78
+ sendJson(res, 400, { error: 'No active pending decision matches that requestId.' });
79
+ return true;
80
+ }
81
+ targetRun.status = 'running';
82
+ targetRun.loop.resolveDecision(requestId, label ? { optionId, label, custom } : null);
83
+ sendJson(res, 200, { ok: true, requestId, label });
84
+ return true;
85
+ }
86
+
87
+ if (req.method === 'POST' && pathname === '/api/stop') {
88
+ let stopSessionId = '';
89
+ try {
90
+ const body = await readJsonBody(req);
91
+ if (typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())) {
92
+ stopSessionId = body.sessionId.trim();
93
+ }
94
+ } catch {
95
+ // Empty body is valid for /api/stop.
96
+ }
97
+ if (stopSessionId) {
98
+ const run = ctx.activeRuns.get(stopSessionId);
99
+ if (run) {
100
+ run.userStopped = true;
101
+ run.loop.abort?.();
102
+ }
103
+ } else {
104
+ for (const run of ctx.activeRuns.values()) {
105
+ run.userStopped = true;
106
+ run.loop.abort?.();
107
+ }
108
+ }
109
+ sendJson(res, 200, { ok: true });
110
+ return true;
111
+ }
112
+
113
+ if (req.method === 'POST' && pathname === '/api/chat') {
114
+ const body = await readJsonBody(req);
115
+ const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
116
+ const requestedSessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
117
+ ? body.sessionId.trim()
118
+ : '';
119
+ const explicitPreset = normalizePermissionPreset(body.permissionPreset)
120
+ ?? normalizePermissionPreset(body.mode);
121
+ const resolvedPreset = explicitPreset ?? getSessionPermissionPreset(requestedSessionId || null);
122
+ const mode = presetToAutonomyMode(resolvedPreset);
123
+ const providerOverride = typeof body.provider === 'string' && SAFE_PROVIDER_RE.test(body.provider.trim())
124
+ ? body.provider.trim()
125
+ : undefined;
126
+ const modelOverride = typeof body.model === 'string' && SAFE_MODEL_RE.test(body.model.trim())
127
+ ? body.model.trim()
128
+ : undefined;
129
+ if (!prompt) {
130
+ sendJson(res, 400, { error: 'Prompt text is required.' });
131
+ return true;
132
+ }
133
+
134
+ let boundSession = requestedSessionId ? getSession(requestedSessionId) : null;
135
+ if (boundSession && !workspaceMatchesSession(boundSession.workspace, workspaceRoot)) {
136
+ boundSession = null;
137
+ }
138
+ if (!boundSession && !ctx.hasCustomFactory) {
139
+ boundSession = createSession(workspaceRoot, prompt.slice(0, 60), false);
140
+ }
141
+ if (boundSession && explicitPreset) {
142
+ setSessionPermissionPreset(boundSession.id, resolvedPreset);
143
+ }
144
+
145
+ const runKey = boundSession?.id || '__ephemeral__';
146
+ const existingRun = ctx.activeRuns.get(runKey);
147
+ if (existingRun && (existingRun.status === 'running' || existingRun.status === 'awaiting_client')) {
148
+ sendJson(res, 409, {
149
+ error: 'This conversation already has a task running. Stop it or wait for completion.'
150
+ });
151
+ return true;
152
+ }
153
+
154
+ const { effectivePrompt, attachedPaths } = buildWorkspacePromptWithAttachments(
155
+ workspaceRoot,
156
+ prompt,
157
+ body.attachments
158
+ );
159
+
160
+ const taskId = ctx.nextTaskId();
161
+ let collectedAssistantText = '';
162
+ let runRef: SessionActiveRun | null = null;
163
+
164
+ const emitFrame = (raw: string): void => {
165
+ const clean = raw.replace(/\r?\n/g, ' ');
166
+ try {
167
+ const parsed = JSON.parse(clean) as {
168
+ type?: string;
169
+ delta?: string;
170
+ content?: string;
171
+ tool?: string;
172
+ actionName?: string;
173
+ detail?: string;
174
+ path?: string;
175
+ args?: Record<string, unknown>;
176
+ };
177
+ if (parsed.type === 'agent_chunk' && typeof parsed.delta === 'string') {
178
+ collectedAssistantText += parsed.delta;
179
+ } else if (parsed.type === 'agent_message' && typeof parsed.content === 'string' && !collectedAssistantText) {
180
+ collectedAssistantText = parsed.content;
181
+ }
182
+ if (runRef && (parsed.type === 'approval_request' || parsed.type === 'decision_request')) {
183
+ runRef.status = 'awaiting_client';
184
+ }
185
+ const toolLower = typeof parsed.tool === 'string' ? parsed.tool.toLowerCase() : '';
186
+ const actionLower = typeof parsed.actionName === 'string' ? parsed.actionName.toLowerCase() : '';
187
+ if (boundSession?.id) {
188
+ if (parsed.type === 'code_progress' && typeof parsed.path === 'string') {
189
+ ctx.recordSessionTouchedFile(boundSession.id, parsed.path);
190
+ } else if (
191
+ (parsed.type === 'step_complete' || parsed.type === 'tool_result')
192
+ && MUTATING_FILE_TOOLS.has(toolLower)
193
+ && parsed.args
194
+ ) {
195
+ for (const key of ['path', 'filePath', 'file_path', 'targetFile', 'filename', 'file', 'destination']) {
196
+ ctx.recordSessionTouchedFile(boundSession.id, parsed.args[key]);
197
+ }
198
+ } else if (parsed.type === 'notice' && MUTATING_FILE_TOOLS.has(actionLower) && parsed.detail) {
199
+ ctx.recordSessionTouchedFile(boundSession.id, parsed.detail);
200
+ }
201
+ }
202
+ const isBrowserTool = toolLower.includes('browser');
203
+ const isComputerTool = toolLower.includes('computer_use') || toolLower.includes('desktop_act');
204
+ if ((parsed.type === 'step_start' || parsed.type === 'tool_start') && (isBrowserTool || isComputerTool)) {
205
+ if (isBrowserTool) ctx.setBrowserControlOwner('agent');
206
+ const detail = isBrowserTool && Array.isArray(parsed.args?.actions) && parsed.args.actions[0]
207
+ ? String((parsed.args.actions[0] as Record<string, unknown>).type || 'browser.act')
208
+ : String(parsed.args?.action || parsed.tool || '');
209
+ ctx.setBrowserAgentActivity({
210
+ active: true,
211
+ tool: parsed.tool || 'browser.act',
212
+ detail: detail.slice(0, 80),
213
+ updatedAt: Date.now()
214
+ });
215
+ ctx.broadcastBrowserNotice({
216
+ type: 'agent_activity',
217
+ controlOwner: ctx.getBrowserControlOwner(),
218
+ agentActivity: ctx.getBrowserAgentActivity()
219
+ });
220
+ } else if ((parsed.type === 'step_complete' || parsed.type === 'step_error' || parsed.type === 'tool_complete')
221
+ && (isBrowserTool || isComputerTool)) {
222
+ ctx.setBrowserAgentActivity({ active: false, tool: '', detail: '', updatedAt: Date.now() });
223
+ ctx.broadcastBrowserNotice({
224
+ type: 'agent_activity',
225
+ controlOwner: ctx.getBrowserControlOwner(),
226
+ agentActivity: ctx.getBrowserAgentActivity()
227
+ });
228
+ }
229
+ } catch {
230
+ // pass raw frame through untouched
231
+ }
232
+ if (runRef) ctx.pushRunFrame(runRef, clean);
233
+ };
234
+
235
+ const wrappedSink = { readyState: 1, send: emitFrame };
236
+ const loop = ctx.loopFactory(wrappedSink, taskId, effectivePrompt, {
237
+ workspaceRoot,
238
+ mode,
239
+ permissionPreset: resolvedPreset,
240
+ sessionId: boundSession?.id,
241
+ provider: providerOverride,
242
+ model: modelOverride
243
+ });
244
+
245
+ const run: SessionActiveRun = {
246
+ key: runKey,
247
+ sessionId: boundSession?.id || null,
248
+ taskId,
249
+ prompt,
250
+ startedAt: Date.now(),
251
+ status: 'running',
252
+ userStopped: false,
253
+ loop,
254
+ frames: [],
255
+ bufferedBytes: 0,
256
+ subscribers: new Set(),
257
+ doneSubscribers: new Set()
258
+ };
259
+ runRef = run;
260
+ ctx.activeRuns.set(runKey, run);
261
+
262
+ if (boundSession) {
263
+ ctx.pushRunFrame(run, JSON.stringify({
264
+ type: 'session_bound',
265
+ sessionId: boundSession.id,
266
+ title: boundSession.title,
267
+ attachments: attachedPaths
268
+ }));
269
+ }
270
+
271
+ ctx.attachRunStream(req, res, run, true);
272
+
273
+ void (async () => {
274
+ try {
275
+ await loop.run();
276
+ if (boundSession && ctx.hasCustomFactory && collectedAssistantText.trim()) {
277
+ const latest = getSession(boundSession.id);
278
+ if (latest) {
279
+ const nextMessages: SessionMessage[] = [
280
+ ...latest.messages,
281
+ { role: 'user', content: prompt },
282
+ { role: 'assistant', content: collectedAssistantText.trim() }
283
+ ];
284
+ saveSessionMessages(boundSession.id, nextMessages);
285
+ }
286
+ }
287
+ const refreshed = boundSession ? getSession(boundSession.id) : null;
288
+ if (run.userStopped) {
289
+ run.status = 'stopped';
290
+ ctx.pushRunFrame(run, JSON.stringify({
291
+ type: 'stopped',
292
+ taskId,
293
+ sessionId: boundSession?.id || null,
294
+ title: refreshed?.title || boundSession?.title || null,
295
+ userStopped: true
296
+ }));
297
+ } else {
298
+ run.status = 'completed';
299
+ ctx.pushRunFrame(run, JSON.stringify({
300
+ type: 'done',
301
+ taskId,
302
+ sessionId: boundSession?.id || null,
303
+ title: refreshed?.title || boundSession?.title || null
304
+ }));
305
+ }
306
+ } catch (err: unknown) {
307
+ run.status = run.userStopped ? 'stopped' : 'errored';
308
+ if (run.userStopped) {
309
+ ctx.pushRunFrame(run, JSON.stringify({
310
+ type: 'stopped',
311
+ taskId,
312
+ sessionId: boundSession?.id || null,
313
+ userStopped: true
314
+ }));
315
+ } else if (err instanceof EntitlementAccessError && err.code === 'DAILY_LIMIT_REACHED') {
316
+ ctx.pushRunFrame(run, JSON.stringify({
317
+ type: 'error',
318
+ code: 'DAILY_LIMIT_REACHED',
319
+ message: err.message || DAILY_LIMIT_SUPPORT_MESSAGE
320
+ }));
321
+ } else {
322
+ auditLog.log({
323
+ event: 'skybridge_chat_error',
324
+ taskId,
325
+ detail: redactProviderSecrets(err instanceof Error ? err.message : String(err)).slice(0, 300)
326
+ });
327
+ ctx.pushRunFrame(run, JSON.stringify({
328
+ type: 'error',
329
+ message: 'Task failed. Inspect local audit log or run `/doctor --report` for sanitized details.'
330
+ }));
331
+ }
332
+ } finally {
333
+ for (const doneCb of [...run.doneSubscribers]) {
334
+ try { doneCb(); } catch { /* ignore */ }
335
+ }
336
+ run.subscribers.clear();
337
+ run.doneSubscribers.clear();
338
+ if (ctx.activeRuns.get(runKey) === run) {
339
+ ctx.activeRuns.delete(runKey);
340
+ }
341
+ }
342
+ })();
343
+ return true;
344
+ }
345
+
346
+ return false;
347
+ }