@causyne/agent 1.20.124 → 1.20.128

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/bin/causyne.js +1 -1
  2. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  3. package/package.json +6 -4
  4. package/src/acp/protocol.ts +19 -1
  5. package/src/acp/server.js +282 -8
  6. package/src/acp/server.ts +284 -8
  7. package/src/agent/abortableDelay.js +2 -2
  8. package/src/agent/abortableDelay.ts +2 -2
  9. package/src/agent/errorClassifier.js +9 -1
  10. package/src/agent/errorClassifier.ts +8 -1
  11. package/src/agentLoop.js +142 -53
  12. package/src/agentLoop.ts +151 -50
  13. package/src/approvalPolicy.js +34 -10
  14. package/src/approvalPolicy.ts +42 -11
  15. package/src/browser/causyneBrowser.js +61 -3
  16. package/src/browser/causyneBrowser.ts +65 -3
  17. package/src/browser/urlPolicy.js +14 -1
  18. package/src/browser/urlPolicy.ts +12 -1
  19. package/src/cliMode.js +21 -9
  20. package/src/cliMode.ts +20 -8
  21. package/src/commands.js +365 -45
  22. package/src/commands.ts +403 -45
  23. package/src/config.js +19 -4
  24. package/src/config.ts +18 -4
  25. package/src/core/contextCompactor.js +54 -7
  26. package/src/core/contextCompactor.ts +63 -7
  27. package/src/core/goalLoop.js +257 -0
  28. package/src/core/goalLoop.ts +310 -0
  29. package/src/entrypoint.js +135 -3
  30. package/src/entrypoint.ts +136 -3
  31. package/src/game/causyneCoreBridge.js +686 -0
  32. package/src/game/causyneCoreBridge.ts +702 -0
  33. package/src/game/gameLauncher.js +287 -0
  34. package/src/game/gameLauncher.ts +352 -0
  35. package/src/game/gameProvisioner.js +425 -0
  36. package/src/game/gameProvisioner.ts +488 -0
  37. package/src/headlessCli.js +19 -12
  38. package/src/headlessCli.ts +22 -8
  39. package/src/infra/atomicWriter.js +40 -4
  40. package/src/infra/atomicWriter.ts +36 -4
  41. package/src/launchIntent.js +73 -3
  42. package/src/launchIntent.ts +76 -3
  43. package/src/lsp/lspClient.js +83 -12
  44. package/src/lsp/lspClient.ts +75 -12
  45. package/src/mcp/mcpRegistry.js +75 -8
  46. package/src/mcp/mcpRegistry.ts +70 -7
  47. package/src/memory/contextBudget.js +2 -0
  48. package/src/memory/contextBudget.ts +1 -0
  49. package/src/memory/episodicStore.js +40 -0
  50. package/src/memory/episodicStore.ts +46 -0
  51. package/src/memory.js +67 -0
  52. package/src/memory.ts +65 -0
  53. package/src/modelVariants.js +45 -0
  54. package/src/modelVariants.ts +54 -0
  55. package/src/outputRecovery.js +3 -2
  56. package/src/outputRecovery.ts +4 -2
  57. package/src/permissionPresets.js +327 -0
  58. package/src/permissionPresets.ts +361 -0
  59. package/src/personalization.js +365 -0
  60. package/src/personalization.ts +471 -0
  61. package/src/projectInstructions.js +30 -10
  62. package/src/projectInstructions.ts +31 -12
  63. package/src/providers/acp.js +3 -2
  64. package/src/providers/acp.ts +3 -2
  65. package/src/providers/antigravity.js +64 -9
  66. package/src/providers/antigravity.ts +75 -9
  67. package/src/providers/byokHttp.js +7 -1
  68. package/src/providers/byokHttp.ts +6 -1
  69. package/src/providers/byokStream.js +21 -8
  70. package/src/providers/byokStream.ts +17 -7
  71. package/src/providers/dashscope-byok.js +21 -5
  72. package/src/providers/dashscope-byok.ts +29 -11
  73. package/src/providers/moonshot.js +26 -7
  74. package/src/providers/moonshot.ts +34 -13
  75. package/src/providers/muse.js +6 -0
  76. package/src/providers/muse.ts +8 -0
  77. package/src/providers/ollama.js +39 -7
  78. package/src/providers/ollama.ts +36 -7
  79. package/src/providers/openai-compatible.js +16 -3
  80. package/src/providers/openai-compatible.ts +13 -3
  81. package/src/providers/openai.js +62 -4
  82. package/src/providers/openai.ts +50 -4
  83. package/src/providers/openrouter.js +19 -4
  84. package/src/providers/openrouter.ts +21 -4
  85. package/src/providers/qwen-byok.js +21 -5
  86. package/src/providers/qwen-byok.ts +29 -11
  87. package/src/providers/xai.js +26 -10
  88. package/src/providers/xai.ts +34 -16
  89. package/src/reporting.js +4 -2
  90. package/src/reporting.ts +4 -2
  91. package/src/sandbox.js +34 -0
  92. package/src/sandbox.ts +43 -0
  93. package/src/scheduler/scheduler.js +372 -0
  94. package/src/scheduler/scheduler.ts +433 -0
  95. package/src/sessionSearchIndex.js +267 -0
  96. package/src/sessionSearchIndex.ts +311 -0
  97. package/src/skillsManager.js +2 -3
  98. package/src/skillsManager.ts +2 -3
  99. package/src/toolPacks.js +6 -0
  100. package/src/toolPacks.ts +6 -0
  101. package/src/tools/applyPatch.js +1 -1
  102. package/src/tools/applyPatch.ts +1 -1
  103. package/src/tools/generateMediaViaApi.js +4 -3
  104. package/src/tools/generateMediaViaApi.ts +4 -3
  105. package/src/tools/memoryWrite.js +15 -1
  106. package/src/tools/memoryWrite.ts +16 -1
  107. package/src/tools/nativeEngine.js +2 -2
  108. package/src/tools/nativeEngine.ts +2 -2
  109. package/src/tools/openSourceToolProvisioner.js +2 -2
  110. package/src/tools/openSourceToolProvisioner.ts +2 -2
  111. package/src/tools/osSandbox.js +1 -1
  112. package/src/tools/osSandbox.ts +1 -1
  113. package/src/tools/payloadSanitizer.js +0 -1
  114. package/src/tools/payloadSanitizer.ts +0 -1
  115. package/src/tools/pdfReader.js +122 -20
  116. package/src/tools/pdfReader.ts +111 -20
  117. package/src/tools/presentDeliverable.js +103 -0
  118. package/src/tools/presentDeliverable.ts +127 -0
  119. package/src/tools/ptcRuntime.js +444 -0
  120. package/src/tools/ptcRuntime.ts +490 -0
  121. package/src/tools/ptyTerminal.js +1108 -0
  122. package/src/tools/ptyTerminal.ts +1245 -0
  123. package/src/tools/registry.js +21 -12
  124. package/src/tools/registry.ts +21 -12
  125. package/src/tools/toolOutputStore.js +26 -4
  126. package/src/tools/toolOutputStore.ts +22 -4
  127. package/src/tools/webFetch.js +158 -11
  128. package/src/tools/webFetch.ts +145 -11
  129. package/src/tools/webSearch.js +123 -36
  130. package/src/tools/webSearch.ts +124 -33
  131. package/src/tui/banner.js +5 -1
  132. package/src/tui/banner.ts +6 -1
  133. package/src/tui/chatRenderer.js +1 -2
  134. package/src/tui/chatRenderer.ts +1 -2
  135. package/src/tui/completion.js +1 -0
  136. package/src/tui/completion.ts +1 -0
  137. package/src/tui/composerControls.js +111 -27
  138. package/src/tui/composerControls.ts +124 -28
  139. package/src/tui/dialogs.js +3 -16
  140. package/src/tui/dialogs.ts +3 -16
  141. package/src/tui/home.js +1 -0
  142. package/src/tui/home.ts +1 -0
  143. package/src/tui/invocation.js +1 -2
  144. package/src/tui/invocation.ts +1 -2
  145. package/src/tui/modelPicker.js +22 -12
  146. package/src/tui/modelPicker.ts +22 -12
  147. package/src/tui/overlay.js +2 -5
  148. package/src/tui/overlay.ts +2 -5
  149. package/src/tui/prompt.js +6 -4
  150. package/src/tui/prompt.ts +6 -4
  151. package/src/tui/selectList.js +4 -12
  152. package/src/tui/selectList.ts +4 -12
  153. package/src/tui/setup.js +22 -9
  154. package/src/tui/setup.ts +26 -9
  155. package/src/tui/statusLine.ts +2 -0
  156. package/src/web/client/browserPanel.js +905 -0
  157. package/src/web/client/browserPanel.ts +872 -0
  158. package/src/web/client/chatStream.js +321 -0
  159. package/src/web/client/chatStream.ts +297 -0
  160. package/src/web/client/cliPanel.js +165 -0
  161. package/src/web/client/cliPanel.ts +171 -0
  162. package/src/web/client/composer.js +204 -0
  163. package/src/web/client/composer.ts +209 -0
  164. package/src/web/client/diffPanel.js +176 -0
  165. package/src/web/client/diffPanel.ts +203 -0
  166. package/src/web/client/dom.js +271 -0
  167. package/src/web/client/dom.ts +272 -0
  168. package/src/web/client/filesAndCanvas.js +233 -0
  169. package/src/web/client/filesAndCanvas.ts +240 -0
  170. package/src/web/client/gameLauncherUi.js +78 -0
  171. package/src/web/client/gameLauncherUi.ts +78 -0
  172. package/src/web/client/main.js +316 -0
  173. package/src/web/client/main.ts +391 -0
  174. package/src/web/client/markdown.js +364 -0
  175. package/src/web/client/markdown.ts +373 -0
  176. package/src/web/client/modelPicker.js +455 -0
  177. package/src/web/client/modelPicker.ts +451 -0
  178. package/src/web/client/permissionPresetsUi.js +307 -0
  179. package/src/web/client/permissionPresetsUi.ts +333 -0
  180. package/src/web/client/sessions.js +353 -0
  181. package/src/web/client/sessions.ts +372 -0
  182. package/src/web/client/settingsModal.js +824 -0
  183. package/src/web/client/settingsModal.ts +959 -0
  184. package/src/web/client/state.js +280 -0
  185. package/src/web/client/state.ts +259 -0
  186. package/src/web/client/streamSmoother.js +127 -0
  187. package/src/web/client/streamSmoother.ts +119 -0
  188. package/src/web/client/studioLayout.js +89 -0
  189. package/src/web/client/studioLayout.ts +103 -0
  190. package/src/web/client/studioShell.js +660 -0
  191. package/src/web/client/studioShell.ts +672 -0
  192. package/src/web/client/studioStart.js +77 -0
  193. package/src/web/client/studioStart.ts +89 -0
  194. package/src/web/client/terminalPanel.js +606 -0
  195. package/src/web/client/terminalPanel.ts +632 -0
  196. package/src/web/client/terminalTheme.js +249 -0
  197. package/src/web/client/terminalTheme.ts +258 -0
  198. package/src/web/client/turnView.js +934 -0
  199. package/src/web/client/turnView.ts +981 -0
  200. package/src/web/client/types.js +1 -0
  201. package/src/web/client/types.ts +322 -0
  202. package/src/web/client/validators.js +147 -0
  203. package/src/web/client/validators.ts +140 -0
  204. package/src/web/server/activeRuns.js +152 -0
  205. package/src/web/server/activeRuns.ts +171 -0
  206. package/src/web/server/routesBrowser.js +409 -0
  207. package/src/web/server/routesBrowser.ts +435 -0
  208. package/src/web/server/routesChat.js +304 -0
  209. package/src/web/server/routesChat.ts +347 -0
  210. package/src/web/server/routesCore.js +472 -0
  211. package/src/web/server/routesCore.ts +522 -0
  212. package/src/web/server/routesSettings.js +344 -0
  213. package/src/web/server/routesSettings.ts +397 -0
  214. package/src/web/server/routesTerminal.js +162 -0
  215. package/src/web/server/routesTerminal.ts +182 -0
  216. package/src/web/server/routesWorkspace.js +510 -0
  217. package/src/web/server/routesWorkspace.ts +546 -0
  218. package/src/web/server/security.js +98 -0
  219. package/src/web/server/security.ts +108 -0
  220. package/src/web/server/sessionTranscript.js +586 -0
  221. package/src/web/server/sessionTranscript.ts +566 -0
  222. package/src/web/server/staticAssets.js +104 -0
  223. package/src/web/server/staticAssets.ts +116 -0
  224. package/src/web/server/types.js +1 -0
  225. package/src/web/server/types.ts +135 -0
  226. package/src/web/server/workspaceFiles.js +368 -0
  227. package/src/web/server/workspaceFiles.ts +363 -0
  228. package/src/web/skybridgeServer.js +78 -2448
  229. package/src/web/skybridgeServer.ts +120 -2600
  230. package/src/web/skybridgeUi.js +20 -450
  231. package/src/web/skybridgeUi.ts +24 -455
  232. package/src/web/styles/agent.css +380 -0
  233. package/src/web/styles/composer.css +193 -0
  234. package/src/web/styles/overlays.css +935 -0
  235. package/src/web/styles/shell.css +387 -0
  236. package/src/web/styles/studio.css +951 -0
  237. package/src/web/styles/thread.css +221 -0
  238. package/src/web/styles/tokens.css +94 -0
  239. package/src/web/ui/brandMark.js +73 -0
  240. package/src/web/ui/brandMark.ts +82 -0
  241. package/src/web/ui/modalsTemplate.js +388 -0
  242. package/src/web/ui/modalsTemplate.ts +388 -0
  243. package/src/web/ui/sidebarTemplate.js +63 -0
  244. package/src/web/ui/sidebarTemplate.ts +64 -0
  245. package/src/web/ui/studioTemplate.js +256 -0
  246. package/src/web/ui/studioTemplate.ts +256 -0
  247. package/src/web/ui/workspaceTemplate.js +72 -0
  248. package/src/web/ui/workspaceTemplate.ts +73 -0
  249. package/src/worktreeManager.js +16 -1
  250. package/src/worktreeManager.ts +22 -1
  251. package/src/web/skybridgeClientScript.js +0 -3951
  252. package/src/web/skybridgeClientScript.ts +0 -3952
  253. package/src/web/skybridgeStyles.js +0 -827
  254. package/src/web/skybridgeStyles.ts +0 -828
