@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
@@ -1,1058 +1,78 @@
1
- /**
2
- * Causyne Local Skybridge Server (`causyne web`)
3
- *
4
- * Foreground, user-initiated, loopback-only (`127.0.0.1`) HTTP + NDJSON bridge
5
- * connecting a local browser tab (or verified `https://causyne.com` origin) to
6
- * the user's selected local workspace folder and full Causyne Agent runtime.
7
- *
8
- * Security invariants:
9
- * 1. Binds strictly to `127.0.0.1` — never `0.0.0.0` or LAN interfaces.
10
- * 2. Strict `Host` header validation (`127.0.0.1:<port>` / `localhost:<port>`)
11
- * blocks DNS Rebinding attacks.
12
- * 3. Strict `Origin` allowlist (`http://127.0.0.1:<port>`, `http://localhost:<port>`,
13
- * `https://causyne.com`, `https://www.causyne.com`) + Chrome Private Network
14
- * Access (PNA) preflight headers block CSRF & cross-site hijacking.
15
- * 4. 256-bit cryptographic session nonce verified with `crypto.timingSafeEqual`
16
- * on every `/api/*` endpoint via `Authorization: Bearer <token>`.
17
- * 5. Every file read/list/write is strictly locked inside `workspaceRoot` via
18
- * `isPhysicalPathAllowed()` + `atomicWriteFileSync()` + audit logging.
19
- * 6. Zero persistent daemon, zero `postinstall`, zero outbound reverse tunnel.
20
- */
21
-
22
1
  import http from 'node:http';
23
2
  import crypto from 'node:crypto';
24
3
  import fs from 'node:fs';
25
4
  import path from 'node:path';
26
- import { execFileSync } from 'node:child_process';
27
5
  import type { AddressInfo } from 'node:net';
28
6
 
29
- import { AgentLoop } from '../agentLoop.js';
30
7
  import { createApprovalScope } from '../approvalGrants.js';
31
- import { isPhysicalPathAllowed, physicalPath } from '../agent/workspaceBoundary.js';
32
- import { atomicWriteFileSync } from '../infra/atomicWriter.js';
33
- import {
34
- applyProviderOverrides,
35
- loadConfig,
36
- resolveProviderApiKey,
37
- saveConfig
38
- } from '../config.js';
39
- import { detectZeroCostProviders } from '../zeroCostRouting.js';
40
- import { DEFAULT_MODEL_BY_PROVIDER, MODEL_CATALOGUE } from '../modelCatalogue.js';
41
- import {
42
- getAvailableProvidersOverview,
43
- resolveAvailableProvidersOverview
44
- } from '../dynamicCatalogue.js';
45
- import { buildModelPickerItems } from '../tui/modelPicker.js';
46
- import { disconnectOpenRouter } from '../auth/openrouterAuth.js';
47
- import {
48
- createSession,
49
- deleteSession,
50
- getSession,
51
- listSessions,
52
- renameSession,
53
- saveSessionMessages,
54
- type SessionMessage
55
- } from '../sessionJournal.js';
56
- import { collectWorkingTreeDiff, parseUnifiedDiff } from '../diffReview.js';
8
+ import { physicalPath } from '../agent/workspaceBoundary.js';
57
9
  import { auditLog } from '../auditLog.js';
58
10
  import { getPackageVersion } from '../version.js';
59
- import { formatRedactedProviderErrorReport, redactProviderSecrets } from '../providers/byokHttp.js';
60
- import { isIgnoredByCausyneIgnore } from '../ignoreRules.js';
61
- import { listCommands, parseCommand, runCommand } from '../commands.js';
62
- import { formatByokProbeReport, runZeroSpendByokProbe } from '../verification/byokSmokeProbe.js';
63
- import { listGroups } from '../checkpoints.js';
64
- import { listCompiledSkills } from '../skillsManager.js';
65
- import { serverStatus, closeAll as closeAllMcpServers } from '../mcp/mcpRegistry.js';
11
+ import { redactProviderSecrets } from '../providers/byokHttp.js';
12
+ import { closeAll as closeAllMcpServers } from '../mcp/mcpRegistry.js';
66
13
  import { lspSessionManager } from '../lsp/lspClient.js';
67
- import { listAllPeers } from '../acp/peerProfiles.js';
68
- import { listWorktrees } from '../worktreeManager.js';
69
14
  import { backgroundTaskManager } from '../backgroundTasks.js';
15
+ import { ptyTerminalManager } from '../tools/ptyTerminal.js';
16
+ import { renderSkybridgeHtml, getCausyneFaviconSvg } from './skybridgeUi.js';
70
17
  import {
71
- causyneBrowser,
72
- expandSearchMacro,
73
- type BrowserEnginePreference,
74
- type LiveBrowserInteraction
75
- } from '../browser/causyneBrowser.js';
76
- import {
77
- discoverLocalCdpTabs,
78
- importExplicitUserBrowserData,
79
- syncLocalCdpTabToCausyne
80
- } from './skybridgeBrowserBridge.js';
81
- import {
82
- CAUSYNE_BROWSER_MCP_NAME,
83
- handleBrowserMcpRpc,
84
- type JsonRpcMessage
85
- } from './skybridgeBrowserMcp.js';
86
- import type { McpServer } from '../acp/protocol.js';
18
+ SAFE_SESSION_ID_RE,
19
+ applySecurityHeaders,
20
+ isAllowedSkybridgeHost,
21
+ isAllowedSkybridgeOrigin,
22
+ sendJson,
23
+ timingSafeBearerMatch
24
+ } from './server/security.js';
25
+ import { serveStaticAsset } from './server/staticAssets.js';
87
26
  import {
88
- DAILY_LIMIT_SUPPORT_MESSAGE,
89
- EntitlementAccessError,
90
- EntitlementClient
91
- } from '../licensing/entitlements.js';
27
+ extractSessionFileEvidence,
28
+ extractSessionTouchedFiles,
29
+ normalizeWorkspaceRelCandidate
30
+ } from './server/sessionTranscript.js';
92
31
  import {
93
- LICENSE_ENFORCEMENT_ENABLED,
94
- isValidLicensePlan
95
- } from '../licensing/policy.js';
96
- import { renderSkybridgeHtml, getCausyneFaviconSvg } from './skybridgeUi.js';
97
-
98
- const MAX_JSON_BODY_BYTES = 1024 * 1024;
99
- const MAX_FILE_READ_BYTES = 512 * 1024;
100
- const MAX_FILE_WRITE_BYTES = 2 * 1024 * 1024;
101
- const MAX_ATTACHMENT_BYTES = 32 * 1024;
102
- const MAX_ATTACHMENTS = 6;
103
- const MAX_LIST_ENTRIES = 250;
104
- const SKIPPED_DIRS = new Set(['.git', 'node_modules', '.next', 'dist', 'build', '.venv']);
105
- const ALLOWED_REMOTE_ORIGINS = new Set(['https://causyne.com', 'https://www.causyne.com']);
106
- const SAFE_SESSION_ID_RE = /^s_[a-zA-Z0-9_-]{3,80}$/;
107
- const SAFE_PROVIDER_RE = /^[a-zA-Z0-9._/-]{1,64}$/;
108
- const SAFE_MODEL_RE = /^[a-zA-Z0-9._/:()+ -]{1,128}$/;
109
-
110
- const PROVIDER_KEY_FOR_CATALOG_LABEL: Record<string, string> = {
111
- 'DeepSeek': 'deepseek',
112
- 'Qwen': 'qwen',
113
- 'Anthropic': 'anthropic',
114
- 'OpenAI': 'openai',
115
- 'Gemini': 'gemini',
116
- 'Meta (Muse)': 'muse',
117
- 'Ollama (Local)': 'ollama',
118
- 'Alibaba (DashScope)': 'dashscope-byok',
119
- 'Moonshot (Kimi)': 'moonshot',
120
- 'xAI (Grok)': 'xai',
121
- 'Google Antigravity': 'antigravity',
122
- 'Pi (Local Peer)': 'pi',
123
- 'ACP (Peer Agents)': 'acp',
124
- 'OpenCode (ACP)': 'acp/opencode',
125
- 'Claude Code (ACP)': 'acp/claude',
126
- 'OpenRouter (Free)': 'openrouter',
127
- 'Groq (Free Tier)': 'groq',
128
- 'Cerebras (Free Tier)': 'cerebras',
129
- 'Mistral (Free Tier)': 'mistral'
32
+ attachRunStream,
33
+ createDefaultLoopFactory,
34
+ pushRunFrame
35
+ } from './server/activeRuns.js';
36
+ import { handleCoreRoutes } from './server/routesCore.js';
37
+ import { handleWorkspaceRoutes } from './server/routesWorkspace.js';
38
+ import { handleBrowserRoutes } from './server/routesBrowser.js';
39
+ import { handleTerminalRoutes } from './server/routesTerminal.js';
40
+ import { handleChatRoutes } from './server/routesChat.js';
41
+ import type {
42
+ BrowserAgentActivity,
43
+ SessionActiveRun,
44
+ SessionDisplayBlock,
45
+ SessionDisplayMessage,
46
+ SessionDisplayStep,
47
+ SessionFileEvidence,
48
+ SkybridgeContext,
49
+ SkybridgeDecisionAnswer,
50
+ SkybridgeEntitlementClientLike,
51
+ SkybridgeHandle,
52
+ SkybridgeLoopFactory,
53
+ SkybridgeLoopLike,
54
+ StartSkybridgeOptions
55
+ } from './server/types.js';
56
+
57
+ export type {
58
+ SessionDisplayBlock,
59
+ SessionDisplayMessage,
60
+ SessionDisplayStep,
61
+ SessionFileEvidence,
62
+ SkybridgeDecisionAnswer,
63
+ SkybridgeEntitlementClientLike,
64
+ SkybridgeHandle,
65
+ SkybridgeLoopFactory,
66
+ SkybridgeLoopLike,
67
+ StartSkybridgeOptions
130
68
  };
131
69
 
