@causyne/agent 1.20.124 → 1.20.127

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