@@ -0,0 +1,686 @@
1
+ /**
2
+ * Authenticated loopback-only Direct Core SSE Bridge for Causyne Game.
3
+ *
4
+ * Mirrors Causyne Web GUI (Skybridge): Causyne Game operates as a thin visual
5
+ * shell directly over Causyne Agent's warm in-process core (`AgentLoop`,
6
+ * `mcpRegistry`, `sessionJournal`, and `src/licensing/` entitlement gate).
7
+ *
8
+ * Security invariants:
9
+ * - Binds strictly to `127.0.0.1` on an ephemeral port (never wildcard/LAN).
10
+ * - Requires a 256-bit random Bearer token verified via `crypto.timingSafeEqual`.
11
+ * - Enforces exact loopback `Host` header to defeat DNS rebinding.
12
+ * - Validates every workspace root via `fs.realpathSync` + `isBlockedWorkspaceRoot`.
13
+ * - Accepts stdio-only session-scoped MCP servers validated via `McpClient.validateDefinition`.
14
+ * - Zero hidden daemons: starts with `launchGameStudio()` and shuts down with `stopGameStudio()`.
15
+ */
16
+ import crypto from 'node:crypto';
17
+ import fs from 'node:fs';
18
+ import http, {} from 'node:http';
19
+ import path from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+ import { AgentLoop } from '../agentLoop.js';
22
+ import { createApprovalScope } from '../approvalGrants.js';
23
+ import { loadConfig } from '../config.js';
24
+ import { getAvailableProvidersOverview, getLiveAntigravityModels, getModelVariantsForPeer } from '../dynamicCatalogue.js';
25
+ import { LICENSE_ENFORCEMENT_ENABLED } from '../licensing/policy.js';
26
+ import { McpClient } from '../mcp/mcpClient.js';
27
+ import { registerSessionMcpServers, unregisterSessionMcpServers } from '../mcp/mcpRegistry.js';
28
+ import { DEFAULT_MODEL_BY_PROVIDER, MODEL_CATALOGUE, PEER_MODEL_CATALOGUE } from '../modelCatalogue.js';
29
+ import { resolveModelVariants } from '../modelVariants.js';
30
+ import { isAcpProvider } from '../providers/acp.js';
31
+ import { isBlockedWorkspaceRoot } from '../sandboxPolicy.js';
32
+ import { createSession, getSession } from '../sessionJournal.js';
33
+ const MAX_BODY_BYTES = 4 * 1024 * 1024;
34
+ const MAX_PROMPT_BYTES = 2 * 1024 * 1024;
35
+ const MAX_SESSION_MCP_SERVERS = 16;
36
+ const HEARTBEAT_INTERVAL_MS = 15_000;
37
+ const DECISION_TIMEOUT_MS = 5 * 60_000;
38
+ const FORBIDDEN_ENV_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
39
+ function readPackageVersion() {
40
+ try {
41
+ const here = path.dirname(fileURLToPath(import.meta.url));
42
+ const pkgPath = path.resolve(here, '..', '..', 'package.json');
43
+ const parsed = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
44
+ return typeof parsed.version === 'string' && parsed.version.trim() ? parsed.version.trim() : '0.0.0';
45
+ }
46
+ catch {
47
+ return '0.0.0';
48
+ }
49
+ }
50
+ function sendJson(res, status, payload) {
51
+ if (res.writableEnded)
52
+ return;
53
+ const body = JSON.stringify(payload);
54
+ res.writeHead(status, {
55
+ 'Content-Type': 'application/json; charset=utf-8',
56
+ 'Cache-Control': 'no-store',
57
+ 'X-Content-Type-Options': 'nosniff'
58
+ });
59
+ res.end(body);
60
+ }
61
+ function sendSse(res, event, data) {
62
+ if (res.writableEnded || res.destroyed)
63
+ return;
64
+ try {
65
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
66
+ }
67
+ catch {
68
+ // Client disconnected.
69
+ }
70
+ }
71
+ function isAuthorized(req, expectedToken) {
72
+ const raw = req.headers.authorization;
73
+ if (typeof raw !== 'string' || !raw.startsWith('Bearer '))
74
+ return false;
75
+ const provided = raw.slice('Bearer '.length).trim();
76
+ const a = Buffer.from(provided, 'utf8');
77
+ const b = Buffer.from(expectedToken, 'utf8');
78
+ if (a.length !== b.length || a.length === 0)
79
+ return false;
80
+ return crypto.timingSafeEqual(a, b);
81
+ }
82
+ function isAllowedHost(req, port) {
83
+ const host = String(req.headers.host || '').trim().toLowerCase();
84
+ return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
85
+ }
86
+ async function readJsonBody(req) {
87
+ const chunks = [];
88
+ let total = 0;
89
+ for await (const chunk of req) {
90
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
91
+ total += buf.byteLength;
92
+ if (total > MAX_BODY_BYTES) {
93
+ throw Object.assign(new Error('Request body too large'), { status: 413 });
94
+ }
95
+ chunks.push(buf);
96
+ }
97
+ const raw = Buffer.concat(chunks, total).toString('utf8').trim();
98
+ if (!raw)
99
+ return {};
100
+ let parsed;
101
+ try {
102
+ parsed = JSON.parse(raw);
103
+ }
104
+ catch {
105
+ throw Object.assign(new Error('Invalid JSON request body'), { status: 400 });
106
+ }
107
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
108
+ throw Object.assign(new Error('Request body must be a JSON object'), { status: 400 });
109
+ }
110
+ return parsed;
111
+ }
112
+ function resolveSafeWorkspace(rawCwd) {
113
+ if (typeof rawCwd !== 'string' || !rawCwd.trim() || rawCwd.includes('\0')) {
114
+ throw Object.assign(new Error('cwd is required'), { status: 400 });
115
+ }
116
+ let resolved;
117
+ try {
118
+ resolved = fs.realpathSync(path.resolve(rawCwd.trim()));
119
+ if (!fs.statSync(resolved).isDirectory())
120
+ throw new Error('not a directory');
121
+ }
122
+ catch {
123
+ throw Object.assign(new Error('cwd is not an accessible directory'), { status: 400 });
124
+ }
125
+ if (isBlockedWorkspaceRoot(resolved)) {
126
+ throw Object.assign(new Error('cwd points to a blocked system directory'), { status: 403 });
127
+ }
128
+ return resolved;
129
+ }
130
+ function parseStdioMcpServers(raw, cwd) {
131
+ if (raw === undefined || raw === null)
132
+ return [];
133
+ if (!Array.isArray(raw)) {
134
+ throw Object.assign(new Error('mcpServers must be an array'), { status: 400 });
135
+ }
136
+ if (raw.length > MAX_SESSION_MCP_SERVERS) {
137
+ throw Object.assign(new Error(`Maximum ${MAX_SESSION_MCP_SERVERS} MCP servers exceeded`), { status: 400 });
138
+ }
139
+ const defs = [];
140
+ for (const entry of raw) {
141
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
142
+ throw Object.assign(new Error('Each MCP server must be an object'), { status: 400 });
143
+ }
144
+ const item = entry;
145
+ const rawType = typeof item.type === 'string' ? item.type.trim().toLowerCase() : '';
146
+ if (rawType === 'http' || rawType === 'sse' || typeof item.url === 'string') {
147
+ throw Object.assign(new Error('Only stdio MCP servers are accepted by Causyne Core Bridge'), { status: 400 });
148
+ }
149
+ if (typeof item.name !== 'string' || !item.name.trim()) {
150
+ throw Object.assign(new Error('MCP server requires a non-empty name'), { status: 400 });
151
+ }
152
+ if (typeof item.command !== 'string' || !item.command.trim()) {
153
+ throw Object.assign(new Error('MCP server requires a non-empty command'), { status: 400 });
154
+ }
155
+ if (!Array.isArray(item.args) || !item.args.every((a) => typeof a === 'string')) {
156
+ throw Object.assign(new Error('MCP server requires string[] args'), { status: 400 });
157
+ }
158
+ let env;
159
+ if (item.env !== undefined) {
160
+ const mapped = Object.create(null);
161
+ if (Array.isArray(item.env)) {
162
+ for (const pair of item.env) {
163
+ if (!pair || typeof pair !== 'object' || Array.isArray(pair)) {
164
+ throw Object.assign(new Error('MCP env array entries must be { name, value }'), { status: 400 });
165
+ }
166
+ const rec = pair;
167
+ if (typeof rec.name !== 'string' || !rec.name || typeof rec.value !== 'string') {
168
+ throw Object.assign(new Error('MCP env entries require string name and value'), { status: 400 });
169
+ }
170
+ if (!FORBIDDEN_ENV_KEYS.has(rec.name))
171
+ mapped[rec.name] = rec.value;
172
+ }
173
+ }
174
+ else if (typeof item.env === 'object' && item.env !== null) {
175
+ for (const [k, v] of Object.entries(item.env)) {
176
+ if (typeof v !== 'string') {
177
+ throw Object.assign(new Error('MCP env values must be strings'), { status: 400 });
178
+ }
179
+ if (!FORBIDDEN_ENV_KEYS.has(k))
180
+ mapped[k] = v;
181
+ }
182
+ }
183
+ else {
184
+ throw Object.assign(new Error('Invalid MCP env shape'), { status: 400 });
185
+ }
186
+ if (Object.keys(mapped).length > 0)
187
+ env = { ...mapped };
188
+ }
189
+ const def = {
190
+ name: item.name.trim(),
191
+ command: item.command.trim(),
192
+ args: [...item.args],
193
+ cwd,
194
+ ...(env ? { env } : {})
195
+ };
196
+ const problem = McpClient.validateDefinition(def);
197
+ if (problem) {
198
+ throw Object.assign(new Error(`Invalid MCP server "${def.name}": ${problem}`), { status: 400 });
199
+ }
200
+ defs.push(def);
201
+ }
202
+ return defs;
203
+ }
204
+ function buildModelsPayload(version) {
205
+ const config = loadConfig();
206
+ const provider = typeof config.provider === 'string' && config.provider.trim()
207
+ ? config.provider.trim()
208
+ : 'deepseek';
209
+ const configuredModel = typeof config.model === 'string' && config.model.trim()
210
+ ? config.model.trim()
211
+ : (DEFAULT_MODEL_BY_PROVIDER[provider.toLowerCase()] || '');
212
+ const overview = getAvailableProvidersOverview(config);
213
+ const norm = provider.toLowerCase();
214
+ const peerKey = norm.startsWith('acp/') ? norm.slice(4) : norm;
215
+ const seen = new Set();
216
+ const modelIds = [];
217
+ const add = (id) => {
218
+ const clean = id.trim();
219
+ if (!clean || seen.has(clean))
220
+ return;
221
+ seen.add(clean);
222
+ modelIds.push(clean);
223
+ };
224
+ if (configuredModel)
225
+ add(configuredModel);
226
+ const peerMatch = overview.acp.find((p) => p.providerKey.toLowerCase() === norm || p.id.toLowerCase() === peerKey);
227
+ if (peerMatch) {
228
+ for (const m of peerMatch.models)
229
+ add(m);
230
+ }
231
+ const byokMatch = overview.byok.find((p) => p.id.toLowerCase() === norm);
232
+ if (byokMatch) {
233
+ for (const m of byokMatch.models)
234
+ add(m);
235
+ }
236
+ if (Object.hasOwn(PEER_MODEL_CATALOGUE, peerKey)) {
237
+ for (const m of PEER_MODEL_CATALOGUE[peerKey] ?? [])
238
+ add(m);
239
+ }
240
+ if (Object.hasOwn(MODEL_CATALOGUE, norm)) {
241
+ for (const m of MODEL_CATALOGUE[norm] ?? [])
242
+ add(m);
243
+ }
244
+ const liveAgyModels = (norm.includes('antigravity') || norm === 'agy')
245
+ ? getLiveAntigravityModels(config)
246
+ : undefined;
247
+ const models = modelIds.slice(0, 40).map((id) => {
248
+ const peerModelVariants = isAcpProvider(provider) ? getModelVariantsForPeer(provider, id, config) : undefined;
249
+ const spec = resolveModelVariants({
250
+ provider,
251
+ model: id,
252
+ currentVariant: typeof config.reasoningEffort === 'string' ? config.reasoningEffort : null,
253
+ peerModelVariants,
254
+ availableAgyModels: liveAgyModels && liveAgyModels.length > 0 ? liveAgyModels : undefined
255
+ });
256
+ const reasoningLevels = spec.supported ? spec.options.map((o) => o.id) : [];
257
+ return {
258
+ id,
259
+ label: id,
260
+ ...(reasoningLevels.length > 0 ? { reasoningLevels } : {}),
261
+ ...(spec.defaultVariant ? { defaultReasoning: spec.defaultVariant } : {})
262
+ };
263
+ });
264
+ return {
265
+ ok: true,
266
+ agent: 'causyne',
267
+ version,
268
+ provider,
269
+ currentModel: configuredModel || modelIds[0] || undefined,
270
+ models
271
+ };
272
+ }
273
+ const MODELS_CACHE_TTL_MS = 30_000;
274
+ export async function startCausyneCoreBridge() {
275
+ const token = crypto.randomBytes(32).toString('hex');
276
+ const version = readPackageVersion();
277
+ const sessions = new Map();
278
+ const activeTurns = new Map();
279
+ let boundPort = 0;
280
+ let cachedModels = null;
281
+ const getModelsPayload = (forceRefresh) => {
282
+ const now = Date.now();
283
+ if (!forceRefresh && cachedModels && now < cachedModels.expiresAt) {
284
+ return cachedModels.payload;
285
+ }
286
+ const payload = buildModelsPayload(version);
287
+ cachedModels = { payload, expiresAt: now + MODELS_CACHE_TTL_MS };
288
+ return payload;
289
+ };
290
+ const server = http.createServer((req, res) => {
291
+ void (async () => {
292
+ if (!isAllowedHost(req, boundPort)) {
293
+ sendJson(res, 403, { ok: false, error: 'Invalid Host header' });
294
+ return;
295
+ }
296
+ if (!isAuthorized(req, token)) {
297
+ sendJson(res, 401, { ok: false, error: 'Unauthorized' });
298
+ return;
299
+ }
300
+ const parsedUrl = new URL(req.url || '/', `http://127.0.0.1:${boundPort}`);
301
+ const pathname = parsedUrl.pathname;
302
+ if (req.method === 'GET' && pathname === '/v1/health') {
303
+ sendJson(res, 200, {
304
+ ok: true,
305
+ agent: 'causyne',
306
+ version,
307
+ mode: 'direct-core',
308
+ licensingEnforced: LICENSE_ENFORCEMENT_ENABLED,
309
+ activeTurns: activeTurns.size
310
+ });
311
+ return;
312
+ }
313
+ if (req.method === 'GET' && pathname === '/v1/models') {
314
+ const forceRefresh = parsedUrl.searchParams.get('refresh') === '1';
315
+ sendJson(res, 200, getModelsPayload(forceRefresh));
316
+ return;
317
+ }
318
+ if (req.method === 'POST' && pathname === '/v1/cancel') {
319
+ const body = await readJsonBody(req);
320
+ const turnId = typeof body.turnId === 'string' ? body.turnId.trim() : '';
321
+ const active = turnId ? activeTurns.get(turnId) : undefined;
322
+ if (!active) {
323
+ sendJson(res, 200, { ok: true, cancelled: false });
324
+ return;
325
+ }
326
+ active.aborted = true;
327
+ for (const pending of active.pendingDecisions.values()) {
328
+ clearTimeout(pending.timer);
329
+ pending.resolve(null);
330
+ }
331
+ active.pendingDecisions.clear();
332
+ try {
333
+ active.loop?.abort();
334
+ }
335
+ catch { /* best-effort */ }
336
+ sendJson(res, 200, { ok: true, cancelled: true });
337
+ return;
338
+ }
339
+ if (req.method === 'POST' && pathname === '/v1/decision') {
340
+ const body = await readJsonBody(req);
341
+ const turnId = typeof body.turnId === 'string' ? body.turnId.trim() : '';
342
+ const requestId = typeof body.requestId === 'string' ? body.requestId.trim() : '';
343
+ const approved = body.approved === true;
344
+ const active = turnId ? activeTurns.get(turnId) : undefined;
345
+ const pending = active?.pendingDecisions.get(requestId);
346
+ if (!active || !pending) {
347
+ sendJson(res, 404, { ok: false, error: 'No pending decision found' });
348
+ return;
349
+ }
350
+ active.pendingDecisions.delete(requestId);
351
+ clearTimeout(pending.timer);
352
+ pending.resolve(approved
353
+ ? { optionId: 'allow_once', label: 'Allow once' }
354
+ : { optionId: 'reject_once', label: 'Deny' });
355
+ sendJson(res, 200, { ok: true });
356
+ return;
357
+ }
358
+ if (req.method === 'POST' && pathname === '/v1/turn') {
359
+ const body = await readJsonBody(req);
360
+ const cwd = resolveSafeWorkspace(body.cwd);
361
+ const prompt = typeof body.prompt === 'string' ? body.prompt : '';
362
+ if (!prompt.trim() || Buffer.byteLength(prompt, 'utf8') > MAX_PROMPT_BYTES) {
363
+ sendJson(res, 400, { ok: false, error: 'prompt must be non-empty and under 2 MiB' });
364
+ return;
365
+ }
366
+ const instructions = typeof body.instructions === 'string' && body.instructions.trim()
367
+ ? body.instructions.trim()
368
+ : undefined;
369
+ const model = typeof body.model === 'string' && body.model.trim() && body.model.trim() !== 'default'
370
+ ? body.model.trim()
371
+ : undefined;
372
+ const reasoning = typeof body.reasoning === 'string' && body.reasoning.trim() && body.reasoning.trim() !== 'default'
373
+ ? body.reasoning.trim()
374
+ : undefined;
375
+ const permissionMode = typeof body.permissionMode === 'string' ? body.permissionMode.trim().toLowerCase() : 'auto';
376
+ const requestedThreadId = typeof body.threadId === 'string' && body.threadId.trim()
377
+ ? body.threadId.trim()
378
+ : undefined;
379
+ const mcpDefs = parseStdioMcpServers(body.mcpServers, cwd);
380
+ let sessionState = requestedThreadId ? sessions.get(requestedThreadId) : undefined;
381
+ if (!sessionState) {
382
+ const existingRecord = requestedThreadId ? getSession(requestedThreadId) : null;
383
+ const record = existingRecord ?? createSession(cwd, prompt.slice(0, 80), false);
384
+ sessionState = {
385
+ id: record.id,
386
+ cwd,
387
+ approvalScope: createApprovalScope()
388
+ };
389
+ sessions.set(sessionState.id, sessionState);
390
+ }
391
+ const turnId = `core-${crypto.randomUUID()}`;
392
+ const turn = {
393
+ turnId,
394
+ sessionId: sessionState.id,
395
+ loop: null,
396
+ aborted: false,
397
+ pendingDecisions: new Map()
398
+ };
399
+ activeTurns.set(turnId, turn);
400
+ const mcpRegistrationKey = `${sessionState.id}:${turnId}`;
401
+ if (mcpDefs.length > 0) {
402
+ registerSessionMcpServers(mcpRegistrationKey, mcpDefs);
403
+ }
404
+ res.writeHead(200, {
405
+ 'Content-Type': 'text/event-stream; charset=utf-8',
406
+ 'Cache-Control': 'no-cache, no-transform',
407
+ 'Connection': 'keep-alive',
408
+ 'X-Content-Type-Options': 'nosniff'
409
+ });
410
+ res.flushHeaders?.();
411
+ sendSse(res, 'thread', { threadId: sessionState.id, turnId });
412
+ sendSse(res, 'status', { phase: 'thinking', label: 'Causyne Agent' });
413
+ const heartbeat = setInterval(() => {
414
+ if (!res.writableEnded && !res.destroyed) {
415
+ try {
416
+ res.write(': keepalive\n\n');
417
+ }
418
+ catch { /* ignore */ }
419
+ }
420
+ }, HEARTBEAT_INTERVAL_MS);
421
+ heartbeat.unref?.();
422
+ const onClientClose = () => {
423
+ if (turn.aborted)
424
+ return;
425
+ turn.aborted = true;
426
+ for (const pending of turn.pendingDecisions.values()) {
427
+ clearTimeout(pending.timer);
428
+ pending.resolve(null);
429
+ }
430
+ turn.pendingDecisions.clear();
431
+ try {
432
+ turn.loop?.abort();
433
+ }
434
+ catch { /* ignore */ }
435
+ };
436
+ req.once('close', onClientClose);
437
+ let lastAssistantStreamKey = '';
438
+ let lastAssistantText = '';
439
+ let lastReasoningText = '';
440
+ let failed = false;
441
+ let lastErrorMessage = '';
442
+ const sink = {
443
+ readyState: 1,
444
+ send: (rawPayload) => {
445
+ if (turn.aborted || res.writableEnded)
446
+ return;
447
+ let event;
448
+ try {
449
+ event = JSON.parse(rawPayload);
450
+ }
451
+ catch {
452
+ return;
453
+ }
454
+ if (!event || typeof event !== 'object' || typeof event.type !== 'string')
455
+ return;
456
+ switch (event.type) {
457
+ case 'agent_message': {
458
+ const text = String(event.content ?? '');
459
+ const key = typeof event.streamId === 'number' || typeof event.streamId === 'string'
460
+ ? String(event.streamId)
461
+ : '';
462
+ const sameStream = (Boolean(key) || event.streaming === true) && key === lastAssistantStreamKey;
463
+ const delta = sameStream && text.startsWith(lastAssistantText)
464
+ ? text.slice(lastAssistantText.length)
465
+ : text;
466
+ lastAssistantStreamKey = key;
467
+ lastAssistantText = text;
468
+ if (delta)
469
+ sendSse(res, 'message_delta', { id: key || `msg-${turnId}`, delta });
470
+ if (event.streaming !== true && text) {
471
+ sendSse(res, 'message_complete', { id: key || `msg-${turnId}`, text });
472
+ lastAssistantText = '';
473
+ }
474
+ return;
475
+ }
476
+ case 'agent_reasoning': {
477
+ const text = String(event.content ?? '');
478
+ const delta = text.startsWith(lastReasoningText) ? text.slice(lastReasoningText.length) : text;
479
+ lastReasoningText = event.streaming === true ? text : '';
480
+ if (delta)
481
+ sendSse(res, 'reasoning_delta', { id: `reason-${turnId}`, delta });
482
+ if (event.streaming !== true && text) {
483
+ sendSse(res, 'reasoning_complete', { id: `reason-${turnId}`, text });
484
+ }
485
+ return;
486
+ }
487
+ case 'status':
488
+ case 'notice': {
489
+ const label = String(event.message ?? '').trim();
490
+ if (label)
491
+ sendSse(res, 'status', { phase: 'thinking', label });
492
+ return;
493
+ }
494
+ case 'step_start': {
495
+ const callId = String(event.toolCallId ?? `tool-${crypto.randomUUID().slice(0, 8)}`);
496
+ const tool = String(event.tool ?? 'tool');
497
+ sendSse(res, 'tool_start', {
498
+ callId,
499
+ tool,
500
+ args: event.args && typeof event.args === 'object' ? event.args : {}
501
+ });
502
+ return;
503
+ }
504
+ case 'step_end':
505
+ case 'step_error': {
506
+ const callId = String(event.toolCallId ?? `tool-${crypto.randomUUID().slice(0, 8)}`);
507
+ const tool = String(event.tool ?? 'tool');
508
+ const ok = event.type === 'step_end' && event.success !== false;
509
+ sendSse(res, 'tool_end', {
510
+ callId,
511
+ tool,
512
+ status: ok ? 'completed' : 'failed',
513
+ result: event.result ?? event.output,
514
+ error: event.error ? String(event.error) : undefined,
515
+ args: event.args && typeof event.args === 'object' ? event.args : undefined
516
+ });
517
+ return;
518
+ }
519
+ case 'plan_update': {
520
+ if (Array.isArray(event.plan)) {
521
+ sendSse(res, 'plan', { entries: event.plan });
522
+ }
523
+ return;
524
+ }
525
+ case 'usage':
526
+ case 'token_usage': {
527
+ sendSse(res, 'usage', {
528
+ inputTokens: typeof event.inputTokens === 'number' ? event.inputTokens : undefined,
529
+ outputTokens: typeof event.outputTokens === 'number' ? event.outputTokens : undefined,
530
+ totalTokens: typeof event.totalTokens === 'number' ? event.totalTokens : undefined
531
+ });
532
+ return;
533
+ }
534
+ case 'error': {
535
+ failed = true;
536
+ lastErrorMessage = String(event.message ?? 'Causyne Core execution failed');
537
+ sendSse(res, 'error', { message: lastErrorMessage });
538
+ return;
539
+ }
540
+ default:
541
+ return;
542
+ }
543
+ }
544
+ };
545
+ const peerMcpServers = mcpDefs
546
+ .filter((def) => typeof def.command === 'string' && def.command.length > 0)
547
+ .map((def) => ({
548
+ name: def.name,
549
+ command: def.command,
550
+ args: Array.isArray(def.args) ? [...def.args] : [],
551
+ env: Object.entries(def.env ?? {}).map(([name, value]) => ({ name, value }))
552
+ }));
553
+ try {
554
+ const loop = new AgentLoop(sink, turnId, prompt, {
555
+ workspaceRoot: cwd,
556
+ memorySessionId: sessionState.id,
557
+ approvalScope: sessionState.approvalScope,
558
+ ...(model ? { model } : {}),
559
+ ...(reasoning ? { variant: reasoning } : {}),
560
+ ...(instructions ? { hostSystemInstructions: instructions } : {}),
561
+ ...(peerMcpServers.length > 0 ? { peerMcpServers } : {})
562
+ });
563
+ const autonomy = permissionMode === 'auto' ? 'C' : (permissionMode === 'ask' ? 'A' : 'B');
564
+ try {
565
+ loop.setAutonomyMode(autonomy);
566
+ }
567
+ catch { /* keep configured mode */ }
568
+ loop.waitForDecision = (request) => {
569
+ if (turn.aborted || res.writableEnded)
570
+ return Promise.resolve(null);
571
+ const rec = (request && typeof request === 'object' ? request : {});
572
+ const requestId = typeof rec.id === 'string' && rec.id ? rec.id : crypto.randomUUID();
573
+ const title = typeof rec.question === 'string' ? rec.question.slice(0, 300) : 'Approval required';
574
+ const detail = typeof rec.detail === 'string' ? rec.detail.slice(0, 1200) : '';
575
+ const kind = typeof rec.kind === 'string' ? rec.kind : 'other';
576
+ return new Promise((resolve) => {
577
+ const timer = setTimeout(() => {
578
+ turn.pendingDecisions.delete(requestId);
579
+ resolve(null);
580
+ }, DECISION_TIMEOUT_MS);
581
+ timer.unref?.();
582
+ turn.pendingDecisions.set(requestId, { resolve, timer });
583
+ sendSse(res, 'approval_request', { turnId, requestId, kind, title, detail });
584
+ });
585
+ };
586
+ turn.loop = loop;
587
+ await loop.run();
588
+ if (!turn.aborted) {
589
+ sendSse(res, 'done', {
590
+ ok: !failed,
591
+ stopReason: failed ? 'error' : 'end_turn',
592
+ ...(failed && lastErrorMessage ? { error: lastErrorMessage } : {})
593
+ });
594
+ }
595
+ }
596
+ catch (err) {
597
+ const msg = err instanceof Error ? err.message : String(err);
598
+ if (!turn.aborted) {
599
+ sendSse(res, 'error', { message: msg });
600
+ sendSse(res, 'done', { ok: false, stopReason: 'error', error: msg });
601
+ }
602
+ }
603
+ finally {
604
+ clearInterval(heartbeat);
605
+ req.off('close', onClientClose);
606
+ for (const pending of turn.pendingDecisions.values()) {
607
+ clearTimeout(pending.timer);
608
+ pending.resolve(null);
609
+ }
610
+ turn.pendingDecisions.clear();
611
+ turn.loop = null;
612
+ activeTurns.delete(turnId);
613
+ await unregisterSessionMcpServers(mcpRegistrationKey).catch(() => { });
614
+ if (!res.writableEnded)
615
+ res.end();
616
+ }
617
+ return;
618
+ }
619
+ sendJson(res, 404, { ok: false, error: 'Not found' });
620
+ })().catch((err) => {
621
+ const status = typeof err?.status === 'number'
622
+ ? err.status
623
+ : 500;
624
+ const safeError = status === 413
625
+ ? 'Request body too large'
626
+ : status === 400
627
+ ? 'Invalid JSON request body'
628
+ : status === 403
629
+ ? 'Forbidden'
630
+ : status === 404
631
+ ? 'Not found'
632
+ : 'Internal bridge error';
633
+ sendJson(res, status, {
634
+ ok: false,
635
+ error: safeError
636
+ });
637
+ });
638
+ });
639
+ await new Promise((resolve, reject) => {
640
+ server.once('error', reject);
641
+ server.listen(0, '127.0.0.1', () => {
642
+ server.off('error', reject);
643
+ const addr = server.address();
644
+ if (!addr || typeof addr !== 'object') {
645
+ reject(new Error('Failed to bind Causyne Core Bridge on 127.0.0.1'));
646
+ return;
647
+ }
648
+ boundPort = addr.port;
649
+ resolve();
650
+ });
651
+ });
652
+ const warmupTimer = setTimeout(() => {
653
+ try {
654
+ getModelsPayload(false);
655
+ }
656
+ catch { /* best-effort warmup */ }
657
+ }, 50);
658
+ warmupTimer.unref();
659
+ const origin = `http://127.0.0.1:${boundPort}`;
660
+ return {
661
+ url: origin,
662
+ origin,
663
+ port: boundPort,
664
+ token,
665
+ close: async () => {
666
+ clearTimeout(warmupTimer);
667
+ for (const turn of activeTurns.values()) {
668
+ turn.aborted = true;
669
+ for (const pending of turn.pendingDecisions.values()) {
670
+ clearTimeout(pending.timer);
671
+ pending.resolve(null);
672
+ }
673
+ turn.pendingDecisions.clear();
674
+ try {
675
+ turn.loop?.abort();
676
+ }
677
+ catch { /* ignore */ }
678
+ }
679
+ activeTurns.clear();
680
+ await new Promise((resolve) => {
681
+ server.closeAllConnections?.();
682
+ server.close(() => resolve());
683
+ });
684
+ }
685
+ };
686
+ }