132
- export interface SkybridgeDecisionAnswer {
133
- optionId?: string | null | undefined;
134
- label: string;
135
- custom?: boolean | undefined;
136
- }
137
-
138
- export interface SkybridgeLoopLike {
139
- run(): Promise<void>;
140
- abort?(): void;
141
- resolveApproval?(toolCallId: string, approved: boolean): void;
142
- resolveDecision?(requestId: string, answer: SkybridgeDecisionAnswer | null): void;
143
- grantAlways?(toolName: string): void;
144
- }
145
-
146
- export type SkybridgeLoopFactory = (
147
- sink: { readyState: number; send(raw: string): void },
148
- taskId: string,
149
- prompt: string,
150
- options: {
151
- workspaceRoot: string;
152
- mode: string;
153
- sessionId?: string | undefined;
154
- provider?: string | undefined;
155
- model?: string | undefined;
156
- }
157
- ) => SkybridgeLoopLike;
158
-
159
- export interface SkybridgeEntitlementClientLike {
160
- status(): Promise<any>;
161
- checkout(plan: string): Promise<any>;
162
- recover(recoveryCode: string): Promise<any>;
163
- portal(): Promise<any>;
164
- }
165
-
166
- export interface StartSkybridgeOptions {
167
- workspaceRoot?: string | undefined;
168
- port?: number | undefined;
169
- token?: string | undefined;
170
- allowedOrigins?: readonly string[] | undefined;
171
- loopFactory?: SkybridgeLoopFactory | undefined;
172
- entitlementClient?: SkybridgeEntitlementClientLike | undefined;
173
- }
174
-
175
- export interface SkybridgeHandle {
176
- url: string;
177
- origin: string;
178
- port: number;
179
- token: string;
180
- workspaceRoot: string;
181
- close(): Promise<void>;
182
- }
183
-
184
- export function isAllowedSkybridgeHost(hostHeader: string | undefined, port: number): boolean {
185
- if (!hostHeader || typeof hostHeader !== 'string') return false;
186
- const normalized = hostHeader.trim().toLowerCase();
187
- return normalized === `127.0.0.1:${port}`
188
- || normalized === `localhost:${port}`
189
- || normalized === `[::1]:${port}`;
190
- }
191
-
192
- export function isAllowedSkybridgeOrigin(
193
- originHeader: string | undefined,
194
- port: number,
195
- extraOrigins: readonly string[] = []
196
- ): boolean {
197
- if (!originHeader || typeof originHeader !== 'string') return true;
198
- const trimmed = originHeader.trim();
199
- if (!trimmed || trimmed === 'null') return false;
200
- let parsed: URL;
201
- try {
202
- parsed = new URL(trimmed);
203
- } catch {
204
- return false;
205
- }
206
- const canonical = parsed.origin.toLowerCase();
207
- if (canonical === `http://127.0.0.1:${port}` || canonical === `http://localhost:${port}`) {
208
- return true;
209
- }
210
- if (ALLOWED_REMOTE_ORIGINS.has(canonical)) return true;
211
- for (const extra of extraOrigins) {
212
- try {
213
- const parsedExtra = new URL(extra);
214
- if (parsedExtra.protocol === 'https:' && parsedExtra.origin.toLowerCase() === canonical) {
215
- return true;
216
- }
217
- } catch {
218
- // ignore invalid extra origin
219
- }
220
- }
221
- return false;
222
- }
223
-
224
- function timingSafeBearerMatch(authHeader: string | undefined, expectedToken: string): boolean {
225
- if (!authHeader || typeof authHeader !== 'string') return false;
226
- const prefix = 'Bearer ';
227
- if (!authHeader.startsWith(prefix)) return false;
228
- const supplied = authHeader.slice(prefix.length).trim();
229
- const a = Buffer.from(supplied, 'utf8');
230
- const b = Buffer.from(expectedToken, 'utf8');
231
- if (a.length !== b.length || a.length === 0) return false;
232
- return crypto.timingSafeEqual(a, b);
233
- }
234
-
235
- function applySecurityHeaders(
236
- res: http.ServerResponse,
237
- originHeader: string | undefined,
238
- originAllowed: boolean
239
- ): void {
240
- res.setHeader('X-Content-Type-Options', 'nosniff');
241
- res.setHeader('X-Frame-Options', 'DENY');
242
- res.setHeader('Referrer-Policy', 'no-referrer');
243
- res.setHeader('Cache-Control', 'no-store');
244
- if (originHeader && originAllowed) {
245
- res.setHeader('Access-Control-Allow-Origin', originHeader);
246
- res.setHeader('Access-Control-Allow-Private-Network', 'true');
247
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS');
248
- res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type');
249
- res.setHeader('Vary', 'Origin, Access-Control-Request-Private-Network');
250
- }
251
- }
252
-
253
- function sendJson(res: http.ServerResponse, status: number, payload: unknown): void {
254
- const body = JSON.stringify(payload);
255
- res.statusCode = status;
256
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
257
- res.end(body);
258
- }
259
-
260
- async function readJsonBody(
261
- req: http.IncomingMessage,
262
- maxBytes = MAX_JSON_BODY_BYTES
263
- ): Promise<Record<string, any>> {
264
- const chunks: Buffer[] = [];
265
- let total = 0;
266
- for await (const chunk of req) {
267
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
268
- total += buf.length;
269
- if (total > maxBytes) {
270
- throw new Error('Request body exceeded maximum allowed size.');
271
- }
272
- chunks.push(buf);
273
- }
274
- const text = Buffer.concat(chunks).toString('utf8').trim();
275
- if (!text) return {};
276
- const parsed = JSON.parse(text);
277
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
278
- throw new Error('JSON request body must be an object.');
279
- }
280
- return parsed as Record<string, any>;
281
- }
282
-
283
- function resolveWorkspaceRelativePath(workspaceRoot: string, rawRel: string): string | null {
284
- if (typeof rawRel !== 'string' || rawRel.includes('\0')) return null;
285
- const cleaned = rawRel.trim();
286
- if (!cleaned) return null;
287
- if (path.isAbsolute(cleaned)) return null;
288
- const candidate = path.resolve(workspaceRoot, cleaned);
289
- if (!isPhysicalPathAllowed(candidate, [workspaceRoot], false)) return null;
290
- return candidate;
291
- }
292
-
293
- function listWorkspaceEntries(
294
- workspaceRoot: string,
295
- relDir: string,
296
- query = ''
297
- ): Array<{ path: string; name: string; type: 'dir' | 'file'; size: number }> {
298
- const targetDir = relDir ? resolveWorkspaceRelativePath(workspaceRoot, relDir) : workspaceRoot;
299
- if (!targetDir) throw new Error('Requested directory is outside the locked workspace.');
300
- const q = query.trim().toLowerCase();
301
- const entries: Array<{ path: string; name: string; type: 'dir' | 'file'; size: number }> = [];
302
-
303
- const scan = (dir: string, depth: number): void => {
304
- if (entries.length >= MAX_LIST_ENTRIES) return;
305
- let dirents: fs.Dirent[];
306
- try {
307
- dirents = fs.readdirSync(dir, { withFileTypes: true });
308
- } catch {
309
- return;
310
- }
311
- for (const d of dirents) {
312
- if (entries.length >= MAX_LIST_ENTRIES) break;
313
- if (d.isSymbolicLink()) continue;
314
- if (d.isDirectory() && SKIPPED_DIRS.has(d.name)) continue;
315
- const abs = path.join(dir, d.name);
316
- if (!isPhysicalPathAllowed(abs, [workspaceRoot], false)) continue;
317
- if (isIgnoredByCausyneIgnore(abs, workspaceRoot, d.isDirectory())) continue;
318
- const rel = path.relative(workspaceRoot, abs).split(path.sep).join('/');
319
- const isDir = d.isDirectory();
320
- let size = 0;
321
- if (!isDir) {
322
- try { size = fs.statSync(abs).size; } catch { size = 0; }
323
- }
324
- if (!q || rel.toLowerCase().includes(q)) {
325
- entries.push({ path: rel, name: d.name, type: isDir ? 'dir' : 'file', size });
326
- }
327
- if (q && isDir && depth < 3) {
328
- scan(abs, depth + 1);
329
- }
330
- }
331
- };
332
-
333
- scan(targetDir, 0);
334
- entries.sort((a, b) => (a.type === b.type ? a.path.localeCompare(b.path) : a.type === 'dir' ? -1 : 1));
335
- return entries;
336
- }
337
-
338
- const MUTATING_FILE_TOOLS = new Set([
339
- 'fs_write', 'fs_edit', 'multi_edit', 'apply_patch', 'fs_delete', 'fs_move',
340
- 'write_file', 'edit_file', 'write', 'edit', 'multiedit', 'replace_file_content',
341
- 'multi_replace_file_content', 'write_to_file', 'create_file', 'document_forge',
342
- 'ui_forge', 'screenshot', 'generate_media_via_api', 'code_verify_syntax'
343
- ]);
344
-
345
- const SHELL_TOOLS = new Set(['sysrun', 'bash', 'shell', 'run_command', 'execute_command']);
346
-
347
- export interface SessionFileEvidence {
348
- path: string;
349
- status: 'added' | 'modified' | 'deleted';
350
- bytesWritten?: number | undefined;
351
- additions: number;
352
- deletions: number;
353
- hunks: Array<{ header: string; lines: string[] }>;
354
- }
355
-
356
- function formatByteSize(bytes: number): string {
357
- if (!Number.isFinite(bytes) || bytes < 0) return '0 B';
358
- if (bytes < 1024) return `${Math.round(bytes)} B`;
359
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
360
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
361
- }
362
-
363
- function normalizeWorkspaceRelCandidate(
364
- workspaceRoot: string,
365
- raw: unknown,
366
- baseDir?: string
367
- ): string | null {
368
- if (typeof raw !== 'string') return null;
369
- let trimmed = raw.trim().replace(/^["'`]+|["'`]+$/g, '');
370
- if (!trimmed || trimmed.includes('\0') || trimmed.length > 500) return null;
371
- if (/^https?:\/\//i.test(trimmed)) return null;
372
- if (trimmed.toLowerCase().startsWith('file://')) {
373
- trimmed = trimmed.slice('file://'.length);
374
- const hashIdx = trimmed.indexOf('#');
375
- if (hashIdx >= 0) trimmed = trimmed.slice(0, hashIdx);
376
- const queryIdx = trimmed.indexOf('?');
377
- if (queryIdx >= 0) trimmed = trimmed.slice(0, queryIdx);
378
- try {
379
- trimmed = decodeURIComponent(trimmed);
380
- } catch {
381
- // Keep raw decoded string if percent encoding is malformed.
382
- }
383
- if (/^\/[A-Za-z]:[\\/]/.test(trimmed)) {
384
- trimmed = trimmed.slice(1);
385
- }
386
- } else {
387
- const lineAnchor = trimmed.match(/^(.+?\.[a-zA-Z0-9]{1,8})#L\d+(?:-L?\d+)?$/);
388
- if (lineAnchor?.[1]) trimmed = lineAnchor[1];
389
- }
390
- const escNl = trimmed.indexOf('\\n');
391
- if (escNl >= 0) trimmed = trimmed.slice(0, escNl);
392
- trimmed = trimmed.replace(/[),.;:]+$/g, '').trim();
393
- if (!trimmed || trimmed === '.' || trimmed === '/') return null;
394
- let rel = trimmed;
395
- if (path.isAbsolute(trimmed)) {
396
- const absNorm = path.resolve(trimmed);
397
- if (!isPhysicalPathAllowed(absNorm, [workspaceRoot], false)) return null;
398
- rel = path.relative(workspaceRoot, absNorm);
399
- } else if (baseDir && path.isAbsolute(baseDir)) {
400
- const absNorm = path.resolve(baseDir, trimmed);
401
- if (!isPhysicalPathAllowed(absNorm, [workspaceRoot], false)) return null;
402
- rel = path.relative(workspaceRoot, absNorm);
403
- }
404
- const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
405
- if (!abs) return null;
406
- const normalized = path.relative(workspaceRoot, abs).split(path.sep).join('/');
407
- return normalized && !normalized.startsWith('..') ? normalized : null;
408
- }
409
-
410
- function tokenizeSimpleShell(command: string): string[] {
411
- const tokens: string[] = [];
412
- let current = '';
413
- let quote: '"' | "'" | null = null;
414
- for (let i = 0; i < command.length; i += 1) {
415
- const ch = command[i]!;
416
- if (quote) {
417
- if (ch === quote) {
418
- quote = null;
419
- } else {
420
- current += ch;
421
- }
422
- continue;
423
- }
424
- if (ch === '"' || ch === "'") {
425
- quote = ch;
426
- continue;
427
- }
428
- if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
429
- if (current) {
430
- tokens.push(current);
431
- current = '';
432
- }
433
- continue;
434
- }
435
- if (ch === ';' || ch === '|') {
436
- if (current) {
437
- tokens.push(current);
438
- current = '';
439
- }
440
- tokens.push(ch);
441
- continue;
442
- }
443
- if (ch === '&' && command[i + 1] === '&') {
444
- if (current) {
445
- tokens.push(current);
446
- current = '';
447
- }
448
- tokens.push('&&');
449
- i += 1;
450
- continue;
451
- }
452
- current += ch;
453
- }
454
- if (current) tokens.push(current);
455
- return tokens;
456
- }
457
-
458
- function extractShellWriteTargets(command: string, workspaceRoot: string, cwdArg?: unknown): string[] {
459
- const found: string[] = [];
460
- let curDir = workspaceRoot;
461
- if (typeof cwdArg === 'string' && cwdArg.trim()) {
462
- const resolvedCwd = path.isAbsolute(cwdArg.trim())
463
- ? path.resolve(cwdArg.trim())
464
- : path.resolve(workspaceRoot, cwdArg.trim());
465
- if (isPhysicalPathAllowed(resolvedCwd, [workspaceRoot], false)) {
466
- curDir = resolvedCwd;
467
- }
468
- }
469
- const tokens = tokenizeSimpleShell(command);
470
- for (let i = 0; i < tokens.length; i += 1) {
471
- const tok = tokens[i]!;
472
- if (tok === 'cd' && tokens[i + 1]) {
473
- const nextDir = tokens[i + 1]!;
474
- const resolved = path.isAbsolute(nextDir)
475
- ? path.resolve(nextDir)
476
- : path.resolve(curDir, nextDir);
477
- if (isPhysicalPathAllowed(resolved, [workspaceRoot], false)) {
478
- curDir = resolved;
479
- }
480
- i += 1;
481
- continue;
482
- }
483
- if ((tok === '-o' || tok === '--output' || tok === '>' || tok === '>>' || tok === 'tee') && tokens[i + 1]) {
484
- const target = tokens[i + 1]!;
485
- if (target !== '/dev/null' && !target.startsWith('-')) {
486
- const norm = normalizeWorkspaceRelCandidate(workspaceRoot, target, curDir);
487
- if (norm) found.push(norm);
488
- }
489
- i += 1;
490
- continue;
491
- }
492
- if (tok === 'screencapture') {
493
- let j = i + 1;
494
- while (j < tokens.length && tokens[j] !== ';' && tokens[j] !== '&&' && tokens[j] !== '|') {
495
- const arg = tokens[j]!;
496
- if (!arg.startsWith('-')) {
497
- const norm = normalizeWorkspaceRelCandidate(workspaceRoot, arg, curDir);
498
- if (norm) found.push(norm);
499
- }
500
- j += 1;
501
- }
502
- i = j - 1;
503
- }
504
- }
505
- return found;
506
- }
507
-
508
- function extractPatchPathsFromText(patchText: string): string[] {
509
- const found: string[] = [];
510
- for (const line of patchText.split(/\r?\n/)) {
511
- const m = line.match(/^\*\*\*\s+(?:Add|Update|Delete)\s+File:\s+(.+)$/);
512
- if (m?.[1]) found.push(m[1].trim());
513
- const diffM = line.match(/^(?:\+\+\+|---)\s+[ab]\/(.+)$/);
514
- if (diffM?.[1]) found.push(diffM[1].trim());
515
- }
516
- return found;
517
- }
518
-
519
- function buildSynthesizedWriteHunk(content: string): { additions: number; hunks: Array<{ header: string; lines: string[] }> } {
520
- const lines = content.split(/\r?\n/);
521
- if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
522
- const capped = lines.slice(0, 140).map((ln) => `+${ln}`);
523
- if (lines.length > 140) capped.push(`+... (${lines.length - 140} more lines)`);
524
- return {
525
- additions: lines.length,
526
- hunks: capped.length > 0
527
- ? [{ header: `@@ -0,0 +1,${lines.length} @@`, lines: capped }]
528
- : []
529
- };
530
- }
531
-
532
- function buildSynthesizedEditHunk(oldStr: string, newStr: string): {
533
- additions: number;
534
- deletions: number;
535
- hunks: Array<{ header: string; lines: string[] }>;
536
- } {
537
- const oldLines = oldStr ? oldStr.split(/\r?\n/) : [];
538
- const newLines = newStr ? newStr.split(/\r?\n/) : [];
539
- const diffLines: string[] = [];
540
- for (const ln of oldLines.slice(0, 80)) diffLines.push(`-${ln}`);
541
- for (const ln of newLines.slice(0, 80)) diffLines.push(`+${ln}`);
542
- return {
543
- additions: newLines.length,
544
- deletions: oldLines.length,
545
- hunks: diffLines.length > 0
546
- ? [{ header: `@@ -1,${oldLines.length} +1,${newLines.length} @@`, lines: diffLines }]
547
- : []
548
- };
549
- }
550
-
551
- function hasFileExtension(relPath: string): boolean {
552
- const base = path.posix.basename(relPath);
553
- const dot = base.lastIndexOf('.');
554
- return dot > 0 && dot < base.length - 1 && base.length - dot <= 10;
555
- }
556
-
557
- export function extractSessionFileEvidence(
558
- messages: readonly SessionMessage[],
559
- workspaceRoot: string
560
- ): Map<string, SessionFileEvidence> {
561
- const evidenceMap = new Map<string, SessionFileEvidence>();
562
- const touchedDirs = new Set<string>();
563
-
564
- const recordFile = (
565
- raw: unknown,
566
- opts: {
567
- status?: 'added' | 'modified' | 'deleted' | undefined;
568
- bytesWritten?: number | undefined;
569
- additions?: number | undefined;
570
- deletions?: number | undefined;
571
- hunks?: Array<{ header: string; lines: string[] }> | undefined;
572
- baseDir?: string | undefined;
573
- } = {}
574
- ): void => {
575
- const norm = normalizeWorkspaceRelCandidate(workspaceRoot, raw, opts.baseDir);
576
- if (!norm) return;
577
- const dir = path.posix.dirname(norm);
578
- if (dir && dir !== '.') touchedDirs.add(dir);
579
- const existing = evidenceMap.get(norm);
580
- if (!existing) {
581
- evidenceMap.set(norm, {
582
- path: norm,
583
- status: opts.status ?? 'added',
584
- bytesWritten: opts.bytesWritten,
585
- additions: opts.additions ?? 0,
586
- deletions: opts.deletions ?? 0,
587
- hunks: opts.hunks ?? []
588
- });
589
- return;
590
- }
591
- if (opts.status === 'deleted') existing.status = 'deleted';
592
- else if (opts.status === 'modified' && existing.status !== 'added') existing.status = 'modified';
593
- if (typeof opts.bytesWritten === 'number' && opts.bytesWritten > 0) {
594
- existing.bytesWritten = opts.bytesWritten;
595
- }
596
- if (opts.hunks && opts.hunks.length > 0) {
597
- existing.hunks = opts.hunks;
598
- existing.additions = opts.additions ?? existing.additions;
599
- existing.deletions = opts.deletions ?? existing.deletions;
600
- }
601
- };
602
-
603
- const assistantBacktickCandidates: string[] = [];
604
-
605
- for (const msg of messages) {
606
- const rec = msg as Record<string, unknown>;
607
- const toolCalls = Array.isArray(rec.tool_calls)
608
- ? (rec.tool_calls as Array<Record<string, unknown>>)
609
- : [];
610
- for (const tc of toolCalls) {
611
- const fn = (tc.function && typeof tc.function === 'object' ? tc.function : tc) as Record<string, unknown>;
612
- const name = typeof fn.name === 'string' ? fn.name.trim().toLowerCase() : '';
613
- if (!name) continue;
614
- let args: Record<string, unknown> | null = null;
615
- if (typeof fn.arguments === 'string') {
616
- try {
617
- const parsed = JSON.parse(fn.arguments);
618
- if (parsed && typeof parsed === 'object') args = parsed as Record<string, unknown>;
619
- } catch {
620
- args = null;
621
- }
622
- } else if (fn.arguments && typeof fn.arguments === 'object') {
623
- args = fn.arguments as Record<string, unknown>;
624
- }
625
- if (!args) continue;
626
-
627
- if (MUTATING_FILE_TOOLS.has(name)) {
628
- const status: 'added' | 'modified' | 'deleted' = name === 'fs_delete'
629
- ? 'deleted'
630
- : name.includes('edit') || name.includes('patch') || name.includes('replace')
631
- ? 'modified'
632
- : 'added';
633
- const synthWrite = typeof args.content === 'string' && args.content.length > 0
634
- ? buildSynthesizedWriteHunk(args.content)
635
- : null;
636
- const synthEdit = (typeof args.old_string === 'string' || typeof args.new_string === 'string')
637
- && (Boolean(args.old_string) || Boolean(args.new_string))
638
- ? buildSynthesizedEditHunk(String(args.old_string || ''), String(args.new_string || ''))
639
- : null;
640
- const pathKeys = [
641
- 'path', 'filePath', 'file_path', 'targetFile', 'target_path',
642
- 'filename', 'file', 'destination', 'outputFile', 'output_path', 'outputPath'
643
- ];
644
- for (const key of pathKeys) {
645
- recordFile(args[key], {
646
- status,
647
- additions: synthWrite?.additions ?? synthEdit?.additions ?? 0,
648
- deletions: synthEdit?.deletions ?? 0,
649
- hunks: synthWrite?.hunks ?? synthEdit?.hunks ?? []
650
- });
651
- }
652
- if (typeof args.patch === 'string') {
653
- for (const p of extractPatchPathsFromText(args.patch)) {
654
- recordFile(p, { status: 'modified' });
655
- }
656
- }
657
- if (Array.isArray(args.edits)) {
658
- for (const ed of args.edits) {
659
- if (ed && typeof ed === 'object') {
660
- recordFile((ed as Record<string, unknown>).path, { status: 'modified' });
661
- }
662
- }
663
- }
664
- } else if (name === 'browser_act' && Array.isArray(args.actions)) {
665
- for (const a of args.actions) {
666
- if (a && typeof a === 'object') {
667
- const actObj = a as Record<string, unknown>;
668
- if (actObj.filePath) recordFile(actObj.filePath, { status: 'modified' });
669
- if (actObj.outputPath) recordFile(actObj.outputPath, { status: 'added' });
670
- }
671
- }
672
- } else if (SHELL_TOOLS.has(name) && typeof args.command === 'string') {
673
- for (const p of extractShellWriteTargets(args.command, workspaceRoot, args.cwd)) {
674
- recordFile(p, { status: 'added' });
675
- }
676
- }
677
- }
678
-
679
- const extActions = Array.isArray(rec.external_actions)
680
- ? (rec.external_actions as Array<Record<string, unknown>>)
681
- : [];
682
- for (const act of extActions) {
683
- const name = typeof act.name === 'string' ? act.name.trim().toLowerCase() : '';
684
- if (!name) continue;
685
- if (MUTATING_FILE_TOOLS.has(name)) {
686
- recordFile(act.detail, { status: name.includes('edit') ? 'modified' : 'added' });
687
- const params = act.parameters && typeof act.parameters === 'object'
688
- ? (act.parameters as Record<string, unknown>)
689
- : null;
690
- if (params) {
691
- for (const key of ['path', 'filePath', 'file_path', 'targetFile', 'filename', 'file', 'destination', 'outputPath']) {
692
- recordFile(params[key], { status: name.includes('edit') ? 'modified' : 'added' });
693
- }
694
- }
695
- } else if (SHELL_TOOLS.has(name) && typeof act.detail === 'string') {
696
- for (const p of extractShellWriteTargets(act.detail, workspaceRoot)) {
697
- recordFile(p, { status: 'added' });
698
- }
699
- }
700
- }
701
-
702
- const rawText = typeof msg.content === 'string' ? msg.content : '';
703
- if (msg.role === 'tool' && rawText) {
704
- let toolText = rawText;
705
- try {
706
- const parsed = JSON.parse(rawText) as Record<string, unknown>;
707
- if (parsed && typeof parsed === 'object' && typeof parsed.output === 'string') {
708
- toolText = parsed.output;
709
- }
710
- } catch {
711
- // Keep raw plain text tool output.
712
- }
713
- for (const m of toolText.matchAll(/Atomically wrote (\d+) bytes to ([^\r\n"'}]+)/g)) {
714
- recordFile(m[2], { status: 'added', bytesWritten: Number(m[1]) || undefined });
715
- }
716
- for (const m of toolText.matchAll(/Saved (\d+)-byte screenshot to ([^\r\n"'}]+)/g)) {
717
- recordFile(m[2], { status: 'added', bytesWritten: Number(m[1]) || undefined });
718
- }
719
- for (const m of toolText.matchAll(/(?:Successfully edited|Successfully wrote|Created file|Patched)\s+([^\r\n"'}]+)/g)) {
720
- recordFile(m[1], { status: 'modified' });
721
- }
722
- }
723
-
724
- if (msg.role === 'assistant' && rawText) {
725
- for (const m of rawText.matchAll(/file:\/\/[^\s)\]"'<>]+/g)) {
726
- recordFile(m[0], { status: 'added' });
727
- }
728
- for (const m of rawText.matchAll(/`([^`\r\n]{3,240})`/g)) {
729
- const candidate = m[1]!;
730
- if (candidate.includes('/') && hasFileExtension(candidate) && !candidate.includes(' ')) {
731
- assistantBacktickCandidates.push(candidate);
732
- }
733
- }
734
- }
735
- }
736
-
737
- for (const cand of assistantBacktickCandidates) {
738
- const norm = normalizeWorkspaceRelCandidate(workspaceRoot, cand);
739
- if (!norm || evidenceMap.has(norm)) continue;
740
- const dir = path.posix.dirname(norm);
741
- const abs = resolveWorkspaceRelativePath(workspaceRoot, norm);
742
- const inTouchedDir = Boolean(dir && dir !== '.' && touchedDirs.has(dir));
743
- const existsUntrackedDotAsset = Boolean(abs && norm.startsWith('.') && fs.existsSync(abs));
744
- if (inTouchedDir || existsUntrackedDotAsset) {
745
- recordFile(norm, { status: 'added' });
746
- }
747
- }
748
-
749
- // Drop bare parent directories when concrete child files in that directory are present.
750
- const allPaths = [...evidenceMap.keys()];
751
- for (const p of allPaths) {
752
- if (!hasFileExtension(p)) {
753
- const prefix = `${p}/`;
754
- if (allPaths.some((other) => other.startsWith(prefix))) {
755
- evidenceMap.delete(p);
756
- }
757
- }
758
- }
759
-
760
- return evidenceMap;
761
- }
762
-
763
- export function extractSessionTouchedFiles(
764
- messages: readonly SessionMessage[],
765
- workspaceRoot: string
766
- ): string[] {
767
- return [...extractSessionFileEvidence(messages, workspaceRoot).keys()].sort();
768
- }
769
-
770
- export interface SessionDisplayStep {
771
- tool: string;
772
- target: string;
773
- status: 'done' | 'failed';
774
- output?: string | undefined;
775
- }
776
-
777
- export type SessionDisplayBlock =
778
- | { kind: 'reasoning'; content: string }
779
- | { kind: 'steps'; steps: SessionDisplayStep[] }
780
- | { kind: 'text'; content: string };
781
-
782
- export interface SessionDisplayMessage {
783
- role: 'user' | 'assistant';
784
- content: string;
785
- reasoning?: string | undefined;
786
- steps?: SessionDisplayStep[] | undefined;
787
- blocks?: SessionDisplayBlock[] | undefined;
788
- }
789
-
790
- function summarizeArgsTarget(args: Record<string, unknown> | null): string {
791
- if (!args) return '';
792
- for (const key of ['path', 'filePath', 'file_path', 'file', 'command', 'query', 'url', 'skill_id']) {
793
- if (typeof args[key] === 'string' && String(args[key]).trim()) {
794
- return String(args[key]).trim().slice(0, 100);
795
- }
796
- }
797
- return '';
798
- }
799
-
800
- function extractSessionDisplayMessages(
801
- messages: readonly SessionMessage[]
802
- ): SessionDisplayMessage[] {
803
- const toolOutputsById = new Map<string, { output: string; failed: boolean }>();
804
- for (const msg of messages) {
805
- if (msg.role !== 'tool') continue;
806
- const rec = msg as Record<string, unknown>;
807
- const id = typeof rec.tool_call_id === 'string' ? rec.tool_call_id : '';
808
- if (!id) continue;
809
- const raw = typeof msg.content === 'string' ? msg.content : '';
810
- let failed = false;
811
- let summary = raw.trim().slice(0, 360);
812
- try {
813
- const parsed = JSON.parse(raw) as Record<string, unknown>;
814
- if (parsed && typeof parsed === 'object') {
815
- if (parsed.success === false || typeof parsed.error === 'string') failed = true;
816
- if (typeof parsed.error === 'string') summary = parsed.error.slice(0, 360);
817
- else if (typeof parsed.output === 'string') summary = parsed.output.slice(0, 360);
818
- }
819
- } catch {
820
- // plain text tool output
821
- }
822
- toolOutputsById.set(id, { output: summary, failed });
823
- }
824
-
825
- const out: SessionDisplayMessage[] = [];
826
- for (const msg of messages) {
827
- if (msg.role !== 'user' && msg.role !== 'assistant') continue;
828
- const rec = msg as Record<string, unknown>;
829
- let text = '';
830
- if (typeof msg.content === 'string') {
831
- text = msg.content;
832
- } else if (Array.isArray(msg.content)) {
833
- const parts: string[] = [];
834
- for (const block of msg.content) {
835
- if (block && typeof block === 'object' && typeof (block as any).text === 'string') {
836
- parts.push(String((block as any).text));
837
- }
838
- }
839
- text = parts.join('\n');
840
- }
841
- const trimmed = text.trim();
842
- if (msg.role === 'user') {
843
- if (!trimmed) continue;
844
- out.push({ role: 'user', content: trimmed });
845
- continue;
846
- }
847
-
848
- const steps: SessionDisplayStep[] = [];
849
- const extActions = Array.isArray(rec.external_actions)
850
- ? (rec.external_actions as Array<Record<string, unknown>>)
851
- : [];
852
- for (const act of extActions) {
853
- const rawName = typeof act.name === 'string' ? act.name.trim() : '';
854
- const rawDetail = typeof act.detail === 'string' ? act.detail.trim() : '';
855
- if (!rawName || rawName === 'true' || rawName === ':' || rawDetail === 'true' || rawDetail === ':') continue;
856
- steps.push({
857
- tool: rawName.replace(/^causyne[-_]browser[_:]/i, ''),
858
- target: rawDetail.slice(0, 100),
859
- status: act.status === 'failed' ? 'failed' : 'done'
860
- });
861
- }
862
- const toolCalls = Array.isArray(rec.tool_calls)
863
- ? (rec.tool_calls as Array<Record<string, unknown>>)
864
- : [];
865
- for (const tc of toolCalls) {
866
- const fn = (tc.function && typeof tc.function === 'object' ? tc.function : tc) as Record<string, unknown>;
867
- const name = typeof fn.name === 'string' ? fn.name.trim() : '';
868
- if (!name || name === 'true' || name === ':') continue;
869
- let args: Record<string, unknown> | null = null;
870
- if (typeof fn.arguments === 'string') {
871
- try {
872
- const parsed = JSON.parse(fn.arguments);
873
- if (parsed && typeof parsed === 'object') args = parsed as Record<string, unknown>;
874
- } catch {
875
- args = null;
876
- }
877
- } else if (fn.arguments && typeof fn.arguments === 'object') {
878
- args = fn.arguments as Record<string, unknown>;
879
- }
880
- const tcId = typeof tc.id === 'string' ? tc.id : '';
881
- const matchedOut = tcId ? toolOutputsById.get(tcId) : undefined;
882
- steps.push({
883
- tool: name,
884
- target: summarizeArgsTarget(args),
885
- status: matchedOut?.failed ? 'failed' : 'done',
886
- ...(matchedOut?.output ? { output: matchedOut.output } : {})
887
- });
888
- }
889
- const rawReasoning = typeof rec.reasoning_content === 'string' ? rec.reasoning_content.trim() : '';
890
- const reasoning = rawReasoning ? rawReasoning.slice(0, 8000) : undefined;
891
-
892
- if (!trimmed && steps.length === 0 && !reasoning) continue;
893
- const msgBlocks: SessionDisplayBlock[] = [];
894
- if (reasoning) msgBlocks.push({ kind: 'reasoning', content: reasoning });
895
- if (steps.length > 0) msgBlocks.push({ kind: 'steps', steps });
896
- if (trimmed) msgBlocks.push({ kind: 'text', content: trimmed });
897
-
898
- // Merge consecutive assistant messages between user turns into one cohesive Claude-style turn
899
- // while preserving exact chronological interleaved blocks (reasoning -> steps -> text -> steps -> text).
900
- const prev = out.length > 0 ? out[out.length - 1] : null;
901
- if (prev && prev.role === 'assistant') {
902
- const prevBlocks = prev.blocks ? [...prev.blocks] : [];
903
- for (const blk of msgBlocks) {
904
- const lastBlk = prevBlocks.length > 0 ? prevBlocks[prevBlocks.length - 1] : null;
905
- if (blk.kind === 'steps' && lastBlk && lastBlk.kind === 'steps') {
906
- lastBlk.steps = [...lastBlk.steps, ...blk.steps];
907
- } else if (blk.kind === 'reasoning' && lastBlk && lastBlk.kind === 'reasoning') {
908
- lastBlk.content = `${lastBlk.content}\n\n${blk.content}`.slice(0, 8000);
909
- } else {
910
- prevBlocks.push(blk);
911
- }
912
- }
913
- prev.blocks = prevBlocks;
914
- if (steps.length > 0) prev.steps = [...(prev.steps || []), ...steps];
915
- if (reasoning) prev.reasoning = prev.reasoning ? `${prev.reasoning}\n\n${reasoning}`.slice(0, 8000) : reasoning;
916
- if (trimmed) prev.content = prev.content ? `${prev.content}\n\n${trimmed}` : trimmed;
917
- continue;
918
- }
919
- out.push({
920
- role: 'assistant',
921
- content: trimmed,
922
- ...(reasoning ? { reasoning } : {}),
923
- ...(steps.length > 0 ? { steps } : {}),
924
- blocks: msgBlocks
925
- });
926
- }
927
- return out;
928
- }
929
-
930
- function buildWorkspacePromptWithAttachments(
931
- workspaceRoot: string,
932
- prompt: string,
933
- rawAttachments: unknown
934
- ): { effectivePrompt: string; attachedPaths: string[] } {
935
- if (!Array.isArray(rawAttachments) || rawAttachments.length === 0) {
936
- return { effectivePrompt: prompt, attachedPaths: [] };
937
- }
938
- const attachedPaths: string[] = [];
939
- const sections: string[] = [];
940
- for (const raw of rawAttachments.slice(0, MAX_ATTACHMENTS)) {
941
- if (typeof raw !== 'string') continue;
942
- const abs = resolveWorkspaceRelativePath(workspaceRoot, raw);
943
- if (!abs) continue;
944
- if (isIgnoredByCausyneIgnore(abs, workspaceRoot, false)) continue;
945
- try {
946
- const stat = fs.lstatSync(abs);
947
- if (stat.isSymbolicLink() || !stat.isFile()) continue;
948
- const buf = fs.readFileSync(abs);
949
- if (buf.includes(0)) continue;
950
- const sliced = buf.length > MAX_ATTACHMENT_BYTES ? buf.subarray(0, MAX_ATTACHMENT_BYTES) : buf;
951
- const rel = path.relative(workspaceRoot, abs).split(path.sep).join('/');
952
- const truncatedNote = buf.length > MAX_ATTACHMENT_BYTES ? '\n[truncated]' : '';
953
- attachedPaths.push(rel);
954
- sections.push(`--- Attached workspace file: ${rel} ---\n${sliced.toString('utf8')}${truncatedNote}`);
955
- } catch {
956
- // skip unreadable attachment
957
- }
958
- }
959
- if (sections.length === 0) {
960
- return { effectivePrompt: prompt, attachedPaths: [] };
961
- }
962
- return {
963
- effectivePrompt: `${sections.join('\n\n')}\n\n${prompt}`,
964
- attachedPaths
965
- };
966
- }
967
-
968
- function workspaceMatchesSession(sessionWorkspace: string, workspaceRoot: string): boolean {
969
- if (!sessionWorkspace) return false;
970
- const resolvedSession = physicalPath(sessionWorkspace);
971
- return resolvedSession === workspaceRoot || sessionWorkspace === workspaceRoot;
972
- }
973
-
974
- function parseSessionIdRoute(pathname: string): string | null {
975
- const prefix = '/api/sessions/';
976
- if (!pathname.startsWith(prefix)) return null;
977
- const raw = pathname.slice(prefix.length);
978
- if (!raw || raw.includes('/')) return null;
979
- let decoded = '';
980
- try {
981
- decoded = decodeURIComponent(raw);
982
- } catch {
983
- return null;
984
- }
985
- return SAFE_SESSION_ID_RE.test(decoded) ? decoded : null;
986
- }
987
-
988
- function parseSessionStreamRoute(pathname: string): string | null {
989
- const prefix = '/api/sessions/';
990
- const suffix = '/stream';
991
- if (!pathname.startsWith(prefix) || !pathname.endsWith(suffix)) return null;
992
- const raw = pathname.slice(prefix.length, pathname.length - suffix.length);
993
- if (!raw || raw.includes('/')) return null;
994
- let decoded = '';
995
- try {
996
- decoded = decodeURIComponent(raw);
997
- } catch {
998
- return null;
999
- }
1000
- return SAFE_SESSION_ID_RE.test(decoded) ? decoded : null;
1001
- }
1002
-
1003
- interface SessionActiveRun {
1004
- key: string;
1005
- sessionId: string | null;
1006
- taskId: string;
1007
- prompt: string;
1008
- startedAt: number;
1009
- status: 'running' | 'awaiting_client' | 'completed' | 'stopped' | 'errored';
1010
- userStopped: boolean;
1011
- loop: SkybridgeLoopLike;
1012
- frames: string[];
1013
- bufferedBytes: number;
1014
- subscribers: Set<(frame: string) => void>;
1015
- doneSubscribers: Set<() => void>;
1016
- }
1017
-
1018
- const MAX_RUN_BUFFERED_FRAMES = 2400;
1019
- const MAX_RUN_BUFFERED_BYTES = 2 * 1024 * 1024;
1020
- const STREAM_HEARTBEAT_MS = 15_000;
1021
-
1022
- function readLastGitCommitDiffForFile(
1023
- workspaceRoot: string,
1024
- relPath: string
1025
- ): { additions: number; deletions: number; hunks: Array<{ header: string; lines: string[] }> } | null {
1026
- if (!relPath || relPath.startsWith('-') || relPath.includes('\0')) return null;
1027
- try {
1028
- const raw = execFileSync(
1029
- 'git',
1030
- ['log', '-n', '1', '--format=', '--unified=3', '--no-color', '-p', '--', relPath],
1031
- {
1032
- cwd: workspaceRoot,
1033
- encoding: 'utf8',
1034
- stdio: ['ignore', 'pipe', 'ignore'],
1035
- maxBuffer: 256 * 1024,
1036
- timeout: 3000,
1037
- windowsHide: true
1038
- }
1039
- );
1040
- if (!raw || !raw.trim()) return null;
1041
- const parsed = parseUnifiedDiff(raw);
1042
- const first = parsed[0];
1043
- if (!first || first.hunks.length === 0) return null;
1044
- return {
1045
- additions: first.additions,
1046
- deletions: first.deletions,
1047
- hunks: first.hunks.slice(0, 12).map((h) => ({
1048
- header: h.header,
1049
- lines: h.lines.slice(0, 140)
1050
- }))
1051
- };
1052
- } catch {
1053
- return null;
1054
- }
1055
- }
70
+ export {
71
+ extractSessionFileEvidence,
72
+ extractSessionTouchedFiles,
73
+ isAllowedSkybridgeHost,
74
+ isAllowedSkybridgeOrigin
75
+ };
1056
76
 
1057
77
  export async function startSkybridgeServer(options: StartSkybridgeOptions = {}): Promise<SkybridgeHandle> {
1058
78
  const rawRoot = options.workspaceRoot || process.cwd();
@@ -1072,189 +92,62 @@ export async function startSkybridgeServer(options: StartSkybridgeOptions = {}):
1072
92
  const version = getPackageVersion();
1073
93
  const hasCustomFactory = typeof options.loopFactory === 'function';
1074
94
  let boundPort = requestedPort;
1075
- const serverApprovalScope = createApprovalScope();
1076
- const buildSharedBrowserPeerMcp = (): McpServer[] => {
1077
- if (!boundPort) return [];
1078
- return [{
1079
- type: 'http',
1080
- name: CAUSYNE_BROWSER_MCP_NAME,
1081
- url: `http://127.0.0.1:${boundPort}/api/mcp/browser`,
1082
- headers: [{ name: 'Authorization', value: `Bearer ${token}` }]
1083
- }];
1084
- };
1085
- const loopFactory: SkybridgeLoopFactory = options.loopFactory ?? ((sink, taskId, prompt, opts) => {
1086
- const loopOptions: {
1087
- workspaceRoot: string;
1088
- memorySessionId?: string | null;
1089
- provider?: string;
1090
- model?: string;
1091
- approvalScope?: ReturnType<typeof createApprovalScope>;
1092
- peerMcpServers?: McpServer[];
1093
- } = {
1094
- workspaceRoot: opts.workspaceRoot,
1095
- approvalScope: serverApprovalScope,
1096
- peerMcpServers: buildSharedBrowserPeerMcp()
1097
- };
1098
- if (opts.sessionId) loopOptions.memorySessionId = opts.sessionId;
1099
- if (opts.provider) loopOptions.provider = opts.provider;
1100
- if (opts.model) loopOptions.model = opts.model;
1101
- const loop = new AgentLoop(sink, taskId, prompt, loopOptions);
1102
- if (opts.mode === 'A' || opts.mode === 'B' || opts.mode === 'C') {
1103
- try {
1104
- loop.setAutonomyMode(opts.mode);
1105
- } catch {
1106
- // Fallback when custom mode normalization differs.
1107
- }
1108
- if (loop.sandbox) {
1109
- loop.sandbox.autonomyMode = opts.mode;
1110
- }
1111
- }
1112
- const pendingDecisions = new Map<string, (answer: SkybridgeDecisionAnswer | null) => void>();
1113
- loop.waitForDecision = (request: any) => {
1114
- const reqId = typeof request?.id === 'string' && request.id ? request.id : `dec_${Date.now()}`;
1115
- return new Promise<SkybridgeDecisionAnswer | null>((resolve) => {
1116
- pendingDecisions.set(reqId, resolve);
1117
- });
1118
- };
1119
- return {
1120
- run: () => loop.run(),
1121
- abort: () => {
1122
- for (const [, resolve] of pendingDecisions) {
1123
- try { resolve(null); } catch { /* ignore */ }
1124
- }
1125
- pendingDecisions.clear();
1126
- loop.abort();
1127
- },
1128
- resolveApproval: (toolCallId: string, approved: boolean) => {
1129
- const resolver = loop.pendingApprovals.get(toolCallId);
1130
- if (resolver) resolver(approved);
1131
- },
1132
- resolveDecision: (requestId: string, answer: SkybridgeDecisionAnswer | null) => {
1133
- const resolver = pendingDecisions.get(requestId);
1134
- if (resolver) {
1135
- pendingDecisions.delete(requestId);
1136
- resolver(answer);
1137
- }
1138
- },
1139
- grantAlways: (toolName: string) => {
1140
- serverApprovalScope.grantAlways(toolName);
1141
- }
1142
- };
1143
- });
1144
-
1145
- const activeRuns = new Map<string, SessionActiveRun>();
1146
95
  let taskCounter = 0;
1147
96
 
1148
- const findActiveRun = (sessionId?: string | null): SessionActiveRun | null => {
1149
- if (sessionId && activeRuns.has(sessionId)) {
1150
- return activeRuns.get(sessionId) ?? null;
1151
- }
1152
- if (!sessionId && activeRuns.size === 1) {
1153
- return activeRuns.values().next().value ?? null;
1154
- }
1155
- return null;
1156
- };
1157
-
1158
- const pushRunFrame = (run: SessionActiveRun, raw: string): void => {
1159
- const clean = raw.replace(/\r?\n/g, ' ');
1160
- const frameBytes = Buffer.byteLength(clean, 'utf8');
1161
- if (run.frames.length < MAX_RUN_BUFFERED_FRAMES && run.bufferedBytes + frameBytes <= MAX_RUN_BUFFERED_BYTES) {
1162
- run.frames.push(clean);
1163
- run.bufferedBytes += frameBytes;
1164
- }
1165
- for (const send of run.subscribers) {
1166
- try {
1167
- send(clean);
1168
- } catch {
1169
- // Isolate subscriber write failures so detached runs continue uninterrupted.
1170
- }
1171
- }
1172
- };
1173
-
1174
- const attachRunStream = (
1175
- req: http.IncomingMessage,
1176
- res: http.ServerResponse,
1177
- run: SessionActiveRun,
1178
- replayBuffered: boolean
1179
- ): void => {
1180
- req.setTimeout(0);
1181
- res.setTimeout(0);
1182
- try { req.socket?.setKeepAlive(true, STREAM_HEARTBEAT_MS); } catch { /* ignore */ }
1183
- res.statusCode = 200;
1184
- res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
1185
- res.setHeader('Transfer-Encoding', 'chunked');
1186
- res.setHeader('Cache-Control', 'no-store');
1187
- res.setHeader('X-Accel-Buffering', 'no');
1188
- res.flushHeaders?.();
1189
-
1190
- const writeLine = (cleanFrame: string): void => {
1191
- if (res.writableEnded || res.destroyed) return;
1192
- res.write(`${cleanFrame}\n`);
1193
- };
1194
-
1195
- const heartbeatTimer = setInterval(() => {
1196
- if (res.writableEnded || res.destroyed) return;
1197
- writeLine(JSON.stringify({ type: 'heartbeat', ts: Date.now() }));
1198
- }, STREAM_HEARTBEAT_MS);
1199
- heartbeatTimer.unref?.();
1200
-
1201
- let detached = false;
1202
- const detach = (): void => {
1203
- if (detached) return;
1204
- detached = true;
1205
- clearInterval(heartbeatTimer);
1206
- run.subscribers.delete(writeLine);
1207
- run.doneSubscribers.delete(finishResponse);
1208
- };
1209
-
1210
- const finishResponse = (): void => {
1211
- detach();
1212
- if (!res.writableEnded && !res.destroyed) res.end();
1213
- };
1214
-
1215
- // Disconnecting a browser tab or switching chats ONLY unsubscribes this HTTP response.
1216
- // It NEVER aborts the detached AgentLoop; only explicit POST /api/stop cancels it.
1217
- res.on('close', detach);
1218
-
1219
- if (replayBuffered) {
1220
- for (const frame of run.frames) {
1221
- writeLine(frame);
1222
- }
1223
- }
97
+ const serverApprovalScope = createApprovalScope();
98
+ const loopFactory: SkybridgeLoopFactory = options.loopFactory
99
+ ?? createDefaultLoopFactory(serverApprovalScope, () => boundPort, token);
1224
100
 
1225
- if (run.status === 'running' || run.status === 'awaiting_client') {
1226
- run.subscribers.add(writeLine);
1227
- run.doneSubscribers.add(finishResponse);
1228
- } else {
1229
- finishResponse();
1230
- }
1231
- };
101
+ const activeRuns = new Map<string, SessionActiveRun>();
1232
102
  const sessionTouchedFilesMap = new Map<string, Set<string>>();
1233
- const recordSessionTouchedFile = (sessionId: string | null | undefined, rawPath: unknown): void => {
1234
- if (!sessionId || !SAFE_SESSION_ID_RE.test(sessionId)) return;
1235
- const norm = normalizeWorkspaceRelCandidate(workspaceRoot, rawPath);
1236
- if (!norm) return;
1237
- let set = sessionTouchedFilesMap.get(sessionId);
1238
- if (!set) {
1239
- set = new Set<string>();
1240
- sessionTouchedFilesMap.set(sessionId, set);
1241
- }
1242
- set.add(norm);
1243
- };
103
+ const browserStreamClients = new Set<(payload: Record<string, unknown>) => void>();
104
+
1244
105
  let browserControlOwner: 'human' | 'agent' = 'human';
1245
- let browserAgentActivity: { active: boolean; tool: string; detail: string; updatedAt: number } = {
106
+ let browserAgentActivity: BrowserAgentActivity = {
1246
107
  active: false,
1247
108
  tool: '',
1248
109
  detail: '',
1249
110
  updatedAt: 0
1250
111
  };
1251
- const browserStreamClients = new Set<(payload: Record<string, unknown>) => void>();
1252
- const broadcastBrowserNotice = (payload: Record<string, unknown>): void => {
1253
- for (const send of browserStreamClients) {
1254
- try {
1255
- send(payload);
1256
- } catch {
1257
- // Isolate individual stream clients.
112
+
113
+ const ctx: SkybridgeContext = {
114
+ workspaceRoot,
115
+ version,
116
+ token,
117
+ hasCustomFactory,
118
+ entitlementClient: options.entitlementClient,
119
+ loopFactory,
120
+ serverApprovalScope,
121
+ activeRuns,
122
+ sessionTouchedFilesMap,
123
+ browserStreamClients,
124
+ getBoundPort: () => boundPort,
125
+ nextTaskId: () => `web-${++taskCounter}-${Date.now()}`,
126
+ findActiveRun: (sessionId?: string | null) => {
127
+ if (sessionId && activeRuns.has(sessionId)) return activeRuns.get(sessionId) ?? null;
128
+ if (!sessionId && activeRuns.size === 1) return activeRuns.values().next().value ?? null;
129
+ return null;
130
+ },
131
+ pushRunFrame,
132
+ attachRunStream,
133
+ recordSessionTouchedFile: (sessionId: string | null | undefined, rawPath: unknown) => {
134
+ if (!sessionId || !SAFE_SESSION_ID_RE.test(sessionId)) return;
135
+ const norm = normalizeWorkspaceRelCandidate(workspaceRoot, rawPath);
136
+ if (!norm) return;
137
+ let set = sessionTouchedFilesMap.get(sessionId);
138
+ if (!set) {
139
+ set = new Set<string>();
140
+ sessionTouchedFilesMap.set(sessionId, set);
141
+ }
142
+ set.add(norm);
143
+ },
144
+ getBrowserControlOwner: () => browserControlOwner,
145
+ setBrowserControlOwner: (owner) => { browserControlOwner = owner; },
146
+ getBrowserAgentActivity: () => browserAgentActivity,
147
+ setBrowserAgentActivity: (activity) => { browserAgentActivity = activity; },
148
+ broadcastBrowserNotice: (payload) => {
149
+ for (const send of browserStreamClients) {
150
+ try { send(payload); } catch { /* isolate client write errors */ }
1258
151
  }
1259
152
  }
1260
153
  };
@@ -1300,6 +193,12 @@ export async function startSkybridgeServer(options: StartSkybridgeOptions = {}):
1300
193
  return;
1301
194
  }
1302
195
 
196
+ if (req.method === 'GET' && pathname.startsWith('/assets/')) {
197
+ if (serveStaticAsset(pathname, res)) return;
198
+ sendJson(res, 404, { error: 'Static asset not found.' });
199
+ return;
200
+ }
201
+
1303
202
  if (req.method === 'GET' && pathname === '/') {
1304
203
  const cspNonce = crypto.randomBytes(16).toString('base64url');
1305
204
  res.statusCode = 200;
@@ -1330,1392 +229,11 @@ export async function startSkybridgeServer(options: StartSkybridgeOptions = {}):
1330
229
  }
1331
230
 
1332
231
  try {
1333
- if (req.method === 'GET' && pathname === '/api/health') {
1334
- const config = loadConfig();
1335
- const zeroCost = await detectZeroCostProviders({ config, probeOllama: false });
1336
- const readyZeroCost = zeroCost.filter((z) => z.readiness === 'ready');
1337
- sendJson(res, 200, {
1338
- ok: true,
1339
- version,
1340
- workspaceRoot,
1341
- workspaceName: path.basename(workspaceRoot),
1342
- provider: config.provider || 'unconfigured',
1343
- model: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default',
1344
- zeroCostReadyCount: readyZeroCost.length,
1345
- zeroCostRoutes: readyZeroCost.map((z) => ({
1346
- id: z.id,
1347
- provider: z.provider,
1348
- model: z.model,
1349
- label: z.label,
1350
- costTier: z.costTier
1351
- })),
1352
- busy: activeRuns.size > 0
1353
- });
1354
- return;
1355
- }
1356
-
1357
- if (req.method === 'GET' && pathname === '/api/models') {
1358
- const config = loadConfig();
1359
- const forceRefresh = parsedUrl.searchParams.get('refresh') === '1';
1360
- const allowLive = forceRefresh || parsedUrl.searchParams.get('live') === '1';
1361
- const overview = allowLive
1362
- ? await resolveAvailableProvidersOverview(config, { forceRefresh })
1363
- : getAvailableProvidersOverview(config);
1364
- const activeProviderRaw = String(config.provider || '').toLowerCase().trim();
1365
- const initialTab: 'acp' | 'byok' | 'free' = activeProviderRaw === 'openrouter'
1366
- ? 'free'
1367
- : (activeProviderRaw === 'antigravity'
1368
- || activeProviderRaw === 'agy'
1369
- || activeProviderRaw === 'pi'
1370
- || activeProviderRaw === 'acp'
1371
- || activeProviderRaw.startsWith('acp/')
1372
- ? 'acp'
1373
- : 'byok');
1374
- const tabs = {
1375
- acp: buildModelPickerItems(config, overview, { tab: 'acp', maxAcpPerPeer: Infinity }),
1376
- byok: buildModelPickerItems(config, overview, { tab: 'byok', maxAcpPerPeer: Infinity }),
1377
- free: buildModelPickerItems(config, overview, { tab: 'free', maxAcpPerPeer: Infinity })
1378
- };
1379
- const zeroCost = await detectZeroCostProviders({ config, probeOllama: false });
1380
- const readySet = new Set(zeroCost.filter((z) => z.readiness === 'ready').map((z) => z.provider));
1381
- const groups = Object.entries(MODEL_CATALOGUE).map(([label, models]) => {
1382
- const providerId = PROVIDER_KEY_FOR_CATALOG_LABEL[label] || label.toLowerCase();
1383
- const hasKey = Boolean(resolveProviderApiKey(config, providerId));
1384
- const isZeroCostReady = readySet.has(providerId);
1385
- return {
1386
- label,
1387
- provider: providerId,
1388
- configured: hasKey || isZeroCostReady,
1389
- zeroCostReady: isZeroCostReady,
1390
- defaultModel: DEFAULT_MODEL_BY_PROVIDER[providerId] || models[0] || '',
1391
- models
1392
- };
1393
- });
1394
- sendJson(res, 200, {
1395
- ok: true,
1396
- activeProvider: config.provider || 'unconfigured',
1397
- activeModel: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || '',
1398
- initialTab,
1399
- tabs,
1400
- overview,
1401
- zeroCost: zeroCost.map((z) => ({
1402
- id: z.id,
1403
- provider: z.provider,
1404
- model: z.model,
1405
- label: z.label,
1406
- costTier: z.costTier,
1407
- readiness: z.readiness
1408
- })),
1409
- groups
1410
- });
1411
- return;
1412
- }
1413
-
1414
- if (req.method === 'POST' && pathname === '/api/model') {
1415
- const body = await readJsonBody(req);
1416
- const action = typeof body.action === 'string' ? body.action.trim() : '';
1417
- const provider = typeof body.provider === 'string' ? body.provider.trim() : '';
1418
- const model = typeof body.model === 'string' ? body.model.trim() : '';
1419
- if (action === 'disconnect' && provider === 'openrouter') {
1420
- disconnectOpenRouter();
1421
- const updated = loadConfig();
1422
- auditLog.log({ event: 'skybridge_openrouter_disconnect' });
1423
- sendJson(res, 200, {
1424
- ok: true,
1425
- disconnected: true,
1426
- provider: updated.provider || 'unconfigured',
1427
- model: updated.model || DEFAULT_MODEL_BY_PROVIDER[String(updated.provider || '')] || 'default'
1428
- });
1429
- return;
1430
- }
1431
- if (!provider || !SAFE_PROVIDER_RE.test(provider)) {
1432
- sendJson(res, 400, { error: 'Valid provider identifier is required.' });
1433
- return;
1434
- }
1435
- if (model && !SAFE_MODEL_RE.test(model)) {
1436
- sendJson(res, 400, { error: 'Invalid model identifier.' });
1437
- return;
1438
- }
1439
- const config = loadConfig();
1440
- const resolvedModel = model || DEFAULT_MODEL_BY_PROVIDER[provider] || '';
1441
- applyProviderOverrides(config, provider, resolvedModel);
1442
- saveConfig(config);
1443
- auditLog.log({
1444
- event: 'skybridge_model_switch',
1445
- provider: config.provider,
1446
- model: config.model
1447
- });
1448
- sendJson(res, 200, {
1449
- ok: true,
1450
- provider: config.provider,
1451
- model: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default'
1452
- });
1453
- return;
1454
- }
1455
-
1456
- if (req.method === 'GET' && pathname === '/api/sessions') {
1457
- const all = listSessions();
1458
- const scoped = all.filter((row) => workspaceMatchesSession(row.workspace, workspaceRoot));
1459
- sendJson(res, 200, {
1460
- ok: true,
1461
- sessions: scoped.slice(0, 50).map((row) => {
1462
- const run = activeRuns.get(row.id);
1463
- const isRunning = Boolean(run && (run.status === 'running' || run.status === 'awaiting_client'));
1464
- return {
1465
- id: row.id,
1466
- title: row.title,
1467
- createdAt: row.createdAt,
1468
- updatedAt: row.updatedAt,
1469
- messageCount: row.messageCount,
1470
- running: isRunning,
1471
- awaitingClient: Boolean(run && run.status === 'awaiting_client')
1472
- };
1473
- })
1474
- });
1475
- return;
1476
- }
1477
-
1478
- const sessionStreamId = parseSessionStreamRoute(pathname);
1479
- if (req.method === 'GET' && sessionStreamId) {
1480
- const run = activeRuns.get(sessionStreamId);
1481
- if (!run || (run.status !== 'running' && run.status !== 'awaiting_client')) {
1482
- res.statusCode = 200;
1483
- res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
1484
- res.setHeader('Cache-Control', 'no-store');
1485
- res.end(`${JSON.stringify({ type: 'idle', sessionId: sessionStreamId })}\n`);
1486
- return;
1487
- }
1488
- attachRunStream(req, res, run, true);
1489
- return;
1490
- }
1491
-
1492
- if (req.method === 'POST' && pathname === '/api/sessions') {
1493
- const body = await readJsonBody(req);
1494
- const rawTitle = typeof body.title === 'string' ? body.title.trim().slice(0, 80) : '';
1495
- const created = createSession(workspaceRoot, rawTitle || 'Untitled', false);
1496
- sendJson(res, 201, {
1497
- ok: true,
1498
- session: {
1499
- id: created.id,
1500
- title: created.title,
1501
- createdAt: created.createdAt,
1502
- updatedAt: created.updatedAt,
1503
- messageCount: 0,
1504
- messages: []
1505
- }
1506
- });
1507
- return;
1508
- }
1509
-
1510
- const sessionIdParam = parseSessionIdRoute(pathname);
1511
- if (sessionIdParam) {
1512
- const existing = getSession(sessionIdParam);
1513
- if (!existing || !workspaceMatchesSession(existing.workspace, workspaceRoot)) {
1514
- sendJson(res, 404, { error: 'Session not found in this workspace.' });
1515
- return;
1516
- }
1517
- if (req.method === 'GET') {
1518
- const persistedTouched = extractSessionTouchedFiles(existing.messages, workspaceRoot);
1519
- const liveTouched = [...(sessionTouchedFilesMap.get(existing.id) ?? [])];
1520
- const touchedFiles = [...new Set([...persistedTouched, ...liveTouched])].sort();
1521
- const activeRun = activeRuns.get(existing.id);
1522
- const isRunning = Boolean(activeRun && (activeRun.status === 'running' || activeRun.status === 'awaiting_client'));
1523
- sendJson(res, 200, {
1524
- ok: true,
1525
- session: {
1526
- id: existing.id,
1527
- title: existing.title,
1528
- createdAt: existing.createdAt,
1529
- updatedAt: existing.updatedAt,
1530
- messageCount: existing.messages.length,
1531
- messages: extractSessionDisplayMessages(existing.messages),
1532
- touchedFiles,
1533
- running: isRunning,
1534
- awaitingClient: Boolean(activeRun && activeRun.status === 'awaiting_client'),
1535
- activeRun: isRunning && activeRun ? {
1536
- taskId: activeRun.taskId,
1537
- status: activeRun.status,
1538
- prompt: activeRun.prompt,
1539
- startedAt: activeRun.startedAt
1540
- } : null
1541
- }
1542
- });
1543
- return;
1544
- }
1545
- if (req.method === 'PATCH') {
1546
- const body = await readJsonBody(req);
1547
- const nextTitle = typeof body.title === 'string' ? body.title.trim().slice(0, 80) : '';
1548
- if (!nextTitle) {
1549
- sendJson(res, 400, { error: 'A non-empty session title is required.' });
1550
- return;
1551
- }
1552
- const updated = renameSession(existing.id, nextTitle);
1553
- if (!updated) {
1554
- sendJson(res, 400, { error: 'Could not rename session.' });
1555
- return;
1556
- }
1557
- sendJson(res, 200, { ok: true, id: existing.id, title: nextTitle });
1558
- return;
1559
- }
1560
- if (req.method === 'DELETE') {
1561
- const removed = deleteSession(existing.id);
1562
- sendJson(res, removed ? 200 : 404, { ok: removed, id: existing.id });
1563
- return;
1564
- }
1565
- }
1566
-
1567
- if (req.method === 'GET' && pathname === '/api/files') {
1568
- const dir = parsedUrl.searchParams.get('dir') || '';
1569
- const q = parsedUrl.searchParams.get('q') || '';
1570
- const entries = listWorkspaceEntries(workspaceRoot, dir, q);
1571
- const parentDir = dir ? path.posix.dirname(dir.replace(/\\/g, '/')) : '';
1572
- sendJson(res, 200, {
1573
- ok: true,
1574
- dir,
1575
- parentDir: parentDir === '.' ? '' : parentDir,
1576
- entries
1577
- });
1578
- return;
1579
- }
1580
-
1581
- if (req.method === 'GET' && pathname === '/api/file') {
1582
- const rel = parsedUrl.searchParams.get('path') || '';
1583
- const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
1584
- if (!abs) {
1585
- sendJson(res, 403, { error: 'Path is outside the locked workspace boundary.' });
1586
- return;
1587
- }
1588
- const stat = fs.lstatSync(abs);
1589
- if (stat.isSymbolicLink() || !stat.isFile()) {
1590
- sendJson(res, 403, { error: 'Only regular workspace files can be read.' });
1591
- return;
1592
- }
1593
- if (stat.size > MAX_FILE_READ_BYTES) {
1594
- sendJson(res, 413, { error: `File exceeds ${MAX_FILE_READ_BYTES} byte preview limit.` });
1595
- return;
1596
- }
1597
- const content = fs.readFileSync(abs, 'utf8');
1598
- sendJson(res, 200, {
1599
- ok: true,
1600
- path: path.relative(workspaceRoot, abs).split(path.sep).join('/'),
1601
- size: stat.size,
1602
- content
1603
- });
1604
- return;
1605
- }
1606
-
1607
- if (req.method === 'POST' && pathname === '/api/file') {
1608
- const body = await readJsonBody(req, MAX_FILE_WRITE_BYTES);
1609
- const rel = typeof body.path === 'string' ? body.path : '';
1610
- const content = typeof body.content === 'string' ? body.content : null;
1611
- if (!rel || content === null) {
1612
- sendJson(res, 400, { error: 'Both `path` and string `content` are required.' });
1613
- return;
1614
- }
1615
- const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
1616
- if (!abs) {
1617
- sendJson(res, 403, { error: 'Refusing write outside locked workspace boundary.' });
1618
- return;
1619
- }
1620
- const relNormalized = path.relative(workspaceRoot, abs).split(path.sep).join('/');
1621
- if (isIgnoredByCausyneIgnore(abs, workspaceRoot, false)) {
1622
- sendJson(res, 403, { error: 'File path is blocked by .causyneignore.' });
1623
- return;
1624
- }
1625
- const byteCount = Buffer.byteLength(content, 'utf8');
1626
- if (byteCount > MAX_FILE_WRITE_BYTES) {
1627
- sendJson(res, 413, { error: 'File content exceeds maximum write limit.' });
1628
- return;
1629
- }
1630
- atomicWriteFileSync(abs, content);
1631
- if (typeof body.sessionId === 'string') {
1632
- recordSessionTouchedFile(body.sessionId.trim(), relNormalized);
1633
- }
1634
- auditLog.log({ event: 'skybridge_file_write', path: relNormalized, bytes: byteCount });
1635
- sendJson(res, 200, { ok: true, path: relNormalized, bytes: byteCount });
1636
- return;
1637
- }
1638
-
1639
- if (req.method === 'GET' && pathname === '/api/diff') {
1640
- const staged = parsedUrl.searchParams.get('staged') === '1';
1641
- const rawSessionId = (parsedUrl.searchParams.get('sessionId') || '').trim();
1642
- const sessionId = SAFE_SESSION_ID_RE.test(rawSessionId) ? rawSessionId : '';
1643
- const rawScope = (parsedUrl.searchParams.get('scope') || '').trim().toLowerCase();
1644
- const scope: 'session' | 'workspace' = rawScope === 'session' && sessionId ? 'session' : 'workspace';
1645
-
1646
- const sessionEvidenceMap = new Map<string, SessionFileEvidence>();
1647
- if (sessionId) {
1648
- const sess = getSession(sessionId);
1649
- if (sess && workspaceMatchesSession(sess.workspace, workspaceRoot)) {
1650
- for (const [p, ev] of extractSessionFileEvidence(sess.messages, workspaceRoot)) {
1651
- sessionEvidenceMap.set(p, ev);
1652
- }
1653
- }
1654
- for (const p of sessionTouchedFilesMap.get(sessionId) ?? []) {
1655
- if (!sessionEvidenceMap.has(p)) {
1656
- sessionEvidenceMap.set(p, {
1657
- path: p,
1658
- status: 'modified',
1659
- additions: 0,
1660
- deletions: 0,
1661
- hunks: []
1662
- });
1663
- }
1664
- }
1665
- }
1666
-
1667
- const buildNonGitSessionEntry = (rel: string, ev: SessionFileEvidence | undefined, isGit: boolean) => {
1668
- const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
1669
- let existsOnDisk = false;
1670
- let diskSize = 0;
1671
- let diskHunks: Array<{ header: string; lines: string[] }> = [];
1672
- let diskAdditions = 0;
1673
- let diskDeletions = 0;
1674
- let fromLastCommit = false;
1675
- if (abs) {
1676
- try {
1677
- const st = fs.lstatSync(abs);
1678
- if (!st.isSymbolicLink() && st.isFile()) {
1679
- existsOnDisk = true;
1680
- diskSize = st.size;
1681
- if (isGit && (!ev || ev.hunks.length === 0)) {
1682
- const commitDiff = readLastGitCommitDiffForFile(workspaceRoot, rel);
1683
- if (commitDiff) {
1684
- diskHunks = commitDiff.hunks;
1685
- diskAdditions = commitDiff.additions;
1686
- diskDeletions = commitDiff.deletions;
1687
- fromLastCommit = true;
1688
- }
1689
- }
1690
- if (diskHunks.length === 0 && st.size > 0 && st.size <= 48 * 1024 && (!ev || ev.hunks.length === 0)) {
1691
- const buf = fs.readFileSync(abs);
1692
- if (!buf.includes(0)) {
1693
- const synth = buildSynthesizedWriteHunk(buf.toString('utf8'));
1694
- diskHunks = synth.hunks;
1695
- diskAdditions = synth.additions;
1696
- }
1697
- }
1698
- }
1699
- } catch {
1700
- existsOnDisk = false;
1701
- }
1702
- }
1703
- const hunks = ev && ev.hunks.length > 0 ? ev.hunks : diskHunks;
1704
- const additions = ev && ev.additions > 0 ? ev.additions : diskAdditions;
1705
- const deletions = ev && ev.deletions > 0 ? ev.deletions : diskDeletions;
1706
- const status = fromLastCommit && diskDeletions > 0
1707
- ? 'modified'
1708
- : (ev?.status ?? (existsOnDisk ? 'modified' : 'added'));
1709
- let note: string | undefined;
1710
- if (existsOnDisk) {
1711
- if (fromLastCommit) {
1712
- note = 'Latest committed diff on disk';
1713
- } else if (hunks.length === 0) {
1714
- note = diskSize > 0
1715
- ? `On disk (${formatByteSize(diskSize)}) · ${isGit ? 'committed or binary asset' : 'workspace file'}`
1716
- : (isGit ? 'Clean on disk' : 'Touched in this conversation');
1717
- }
1718
- } else {
1719
- const sizeLabel = ev?.bytesWritten ? ` (${formatByteSize(ev.bytesWritten)})` : '';
1720
- note = `Written in this chat${sizeLabel} · no longer on disk`;
1721
- }
1722
- return {
1723
- path: rel,
1724
- status,
1725
- additions,
1726
- deletions,
1727
- inGitDiff: false,
1728
- existsOnDisk,
1729
- note,
1730
- hunks
1731
- };
1732
- };
1733
-
1734
- try {
1735
- const report = collectWorkingTreeDiff(workspaceRoot, { staged });
1736
- const mappedWorkspaceFiles = report.files.slice(0, 60).map((f) => {
1737
- const abs = resolveWorkspaceRelativePath(workspaceRoot, f.displayPath);
1738
- let existsOnDisk = f.status !== 'deleted';
1739
- let note: string | undefined;
1740
- if (abs && f.hunks.length === 0 && f.status !== 'deleted') {
1741
- try {
1742
- const st = fs.lstatSync(abs);
1743
- existsOnDisk = st.isFile();
1744
- if (existsOnDisk) note = `Binary or large asset (${formatByteSize(st.size)})`;
1745
- } catch {
1746
- existsOnDisk = false;
1747
- }
1748
- }
1749
- return {
1750
- path: f.displayPath,
1751
- status: f.status,
1752
- additions: f.additions,
1753
- deletions: f.deletions,
1754
- inGitDiff: true,
1755
- existsOnDisk,
1756
- note,
1757
- hunks: f.hunks.slice(0, 20).map((h) => ({
1758
- header: h.header,
1759
- lines: h.lines.slice(0, 200)
1760
- }))
1761
- };
1762
- });
1763
- const matchedSessionGitFiles = mappedWorkspaceFiles.filter((f) => sessionEvidenceMap.has(f.path));
1764
- const matchedPaths = new Set(matchedSessionGitFiles.map((f) => f.path));
1765
- const extraSessionFiles = [...sessionEvidenceMap.keys()]
1766
- .sort()
1767
- .filter((rel) => !matchedPaths.has(rel))
1768
- .map((rel) => buildNonGitSessionEntry(rel, sessionEvidenceMap.get(rel), true));
1769
- const sessionFiles = [...matchedSessionGitFiles, ...extraSessionFiles];
1770
- const returnedFiles = scope === 'session' ? sessionFiles : mappedWorkspaceFiles;
1771
- const totalAdditions = scope === 'session'
1772
- ? returnedFiles.reduce((sum, f) => sum + f.additions, 0)
1773
- : report.totalAdditions;
1774
- const totalDeletions = scope === 'session'
1775
- ? returnedFiles.reduce((sum, f) => sum + f.deletions, 0)
1776
- : report.totalDeletions;
1777
- sendJson(res, 200, {
1778
- ok: true,
1779
- isGitRepo: true,
1780
- scope,
1781
- sessionId: sessionId || null,
1782
- staged: report.staged,
1783
- workspaceFileCount: mappedWorkspaceFiles.length,
1784
- sessionFileCount: sessionFiles.length,
1785
- totalAdditions,
1786
- totalDeletions,
1787
- truncated: report.truncated,
1788
- files: returnedFiles
1789
- });
1790
- } catch {
1791
- const fallbackSessionFiles = [...sessionEvidenceMap.keys()]
1792
- .sort()
1793
- .map((rel) => buildNonGitSessionEntry(rel, sessionEvidenceMap.get(rel), false));
1794
- sendJson(res, 200, {
1795
- ok: true,
1796
- isGitRepo: false,
1797
- scope,
1798
- sessionId: sessionId || null,
1799
- staged,
1800
- workspaceFileCount: 0,
1801
- sessionFileCount: fallbackSessionFiles.length,
1802
- totalAdditions: fallbackSessionFiles.reduce((sum, f) => sum + f.additions, 0),
1803
- totalDeletions: fallbackSessionFiles.reduce((sum, f) => sum + f.deletions, 0),
1804
- truncated: false,
1805
- files: scope === 'session' ? fallbackSessionFiles : []
1806
- });
1807
- }
1808
- return;
1809
- }
1810
-
1811
- if (req.method === 'GET' && pathname === '/api/doctor/report') {
1812
- const config = loadConfig();
1813
- sendJson(res, 200, {
1814
- ok: true,
1815
- report: formatRedactedProviderErrorReport({
1816
- provider: config.provider,
1817
- model: config.model,
1818
- causyneVersion: version
1819
- })
1820
- });
1821
- return;
1822
- }
1823
-
1824
- if (req.method === 'GET' && pathname === '/api/license/status') {
1825
- const liveRequested = parsedUrl.searchParams.get('live') === '1';
1826
- const hasCustomClient = Boolean(options.entitlementClient);
1827
- if (!LICENSE_ENFORCEMENT_ENABLED && !hasCustomClient && !liveRequested) {
1828
- sendJson(res, 200, {
1829
- ok: true,
1830
- enforcementEnabled: false,
1831
- entitlement: 'free',
1832
- plan: 'free',
1833
- paidUntil: null,
1834
- dailySeconds: 21_600,
1835
- remainingSeconds: 21_600,
1836
- resetsAt: null,
1837
- recoveryCode: null,
1838
- supportMessage: DAILY_LIMIT_SUPPORT_MESSAGE
1839
- });
1840
- return;
1841
- }
1842
- try {
1843
- const client = options.entitlementClient ?? new EntitlementClient();
1844
- const data = await client.status();
1845
- sendJson(res, 200, {
1846
- ok: true,
1847
- enforcementEnabled: LICENSE_ENFORCEMENT_ENABLED,
1848
- entitlement: typeof data?.entitlement === 'string' ? data.entitlement : 'free',
1849
- plan: typeof data?.plan === 'string' ? data.plan : 'free',
1850
- status: typeof data?.status === 'string' ? data.status : 'free',
1851
- paidUntil: typeof data?.paidUntil === 'string' ? data.paidUntil : null,
1852
- dailySeconds: typeof data?.dailySeconds === 'number' ? data.dailySeconds : null,
1853
- remainingSeconds: typeof data?.remainingSeconds === 'number' ? data.remainingSeconds : null,
1854
- resetsAt: typeof data?.resetsAt === 'string' ? data.resetsAt : null,
1855
- recoveryCode: typeof data?.recoveryCode === 'string' ? data.recoveryCode : null,
1856
- supportMessage: typeof data?.upgradeMessage === 'string' ? data.upgradeMessage : DAILY_LIMIT_SUPPORT_MESSAGE
1857
- });
1858
- } catch (err: unknown) {
1859
- const msg = err instanceof EntitlementAccessError
1860
- ? err.message
1861
- : 'Unable to reach licensing service right now.';
1862
- sendJson(res, 503, { ok: false, error: msg, enforcementEnabled: LICENSE_ENFORCEMENT_ENABLED });
1863
- }
1864
- return;
1865
- }
1866
-
1867
- if (req.method === 'POST' && pathname === '/api/license/checkout') {
1868
- const body = await readJsonBody(req);
1869
- const plan = typeof body.plan === 'string' ? body.plan.trim() : '';
1870
- if (!isValidLicensePlan(plan)) {
1871
- sendJson(res, 400, { error: 'Unknown Causyne plan.' });
1872
- return;
1873
- }
1874
- try {
1875
- const client = options.entitlementClient ?? new EntitlementClient();
1876
- const result = await client.checkout(plan);
1877
- auditLog.log({ event: 'skybridge_license_checkout', plan });
1878
- sendJson(res, 200, { ok: true, plan, url: result.url });
1879
- } catch (err: unknown) {
1880
- const msg = err instanceof EntitlementAccessError
1881
- ? err.message
1882
- : 'Unable to start Paddle checkout right now. Visit https://causyne.com/pricing.html.';
1883
- sendJson(res, 502, { ok: false, error: msg });
1884
- }
1885
- return;
1886
- }
1887
-
1888
- if (req.method === 'POST' && pathname === '/api/license/recover') {
1889
- const body = await readJsonBody(req);
1890
- const code = typeof body.recoveryCode === 'string' ? body.recoveryCode.trim() : '';
1891
- try {
1892
- const client = options.entitlementClient ?? new EntitlementClient();
1893
- const result = await client.recover(code);
1894
- auditLog.log({ event: 'skybridge_license_recover', ok: true });
1895
- sendJson(res, 200, {
1896
- ok: true,
1897
- entitlement: result?.entitlement ?? 'pro',
1898
- plan: result?.plan ?? 'monthly',
1899
- paidUntil: result?.paidUntil ?? null
1900
- });
1901
- } catch (err: unknown) {
1902
- const status = err instanceof EntitlementAccessError && err.code === 'INVALID_RECOVERY_CODE' ? 400 : 404;
1903
- const msg = err instanceof EntitlementAccessError ? err.message : 'Could not link recovery code.';
1904
- sendJson(res, status, { ok: false, error: msg });
1905
- }
1906
- return;
1907
- }
1908
-
1909
- if (req.method === 'POST' && pathname === '/api/license/portal') {
1910
- try {
1911
- const client = options.entitlementClient ?? new EntitlementClient();
1912
- const result = await client.portal();
1913
- sendJson(res, 200, { ok: true, url: result.url });
1914
- } catch (err: unknown) {
1915
- const msg = err instanceof EntitlementAccessError ? err.message : 'Billing portal unavailable.';
1916
- sendJson(res, 502, { ok: false, error: msg });
1917
- }
1918
- return;
1919
- }
1920
-
1921
- if (req.method === 'POST' && pathname === '/api/doctor/probe') {
1922
- const report = await runZeroSpendByokProbe();
1923
- sendJson(res, 200, {
1924
- ok: true,
1925
- report: formatByokProbeReport(report),
1926
- summary: {
1927
- testedCount: report.testedCount,
1928
- passedCount: report.passedCount,
1929
- failedCount: report.failedCount,
1930
- skippedCount: report.skippedCount
1931
- }
1932
- });
1933
- return;
1934
- }
1935
-
1936
- if (req.method === 'POST' && pathname === '/api/config/key') {
1937
- const body = await readJsonBody(req);
1938
- const provider = typeof body.provider === 'string' ? body.provider.trim().toLowerCase() : '';
1939
- const apiKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';
1940
- const forbidden = new Set(['__proto__', 'constructor', 'prototype']);
1941
- if (!provider || forbidden.has(provider) || !SAFE_PROVIDER_RE.test(provider)) {
1942
- sendJson(res, 400, { error: 'Valid provider identifier is required.' });
1943
- return;
1944
- }
1945
- if (!apiKey || apiKey.length < 4 || apiKey.length > 512) {
1946
- sendJson(res, 400, { error: 'API key must be between 4 and 512 characters.' });
1947
- return;
1948
- }
1949
- const config = loadConfig();
1950
- const existingKeys = config.providerKeys && typeof config.providerKeys === 'object' && !Array.isArray(config.providerKeys)
1951
- ? { ...(config.providerKeys as Record<string, string>) }
1952
- : {};
1953
- existingKeys[provider] = apiKey;
1954
- config.providerKeys = existingKeys;
1955
- if (String(config.provider || '').trim().toLowerCase() === provider || body.activate === true) {
1956
- applyProviderOverrides(config, provider, typeof body.model === 'string' ? body.model.trim() : undefined);
1957
- }
1958
- saveConfig(config);
1959
- auditLog.log({ event: 'skybridge_vault_key_saved', provider });
1960
- sendJson(res, 200, {
1961
- ok: true,
1962
- provider,
1963
- configured: true,
1964
- activeProvider: config.provider || 'unconfigured',
1965
- activeModel: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default'
1966
- });
1967
- return;
1968
- }
1969
-
1970
- if (req.method === 'GET' && pathname === '/api/commands') {
1971
- const commands = listCommands('terminal').map((cmd) => ({
1972
- name: cmd.name,
1973
- aliases: cmd.aliases ?? [],
1974
- usage: cmd.usage,
1975
- description: cmd.description
1976
- }));
1977
- sendJson(res, 200, { ok: true, commands });
1978
- return;
1979
- }
1980
-
1981
- if (req.method === 'POST' && pathname === '/api/command') {
1982
- const body = await readJsonBody(req);
1983
- let cmdName = '';
1984
- let cmdArgv: string[] = [];
1985
- if (typeof body.input === 'string' && body.input.trim()) {
1986
- const rawLine = body.input.trim().startsWith('/') ? body.input.trim() : `/${body.input.trim()}`;
1987
- const parsed = parseCommand(rawLine);
1988
- if (!parsed) {
1989
- sendJson(res, 400, { error: 'Invalid CLI slash command syntax.' });
1990
- return;
1991
- }
1992
- cmdName = parsed.name;
1993
- cmdArgv = parsed.argv;
1994
- } else if (typeof body.name === 'string' && body.name.trim()) {
1995
- cmdName = body.name.trim().toLowerCase();
1996
- cmdArgv = Array.isArray(body.argv) ? body.argv.map((x: unknown) => String(x ?? '')) : [];
1997
- } else {
1998
- sendJson(res, 400, { error: 'Command input or name is required.' });
1999
- return;
2000
- }
2001
- if (cmdName === 'exit' || cmdName === 'quit') {
2002
- sendJson(res, 200, {
2003
- ok: true,
2004
- command: cmdName,
2005
- title: 'Exit',
2006
- output: 'Press Ctrl+C in the terminal running `causyne web` to stop the local Skybridge server cleanly.'
2007
- });
2008
- return;
2009
- }
2010
- const prevCwd = process.cwd();
2011
- let result: Awaited<ReturnType<typeof runCommand>>;
2012
- try {
2013
- if (prevCwd !== workspaceRoot) process.chdir(workspaceRoot);
2014
- result = await runCommand(cmdName, cmdArgv, {
2015
- surface: 'terminal',
2016
- workspaceRoot,
2017
- cwd: workspaceRoot
2018
- });
2019
- } finally {
2020
- try { if (process.cwd() !== prevCwd) process.chdir(prevCwd); } catch { /* ignore */ }
2021
- }
2022
- auditLog.log({ event: 'skybridge_cli_command', command: cmdName, ok: Boolean(result.ok) });
2023
- sendJson(res, 200, {
2024
- ok: Boolean(result.ok),
2025
- command: cmdName,
2026
- title: typeof result.title === 'string' ? result.title : `/${cmdName}`,
2027
- effect: typeof result.effect === 'string' ? result.effect : null,
2028
- output: redactProviderSecrets(String(result.output || ''))
2029
- });
2030
- return;
2031
- }
2032
-
2033
- if (req.method === 'GET' && pathname === '/api/cli/overview') {
2034
- const checkpoints = listGroups(12).map((g) => ({
2035
- id: g.taskId,
2036
- createdAt: g.ts,
2037
- label: g.prompt || g.taskId,
2038
- fileCount: Array.isArray(g.fileEntries) ? g.fileEntries.length : 0
2039
- }));
2040
- const skills = listCompiledSkills();
2041
- const mcpServers = serverStatus().map((s) => ({
2042
- name: s.name,
2043
- connected: Boolean((s as any).connected),
2044
- granted: Boolean((s as any).granted),
2045
- toolsCount: typeof (s as any).toolsCount === 'number' ? (s as any).toolsCount : 0
2046
- }));
2047
- const peers = listAllPeers().map((p) => ({
2048
- name: p.id,
2049
- label: p.label,
2050
- command: p.command
2051
- }));
2052
- const tasks = backgroundTaskManager.list().slice(0, 20).map((t) => ({
2053
- id: t.taskId,
2054
- label: t.label,
2055
- command: t.command,
2056
- status: t.status,
2057
- startedAt: t.startedAt
2058
- }));
2059
- let worktrees: Array<{ path: string; branch: string; managed: boolean }> = [];
2060
- try {
2061
- worktrees = listWorktrees(workspaceRoot).map((w) => ({
2062
- path: w.path,
2063
- branch: w.branch || 'detached',
2064
- managed: Boolean(w.managed)
2065
- }));
2066
- } catch {
2067
- worktrees = [];
2068
- }
2069
- sendJson(res, 200, {
2070
- ok: true,
2071
- commandsCount: listCommands('terminal').length,
2072
- skillsCount: skills.length,
2073
- checkpoints,
2074
- mcpServers,
2075
- peers,
2076
- tasks,
2077
- worktrees,
2078
- browserActive: causyneBrowser({ workspace: workspaceRoot }).isActive(),
2079
- browserControlOwner
2080
- });
2081
- return;
2082
- }
2083
-
2084
- if (req.method === 'GET' && pathname === '/api/mcp/browser') {
2085
- res.statusCode = 405;
2086
- res.setHeader('Allow', 'POST');
2087
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
2088
- res.end(JSON.stringify({ error: 'Use POST for Streamable HTTP MCP JSON-RPC requests.' }));
2089
- return;
2090
- }
2091
-
2092
- if (req.method === 'POST' && pathname === '/api/mcp/browser') {
2093
- const body = await readJsonBody(req) as JsonRpcMessage;
2094
- const reply = await handleBrowserMcpRpc(body, {
2095
- workspaceRoot,
2096
- version,
2097
- onActivity: (activity) => {
2098
- if (activity.phase === 'start') {
2099
- browserControlOwner = 'agent';
2100
- browserAgentActivity = {
2101
- active: true,
2102
- tool: activity.tool,
2103
- detail: activity.detail,
2104
- updatedAt: Date.now()
2105
- };
2106
- } else {
2107
- browserAgentActivity = { active: false, tool: '', detail: '', updatedAt: Date.now() };
2108
- }
2109
- broadcastBrowserNotice({
2110
- type: 'agent_activity',
2111
- controlOwner: browserControlOwner,
2112
- agentActivity: browserAgentActivity
2113
- });
2114
- }
2115
- });
2116
- if (reply === null) {
2117
- res.statusCode = 202;
2118
- res.end();
2119
- return;
2120
- }
2121
- sendJson(res, 200, reply);
2122
- return;
2123
- }
2124
-
2125
- if (req.method === 'GET' && pathname === '/api/browser/state') {
2126
- const ensure = parsedUrl.searchParams.get('ensure') === '1';
2127
- const browser = causyneBrowser({ workspace: workspaceRoot });
2128
- const frame = await browser.captureLiveFrame({ ensureStarted: ensure });
2129
- sendJson(res, 200, {
2130
- ok: true,
2131
- controlOwner: browserControlOwner,
2132
- agentActivity: browserAgentActivity,
2133
- computerUsePolicy: 'tiered-approval',
2134
- ...frame
2135
- });
2136
- return;
2137
- }
2138
-
2139
- if (req.method === 'GET' && pathname === '/api/browser/stream') {
2140
- const browser = causyneBrowser({ workspace: workspaceRoot });
2141
- res.statusCode = 200;
2142
- res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
2143
- res.setHeader('Transfer-Encoding', 'chunked');
2144
- res.setHeader('X-Accel-Buffering', 'no');
2145
- const writeStreamLine = (payload: Record<string, unknown>): void => {
2146
- if (res.writableEnded || res.destroyed) return;
2147
- try {
2148
- res.write(`${JSON.stringify(payload)}\n`);
2149
- } catch {
2150
- // Stream closed mid-write.
2151
- }
2152
- };
2153
- const unsub = browser.subscribeLiveStream((ev) => {
2154
- writeStreamLine({
2155
- ...ev,
2156
- controlOwner: browserControlOwner,
2157
- agentActivity: browserAgentActivity,
2158
- computerUsePolicy: 'tiered-approval'
2159
- });
2160
- });
2161
- browserStreamClients.add(writeStreamLine);
2162
- writeStreamLine({
2163
- type: 'agent_activity',
2164
- controlOwner: browserControlOwner,
2165
- agentActivity: browserAgentActivity,
2166
- computerUsePolicy: 'tiered-approval'
2167
- });
2168
- const keepAlive = setInterval(() => {
2169
- writeStreamLine({ type: 'ping', ts: Date.now() });
2170
- }, 15_000);
2171
- keepAlive.unref?.();
2172
- const cleanup = (): void => {
2173
- clearInterval(keepAlive);
2174
- browserStreamClients.delete(writeStreamLine);
2175
- unsub();
2176
- };
2177
- req.on('close', cleanup);
2178
- res.on('close', cleanup);
2179
- return;
2180
- }
2181
-
2182
- if (req.method === 'POST' && pathname === '/api/browser/input') {
2183
- const body = await readJsonBody(req);
2184
- const kind = typeof body.kind === 'string' ? body.kind.trim() : '';
2185
- const allowedKinds = new Set([
2186
- 'click', 'dblclick', 'contextmenu', 'mousedown', 'mousemove', 'mouseup', 'wheel', 'type', 'key', 'paste'
2187
- ]);
2188
- if (!allowedKinds.has(kind)) {
2189
- sendJson(res, 400, { error: 'Unsupported live browser input kind.' });
2190
- return;
2191
- }
2192
- browserControlOwner = 'human';
2193
- const browser = causyneBrowser({ workspace: workspaceRoot });
2194
- const result = await browser.dispatchLiveInput({
2195
- kind: kind as LiveBrowserInteraction['kind'],
2196
- x: typeof body.x === 'number' ? body.x : undefined,
2197
- y: typeof body.y === 'number' ? body.y : undefined,
2198
- deltaX: typeof body.deltaX === 'number' ? body.deltaX : undefined,
2199
- deltaY: typeof body.deltaY === 'number' ? body.deltaY : undefined,
2200
- text: typeof body.text === 'string' ? body.text : undefined,
2201
- key: typeof body.key === 'string' ? body.key : undefined,
2202
- button: body.button === 'right' || body.button === 'middle' ? body.button : 'left',
2203
- skipFrame: true
2204
- });
2205
- sendJson(res, 200, { ok: result.ok, controlOwner: browserControlOwner });
2206
- return;
2207
- }
2208
-
2209
- if (req.method === 'POST' && pathname === '/api/browser/action') {
2210
- const body = await readJsonBody(req);
2211
- const action = typeof body.action === 'string' ? body.action.trim() : '';
2212
- const browser = causyneBrowser({ workspace: workspaceRoot });
2213
-
2214
- if (action === 'setMode') {
2215
- browserControlOwner = 'human';
2216
- const rawPref = typeof body.enginePreference === 'string' ? body.enginePreference.trim() : '';
2217
- const enginePreference: BrowserEnginePreference | undefined = rawPref === 'camoufox'
2218
- || rawPref === 'chromium'
2219
- || rawPref === 'auto'
2220
- ? rawPref
2221
- : undefined;
2222
- const frame = await browser.setDisplayMode({
2223
- visible: typeof body.visible === 'boolean' ? body.visible : undefined,
2224
- enginePreference,
2225
- ensureStarted: body.ensureStarted === true
2226
- });
2227
- auditLog.log({
2228
- event: 'skybridge_browser_mode_switch',
2229
- visible: frame.visible,
2230
- engine: frame.engine,
2231
- enginePreference: frame.enginePreference
2232
- });
2233
- broadcastBrowserNotice({
2234
- type: 'meta',
2235
- controlOwner: browserControlOwner,
2236
- agentActivity: browserAgentActivity,
2237
- ...frame
2238
- });
2239
- sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
2240
- return;
2241
- }
2242
- if (action === 'takeControl') {
2243
- browserControlOwner = 'human';
2244
- browserAgentActivity = { active: false, tool: '', detail: '', updatedAt: Date.now() };
2245
- const frame = await browser.captureLiveFrame({ ensureStarted: false });
2246
- broadcastBrowserNotice({ type: 'agent_activity', controlOwner: browserControlOwner, agentActivity: browserAgentActivity });
2247
- sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
2248
- return;
2249
- }
2250
- if (action === 'handToAgent') {
2251
- browserControlOwner = 'agent';
2252
- const frame = await browser.captureLiveFrame({ ensureStarted: false });
2253
- broadcastBrowserNotice({ type: 'agent_activity', controlOwner: browserControlOwner, agentActivity: browserAgentActivity });
2254
- sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
2255
- return;
2256
- }
2257
- if (action === 'start') {
2258
- browserControlOwner = 'human';
2259
- const frame = await browser.captureLiveFrame({ ensureStarted: true });
2260
- sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2261
- return;
2262
- }
2263
- if (action === 'close') {
2264
- await browser.close();
2265
- const frame = await browser.captureLiveFrame({ ensureStarted: false });
2266
- sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2267
- return;
2268
- }
2269
- if (action === 'goto' || action === 'newTab') {
2270
- browserControlOwner = 'human';
2271
- let rawUrl = typeof body.url === 'string' ? body.url.trim() : '';
2272
- if (rawUrl.startsWith('@')) {
2273
- const idx = rawUrl.indexOf(' ');
2274
- const macro = idx === -1 ? rawUrl : rawUrl.slice(0, idx);
2275
- const q = idx === -1 ? '' : rawUrl.slice(idx + 1).trim();
2276
- const expanded = expandSearchMacro(macro, q);
2277
- if (!expanded) {
2278
- sendJson(res, 400, { error: 'Unsupported browser search macro.' });
2279
- return;
2280
- }
2281
- rawUrl = expanded;
2282
- } else if (rawUrl && !/^https?:\/\//i.test(rawUrl)) {
2283
- rawUrl = rawUrl.includes('.') || rawUrl.startsWith('localhost')
2284
- ? `https://${rawUrl}`
2285
- : (expandSearchMacro('@duckduckgo_search', rawUrl) || `https://duckduckgo.com/?q=${encodeURIComponent(rawUrl)}`);
2286
- }
2287
- await browser.run(
2288
- [action === 'newTab' ? { type: 'newTab', ...(rawUrl ? { url: rawUrl } : {}) } : { type: 'goto', url: rawUrl || 'about:blank' }],
2289
- { workspace: workspaceRoot }
2290
- );
2291
- const frame = await browser.captureLiveFrame({ ensureStarted: true });
2292
- sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2293
- return;
2294
- }
2295
- if (action === 'back' || action === 'forward' || action === 'reload') {
2296
- browserControlOwner = 'human';
2297
- await browser.run([{ type: action }], { workspace: workspaceRoot });
2298
- const frame = await browser.captureLiveFrame({ ensureStarted: true });
2299
- sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2300
- return;
2301
- }
2302
- if ((action === 'switchTab' || action === 'closeTab') && typeof body.tabId === 'string' && body.tabId.trim()) {
2303
- browserControlOwner = 'human';
2304
- await browser.run([{ type: action, tabId: body.tabId.trim() }], { workspace: workspaceRoot });
2305
- const frame = await browser.captureLiveFrame({ ensureStarted: true });
2306
- sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2307
- return;
2308
- }
2309
- if (action === 'viewport') {
2310
- const width = Math.max(320, Math.min(1920, Number(body.width) || 1280));
2311
- const height = Math.max(480, Math.min(1200, Number(body.height) || 800));
2312
- await browser.run([{ type: 'viewport', width, height }], { workspace: workspaceRoot });
2313
- const frame = await browser.captureLiveFrame({ ensureStarted: true });
2314
- sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2315
- return;
2316
- }
2317
- if (action === 'snapshot') {
2318
- const snap = await browser.snapshot(0);
2319
- const frame = await browser.captureLiveFrame({ ensureStarted: true });
2320
- sendJson(res, 200, {
2321
- ok: true,
2322
- controlOwner: browserControlOwner,
2323
- snapshot: snap.text,
2324
- refsCount: snap.refsCount,
2325
- ...frame
2326
- });
2327
- return;
2328
- }
2329
- if (
2330
- action === 'click'
2331
- || action === 'dblclick'
2332
- || action === 'contextmenu'
2333
- || action === 'mousedown'
2334
- || action === 'mousemove'
2335
- || action === 'mouseup'
2336
- || action === 'wheel'
2337
- || action === 'type'
2338
- || action === 'key'
2339
- || action === 'paste'
2340
- ) {
2341
- browserControlOwner = 'human';
2342
- const frame = await browser.interactAt({
2343
- kind: action,
2344
- x: typeof body.x === 'number' ? body.x : undefined,
2345
- y: typeof body.y === 'number' ? body.y : undefined,
2346
- deltaX: typeof body.deltaX === 'number' ? body.deltaX : undefined,
2347
- deltaY: typeof body.deltaY === 'number' ? body.deltaY : undefined,
2348
- text: typeof body.text === 'string' ? body.text : undefined,
2349
- key: typeof body.key === 'string' ? body.key : undefined,
2350
- button: body.button === 'right' || body.button === 'middle' ? body.button : 'left'
2351
- });
2352
- sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
2353
- return;
2354
- }
2355
- sendJson(res, 400, { error: 'Unsupported shared browser action.' });
2356
- return;
2357
- }
2358
-
2359
- if (req.method === 'GET' && pathname === '/api/browser/cdp/tabs') {
2360
- const portParam = parsedUrl.searchParams.get('port') || '9222';
2361
- const discovered = await discoverLocalCdpTabs(portParam);
2362
- sendJson(res, 200, {
2363
- ok: true,
2364
- port: discovered.port,
2365
- tabs: discovered.tabs.map((t) => ({ id: t.id, title: t.title, url: t.url }))
2366
- });
2367
- return;
2368
- }
2369
-
2370
- if (req.method === 'POST' && pathname === '/api/browser/cdp/sync') {
2371
- const body = await readJsonBody(req);
2372
- const targetId = typeof body.targetId === 'string' ? body.targetId.trim() : '';
2373
- if (!targetId) {
2374
- sendJson(res, 400, { error: 'targetId is required to sync a local browser tab.' });
2375
- return;
2376
- }
2377
- const synced = await syncLocalCdpTabToCausyne({
2378
- workspaceRoot,
2379
- port: body.port ?? 9222,
2380
- targetId,
2381
- includeCookies: body.includeCookies === true
2382
- });
2383
- browserControlOwner = 'human';
2384
- auditLog.log({
2385
- event: 'skybridge_browser_cdp_sync',
2386
- importedCookies: synced.importedCookies
2387
- });
2388
- sendJson(res, 200, {
2389
- ok: true,
2390
- controlOwner: browserControlOwner,
2391
- syncedUrl: synced.syncedUrl,
2392
- importedCookies: synced.importedCookies,
2393
- ...synced.frame
2394
- });
2395
- return;
2396
- }
2397
-
2398
- if (req.method === 'POST' && pathname === '/api/browser/import') {
2399
- const body = await readJsonBody(req);
2400
- const rawText = typeof body.rawText === 'string' ? body.rawText : '';
2401
- const summary = await importExplicitUserBrowserData({
2402
- workspaceRoot,
2403
- rawText,
2404
- openFirstUrl: body.openFirstUrl !== false
2405
- });
2406
- const frame = await causyneBrowser({ workspace: workspaceRoot }).captureLiveFrame({ ensureStarted: false });
2407
- auditLog.log({
2408
- event: 'skybridge_browser_import',
2409
- importedCookies: summary.importedCookies,
2410
- urlsCount: summary.importedUrls.length
2411
- });
2412
- sendJson(res, 200, {
2413
- ok: true,
2414
- controlOwner: browserControlOwner,
2415
- ...summary,
2416
- ...frame
2417
- });
2418
- return;
2419
- }
2420
-
2421
- if (req.method === 'POST' && pathname === '/api/approve') {
2422
- const body = await readJsonBody(req);
2423
- const toolCallId = typeof body.toolCallId === 'string' ? body.toolCallId.trim() : '';
2424
- const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
2425
- ? body.sessionId.trim()
2426
- : '';
2427
- const approved = body.approved === true;
2428
- const remember = body.remember === true;
2429
- const toolName = typeof body.tool === 'string' ? body.tool.trim().slice(0, 80) : '';
2430
- const targetRun = findActiveRun(sessionId || null);
2431
- if (!toolCallId || !targetRun?.loop.resolveApproval) {
2432
- sendJson(res, 400, { error: 'No active pending approval matches that toolCallId.' });
2433
- return;
2434
- }
2435
- if (approved && remember && toolName && targetRun.loop.grantAlways) {
2436
- targetRun.loop.grantAlways(toolName);
2437
- auditLog.log({ event: 'skybridge_approval_grant_always', tool: toolName });
2438
- }
2439
- targetRun.status = 'running';
2440
- targetRun.loop.resolveApproval(toolCallId, approved);
2441
- sendJson(res, 200, { ok: true, toolCallId, approved, remembered: Boolean(approved && remember && toolName) });
2442
- return;
2443
- }
2444
-
2445
- if (req.method === 'POST' && pathname === '/api/decision') {
2446
- const body = await readJsonBody(req);
2447
- const requestId = typeof body.requestId === 'string' ? body.requestId.trim() : '';
2448
- const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
2449
- ? body.sessionId.trim()
2450
- : '';
2451
- const label = typeof body.label === 'string' ? body.label.trim().slice(0, 400) : '';
2452
- const optionId = typeof body.optionId === 'string' ? body.optionId.trim().slice(0, 120) : null;
2453
- const custom = body.custom === true;
2454
- const targetRun = findActiveRun(sessionId || null);
2455
- if (!requestId || !targetRun?.loop.resolveDecision) {
2456
- sendJson(res, 400, { error: 'No active pending decision matches that requestId.' });
2457
- return;
2458
- }
2459
- targetRun.status = 'running';
2460
- targetRun.loop.resolveDecision(requestId, label ? { optionId, label, custom } : null);
2461
- sendJson(res, 200, { ok: true, requestId, label });
2462
- return;
2463
- }
2464
-
2465
- if (req.method === 'POST' && pathname === '/api/stop') {
2466
- let stopSessionId = '';
2467
- try {
2468
- const body = await readJsonBody(req);
2469
- if (typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())) {
2470
- stopSessionId = body.sessionId.trim();
2471
- }
2472
- } catch {
2473
- // Empty body is valid for /api/stop.
2474
- }
2475
- if (stopSessionId) {
2476
- const run = activeRuns.get(stopSessionId);
2477
- if (run) {
2478
- run.userStopped = true;
2479
- run.loop.abort?.();
2480
- }
2481
- } else {
2482
- for (const run of activeRuns.values()) {
2483
- run.userStopped = true;
2484
- run.loop.abort?.();
2485
- }
2486
- }
2487
- sendJson(res, 200, { ok: true });
2488
- return;
2489
- }
2490
-
2491
- if (req.method === 'POST' && pathname === '/api/chat') {
2492
- const body = await readJsonBody(req);
2493
- const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
2494
- const rawMode = typeof body.mode === 'string' ? body.mode.trim().toUpperCase() : 'B';
2495
- const mode = rawMode === 'A' || rawMode === 'B' || rawMode === 'C' ? rawMode : 'B';
2496
- const requestedSessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
2497
- ? body.sessionId.trim()
2498
- : '';
2499
- const providerOverride = typeof body.provider === 'string' && SAFE_PROVIDER_RE.test(body.provider.trim())
2500
- ? body.provider.trim()
2501
- : undefined;
2502
- const modelOverride = typeof body.model === 'string' && SAFE_MODEL_RE.test(body.model.trim())
2503
- ? body.model.trim()
2504
- : undefined;
2505
- if (!prompt) {
2506
- sendJson(res, 400, { error: 'Prompt text is required.' });
2507
- return;
2508
- }
2509
-
2510
- let boundSession = requestedSessionId ? getSession(requestedSessionId) : null;
2511
- if (boundSession && !workspaceMatchesSession(boundSession.workspace, workspaceRoot)) {
2512
- boundSession = null;
2513
- }
2514
- if (!boundSession && !hasCustomFactory) {
2515
- boundSession = createSession(workspaceRoot, prompt.slice(0, 60), false);
2516
- }
2517
-
2518
- const runKey = boundSession?.id || '__ephemeral__';
2519
- const existingRun = activeRuns.get(runKey);
2520
- if (existingRun && (existingRun.status === 'running' || existingRun.status === 'awaiting_client')) {
2521
- sendJson(res, 409, {
2522
- error: 'This conversation already has a task running. Stop it or wait for completion.'
2523
- });
2524
- return;
2525
- }
2526
-
2527
- const { effectivePrompt, attachedPaths } = buildWorkspacePromptWithAttachments(
2528
- workspaceRoot,
2529
- prompt,
2530
- body.attachments
2531
- );
2532
-
2533
- const taskId = `web-${++taskCounter}-${Date.now()}`;
2534
- let collectedAssistantText = '';
2535
- let runRef: SessionActiveRun | null = null;
2536
-
2537
- const emitFrame = (raw: string): void => {
2538
- const clean = raw.replace(/\r?\n/g, ' ');
2539
- try {
2540
- const parsed = JSON.parse(clean) as {
2541
- type?: string;
2542
- delta?: string;
2543
- content?: string;
2544
- tool?: string;
2545
- actionName?: string;
2546
- detail?: string;
2547
- path?: string;
2548
- args?: Record<string, unknown>;
2549
- };
2550
- if (parsed.type === 'agent_chunk' && typeof parsed.delta === 'string') {
2551
- collectedAssistantText += parsed.delta;
2552
- } else if (parsed.type === 'agent_message' && typeof parsed.content === 'string' && !collectedAssistantText) {
2553
- collectedAssistantText = parsed.content;
2554
- }
2555
- if (runRef && (parsed.type === 'approval_request' || parsed.type === 'decision_request')) {
2556
- runRef.status = 'awaiting_client';
2557
- }
2558
- const toolLower = typeof parsed.tool === 'string' ? parsed.tool.toLowerCase() : '';
2559
- const actionLower = typeof parsed.actionName === 'string' ? parsed.actionName.toLowerCase() : '';
2560
- if (boundSession?.id) {
2561
- if (parsed.type === 'code_progress' && typeof parsed.path === 'string') {
2562
- recordSessionTouchedFile(boundSession.id, parsed.path);
2563
- } else if (
2564
- (parsed.type === 'step_complete' || parsed.type === 'tool_result')
2565
- && MUTATING_FILE_TOOLS.has(toolLower)
2566
- && parsed.args
2567
- ) {
2568
- for (const key of ['path', 'filePath', 'file_path', 'targetFile', 'filename', 'file', 'destination']) {
2569
- recordSessionTouchedFile(boundSession.id, parsed.args[key]);
2570
- }
2571
- } else if (parsed.type === 'notice' && MUTATING_FILE_TOOLS.has(actionLower) && parsed.detail) {
2572
- recordSessionTouchedFile(boundSession.id, parsed.detail);
2573
- }
2574
- }
2575
- const isBrowserTool = toolLower.includes('browser');
2576
- const isComputerTool = toolLower.includes('computer_use') || toolLower.includes('desktop_act');
2577
- if ((parsed.type === 'step_start' || parsed.type === 'tool_start') && (isBrowserTool || isComputerTool)) {
2578
- if (isBrowserTool) browserControlOwner = 'agent';
2579
- const detail = isBrowserTool && Array.isArray(parsed.args?.actions) && parsed.args.actions[0]
2580
- ? String((parsed.args.actions[0] as Record<string, unknown>).type || 'browser.act')
2581
- : String(parsed.args?.action || parsed.tool || '');
2582
- browserAgentActivity = {
2583
- active: true,
2584
- tool: parsed.tool || 'browser.act',
2585
- detail: detail.slice(0, 80),
2586
- updatedAt: Date.now()
2587
- };
2588
- broadcastBrowserNotice({
2589
- type: 'agent_activity',
2590
- controlOwner: browserControlOwner,
2591
- agentActivity: browserAgentActivity
2592
- });
2593
- } else if ((parsed.type === 'step_complete' || parsed.type === 'step_error' || parsed.type === 'tool_complete')
2594
- && (isBrowserTool || isComputerTool)) {
2595
- browserAgentActivity = { active: false, tool: '', detail: '', updatedAt: Date.now() };
2596
- broadcastBrowserNotice({
2597
- type: 'agent_activity',
2598
- controlOwner: browserControlOwner,
2599
- agentActivity: browserAgentActivity
2600
- });
2601
- }
2602
- } catch {
2603
- // pass raw frame through untouched
2604
- }
2605
- if (runRef) pushRunFrame(runRef, clean);
2606
- };
2607
-
2608
- const wrappedSink = { readyState: 1, send: emitFrame };
2609
- const loop = loopFactory(wrappedSink, taskId, effectivePrompt, {
2610
- workspaceRoot,
2611
- mode,
2612
- sessionId: boundSession?.id,
2613
- provider: providerOverride,
2614
- model: modelOverride
2615
- });
2616
-
2617
- const run: SessionActiveRun = {
2618
- key: runKey,
2619
- sessionId: boundSession?.id || null,
2620
- taskId,
2621
- prompt,
2622
- startedAt: Date.now(),
2623
- status: 'running',
2624
- userStopped: false,
2625
- loop,
2626
- frames: [],
2627
- bufferedBytes: 0,
2628
- subscribers: new Set(),
2629
- doneSubscribers: new Set()
2630
- };
2631
- runRef = run;
2632
- activeRuns.set(runKey, run);
2633
-
2634
- if (boundSession) {
2635
- pushRunFrame(run, JSON.stringify({
2636
- type: 'session_bound',
2637
- sessionId: boundSession.id,
2638
- title: boundSession.title,
2639
- attachments: attachedPaths
2640
- }));
2641
- }
2642
-
2643
- // Attach current HTTP response BEFORE starting loop; detaching later never aborts loop.
2644
- attachRunStream(req, res, run, true);
2645
-
2646
- void (async () => {
2647
- try {
2648
- await loop.run();
2649
- if (boundSession && hasCustomFactory && collectedAssistantText.trim()) {
2650
- const latest = getSession(boundSession.id);
2651
- if (latest) {
2652
- const nextMessages: SessionMessage[] = [
2653
- ...latest.messages,
2654
- { role: 'user', content: prompt },
2655
- { role: 'assistant', content: collectedAssistantText.trim() }
2656
- ];
2657
- saveSessionMessages(boundSession.id, nextMessages);
2658
- }
2659
- }
2660
- const refreshed = boundSession ? getSession(boundSession.id) : null;
2661
- if (run.userStopped) {
2662
- run.status = 'stopped';
2663
- pushRunFrame(run, JSON.stringify({
2664
- type: 'stopped',
2665
- taskId,
2666
- sessionId: boundSession?.id || null,
2667
- title: refreshed?.title || boundSession?.title || null,
2668
- userStopped: true
2669
- }));
2670
- } else {
2671
- run.status = 'completed';
2672
- pushRunFrame(run, JSON.stringify({
2673
- type: 'done',
2674
- taskId,
2675
- sessionId: boundSession?.id || null,
2676
- title: refreshed?.title || boundSession?.title || null
2677
- }));
2678
- }
2679
- } catch (err: unknown) {
2680
- run.status = run.userStopped ? 'stopped' : 'errored';
2681
- if (run.userStopped) {
2682
- pushRunFrame(run, JSON.stringify({
2683
- type: 'stopped',
2684
- taskId,
2685
- sessionId: boundSession?.id || null,
2686
- userStopped: true
2687
- }));
2688
- } else if (err instanceof EntitlementAccessError && err.code === 'DAILY_LIMIT_REACHED') {
2689
- pushRunFrame(run, JSON.stringify({
2690
- type: 'error',
2691
- code: 'DAILY_LIMIT_REACHED',
2692
- message: err.message || DAILY_LIMIT_SUPPORT_MESSAGE
2693
- }));
2694
- } else {
2695
- auditLog.log({
2696
- event: 'skybridge_chat_error',
2697
- taskId,
2698
- detail: redactProviderSecrets(err instanceof Error ? err.message : String(err)).slice(0, 300)
2699
- });
2700
- pushRunFrame(run, JSON.stringify({
2701
- type: 'error',
2702
- message: 'Task failed. Inspect local audit log or run `/doctor --report` for sanitized details.'
2703
- }));
2704
- }
2705
- } finally {
2706
- for (const doneCb of [...run.doneSubscribers]) {
2707
- try { doneCb(); } catch { /* ignore */ }
2708
- }
2709
- run.subscribers.clear();
2710
- run.doneSubscribers.clear();
2711
- if (activeRuns.get(runKey) === run) {
2712
- activeRuns.delete(runKey);
2713
- }
2714
- }
2715
- })();
2716
- return;
2717
- }
2718
-
232
+ if (await handleCoreRoutes(req, res, parsedUrl, ctx)) return;
233
+ if (await handleWorkspaceRoutes(req, res, parsedUrl, ctx)) return;
234
+ if (await handleBrowserRoutes(req, res, parsedUrl, ctx)) return;
235
+ if (await handleTerminalRoutes(req, res, parsedUrl, ctx)) return;
236
+ if (await handleChatRoutes(req, res, parsedUrl, ctx)) return;
2719
237
  sendJson(res, 404, { error: 'Unknown Skybridge API endpoint.' });
2720
238
  } catch (err: unknown) {
2721
239
  const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as any).code) : '';
@@ -2734,7 +252,6 @@ export async function startSkybridgeServer(options: StartSkybridgeOptions = {}):
2734
252
  }
2735
253
  });
2736
254
 
2737
- // Disable Node's default 5-minute requestTimeout so long AgentLoop runs never drop mid-stream.
2738
255
  server.requestTimeout = 0;
2739
256
  server.timeout = 0;
2740
257
  server.headersTimeout = 60_000;
@@ -2773,7 +290,8 @@ export async function startSkybridgeServer(options: StartSkybridgeOptions = {}):
2773
290
  Promise.allSettled([
2774
291
  Promise.resolve().then(() => closeAllMcpServers()),
2775
292
  Promise.resolve().then(() => lspSessionManager.shutdownAll()),
2776
- Promise.resolve().then(() => backgroundTaskManager.stopAll())
293
+ Promise.resolve().then(() => backgroundTaskManager.stopAll()),
294
+ Promise.resolve().then(() => ptyTerminalManager.closeAll())
2777
295
  ]),
2778
296
  new Promise<void>((resolve) => {
2779
297
  const timer = setTimeout(resolve, 2500);