kodorun-cli 0.0.0-stage → 0.1.124

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.
package/dist/index.js ADDED
@@ -0,0 +1,3736 @@
1
+ #!/usr/bin/env node
2
+ import { WebSocket } from "ws";
3
+ import qrcode from "qrcode-terminal";
4
+ import shell from "shelljs";
5
+ import { createAiManager, ALL_AI_BACKENDS } from "./ai/index.js";
6
+ import { V2SessionTransport } from "./transport/v2.js";
7
+ import Ignore from "ignore";
8
+ const ignore = Ignore.default;
9
+ import * as fs from "fs/promises";
10
+ import * as fssync from "fs";
11
+ import * as path from "path";
12
+ import * as os from "os";
13
+ import { randomBytes } from "crypto";
14
+ import { spawn, spawnSync, execSync } from "child_process";
15
+ import { createServer, createConnection } from "net";
16
+ import { createInterface } from "readline";
17
+ const DEFAULT_PROXY_URL = normalizeGatewayUrl(process.env.KODORUN_PROXY_URL || "https://imaginative-communication-production-1235543a.up.railway.app");
18
+ const MANAGER_URL = normalizeGatewayUrl(process.env.KODORUN_MANAGER_URL || "https://kodorun-production.up.railway.app");
19
+ const CLI_ARGS = process.argv.slice(2);
20
+ function hasAnyFlag(args, ...flags) {
21
+ return flags.some((flag) => args.includes(flag));
22
+ }
23
+ const SHOW_HELP = hasAnyFlag(CLI_ARGS, "--help", "-h");
24
+ const DEBUG_MODE = hasAnyFlag(CLI_ARGS, "--debug", "-d");
25
+ if (DEBUG_MODE) {
26
+ process.env.KODORUN_DEBUG = "1";
27
+ process.env.KODORUN_DEBUG_AI = "1";
28
+ }
29
+ import { createRequire } from "module";
30
+ import { fileURLToPath } from "url";
31
+ const __require = createRequire(import.meta.url);
32
+ const VERSION = __require("../package.json").version;
33
+ const VERBOSE_AI_LOGS = process.env.KODORUN_DEBUG_AI === "1";
34
+ const PTY_RELEASE_BASE_URL = "https://github.com/codewithevilxd/kodorun/releases/download/v0";
35
+ const AI_RUNTIME_INSTALL_CANDIDATES = {
36
+ opencode: ["opencode-ai", "@opencode-ai/cli", "opencode"],
37
+ codex: ["@openai/codex", "codex"],
38
+ claude: ["@anthropic-ai/claude-code"],
39
+ gemini: ["@google/gemini-cli"],
40
+ };
41
+ const PTY_RELEASES = {
42
+ "linux:x64": {
43
+ fileName: "kodorun-pty-linux-x8664-0",
44
+ url: `${PTY_RELEASE_BASE_URL}/kodorun-pty-linux-x8664-0`,
45
+ },
46
+ "darwin:arm64": {
47
+ fileName: "kodorun-pty-macos-arm64-0",
48
+ url: `${PTY_RELEASE_BASE_URL}/kodorun-pty-macos-arm64-0`,
49
+ },
50
+ "win32:x64": {
51
+ fileName: "kodorun-pty-windows-x8664-1.exe",
52
+ url: `${PTY_RELEASE_BASE_URL}/kodorun-pty-windows-x8664-1.exe`,
53
+ },
54
+ };
55
+ // Root directory - sandbox all file operations to this
56
+ const ROOT_DIR = (() => {
57
+ try {
58
+ return fssync.realpathSync(process.cwd());
59
+ }
60
+ catch {
61
+ return process.cwd();
62
+ }
63
+ })();
64
+ const CLI_CONFIG_PATH = (() => {
65
+ if (process.platform === "darwin") {
66
+ return path.join(os.homedir(), "Library", "Application Support", "kodorun", "config.json");
67
+ }
68
+ if (process.platform === "win32") {
69
+ const appData = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
70
+ return path.join(appData, "kodorun", "config.json");
71
+ }
72
+ const xdgConfig = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
73
+ return path.join(xdgConfig, "kodorun", "config.json");
74
+ })();
75
+ // Terminal sessions (managed by Rust PTY binary)
76
+ const terminals = new Set();
77
+ // PTY binary process
78
+ let ptyProcess = null;
79
+ const ptyPendingSpawns = new Map();
80
+ function getDefaultTerminalShell() {
81
+ const customShell = process.env.KODORUN_SHELL?.trim();
82
+ if (customShell)
83
+ return customShell;
84
+ if (process.platform === "win32") {
85
+ return process.env.COMSPEC || "C:\\Windows\\System32\\cmd.exe";
86
+ }
87
+ return process.env.SHELL || (process.platform === "darwin" ? "/bin/zsh" : "/bin/sh");
88
+ }
89
+ const processes = new Map();
90
+ const processOutputBuffers = new Map();
91
+ // CPU usage tracking
92
+ let lastCpuInfo = null;
93
+ // AI manager — runs OpenCode and Codex simultaneously, routes by backend
94
+ let aiManager = null;
95
+ let aiManagerInitPromise = null;
96
+ // Proxy tunnel management
97
+ let currentSessionCode = null;
98
+ let currentSessionPassword = null;
99
+ let currentPrimaryGateway = DEFAULT_PROXY_URL;
100
+ let activeGatewayUrl = DEFAULT_PROXY_URL;
101
+ let shuttingDown = false;
102
+ let activeV2Transport = null;
103
+ const trackedEditorFiles = new Map();
104
+ const trackedEditorDirectories = new Map();
105
+ const pendingTrackedFileChecks = new Set();
106
+ function logWithTimestamp(scope, message, fields) {
107
+ if (!DEBUG_MODE)
108
+ return;
109
+ const timestamp = new Date().toISOString();
110
+ const suffix = fields ? ` ${JSON.stringify(fields)}` : "";
111
+ console.log(`[${timestamp}] [${scope}] ${message}${suffix}`);
112
+ }
113
+ function debugLog(message, ...args) {
114
+ if (!DEBUG_MODE)
115
+ return;
116
+ console.log(message, ...args);
117
+ }
118
+ function debugWarn(message, ...args) {
119
+ if (!DEBUG_MODE)
120
+ return;
121
+ console.warn(message, ...args);
122
+ }
123
+ function printHelp() {
124
+ console.log(`KodoRun CLI v${VERSION} (${getPlatformDisplayLabel()})
125
+
126
+ Usage:
127
+ npx kodorun-cli [options]
128
+
129
+ Options:
130
+ -h, --help Show help
131
+ -n, --new Create a new session code
132
+ -d, --debug Show verbose debug logs
133
+ --extra-ports Extra local ports to expose, comma-separated (e.g. 3000,8080)
134
+
135
+ Environment:
136
+ KODORUN_SHELL Override default shell (${getDefaultTerminalShell()})
137
+ `);
138
+ }
139
+ const activeTunnels = new Map();
140
+ const PORT_SYNC_INTERVAL_MS = 30_000;
141
+ const CLI_LOCAL_TCP_CONNECT_TIMEOUT_MS = 2_500;
142
+ const PROXY_WS_CONNECT_TIMEOUT_MS = 12_000;
143
+ const TUNNEL_SETUP_BUDGET_MS = 18_000;
144
+ const PROXY_WS_CONNECT_RETRY_ATTEMPTS = 1;
145
+ const PROXY_WS_RETRY_JITTER_MIN_MS = 200;
146
+ const PROXY_WS_RETRY_JITTER_MAX_MS = 500;
147
+ const PROXY_TUNNEL_LINGER_MS = 1_200;
148
+ const LOOPBACK_HOSTS = ["127.0.0.1", "::1"];
149
+ let portSyncTimer = null;
150
+ let portScanInFlight = false;
151
+ let lastDiscoveredPorts = [];
152
+ function redactSensitive(input) {
153
+ const text = typeof input === "string" ? input : JSON.stringify(input);
154
+ return text
155
+ .replace(/([A-Za-z0-9\-_]{20,}\.[A-Za-z0-9\-_]{20,}\.[A-Za-z0-9\-_]{20,})/g, "[redacted_jwt]")
156
+ .replace(/(["']?(?:password|token|authorization|resumeToken|sessionSecret|secret|x-manager-password|x-proxy-password)["']?\s*[:=]\s*["']?)([^"',\s}\]]+)/gi, "$1[redacted]")
157
+ .replace(/[A-Za-z0-9+/=_-]{40,}/g, "[redacted_secret]");
158
+ }
159
+ function parseProxyControlFrame(raw) {
160
+ const text = typeof raw === "string" ? raw : Buffer.isBuffer(raw) ? raw.toString("utf-8") : null;
161
+ if (!text)
162
+ return null;
163
+ try {
164
+ const parsed = JSON.parse(text);
165
+ if (parsed?.v !== 1 || parsed?.t !== "proxy_ctrl")
166
+ return null;
167
+ if (parsed.action !== "fin" && parsed.action !== "rst")
168
+ return null;
169
+ return {
170
+ v: 1,
171
+ t: "proxy_ctrl",
172
+ action: parsed.action,
173
+ reason: typeof parsed.reason === "string" ? parsed.reason : undefined,
174
+ };
175
+ }
176
+ catch {
177
+ return null;
178
+ }
179
+ }
180
+ function sendProxyControl(tunnel, action, reason) {
181
+ if (tunnel.proxyWs.readyState !== WebSocket.OPEN)
182
+ return;
183
+ const frame = { v: 1, t: "proxy_ctrl", action, reason };
184
+ tunnel.proxyWs.send(JSON.stringify(frame));
185
+ }
186
+ function maybeFinalizeTunnel(tunnelId) {
187
+ const tunnel = activeTunnels.get(tunnelId);
188
+ if (!tunnel || tunnel.closing)
189
+ return;
190
+ if (!tunnel.localEnded || !tunnel.remoteEnded)
191
+ return;
192
+ if (tunnel.finalizeTimer)
193
+ return;
194
+ tunnel.finalizeTimer = setTimeout(() => {
195
+ const current = activeTunnels.get(tunnelId);
196
+ if (!current || current.closing)
197
+ return;
198
+ current.closing = true;
199
+ activeTunnels.delete(tunnelId);
200
+ if (!current.tcpSocket.destroyed) {
201
+ current.tcpSocket.destroy();
202
+ }
203
+ if (current.proxyWs.readyState === WebSocket.OPEN || current.proxyWs.readyState === WebSocket.CONNECTING) {
204
+ current.proxyWs.close();
205
+ }
206
+ }, PROXY_TUNNEL_LINGER_MS);
207
+ }
208
+ function parseExtraPortsFromArgs(args) {
209
+ const values = [];
210
+ for (let i = 0; i < args.length; i++) {
211
+ const arg = args[i];
212
+ if (arg.startsWith("--extra-ports=")) {
213
+ values.push(arg.slice("--extra-ports=".length));
214
+ continue;
215
+ }
216
+ if (arg === "--extra-ports" && i + 1 < args.length) {
217
+ values.push(args[i + 1]);
218
+ i++;
219
+ }
220
+ }
221
+ const parsed = new Set();
222
+ for (const value of values) {
223
+ for (const piece of value.split(",")) {
224
+ const trimmed = piece.trim();
225
+ if (!trimmed)
226
+ continue;
227
+ const num = Number(trimmed);
228
+ if (!Number.isInteger(num) || num < 1 || num > 65535)
229
+ continue;
230
+ parsed.add(num);
231
+ }
232
+ }
233
+ return Array.from(parsed).sort((a, b) => a - b);
234
+ }
235
+ const EXTRA_PORTS = parseExtraPortsFromArgs(CLI_ARGS);
236
+ const FORCE_NEW_CODE = hasAnyFlag(CLI_ARGS, "--new", "-n");
237
+ const trackedProxyPorts = new Set(EXTRA_PORTS);
238
+ function samePortSet(a, b) {
239
+ if (a.length !== b.length)
240
+ return false;
241
+ for (let i = 0; i < a.length; i++) {
242
+ if (a[i] !== b[i])
243
+ return false;
244
+ }
245
+ return true;
246
+ }
247
+ // ============================================================================
248
+ // Path Safety
249
+ // ============================================================================
250
+ function normalizePathForCompare(targetPath) {
251
+ return process.platform === "win32" ? targetPath.toLowerCase() : targetPath;
252
+ }
253
+ export function resolveSafePathInRoot(rootDir, requestedPath) {
254
+ if (typeof requestedPath !== "string" || requestedPath.includes("\0")) {
255
+ return null;
256
+ }
257
+ const canonicalRoot = (() => {
258
+ try {
259
+ return fssync.realpathSync(rootDir);
260
+ }
261
+ catch {
262
+ return path.resolve(rootDir);
263
+ }
264
+ })();
265
+ const lexical = path.resolve(canonicalRoot, requestedPath);
266
+ // Walk up to the nearest existing ancestor so symlink escapes fail even when
267
+ // the leaf file/folder has not been created yet.
268
+ let probe = lexical;
269
+ const missingSegments = [];
270
+ while (!fssync.existsSync(probe)) {
271
+ const parent = path.dirname(probe);
272
+ if (parent === probe)
273
+ break;
274
+ missingSegments.unshift(path.basename(probe));
275
+ probe = parent;
276
+ }
277
+ let canonicalBase;
278
+ try {
279
+ canonicalBase = fssync.realpathSync(probe);
280
+ }
281
+ catch {
282
+ return null;
283
+ }
284
+ const canonical = missingSegments.length > 0
285
+ ? path.join(canonicalBase, ...missingSegments)
286
+ : canonicalBase;
287
+ const cmpTarget = normalizePathForCompare(canonical);
288
+ const cmpRoot = normalizePathForCompare(canonicalRoot);
289
+ if (cmpTarget !== cmpRoot && !cmpTarget.startsWith(cmpRoot + path.sep)) {
290
+ return null;
291
+ }
292
+ return canonical;
293
+ }
294
+ function resolveSafePath(requestedPath) {
295
+ return resolveSafePathInRoot(ROOT_DIR, requestedPath);
296
+ }
297
+ function assertSafePath(requestedPath) {
298
+ const safePath = resolveSafePath(requestedPath);
299
+ if (!safePath) {
300
+ const error = new Error("Access denied: path outside root directory");
301
+ error.code = "EACCES";
302
+ throw error;
303
+ }
304
+ return safePath;
305
+ }
306
+ function generatePersistentSecret(length) {
307
+ const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
308
+ const maxValid = Math.floor(256 / alphabet.length) * alphabet.length;
309
+ let out = "";
310
+ while (out.length < length) {
311
+ const bytes = randomBytes(Math.max(16, (length - out.length) * 2));
312
+ for (let i = 0; i < bytes.length && out.length < length; i++) {
313
+ if (bytes[i] < maxValid) {
314
+ out += alphabet[bytes[i] % alphabet.length];
315
+ }
316
+ }
317
+ }
318
+ return out;
319
+ }
320
+ async function readCliConfig() {
321
+ try {
322
+ const raw = await fs.readFile(CLI_CONFIG_PATH, "utf-8");
323
+ const parsed = JSON.parse(raw);
324
+ return {
325
+ version: 1,
326
+ deviceId: typeof parsed.deviceId === "string" && parsed.deviceId ? parsed.deviceId : generatePersistentSecret(32),
327
+ sessions: Array.isArray(parsed.sessions)
328
+ ? parsed.sessions.filter((entry) => (!!entry
329
+ && typeof entry.rootDir === "string"
330
+ && typeof entry.sessionPassword === "string"
331
+ && typeof entry.savedAt === "number")).map((entry) => ({
332
+ rootDir: entry.rootDir,
333
+ sessionCode: typeof entry.sessionCode === "string" ? entry.sessionCode : null,
334
+ sessionPassword: entry.sessionPassword,
335
+ savedAt: entry.savedAt,
336
+ }))
337
+ : [],
338
+ };
339
+ }
340
+ catch {
341
+ return {
342
+ version: 1,
343
+ deviceId: generatePersistentSecret(32),
344
+ sessions: [],
345
+ };
346
+ }
347
+ }
348
+ async function writeCliConfig(config) {
349
+ await fs.mkdir(path.dirname(CLI_CONFIG_PATH), { recursive: true, mode: 0o700 });
350
+ await fs.writeFile(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 0o600 });
351
+ cliConfigPromise = Promise.resolve(config);
352
+ }
353
+ let cliConfigPromise = null;
354
+ async function getCliConfig() {
355
+ if (!cliConfigPromise) {
356
+ cliConfigPromise = readCliConfig();
357
+ }
358
+ return await cliConfigPromise;
359
+ }
360
+ function getSavedSessionForRoot(config, rootDir) {
361
+ const sessions = Array.isArray(config.sessions) ? config.sessions : [];
362
+ return sessions.find((entry) => entry.rootDir === rootDir) || null;
363
+ }
364
+ async function saveSessionForRoot(sessionCode, sessionPassword) {
365
+ const config = await getCliConfig();
366
+ const sessions = Array.isArray(config.sessions) ? [...config.sessions] : [];
367
+ const nextEntry = {
368
+ rootDir: ROOT_DIR,
369
+ sessionCode,
370
+ sessionPassword,
371
+ savedAt: Date.now(),
372
+ };
373
+ const deduped = sessions.filter((entry) => entry.rootDir !== ROOT_DIR);
374
+ deduped.unshift(nextEntry);
375
+ await writeCliConfig({
376
+ ...config,
377
+ sessions: deduped.slice(0, 100),
378
+ });
379
+ }
380
+ async function clearSavedSessionForRoot() {
381
+ const config = await getCliConfig();
382
+ const sessions = Array.isArray(config.sessions) ? config.sessions : [];
383
+ await writeCliConfig({
384
+ ...config,
385
+ sessions: sessions.filter((entry) => entry.rootDir !== ROOT_DIR),
386
+ });
387
+ }
388
+ // ============================================================================
389
+ // File System Handlers
390
+ // ============================================================================
391
+ function isLikelyBinaryBuffer(buffer) {
392
+ if (buffer.length === 0)
393
+ return false;
394
+ if (buffer.includes(0x00))
395
+ return true;
396
+ let suspicious = 0;
397
+ for (let i = 0; i < buffer.length; i++) {
398
+ const byte = buffer[i];
399
+ const isPrintableAscii = byte >= 0x20 && byte <= 0x7e;
400
+ const isCommonControl = byte === 0x09 || byte === 0x0a || byte === 0x0d;
401
+ if (!isPrintableAscii && !isCommonControl)
402
+ suspicious++;
403
+ }
404
+ return suspicious / buffer.length > 0.3;
405
+ }
406
+ async function handleFsLs(payload) {
407
+ const reqPath = payload.path || ".";
408
+ const safePath = assertSafePath(reqPath);
409
+ const entries = await fs.readdir(safePath, { withFileTypes: true });
410
+ const result = [];
411
+ for (const entry of entries) {
412
+ const item = {
413
+ name: entry.name,
414
+ type: entry.isDirectory() ? "directory" : "file",
415
+ };
416
+ // Try to get size and mtime for files
417
+ if (entry.isFile()) {
418
+ try {
419
+ const stat = await fs.stat(path.join(safePath, entry.name));
420
+ item.size = stat.size;
421
+ item.mtime = stat.mtimeMs;
422
+ }
423
+ catch {
424
+ // Ignore stat errors
425
+ }
426
+ }
427
+ result.push(item);
428
+ }
429
+ return { path: reqPath, entries: result };
430
+ }
431
+ async function handleFsSearchFiles(payload) {
432
+ const reqPath = payload.path || ".";
433
+ const query = typeof payload.query === "string" ? payload.query.trim().toLowerCase() : "";
434
+ const maxResults = Math.max(1, Math.min(payload.maxResults || 10, 10));
435
+ const safePath = assertSafePath(reqPath);
436
+ const rootIgnore = await loadGitignore(ROOT_DIR);
437
+ const matches = [];
438
+ async function searchDir(dirPath, relativePath, ig) {
439
+ if (matches.length >= maxResults)
440
+ return;
441
+ const localIgnore = ignore().add(ig);
442
+ try {
443
+ const localGitignorePath = path.join(dirPath, ".gitignore");
444
+ const content = await fs.readFile(localGitignorePath, "utf-8");
445
+ localIgnore.add(content);
446
+ }
447
+ catch {
448
+ // No local .gitignore
449
+ }
450
+ const entries = await fs.readdir(dirPath, { withFileTypes: true });
451
+ for (const entry of entries) {
452
+ if (matches.length >= maxResults)
453
+ break;
454
+ const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
455
+ const checkPath = entry.isDirectory() ? `${relPath}/` : relPath;
456
+ if (localIgnore.ignores(checkPath))
457
+ continue;
458
+ const fullPath = path.join(dirPath, entry.name);
459
+ if (entry.isDirectory()) {
460
+ await searchDir(fullPath, relPath, localIgnore);
461
+ }
462
+ else if (entry.isFile() && relPath.toLowerCase().includes(query)) {
463
+ matches.push({ path: relPath });
464
+ }
465
+ }
466
+ }
467
+ const stat = await fs.stat(safePath);
468
+ if (stat.isDirectory()) {
469
+ await searchDir(safePath, reqPath === "." ? "" : reqPath, rootIgnore);
470
+ }
471
+ else if (stat.isFile() && reqPath.toLowerCase().includes(query)) {
472
+ matches.push({ path: reqPath });
473
+ }
474
+ return { path: reqPath, query, maxResults, files: matches };
475
+ }
476
+ async function handleFsStat(payload) {
477
+ const reqPath = payload.path;
478
+ if (!reqPath)
479
+ throw Object.assign(new Error("path is required"), { code: "EINVAL" });
480
+ const safePath = assertSafePath(reqPath);
481
+ const stat = await fs.stat(safePath);
482
+ const result = {
483
+ path: reqPath,
484
+ type: stat.isDirectory() ? "directory" : "file",
485
+ size: stat.size,
486
+ mtime: stat.mtimeMs,
487
+ mode: stat.mode,
488
+ };
489
+ if (stat.isFile()) {
490
+ try {
491
+ const fd = await fs.open(safePath, "r");
492
+ try {
493
+ const sampleSize = Math.min(stat.size, 8192);
494
+ const sample = Buffer.alloc(sampleSize);
495
+ if (sampleSize > 0) {
496
+ await fd.read(sample, 0, sampleSize, 0);
497
+ }
498
+ result.isBinary = isLikelyBinaryBuffer(sample);
499
+ }
500
+ finally {
501
+ await fd.close();
502
+ }
503
+ }
504
+ catch {
505
+ // Keep stat resilient even if sampling fails
506
+ }
507
+ }
508
+ return result;
509
+ }
510
+ async function handleFsRead(payload) {
511
+ const reqPath = payload.path;
512
+ if (!reqPath)
513
+ throw Object.assign(new Error("path is required"), { code: "EINVAL" });
514
+ const startedAt = Date.now();
515
+ logWithTimestamp("fs-read", "starting", { path: reqPath });
516
+ const safePath = assertSafePath(reqPath);
517
+ // Check if binary
518
+ const stat = await fs.stat(safePath);
519
+ const content = await fs.readFile(safePath);
520
+ // Detect if binary
521
+ const isBinary = isLikelyBinaryBuffer(content.subarray(0, 8192));
522
+ logWithTimestamp("fs-read", "disk read complete", {
523
+ path: reqPath,
524
+ size: stat.size,
525
+ bufferBytes: content.length,
526
+ isBinary,
527
+ durationMs: Date.now() - startedAt,
528
+ });
529
+ if (isBinary) {
530
+ return {
531
+ path: reqPath,
532
+ content: content.toString("base64"),
533
+ encoding: "base64",
534
+ size: stat.size,
535
+ };
536
+ }
537
+ return {
538
+ path: reqPath,
539
+ content: content.toString("utf-8"),
540
+ encoding: "utf8",
541
+ size: stat.size,
542
+ };
543
+ }
544
+ async function handleFsWrite(payload) {
545
+ const reqPath = payload.path;
546
+ const content = payload.content;
547
+ const encoding = payload.encoding || "utf8";
548
+ const source = typeof payload.source === "string" ? payload.source : null;
549
+ if (!reqPath)
550
+ throw Object.assign(new Error("path is required"), { code: "EINVAL" });
551
+ if (typeof content !== "string")
552
+ throw Object.assign(new Error("content is required"), { code: "EINVAL" });
553
+ const safePath = assertSafePath(reqPath);
554
+ const parentDir = path.dirname(safePath);
555
+ await fs.mkdir(parentDir, { recursive: true });
556
+ if (encoding === "base64") {
557
+ await fs.writeFile(safePath, Buffer.from(content, "base64"));
558
+ }
559
+ else {
560
+ await fs.writeFile(safePath, content, "utf-8");
561
+ }
562
+ await noteTrackedFileWrite(reqPath, source);
563
+ return { path: reqPath };
564
+ }
565
+ async function handleFsMkdir(payload) {
566
+ const reqPath = payload.path;
567
+ const recursive = payload.recursive !== false;
568
+ if (!reqPath)
569
+ throw Object.assign(new Error("path is required"), { code: "EINVAL" });
570
+ const safePath = assertSafePath(reqPath);
571
+ await fs.mkdir(safePath, { recursive });
572
+ return { path: reqPath };
573
+ }
574
+ async function handleFsRm(payload) {
575
+ const reqPath = payload.path;
576
+ const recursive = payload.recursive === true;
577
+ if (!reqPath)
578
+ throw Object.assign(new Error("path is required"), { code: "EINVAL" });
579
+ const safePath = assertSafePath(reqPath);
580
+ const canonicalRoot = (() => {
581
+ try {
582
+ return fssync.realpathSync(ROOT_DIR);
583
+ }
584
+ catch {
585
+ return path.resolve(ROOT_DIR);
586
+ }
587
+ })();
588
+ if (normalizePathForCompare(safePath) === normalizePathForCompare(canonicalRoot)) {
589
+ throw Object.assign(new Error("Refusing to delete workspace root directory"), { code: "EACCES" });
590
+ }
591
+ await fs.rm(safePath, { recursive, force: false });
592
+ deleteTrackedEditorFile(reqPath);
593
+ return { path: reqPath };
594
+ }
595
+ async function handleFsMv(payload) {
596
+ const from = payload.from;
597
+ const to = payload.to;
598
+ if (!from)
599
+ throw Object.assign(new Error("from is required"), { code: "EINVAL" });
600
+ if (!to)
601
+ throw Object.assign(new Error("to is required"), { code: "EINVAL" });
602
+ const safeFrom = assertSafePath(from);
603
+ const safeTo = assertSafePath(to);
604
+ await fs.rename(safeFrom, safeTo);
605
+ await renameTrackedEditorFile(from, to);
606
+ return { from, to };
607
+ }
608
+ // Load gitignore patterns
609
+ async function loadGitignore(dirPath) {
610
+ const ig = ignore();
611
+ ig.add(".git");
612
+ try {
613
+ const gitignorePath = path.join(dirPath, ".gitignore");
614
+ const content = await fs.readFile(gitignorePath, "utf-8");
615
+ ig.add(content);
616
+ }
617
+ catch {
618
+ // No .gitignore
619
+ }
620
+ return ig;
621
+ }
622
+ const KNOWN_BINARY_EXTENSIONS = new Set([
623
+ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".avif", ".ico", ".icns", ".heic", ".heif", ".tiff", ".tif",
624
+ ".psd", ".ai", ".eps",
625
+ ".mp3", ".wav", ".ogg", ".m4a", ".flac", ".aac",
626
+ ".mp4", ".mov", ".avi", ".mkv", ".webm", ".wmv", ".m4v",
627
+ ".pdf", ".zip", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar", ".tar",
628
+ ".exe", ".dll", ".so", ".dylib", ".bin", ".class", ".o", ".obj", ".a", ".lib",
629
+ ".ttf", ".otf", ".woff", ".woff2", ".eot",
630
+ ]);
631
+ function isLikelyBinaryContent(content) {
632
+ if (content.length === 0)
633
+ return false;
634
+ const sample = content.subarray(0, Math.min(content.length, 8192));
635
+ let suspicious = 0;
636
+ for (const byte of sample) {
637
+ if (byte === 0)
638
+ return true; // Null bytes strongly indicate binary data.
639
+ if (byte < 7 || (byte > 13 && byte < 32))
640
+ suspicious += 1;
641
+ }
642
+ return suspicious / sample.length > 0.3;
643
+ }
644
+ function shouldSkipAsBinary(filePath, content) {
645
+ const ext = path.extname(filePath).toLowerCase();
646
+ if (KNOWN_BINARY_EXTENSIONS.has(ext))
647
+ return true;
648
+ return isLikelyBinaryContent(content);
649
+ }
650
+ async function handleFsGrep(payload) {
651
+ const reqPath = payload.path || ".";
652
+ const pattern = payload.pattern;
653
+ const caseSensitive = payload.caseSensitive !== false;
654
+ const maxResults = payload.maxResults || 100;
655
+ if (!pattern)
656
+ throw Object.assign(new Error("pattern is required"), { code: "EINVAL" });
657
+ const safePath = assertSafePath(reqPath);
658
+ const matches = [];
659
+ let regex;
660
+ try {
661
+ regex = new RegExp(pattern, caseSensitive ? "g" : "gi");
662
+ }
663
+ catch {
664
+ throw Object.assign(new Error("pattern must be a valid regular expression"), { code: "EINVAL" });
665
+ }
666
+ const rootIgnore = await loadGitignore(ROOT_DIR);
667
+ const previousSilent = shell.config.silent;
668
+ shell.config.silent = true;
669
+ try {
670
+ async function searchFile(filePath, relativePath) {
671
+ if (matches.length >= maxResults)
672
+ return;
673
+ try {
674
+ const rawContent = await fs.readFile(filePath);
675
+ if (shouldSkipAsBinary(relativePath, rawContent)) {
676
+ regex.lastIndex = 0;
677
+ return;
678
+ }
679
+ const content = rawContent.toString("utf-8");
680
+ const lines = content.split("\n");
681
+ for (let i = 0; i < lines.length && matches.length < maxResults; i++) {
682
+ if (regex.test(lines[i])) {
683
+ matches.push({
684
+ file: relativePath,
685
+ line: i + 1,
686
+ content: lines[i].substring(0, 500),
687
+ });
688
+ }
689
+ regex.lastIndex = 0;
690
+ }
691
+ }
692
+ catch {
693
+ regex.lastIndex = 0;
694
+ }
695
+ }
696
+ async function searchDir(dirPath, relativePath, ig) {
697
+ if (matches.length >= maxResults)
698
+ return;
699
+ const localIgnore = ignore().add(ig);
700
+ try {
701
+ const localGitignorePath = path.join(dirPath, ".gitignore");
702
+ const content = await fs.readFile(localGitignorePath, "utf-8");
703
+ localIgnore.add(content);
704
+ }
705
+ catch {
706
+ // No local .gitignore
707
+ }
708
+ const entries = await fs.readdir(dirPath, { withFileTypes: true });
709
+ for (const entry of entries) {
710
+ if (matches.length >= maxResults)
711
+ break;
712
+ const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
713
+ const checkPath = entry.isDirectory() ? `${relPath}/` : relPath;
714
+ if (localIgnore.ignores(checkPath))
715
+ continue;
716
+ const fullPath = path.join(dirPath, entry.name);
717
+ if (entry.isDirectory()) {
718
+ await searchDir(fullPath, relPath, localIgnore);
719
+ }
720
+ else if (entry.isFile()) {
721
+ await searchFile(fullPath, relPath);
722
+ }
723
+ }
724
+ }
725
+ const stat = await fs.stat(safePath);
726
+ if (stat.isDirectory()) {
727
+ await searchDir(safePath, reqPath === "." ? "" : reqPath, rootIgnore);
728
+ }
729
+ else {
730
+ await searchFile(safePath, reqPath);
731
+ }
732
+ }
733
+ finally {
734
+ shell.config.silent = previousSilent;
735
+ }
736
+ return { matches };
737
+ }
738
+ async function handleFsCreate(payload) {
739
+ const reqPath = payload.path;
740
+ const type = payload.type;
741
+ if (!reqPath)
742
+ throw Object.assign(new Error("path is required"), { code: "EINVAL" });
743
+ if (!type || (type !== "file" && type !== "directory")) {
744
+ throw Object.assign(new Error("type must be 'file' or 'directory'"), { code: "EINVAL" });
745
+ }
746
+ const safePath = assertSafePath(reqPath);
747
+ if (type === "directory") {
748
+ await fs.mkdir(safePath, { recursive: true });
749
+ }
750
+ else {
751
+ // Create parent directories if needed
752
+ const parentDir = path.dirname(safePath);
753
+ await fs.mkdir(parentDir, { recursive: true });
754
+ // Create empty file
755
+ await fs.writeFile(safePath, "");
756
+ }
757
+ return { path: reqPath };
758
+ }
759
+ // ============================================================================
760
+ // Git Handlers
761
+ // ============================================================================
762
+ async function runGit(args) {
763
+ return new Promise((resolve) => {
764
+ const proc = spawn("git", args, { cwd: ROOT_DIR });
765
+ let stdout = "";
766
+ let stderr = "";
767
+ proc.stdout.on("data", (data) => (stdout += data.toString()));
768
+ proc.stderr.on("data", (data) => (stderr += data.toString()));
769
+ proc.on("close", (code) => {
770
+ resolve({ stdout, stderr, code: code || 0 });
771
+ });
772
+ proc.on("error", (err) => {
773
+ resolve({ stdout: "", stderr: err.message, code: 1 });
774
+ });
775
+ });
776
+ }
777
+ async function handleGitStatus() {
778
+ // Get branch
779
+ const branchResult = await runGit(["branch", "--show-current"]);
780
+ const branch = branchResult.stdout.trim();
781
+ // Get status
782
+ const statusResult = await runGit(["status", "--porcelain", "-uall"]);
783
+ // Preserve leading whitespace in each porcelain line.
784
+ // Example: " M file" (unstaged-only) starts with a space that is semantically important.
785
+ const lines = statusResult.stdout.split(/\r?\n/).filter((line) => line.length > 0);
786
+ const staged = [];
787
+ const unstaged = [];
788
+ const untracked = [];
789
+ for (const line of lines) {
790
+ const index = line[0];
791
+ const worktree = line[1];
792
+ // Git porcelain format: XY path (where X=index status, Y=worktree status)
793
+ // For renamed files: XY old -> new
794
+ let filepath = line.substring(3).trim();
795
+ // Handle quoted paths (git quotes paths with special chars)
796
+ if (filepath.startsWith('"') && filepath.endsWith('"')) {
797
+ filepath = filepath.slice(1, -1);
798
+ }
799
+ // For renamed files, extract just the new name
800
+ if (filepath.includes(' -> ')) {
801
+ filepath = filepath.split(' -> ')[1];
802
+ }
803
+ if (index === "?" && worktree === "?") {
804
+ untracked.push(filepath);
805
+ }
806
+ else {
807
+ if (index !== " " && index !== "?") {
808
+ staged.push({ path: filepath, status: index });
809
+ }
810
+ if (worktree !== " " && worktree !== "?") {
811
+ unstaged.push({ path: filepath, status: worktree });
812
+ }
813
+ }
814
+ }
815
+ // Get ahead/behind
816
+ const aheadBehind = await runGit(["rev-list", "--left-right", "--count", "@{u}...HEAD"]);
817
+ let ahead = 0;
818
+ let behind = 0;
819
+ if (aheadBehind.code === 0) {
820
+ const parts = aheadBehind.stdout.trim().split(/\s+/);
821
+ behind = parseInt(parts[0]) || 0;
822
+ ahead = parseInt(parts[1]) || 0;
823
+ }
824
+ return { branch, ahead, behind, staged, unstaged, untracked };
825
+ }
826
+ async function handleGitStage(payload) {
827
+ const rawPaths = payload.paths;
828
+ if (!Array.isArray(rawPaths) || !rawPaths.length)
829
+ throw Object.assign(new Error("paths is required"), { code: "EINVAL" });
830
+ const paths = rawPaths.map((p) => {
831
+ const safe = assertSafePath(String(p));
832
+ return path.relative(ROOT_DIR, safe) || ".";
833
+ });
834
+ const result = await runGit(["add", "--", ...paths]);
835
+ if (result.code !== 0) {
836
+ throw Object.assign(new Error(result.stderr || "git add failed"), { code: "EGIT" });
837
+ }
838
+ return {};
839
+ }
840
+ async function handleGitUnstage(payload) {
841
+ const rawPaths = payload.paths;
842
+ if (!Array.isArray(rawPaths) || !rawPaths.length)
843
+ throw Object.assign(new Error("paths is required"), { code: "EINVAL" });
844
+ const paths = rawPaths.map((p) => {
845
+ const safe = assertSafePath(String(p));
846
+ return path.relative(ROOT_DIR, safe) || ".";
847
+ });
848
+ // Use git restore --staged (Git 2.23+) which is more reliable
849
+ // Falls back to git reset HEAD for older versions
850
+ let result = await runGit(["restore", "--staged", "--", ...paths]);
851
+ if (result.code !== 0) {
852
+ // Fallback to reset for older git versions
853
+ result = await runGit(["reset", "HEAD", "--", ...paths]);
854
+ if (result.code !== 0) {
855
+ throw Object.assign(new Error(result.stderr || "git unstage failed"), { code: "EGIT" });
856
+ }
857
+ }
858
+ return {};
859
+ }
860
+ async function handleGitCommit(payload) {
861
+ const message = payload.message;
862
+ if (typeof message !== "string" || !message.trim())
863
+ throw Object.assign(new Error("message is required"), { code: "EINVAL" });
864
+ const result = await runGit(["commit", "-m", message]);
865
+ if (result.code !== 0) {
866
+ throw Object.assign(new Error(result.stderr || "git commit failed"), { code: "EGIT" });
867
+ }
868
+ // Get the commit hash
869
+ const hashResult = await runGit(["rev-parse", "HEAD"]);
870
+ const hash = hashResult.stdout.trim().substring(0, 7);
871
+ return { hash, message };
872
+ }
873
+ async function handleGitLog(payload) {
874
+ const rawLimit = Number(payload.limit ?? 20);
875
+ const limit = Number.isFinite(rawLimit) ? Math.min(500, Math.max(1, Math.trunc(rawLimit))) : 20;
876
+ const result = await runGit([
877
+ "log",
878
+ `-${limit}`,
879
+ "--pretty=format:%H|%s|%an|%at",
880
+ ]);
881
+ if (result.code !== 0) {
882
+ throw Object.assign(new Error(result.stderr || "git log failed"), { code: "EGIT" });
883
+ }
884
+ const commits = result.stdout
885
+ .trim()
886
+ .split("\n")
887
+ .filter(Boolean)
888
+ .map((line) => {
889
+ const [hash, message, author, timestamp] = line.split("|");
890
+ return {
891
+ hash: hash.substring(0, 7),
892
+ message,
893
+ author,
894
+ date: parseInt(timestamp) * 1000,
895
+ };
896
+ });
897
+ return { commits };
898
+ }
899
+ async function handleGitCommitDetails(payload) {
900
+ const hash = (typeof payload.hash === "string" ? payload.hash : "").trim();
901
+ if (!hash)
902
+ throw Object.assign(new Error("hash is required"), { code: "EINVAL" });
903
+ if (hash.startsWith("-") || !/^[a-zA-Z0-9._~^/-]{1,128}$/.test(hash)) {
904
+ throw Object.assign(new Error("invalid commit reference"), { code: "EINVAL" });
905
+ }
906
+ try {
907
+ const commitResult = await runGit(["show", "-s", "--format=%H%n%s%n%an%n%at", hash]);
908
+ if (commitResult.code !== 0 || !commitResult.stdout.trim()) {
909
+ throw Object.assign(new Error("Commit not found"), { code: "EGIT" });
910
+ }
911
+ const commitLines = commitResult.stdout.split(/\r?\n/);
912
+ const fullHash = commitLines[0]?.trim() || "";
913
+ const message = commitLines[1] ?? "";
914
+ const author = commitLines[2] ?? "";
915
+ const timestamp = Number.parseInt(commitLines[3] ?? "0", 10);
916
+ if (!fullHash) {
917
+ throw Object.assign(new Error("Commit not found"), { code: "EGIT" });
918
+ }
919
+ const filesResult = await runGit(["show", "--name-status", "--format=", hash]);
920
+ if (filesResult.code !== 0) {
921
+ throw Object.assign(new Error(filesResult.stderr || "git show failed"), { code: "EGIT" });
922
+ }
923
+ const filesRaw = filesResult.stdout;
924
+ const files = filesRaw
925
+ .split(/\r?\n/)
926
+ .map((line) => line.trim())
927
+ .filter(Boolean)
928
+ .map((line) => {
929
+ const parts = line.split("\t");
930
+ const status = parts[0] || "?";
931
+ // Handles regular + rename/copy name-status output.
932
+ const path = parts[2] || parts[1] || "";
933
+ return { status, path };
934
+ })
935
+ .filter((entry) => !!entry.path);
936
+ const diffResult = await runGit(["show", "--patch", "--format=", hash]);
937
+ if (diffResult.code !== 0) {
938
+ throw Object.assign(new Error(diffResult.stderr || "git show failed"), { code: "EGIT" });
939
+ }
940
+ const diff = diffResult.stdout;
941
+ const fileDiffs = {};
942
+ const fileChunks = diff.split(/^diff --git /m).filter(Boolean);
943
+ for (const chunk of fileChunks) {
944
+ const patch = `diff --git ${chunk}`;
945
+ const firstLine = chunk.split(/\r?\n/, 1)[0] || "";
946
+ const match = firstLine.match(/^a\/(.+?) b\/(.+)$/);
947
+ if (match?.[2]) {
948
+ fileDiffs[match[2]] = patch;
949
+ }
950
+ }
951
+ return {
952
+ commit: {
953
+ hash: fullHash.substring(0, 7),
954
+ fullHash,
955
+ message,
956
+ author,
957
+ date: timestamp * 1000,
958
+ },
959
+ files,
960
+ diff,
961
+ fileDiffs,
962
+ };
963
+ }
964
+ catch (err) {
965
+ const message = err instanceof Error ? err.message : "git show failed";
966
+ throw Object.assign(new Error(message), { code: "EGIT" });
967
+ }
968
+ }
969
+ async function handleGitDiff(payload) {
970
+ const filepath = typeof payload.path === "string" ? payload.path : "";
971
+ const staged = payload.staged === true;
972
+ const args = ["diff"];
973
+ if (staged)
974
+ args.push("--staged");
975
+ if (filepath) {
976
+ const safe = assertSafePath(filepath);
977
+ const rel = path.relative(ROOT_DIR, safe) || ".";
978
+ args.push("--", rel);
979
+ }
980
+ const result = await runGit(args);
981
+ return { diff: result.stdout };
982
+ }
983
+ async function handleGitBranches() {
984
+ const result = await runGit(["branch", "-a"]);
985
+ if (result.code !== 0) {
986
+ throw Object.assign(new Error(result.stderr || "git branch failed"), { code: "EGIT" });
987
+ }
988
+ const lines = result.stdout.trim().split("\n");
989
+ let current = "";
990
+ const branches = [];
991
+ for (const line of lines) {
992
+ const trimmed = line.trim();
993
+ if (trimmed.startsWith("* ")) {
994
+ current = trimmed.substring(2);
995
+ branches.push(current);
996
+ }
997
+ else if (!trimmed.startsWith("remotes/")) {
998
+ branches.push(trimmed);
999
+ }
1000
+ }
1001
+ return { current, branches };
1002
+ }
1003
+ async function handleGitCheckout(payload) {
1004
+ const branch = (typeof payload.branch === "string" ? payload.branch : "").trim();
1005
+ const create = payload.create === true;
1006
+ if (!branch)
1007
+ throw Object.assign(new Error("branch is required"), { code: "EINVAL" });
1008
+ if (branch.startsWith("-") || !/^[a-zA-Z0-9._/@-]+$/.test(branch)) {
1009
+ throw Object.assign(new Error("invalid branch name"), { code: "EINVAL" });
1010
+ }
1011
+ const args = create ? ["checkout", "-b", branch] : ["checkout", branch];
1012
+ const result = await runGit(args);
1013
+ if (result.code !== 0) {
1014
+ throw Object.assign(new Error(result.stderr || "git checkout failed"), { code: "EGIT" });
1015
+ }
1016
+ return { branch };
1017
+ }
1018
+ async function handleGitDeleteBranch(payload) {
1019
+ const branch = (typeof payload.branch === "string" ? payload.branch : "").trim();
1020
+ if (!branch)
1021
+ throw Object.assign(new Error("branch is required"), { code: "EINVAL" });
1022
+ if (branch.startsWith("-") || !/^[a-zA-Z0-9._/@-]+$/.test(branch)) {
1023
+ throw Object.assign(new Error("invalid branch name"), { code: "EINVAL" });
1024
+ }
1025
+ const result = await runGit(["branch", "-d", branch]);
1026
+ if (result.code !== 0) {
1027
+ throw Object.assign(new Error(result.stderr || "git branch delete failed"), { code: "EGIT" });
1028
+ }
1029
+ return { branch };
1030
+ }
1031
+ async function handleGitPull() {
1032
+ const result = await runGit(["pull"]);
1033
+ if (result.code !== 0) {
1034
+ throw Object.assign(new Error(result.stderr || "git pull failed"), { code: "EGIT" });
1035
+ }
1036
+ return { success: true, summary: result.stdout.trim() || result.stderr.trim() };
1037
+ }
1038
+ async function handleGitPush(payload) {
1039
+ const setUpstream = payload.setUpstream === true;
1040
+ const args = ["push"];
1041
+ if (setUpstream) {
1042
+ // Get current branch name
1043
+ const branchResult = await runGit(["branch", "--show-current"]);
1044
+ const branch = branchResult.stdout.trim();
1045
+ args.push("-u", "origin", branch);
1046
+ }
1047
+ const result = await runGit(args);
1048
+ if (result.code !== 0) {
1049
+ throw Object.assign(new Error(result.stderr || "git push failed"), { code: "EGIT" });
1050
+ }
1051
+ return { success: true };
1052
+ }
1053
+ async function handleGitDiscard(payload) {
1054
+ const paths = payload.paths;
1055
+ const all = payload.all === true;
1056
+ if (!paths && !all) {
1057
+ throw Object.assign(new Error("paths or all is required"), { code: "EINVAL" });
1058
+ }
1059
+ if (all) {
1060
+ // Discard all changes
1061
+ const result = await runGit(["checkout", "--", "."]);
1062
+ if (result.code !== 0) {
1063
+ throw Object.assign(new Error(result.stderr || "git checkout failed"), { code: "EGIT" });
1064
+ }
1065
+ // Also clean untracked files
1066
+ await runGit(["clean", "-fd"]);
1067
+ }
1068
+ else if (Array.isArray(paths) && paths.length > 0) {
1069
+ for (const filePath of paths) {
1070
+ const safe = assertSafePath(String(filePath));
1071
+ const rel = path.relative(ROOT_DIR, safe) || ".";
1072
+ const tracked = await runGit(["ls-files", "--error-unmatch", "--", rel]);
1073
+ if (tracked.code === 0) {
1074
+ const result = await runGit(["checkout", "--", rel]);
1075
+ if (result.code !== 0) {
1076
+ throw Object.assign(new Error(result.stderr || `git checkout failed for ${rel}`), { code: "EGIT" });
1077
+ }
1078
+ }
1079
+ else {
1080
+ const cleanResult = await runGit(["clean", "-fd", "--", rel]);
1081
+ if (cleanResult.code !== 0) {
1082
+ throw Object.assign(new Error(cleanResult.stderr || `git clean failed for ${rel}`), { code: "EGIT" });
1083
+ }
1084
+ }
1085
+ }
1086
+ }
1087
+ return {};
1088
+ }
1089
+ function emitAppEvent(msg) {
1090
+ if (activeV2Transport) {
1091
+ if (!activeV2Transport.isSecure()) {
1092
+ if (DEBUG_MODE) {
1093
+ console.error("[transport:v2] dropped event before secure session:", `${msg.ns}.${msg.action}`);
1094
+ }
1095
+ return;
1096
+ }
1097
+ void activeV2Transport.sendEvent(msg).catch((error) => {
1098
+ if (DEBUG_MODE)
1099
+ console.error("[transport:v2] failed to send event:", error instanceof Error ? error.message : String(error));
1100
+ });
1101
+ }
1102
+ }
1103
+ function emitEditorFileChanged(requestPath, mtimeMs, size) {
1104
+ logWithTimestamp("editor-watch", "emitting fileChanged", { path: requestPath, mtime: mtimeMs, size });
1105
+ emitAppEvent({
1106
+ v: 1,
1107
+ id: `editor-change-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
1108
+ ns: "editor",
1109
+ action: "fileChanged",
1110
+ payload: { path: requestPath, mtime: mtimeMs, size },
1111
+ });
1112
+ }
1113
+ function emitEditorFileDeleted(requestPath) {
1114
+ logWithTimestamp("editor-watch", "emitting fileDeleted", { path: requestPath });
1115
+ emitAppEvent({
1116
+ v: 1,
1117
+ id: `editor-delete-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
1118
+ ns: "editor",
1119
+ action: "fileDeleted",
1120
+ payload: { path: requestPath },
1121
+ });
1122
+ }
1123
+ function releaseTrackedEditorDirectory(dirPath) {
1124
+ const trackedDir = trackedEditorDirectories.get(dirPath);
1125
+ if (!trackedDir || trackedDir.filePaths.size > 0) {
1126
+ return;
1127
+ }
1128
+ trackedDir.watcher.close();
1129
+ trackedEditorDirectories.delete(dirPath);
1130
+ }
1131
+ function queueTrackedEditorFileCheck(safePath) {
1132
+ if (pendingTrackedFileChecks.has(safePath)) {
1133
+ return;
1134
+ }
1135
+ pendingTrackedFileChecks.add(safePath);
1136
+ void (async () => {
1137
+ try {
1138
+ const tracked = trackedEditorFiles.get(safePath);
1139
+ if (!tracked) {
1140
+ return;
1141
+ }
1142
+ logWithTimestamp("editor-watch", "checking tracked file", { path: tracked.requestPath });
1143
+ let stat;
1144
+ try {
1145
+ stat = await fs.stat(tracked.safePath);
1146
+ }
1147
+ catch (error) {
1148
+ const nodeError = error;
1149
+ if (nodeError?.code === "ENOENT") {
1150
+ trackedEditorFiles.delete(tracked.safePath);
1151
+ const trackedDir = trackedEditorDirectories.get(tracked.dirPath);
1152
+ if (trackedDir) {
1153
+ trackedDir.filePaths.delete(tracked.safePath);
1154
+ releaseTrackedEditorDirectory(tracked.dirPath);
1155
+ }
1156
+ emitEditorFileDeleted(tracked.requestPath);
1157
+ return;
1158
+ }
1159
+ throw error;
1160
+ }
1161
+ if (!stat.isFile()) {
1162
+ trackedEditorFiles.delete(tracked.safePath);
1163
+ const trackedDir = trackedEditorDirectories.get(tracked.dirPath);
1164
+ if (trackedDir) {
1165
+ trackedDir.filePaths.delete(tracked.safePath);
1166
+ releaseTrackedEditorDirectory(tracked.dirPath);
1167
+ }
1168
+ emitEditorFileDeleted(tracked.requestPath);
1169
+ return;
1170
+ }
1171
+ const changed = tracked.lastMtimeMs !== stat.mtimeMs || tracked.lastSize !== stat.size;
1172
+ logWithTimestamp("editor-watch", "stat compared", {
1173
+ path: tracked.requestPath,
1174
+ changed,
1175
+ prevMtime: tracked.lastMtimeMs,
1176
+ nextMtime: stat.mtimeMs,
1177
+ prevSize: tracked.lastSize,
1178
+ nextSize: stat.size,
1179
+ suppressWatcherUntil: tracked.suppressWatcherUntil,
1180
+ });
1181
+ tracked.lastMtimeMs = stat.mtimeMs;
1182
+ tracked.lastSize = stat.size;
1183
+ if (!changed) {
1184
+ return;
1185
+ }
1186
+ if (Date.now() <= tracked.suppressWatcherUntil) {
1187
+ return;
1188
+ }
1189
+ emitEditorFileChanged(tracked.requestPath, stat.mtimeMs, stat.size);
1190
+ }
1191
+ catch (error) {
1192
+ if (DEBUG_MODE) {
1193
+ console.error("[editor-watch] file check failed:", error instanceof Error ? error.message : String(error));
1194
+ }
1195
+ }
1196
+ finally {
1197
+ pendingTrackedFileChecks.delete(safePath);
1198
+ }
1199
+ })();
1200
+ }
1201
+ function ensureTrackedEditorDirectory(dirPath) {
1202
+ const existing = trackedEditorDirectories.get(dirPath);
1203
+ if (existing) {
1204
+ return existing;
1205
+ }
1206
+ const watcher = fssync.watch(dirPath, (_eventType, fileName) => {
1207
+ const trackedDir = trackedEditorDirectories.get(dirPath);
1208
+ if (!trackedDir) {
1209
+ return;
1210
+ }
1211
+ const changedName = fileName == null ? null : String(fileName);
1212
+ logWithTimestamp("editor-watch", "directory event", { dirPath, fileName: changedName });
1213
+ if (!changedName) {
1214
+ for (const safePath of trackedDir.filePaths) {
1215
+ queueTrackedEditorFileCheck(safePath);
1216
+ }
1217
+ return;
1218
+ }
1219
+ for (const safePath of trackedDir.filePaths) {
1220
+ const tracked = trackedEditorFiles.get(safePath);
1221
+ if (tracked && tracked.baseName === changedName) {
1222
+ queueTrackedEditorFileCheck(safePath);
1223
+ }
1224
+ }
1225
+ });
1226
+ watcher.on("error", (error) => {
1227
+ if (DEBUG_MODE) {
1228
+ console.error("[editor-watch] directory watcher error:", dirPath, error instanceof Error ? error.message : String(error));
1229
+ }
1230
+ });
1231
+ const trackedDir = {
1232
+ watcher,
1233
+ filePaths: new Set(),
1234
+ };
1235
+ trackedEditorDirectories.set(dirPath, trackedDir);
1236
+ return trackedDir;
1237
+ }
1238
+ async function trackEditorFile(requestPath) {
1239
+ const safePath = assertSafePath(requestPath);
1240
+ const stat = await fs.stat(safePath);
1241
+ if (!stat.isFile()) {
1242
+ throw Object.assign(new Error("Only files can be tracked by the editor"), { code: "EINVAL" });
1243
+ }
1244
+ const existing = trackedEditorFiles.get(safePath);
1245
+ if (existing) {
1246
+ existing.openCount += 1;
1247
+ existing.requestPath = requestPath;
1248
+ existing.lastMtimeMs = stat.mtimeMs;
1249
+ existing.lastSize = stat.size;
1250
+ logWithTimestamp("editor-watch", "increment tracked file", { path: requestPath, openCount: existing.openCount });
1251
+ return { path: requestPath, tracked: true };
1252
+ }
1253
+ const dirPath = path.dirname(safePath);
1254
+ const trackedDir = ensureTrackedEditorDirectory(dirPath);
1255
+ trackedDir.filePaths.add(safePath);
1256
+ trackedEditorFiles.set(safePath, {
1257
+ requestPath,
1258
+ safePath,
1259
+ dirPath,
1260
+ baseName: path.basename(safePath),
1261
+ openCount: 1,
1262
+ lastMtimeMs: stat.mtimeMs,
1263
+ lastSize: stat.size,
1264
+ suppressWatcherUntil: 0,
1265
+ });
1266
+ logWithTimestamp("editor-watch", "tracking file", { path: requestPath, dirPath, mtime: stat.mtimeMs, size: stat.size });
1267
+ return { path: requestPath, tracked: true };
1268
+ }
1269
+ function untrackEditorFile(requestPath) {
1270
+ const safePath = assertSafePath(requestPath);
1271
+ const tracked = trackedEditorFiles.get(safePath);
1272
+ if (!tracked) {
1273
+ return { path: requestPath, tracked: false };
1274
+ }
1275
+ tracked.openCount -= 1;
1276
+ logWithTimestamp("editor-watch", "decrement tracked file", { path: requestPath, openCount: tracked.openCount });
1277
+ if (tracked.openCount > 0) {
1278
+ return { path: requestPath, tracked: true };
1279
+ }
1280
+ trackedEditorFiles.delete(safePath);
1281
+ const trackedDir = trackedEditorDirectories.get(tracked.dirPath);
1282
+ if (trackedDir) {
1283
+ trackedDir.filePaths.delete(safePath);
1284
+ releaseTrackedEditorDirectory(tracked.dirPath);
1285
+ }
1286
+ return { path: requestPath, tracked: false };
1287
+ }
1288
+ async function renameTrackedEditorFile(fromPath, toPath) {
1289
+ const safeFrom = assertSafePath(fromPath);
1290
+ const safeTo = assertSafePath(toPath);
1291
+ const tracked = trackedEditorFiles.get(safeFrom);
1292
+ if (!tracked) {
1293
+ return { from: fromPath, to: toPath, tracked: false };
1294
+ }
1295
+ logWithTimestamp("editor-watch", "renaming tracked file", { from: fromPath, to: toPath });
1296
+ const fromDir = trackedEditorDirectories.get(tracked.dirPath);
1297
+ if (fromDir) {
1298
+ fromDir.filePaths.delete(tracked.safePath);
1299
+ releaseTrackedEditorDirectory(tracked.dirPath);
1300
+ }
1301
+ trackedEditorFiles.delete(tracked.safePath);
1302
+ const stat = await fs.stat(safeTo);
1303
+ const nextDirPath = path.dirname(safeTo);
1304
+ const nextDir = ensureTrackedEditorDirectory(nextDirPath);
1305
+ nextDir.filePaths.add(safeTo);
1306
+ tracked.requestPath = toPath;
1307
+ tracked.safePath = safeTo;
1308
+ tracked.dirPath = nextDirPath;
1309
+ tracked.baseName = path.basename(safeTo);
1310
+ tracked.lastMtimeMs = stat.mtimeMs;
1311
+ tracked.lastSize = stat.size;
1312
+ trackedEditorFiles.set(safeTo, tracked);
1313
+ return { from: fromPath, to: toPath, tracked: true };
1314
+ }
1315
+ function deleteTrackedEditorFile(requestPath) {
1316
+ const safePath = assertSafePath(requestPath);
1317
+ const tracked = trackedEditorFiles.get(safePath);
1318
+ if (!tracked) {
1319
+ return { path: requestPath, tracked: false };
1320
+ }
1321
+ logWithTimestamp("editor-watch", "deleting tracked file", { path: requestPath });
1322
+ trackedEditorFiles.delete(safePath);
1323
+ const trackedDir = trackedEditorDirectories.get(tracked.dirPath);
1324
+ if (trackedDir) {
1325
+ trackedDir.filePaths.delete(safePath);
1326
+ releaseTrackedEditorDirectory(tracked.dirPath);
1327
+ }
1328
+ return { path: requestPath, tracked: false };
1329
+ }
1330
+ async function noteTrackedFileWrite(requestPath, source) {
1331
+ const safePath = assertSafePath(requestPath);
1332
+ const tracked = trackedEditorFiles.get(safePath);
1333
+ if (!tracked) {
1334
+ return;
1335
+ }
1336
+ const stat = await fs.stat(safePath);
1337
+ tracked.lastMtimeMs = stat.mtimeMs;
1338
+ tracked.lastSize = stat.size;
1339
+ tracked.suppressWatcherUntil = Date.now() + 1500;
1340
+ logWithTimestamp("editor-watch", "tracked file write noted", {
1341
+ path: tracked.requestPath,
1342
+ source,
1343
+ mtime: stat.mtimeMs,
1344
+ size: stat.size,
1345
+ suppressWatcherUntil: tracked.suppressWatcherUntil,
1346
+ });
1347
+ if (source !== "editor") {
1348
+ emitEditorFileChanged(tracked.requestPath, stat.mtimeMs, stat.size);
1349
+ }
1350
+ }
1351
+ let ensurePtyBinaryPromise = null;
1352
+ function normalizeJsonWithTrailingCommas(text) {
1353
+ return text.replace(/,\s*([}\]])/g, "$1");
1354
+ }
1355
+ function getKodoRunConfigDir() {
1356
+ const platform = os.platform();
1357
+ if (platform === "win32") {
1358
+ const appData = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
1359
+ return path.join(appData, "kodorun");
1360
+ }
1361
+ if (platform === "darwin") {
1362
+ return path.join(os.homedir(), "Library", "Application Support", "kodorun");
1363
+ }
1364
+ const xdg = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
1365
+ return path.join(xdg, "kodorun");
1366
+ }
1367
+ function getPlatformDisplayLabel() {
1368
+ const platform = os.platform();
1369
+ const osLabel = platform === "darwin" ? "macOS" : platform === "win32" ? "Windows" : platform === "linux" ? "Linux" : platform;
1370
+ return `${osLabel} (${os.arch()})`;
1371
+ }
1372
+ function getPtyReleaseTarget() {
1373
+ const platform = os.platform();
1374
+ const arch = os.arch();
1375
+ const release = PTY_RELEASES[`${platform}:${arch}`];
1376
+ if (release)
1377
+ return release;
1378
+ if (platform === "win32" && arch === "arm64") {
1379
+ return PTY_RELEASES["win32:x64"] ?? null;
1380
+ }
1381
+ return null;
1382
+ }
1383
+ function getPtyBinaryPath(fileName) {
1384
+ return path.join(getKodoRunConfigDir(), "pty-releases", fileName);
1385
+ }
1386
+ const MAX_PTY_BINARY_BYTES = 64 * 1024 * 1024;
1387
+ let ensurePtyProcessPromise = null;
1388
+ async function downloadPtyBinary(url, destination) {
1389
+ const tempPath = `${destination}.download`;
1390
+ console.log("[pty] Downloading PTY [downloading...]");
1391
+ const response = await fetch(url, { signal: AbortSignal.timeout(45_000) });
1392
+ if (!response.ok) {
1393
+ throw new Error(`Failed to download PTY binary (${response.status})`);
1394
+ }
1395
+ if (!response.body) {
1396
+ throw new Error("PTY download response had no body");
1397
+ }
1398
+ const reader = response.body.getReader();
1399
+ const chunks = [];
1400
+ let totalBytes = 0;
1401
+ try {
1402
+ while (true) {
1403
+ const { done, value } = await reader.read();
1404
+ if (done)
1405
+ break;
1406
+ if (value) {
1407
+ totalBytes += value.byteLength;
1408
+ if (totalBytes > MAX_PTY_BINARY_BYTES) {
1409
+ throw new Error("PTY binary exceeded maximum allowed size");
1410
+ }
1411
+ chunks.push(value);
1412
+ }
1413
+ }
1414
+ const binary = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));
1415
+ await fs.writeFile(tempPath, binary);
1416
+ if (os.platform() !== "win32") {
1417
+ await fs.chmod(tempPath, 0o755);
1418
+ }
1419
+ await fs.rename(tempPath, destination);
1420
+ console.log(`[pty] Downloaded PTY (${Math.max(1, Math.round(totalBytes / 1024))} KB)`);
1421
+ }
1422
+ catch (err) {
1423
+ await fs.rm(tempPath, { force: true }).catch(() => { });
1424
+ throw err;
1425
+ }
1426
+ }
1427
+ async function ensurePtyBinaryReady() {
1428
+ if (ensurePtyBinaryPromise)
1429
+ return ensurePtyBinaryPromise;
1430
+ ensurePtyBinaryPromise = (async () => {
1431
+ const envBin = process.env.KODORUN_PTY_BIN?.trim();
1432
+ if (envBin) {
1433
+ try {
1434
+ await fs.access(envBin);
1435
+ return envBin;
1436
+ }
1437
+ catch {
1438
+ // fall through
1439
+ }
1440
+ }
1441
+ const cliDir = path.dirname(fileURLToPath(import.meta.url));
1442
+ const localBinName = os.platform() === "win32" ? "kodorun-pty.exe" : "kodorun-pty";
1443
+ const localBin = path.resolve(cliDir, "..", "..", "pty", "target", "release", localBinName);
1444
+ try {
1445
+ await fs.access(localBin);
1446
+ return localBin;
1447
+ }
1448
+ catch {
1449
+ // fall through
1450
+ }
1451
+ const release = getPtyReleaseTarget();
1452
+ if (!release)
1453
+ return null;
1454
+ const binPath = getPtyBinaryPath(release.fileName);
1455
+ await fs.mkdir(path.dirname(binPath), { recursive: true });
1456
+ try {
1457
+ await fs.access(binPath);
1458
+ return binPath;
1459
+ }
1460
+ catch {
1461
+ console.log(`[pty] PTY missing. Installing ${release.fileName}...`);
1462
+ await downloadPtyBinary(release.url, binPath);
1463
+ return binPath;
1464
+ }
1465
+ })();
1466
+ try {
1467
+ return await ensurePtyBinaryPromise;
1468
+ }
1469
+ finally {
1470
+ ensurePtyBinaryPromise = null;
1471
+ }
1472
+ }
1473
+ async function ensurePtyProcess() {
1474
+ if (ptyProcess && ptyProcess.exitCode === null)
1475
+ return;
1476
+ if (ensurePtyProcessPromise)
1477
+ return await ensurePtyProcessPromise;
1478
+ ensurePtyProcessPromise = (async () => {
1479
+ if (ptyProcess && ptyProcess.exitCode === null)
1480
+ return;
1481
+ const binPath = await ensurePtyBinaryReady();
1482
+ if (!binPath) {
1483
+ throw new Error(`PTY is not supported on ${os.platform()}/${os.arch()}`);
1484
+ }
1485
+ const spawned = spawn(binPath, [], {
1486
+ cwd: ROOT_DIR,
1487
+ stdio: ["pipe", "pipe", "pipe"],
1488
+ });
1489
+ ptyProcess = spawned;
1490
+ spawned.stdin?.on("error", (err) => {
1491
+ debugLog(`[pty] stdin error: ${err.message}`);
1492
+ });
1493
+ spawned.on("error", (err) => {
1494
+ console.error("[pty] Failed to start PTY process:", err.message);
1495
+ if (ptyProcess === spawned)
1496
+ ptyProcess = null;
1497
+ for (const [, pending] of ptyPendingSpawns) {
1498
+ pending.reject(new Error(`PTY process error: ${err.message}`));
1499
+ }
1500
+ ptyPendingSpawns.clear();
1501
+ });
1502
+ spawned.stderr?.on("data", (data) => {
1503
+ console.error("[pty]", data.toString().trim());
1504
+ });
1505
+ spawned.on("exit", (code) => {
1506
+ debugLog(`[pty] PTY process exited with code ${code}`);
1507
+ if (ptyProcess === spawned)
1508
+ ptyProcess = null;
1509
+ // Reject all pending spawns
1510
+ for (const [, pending] of ptyPendingSpawns) {
1511
+ pending.reject(new Error("PTY process exited"));
1512
+ }
1513
+ ptyPendingSpawns.clear();
1514
+ });
1515
+ // Parse stdout line by line for events from the Rust binary
1516
+ const rl = createInterface({ input: spawned.stdout });
1517
+ rl.on("line", (line) => {
1518
+ let event;
1519
+ try {
1520
+ event = JSON.parse(line);
1521
+ }
1522
+ catch {
1523
+ return;
1524
+ }
1525
+ if (event.event === "spawned") {
1526
+ const pending = ptyPendingSpawns.get(event.id);
1527
+ if (pending) {
1528
+ pending.resolve();
1529
+ ptyPendingSpawns.delete(event.id);
1530
+ }
1531
+ }
1532
+ else if (event.event === "state") {
1533
+ // Forward screen state to app via data channel
1534
+ const msg = {
1535
+ v: 1,
1536
+ id: `evt-${Date.now()}`,
1537
+ ns: "terminal",
1538
+ action: "state",
1539
+ payload: {
1540
+ terminalId: event.id,
1541
+ cells: event.cells,
1542
+ cursorX: event.cursorX,
1543
+ cursorY: event.cursorY,
1544
+ cols: event.cols,
1545
+ rows: event.rows,
1546
+ cursorVisible: event.cursorVisible,
1547
+ cursorStyle: event.cursorStyle,
1548
+ appCursorKeys: event.appCursorKeys,
1549
+ bracketedPaste: event.bracketedPaste,
1550
+ mouseMode: event.mouseMode,
1551
+ mouseEncoding: event.mouseEncoding,
1552
+ reverseVideo: event.reverseVideo,
1553
+ title: event.title,
1554
+ scrollbackLength: event.scrollbackLength,
1555
+ },
1556
+ };
1557
+ emitAppEvent(msg);
1558
+ }
1559
+ else if (event.event === "exit") {
1560
+ terminals.delete(event.id);
1561
+ const msg = {
1562
+ v: 1,
1563
+ id: `evt-${Date.now()}`,
1564
+ ns: "terminal",
1565
+ action: "exit",
1566
+ payload: { terminalId: event.id, code: event.code },
1567
+ };
1568
+ emitAppEvent(msg);
1569
+ }
1570
+ else if (event.event === "error") {
1571
+ const pending = ptyPendingSpawns.get(event.id);
1572
+ if (pending) {
1573
+ pending.reject(new Error(String(event.message || "PTY error")));
1574
+ ptyPendingSpawns.delete(event.id);
1575
+ }
1576
+ console.error(`[pty] Error for ${event.id}: ${event.message}`);
1577
+ }
1578
+ });
1579
+ })();
1580
+ try {
1581
+ await ensurePtyProcessPromise;
1582
+ }
1583
+ finally {
1584
+ ensurePtyProcessPromise = null;
1585
+ }
1586
+ }
1587
+ function sendToPty(cmd) {
1588
+ if (!ptyProcess || ptyProcess.exitCode !== null || !ptyProcess.stdin?.writable) {
1589
+ throw Object.assign(new Error("PTY process not running"), { code: "ENOPTY" });
1590
+ }
1591
+ ptyProcess.stdin.write(JSON.stringify(cmd) + "\n");
1592
+ }
1593
+ function clampTerminalSize(value, fallback, max) {
1594
+ const num = Number(value);
1595
+ if (!Number.isFinite(num))
1596
+ return fallback;
1597
+ return Math.min(max, Math.max(1, Math.trunc(num)));
1598
+ }
1599
+ async function handleTerminalSpawn(payload) {
1600
+ await ensurePtyProcess();
1601
+ const shell = payload.shell || getDefaultTerminalShell();
1602
+ const cols = clampTerminalSize(payload.cols, 80, 1000);
1603
+ const rows = clampTerminalSize(payload.rows, 24, 500);
1604
+ const terminalId = `term-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
1605
+ // Wait for the Rust binary to confirm spawn
1606
+ const spawnPromise = new Promise((resolve, reject) => {
1607
+ ptyPendingSpawns.set(terminalId, { resolve, reject });
1608
+ setTimeout(() => {
1609
+ if (ptyPendingSpawns.has(terminalId)) {
1610
+ ptyPendingSpawns.delete(terminalId);
1611
+ reject(new Error("Spawn timed out"));
1612
+ }
1613
+ }, 10000);
1614
+ });
1615
+ sendToPty({ cmd: "spawn", id: terminalId, shell, cols, rows });
1616
+ await spawnPromise;
1617
+ terminals.add(terminalId);
1618
+ return { terminalId };
1619
+ }
1620
+ function handleTerminalWrite(payload) {
1621
+ const terminalId = payload.terminalId;
1622
+ const data = payload.data;
1623
+ if (!terminalId)
1624
+ throw Object.assign(new Error("terminalId is required"), { code: "EINVAL" });
1625
+ if (typeof data !== "string")
1626
+ throw Object.assign(new Error("data is required"), { code: "EINVAL" });
1627
+ if (!terminals.has(terminalId))
1628
+ throw Object.assign(new Error("Terminal not found"), { code: "ENOTERM" });
1629
+ sendToPty({ cmd: "write", id: terminalId, data });
1630
+ return {};
1631
+ }
1632
+ function handleTerminalResize(payload) {
1633
+ const terminalId = payload.terminalId;
1634
+ const cols = clampTerminalSize(payload.cols, 80, 1000);
1635
+ const rows = clampTerminalSize(payload.rows, 24, 500);
1636
+ if (!terminalId)
1637
+ throw Object.assign(new Error("terminalId is required"), { code: "EINVAL" });
1638
+ if (!terminals.has(terminalId))
1639
+ throw Object.assign(new Error("Terminal not found"), { code: "ENOTERM" });
1640
+ sendToPty({ cmd: "resize", id: terminalId, cols, rows });
1641
+ return {};
1642
+ }
1643
+ function handleTerminalKill(payload) {
1644
+ const terminalId = payload.terminalId;
1645
+ if (!terminalId)
1646
+ throw Object.assign(new Error("terminalId is required"), { code: "EINVAL" });
1647
+ if (!terminals.has(terminalId))
1648
+ throw Object.assign(new Error("Terminal not found"), { code: "ENOTERM" });
1649
+ sendToPty({ cmd: "kill", id: terminalId });
1650
+ terminals.delete(terminalId);
1651
+ return {};
1652
+ }
1653
+ function handleTerminalScroll(payload) {
1654
+ const terminalId = payload.terminalId;
1655
+ const offset = payload.offset || 0;
1656
+ if (!terminalId)
1657
+ throw Object.assign(new Error("terminalId is required"), { code: "EINVAL" });
1658
+ if (!terminals.has(terminalId))
1659
+ throw Object.assign(new Error("Terminal not found"), { code: "ENOTERM" });
1660
+ sendToPty({ cmd: "scroll", id: terminalId, offset });
1661
+ return {};
1662
+ }
1663
+ // ============================================================================
1664
+ // System Handlers
1665
+ // ============================================================================
1666
+ function handleSystemCapabilities() {
1667
+ return {
1668
+ version: VERSION,
1669
+ namespaces: ["fs", "git", "terminal", "processes", "ports", "monitor", "http", "ai", "proxy", "editor"],
1670
+ platform: os.platform(),
1671
+ rootDir: ROOT_DIR,
1672
+ hostname: os.hostname(),
1673
+ };
1674
+ }
1675
+ function handleSystemPing() {
1676
+ return { pong: true, timestamp: Date.now() };
1677
+ }
1678
+ // ============================================================================
1679
+ // Processes Handlers
1680
+ // ============================================================================
1681
+ function handleProcessesList() {
1682
+ const result = [];
1683
+ for (const [pid, proc] of processes) {
1684
+ result.push({
1685
+ pid,
1686
+ command: `${proc.command} ${proc.args.join(" ")}`.trim(),
1687
+ startTime: proc.startTime,
1688
+ status: proc.proc.killed ? "stopped" : "running",
1689
+ channel: proc.channel,
1690
+ cwd: proc.cwd,
1691
+ });
1692
+ }
1693
+ return { processes: result };
1694
+ }
1695
+ const MAX_PROCESS_OUTPUT_BYTES = 2 * 1024 * 1024;
1696
+ const MAX_PROCESS_OUTPUT_CHUNKS = 1_000;
1697
+ function appendProcessOutputBuffer(channel, text) {
1698
+ const combined = (processOutputBuffers.get(channel) || "") + text;
1699
+ const trimmed = combined.length > MAX_PROCESS_OUTPUT_BYTES
1700
+ ? combined.slice(combined.length - MAX_PROCESS_OUTPUT_BYTES)
1701
+ : combined;
1702
+ processOutputBuffers.set(channel, trimmed);
1703
+ }
1704
+ async function handleProcessesSpawn(payload) {
1705
+ const command = payload.command;
1706
+ const rawArgs = payload.args;
1707
+ const args = Array.isArray(rawArgs) ? rawArgs.map((a) => String(a)) : [];
1708
+ const cwd = payload.cwd;
1709
+ const extraEnvRaw = (payload.env && typeof payload.env === "object" && !Array.isArray(rawArgs ? payload.env : null))
1710
+ ? payload.env
1711
+ : {};
1712
+ const extraEnv = {};
1713
+ for (const [k, v] of Object.entries(extraEnvRaw)) {
1714
+ if (typeof v === "string")
1715
+ extraEnv[k] = v;
1716
+ }
1717
+ if (typeof command !== "string" || !command.trim()) {
1718
+ throw Object.assign(new Error("command is required"), { code: "EINVAL" });
1719
+ }
1720
+ const workDir = cwd ? assertSafePath(cwd) : ROOT_DIR;
1721
+ const proc = spawn(command, args, {
1722
+ cwd: workDir,
1723
+ env: { ...process.env, ...extraEnv },
1724
+ stdio: ["pipe", "pipe", "pipe"],
1725
+ shell: false,
1726
+ });
1727
+ const pid = await new Promise((resolve, reject) => {
1728
+ let settled = false;
1729
+ const handleSpawn = () => {
1730
+ if (settled)
1731
+ return;
1732
+ settled = true;
1733
+ proc.removeListener("error", handleError);
1734
+ if (!proc.pid) {
1735
+ reject(Object.assign(new Error(`Failed to spawn "${command}"`), { code: "ERROR" }));
1736
+ return;
1737
+ }
1738
+ resolve(proc.pid);
1739
+ };
1740
+ const handleError = (err) => {
1741
+ if (settled)
1742
+ return;
1743
+ settled = true;
1744
+ proc.removeListener("spawn", handleSpawn);
1745
+ reject(Object.assign(new Error(err.message || `Failed to spawn "${command}"`), {
1746
+ code: err.code || "ERROR",
1747
+ }));
1748
+ };
1749
+ proc.once("spawn", handleSpawn);
1750
+ proc.once("error", handleError);
1751
+ });
1752
+ const channel = `proc-${pid}`;
1753
+ const managedProc = {
1754
+ pid,
1755
+ proc,
1756
+ command,
1757
+ args,
1758
+ cwd: workDir,
1759
+ startTime: Date.now(),
1760
+ output: [],
1761
+ channel,
1762
+ };
1763
+ processes.set(pid, managedProc);
1764
+ processOutputBuffers.set(channel, "");
1765
+ // Stream output
1766
+ const sendOutput = (stream) => (data) => {
1767
+ const text = data.toString();
1768
+ managedProc.output.push(text);
1769
+ if (managedProc.output.length > MAX_PROCESS_OUTPUT_CHUNKS) {
1770
+ managedProc.output.splice(0, managedProc.output.length - MAX_PROCESS_OUTPUT_CHUNKS);
1771
+ }
1772
+ appendProcessOutputBuffer(channel, text);
1773
+ const msg = {
1774
+ v: 1,
1775
+ id: `evt-${Date.now()}`,
1776
+ ns: "processes",
1777
+ action: "output",
1778
+ payload: { pid, channel, stream, data: text },
1779
+ };
1780
+ emitAppEvent(msg);
1781
+ };
1782
+ proc.stdin?.on("error", (err) => {
1783
+ debugLog(`[processes] stdin error for pid ${pid}: ${err.message}`);
1784
+ });
1785
+ proc.stdout?.on("data", sendOutput("stdout"));
1786
+ proc.stderr?.on("data", sendOutput("stderr"));
1787
+ proc.on("error", (err) => {
1788
+ const message = err.message || `Process "${command}" failed`;
1789
+ appendProcessOutputBuffer(channel, `${message}\n`);
1790
+ emitAppEvent({
1791
+ v: 1,
1792
+ id: `evt-${Date.now()}`,
1793
+ ns: "processes",
1794
+ action: "output",
1795
+ payload: { pid, channel, stream: "stderr", data: `${message}\n` },
1796
+ });
1797
+ });
1798
+ proc.on("close", (code, signal) => {
1799
+ processes.delete(pid);
1800
+ const cleanupTimer = setTimeout(() => {
1801
+ processOutputBuffers.delete(channel);
1802
+ }, 5 * 60 * 1000);
1803
+ cleanupTimer.unref?.();
1804
+ const msg = {
1805
+ v: 1,
1806
+ id: `evt-${Date.now()}`,
1807
+ ns: "processes",
1808
+ action: "exit",
1809
+ payload: { pid, channel, code, signal },
1810
+ };
1811
+ emitAppEvent(msg);
1812
+ });
1813
+ return { pid, channel };
1814
+ }
1815
+ function handleProcessesKill(payload) {
1816
+ const pid = payload.pid;
1817
+ if (!pid)
1818
+ throw Object.assign(new Error("pid is required"), { code: "EINVAL" });
1819
+ const proc = processes.get(pid);
1820
+ if (!proc)
1821
+ throw Object.assign(new Error("Process not found"), { code: "ENOPROC" });
1822
+ proc.proc.kill();
1823
+ processes.delete(pid);
1824
+ return {};
1825
+ }
1826
+ function handleProcessesGetOutput(payload) {
1827
+ const channel = payload.channel;
1828
+ if (!channel)
1829
+ throw Object.assign(new Error("channel is required"), { code: "EINVAL" });
1830
+ const output = processOutputBuffers.get(channel) || "";
1831
+ return { channel, output };
1832
+ }
1833
+ function handleProcessesClearOutput(payload) {
1834
+ const channel = payload.channel;
1835
+ if (channel) {
1836
+ processOutputBuffers.set(channel, "");
1837
+ }
1838
+ else {
1839
+ processOutputBuffers.clear();
1840
+ }
1841
+ return {};
1842
+ }
1843
+ // ============================================================================
1844
+ // Ports Handlers
1845
+ // ============================================================================
1846
+ function handlePortsList() {
1847
+ const platform = os.platform();
1848
+ const ports = [];
1849
+ try {
1850
+ let output;
1851
+ if (platform === "darwin" || platform === "linux") {
1852
+ // Use lsof on macOS/Linux
1853
+ try {
1854
+ output = execSync("lsof -iTCP -sTCP:LISTEN -P -n 2>/dev/null || true", {
1855
+ encoding: "utf-8",
1856
+ timeout: 5000,
1857
+ });
1858
+ const lines = output.trim().split("\n").slice(1); // Skip header
1859
+ for (const line of lines) {
1860
+ const parts = line.split(/\s+/);
1861
+ if (parts.length >= 9) {
1862
+ const processName = parts[0];
1863
+ const pid = parseInt(parts[1]);
1864
+ const nameField = parts[8];
1865
+ // Parse address:port format
1866
+ const match = nameField.match(/:(\d+)$/);
1867
+ if (match) {
1868
+ const port = parseInt(match[1]);
1869
+ const address = nameField.replace(`:${port}`, "") || "0.0.0.0";
1870
+ ports.push({ port, pid, process: processName, address });
1871
+ }
1872
+ }
1873
+ }
1874
+ }
1875
+ catch {
1876
+ // lsof might fail, try netstat
1877
+ output = execSync("netstat -tlnp 2>/dev/null || netstat -an 2>/dev/null || true", {
1878
+ encoding: "utf-8",
1879
+ timeout: 5000,
1880
+ });
1881
+ }
1882
+ }
1883
+ else if (platform === "win32") {
1884
+ output = execSync("netstat -ano | findstr LISTENING", {
1885
+ encoding: "utf-8",
1886
+ timeout: 5000,
1887
+ });
1888
+ const lines = output.trim().split("\n");
1889
+ for (const line of lines) {
1890
+ const parts = line.trim().split(/\s+/);
1891
+ if (parts.length >= 5) {
1892
+ const localAddr = parts[1];
1893
+ const pid = parseInt(parts[4]);
1894
+ const match = localAddr.match(/:(\d+)$/);
1895
+ if (match) {
1896
+ const port = parseInt(match[1]);
1897
+ const address = localAddr.replace(`:${port}`, "");
1898
+ ports.push({ port, pid, process: "unknown", address });
1899
+ }
1900
+ }
1901
+ }
1902
+ }
1903
+ }
1904
+ catch {
1905
+ // Return empty list on error
1906
+ }
1907
+ return { ports };
1908
+ }
1909
+ function handlePortsIsAvailable(payload) {
1910
+ const port = Math.floor(Number(payload.port));
1911
+ if (!Number.isFinite(port) || port < 1 || port > 65535) {
1912
+ throw Object.assign(new Error("port must be an integer between 1 and 65535"), { code: "EINVAL" });
1913
+ }
1914
+ return new Promise((resolve) => {
1915
+ const server = createServer();
1916
+ server.once("error", (err) => {
1917
+ if (err.code === "EADDRINUSE") {
1918
+ resolve({ port, available: false });
1919
+ }
1920
+ else {
1921
+ resolve({ port, available: false, error: err.message });
1922
+ }
1923
+ });
1924
+ server.once("listening", () => {
1925
+ server.close(() => {
1926
+ resolve({ port, available: true });
1927
+ });
1928
+ });
1929
+ server.listen(port, "127.0.0.1");
1930
+ });
1931
+ }
1932
+ function handlePortsKill(payload) {
1933
+ const port = payload.port;
1934
+ if (!port)
1935
+ throw Object.assign(new Error("port is required"), { code: "EINVAL" });
1936
+ // Strict port range validation to prevent injection via crafted numeric values
1937
+ const portNum = Math.floor(Number(port));
1938
+ if (!Number.isFinite(portNum) || portNum < 1 || portNum > 65535) {
1939
+ throw Object.assign(new Error("port must be an integer between 1 and 65535"), { code: "EINVAL" });
1940
+ }
1941
+ const platform = os.platform();
1942
+ try {
1943
+ let pid = null;
1944
+ if (platform === "darwin" || platform === "linux") {
1945
+ // Use spawnSync with an explicit args array — never shell: true — so portNum
1946
+ // cannot escape into a shell command even if it were somehow non-numeric.
1947
+ const result = spawnSync("lsof", ["-ti", String(portNum)], { encoding: "utf-8" });
1948
+ const pids = (result.stdout || "").trim().split("\n").filter(Boolean);
1949
+ for (const pidStr of pids) {
1950
+ const p = parseInt(pidStr, 10);
1951
+ if (!Number.isFinite(p) || p <= 0)
1952
+ continue;
1953
+ if (pid === null)
1954
+ pid = p;
1955
+ // Send SIGKILL directly via process.kill — no shell involved.
1956
+ try {
1957
+ process.kill(p, "SIGKILL");
1958
+ }
1959
+ catch { /* already dead */ }
1960
+ }
1961
+ }
1962
+ else if (platform === "win32") {
1963
+ // Use netstat via args array, parse PIDs, then taskkill via args array.
1964
+ const result = spawnSync("netstat", ["-ano"], { encoding: "utf-8" });
1965
+ const lines = (result.stdout || "").trim().split("\n");
1966
+ for (const line of lines) {
1967
+ const parts = line.trim().split(/\s+/);
1968
+ // netstat -ano columns: Proto Local Foreign State PID
1969
+ // Match only lines where the local address ends with :<portNum>
1970
+ if (parts.length < 5)
1971
+ continue;
1972
+ const localAddr = parts[1] ?? "";
1973
+ if (!localAddr.endsWith(`:${portNum}`))
1974
+ continue;
1975
+ const p = parseInt(parts[4], 10);
1976
+ if (!Number.isFinite(p) || p <= 0)
1977
+ continue;
1978
+ if (pid === null)
1979
+ pid = p;
1980
+ spawnSync("taskkill", ["/F", "/PID", String(p)], { encoding: "utf-8" });
1981
+ break;
1982
+ }
1983
+ }
1984
+ return { port: portNum, pid };
1985
+ }
1986
+ catch (err) {
1987
+ throw Object.assign(new Error(`Failed to kill process on port ${portNum}`), { code: "EPERM" });
1988
+ }
1989
+ }
1990
+ // ============================================================================
1991
+ // Monitor Handlers
1992
+ // ============================================================================
1993
+ function getCpuUsage() {
1994
+ const cpus = os.cpus();
1995
+ const coreUsages = [];
1996
+ let totalIdle = 0;
1997
+ let totalTick = 0;
1998
+ for (let i = 0; i < cpus.length; i++) {
1999
+ const cpu = cpus[i];
2000
+ const total = Object.values(cpu.times).reduce((a, b) => a + b, 0);
2001
+ const idle = cpu.times.idle;
2002
+ if (lastCpuInfo && lastCpuInfo[i]) {
2003
+ const deltaTotal = total - lastCpuInfo[i].total;
2004
+ const deltaIdle = idle - lastCpuInfo[i].idle;
2005
+ const usage = deltaTotal > 0 ? ((deltaTotal - deltaIdle) / deltaTotal) * 100 : 0;
2006
+ coreUsages.push(Math.round(usage * 10) / 10);
2007
+ }
2008
+ else {
2009
+ coreUsages.push(0);
2010
+ }
2011
+ totalIdle += idle;
2012
+ totalTick += total;
2013
+ }
2014
+ // Update last CPU info for next calculation
2015
+ lastCpuInfo = cpus.map((cpu) => ({
2016
+ idle: cpu.times.idle,
2017
+ total: Object.values(cpu.times).reduce((a, b) => a + b, 0),
2018
+ }));
2019
+ const avgUsage = coreUsages.length > 0
2020
+ ? coreUsages.reduce((a, b) => a + b, 0) / coreUsages.length
2021
+ : 0;
2022
+ return { usage: Math.round(avgUsage * 10) / 10, cores: coreUsages };
2023
+ }
2024
+ function getMemoryInfo() {
2025
+ const total = os.totalmem();
2026
+ const free = os.freemem();
2027
+ const used = total - free;
2028
+ const usedPercent = Math.round((used / total) * 1000) / 10;
2029
+ return { total, used, free, usedPercent };
2030
+ }
2031
+ function getDiskInfo() {
2032
+ const platform = os.platform();
2033
+ const disks = [];
2034
+ try {
2035
+ if (platform === "darwin" || platform === "linux") {
2036
+ const output = execSync("df -Pk 2>/dev/null || true", { encoding: "utf-8", timeout: 5000 });
2037
+ const lines = output.trim().split("\n").slice(1);
2038
+ for (const line of lines) {
2039
+ const parts = line.split(/\s+/);
2040
+ if (parts.length >= 6) {
2041
+ const filesystem = parts[0];
2042
+ const size = parseInt(parts[1]) * 1024;
2043
+ const used = parseInt(parts[2]) * 1024;
2044
+ const free = parseInt(parts[3]) * 1024;
2045
+ const mount = parts.slice(5).join(" ");
2046
+ // Skip special filesystems
2047
+ if (mount.startsWith("/") && !filesystem.startsWith("devfs") && !filesystem.startsWith("map ")) {
2048
+ disks.push({
2049
+ mount,
2050
+ filesystem,
2051
+ size,
2052
+ used,
2053
+ free,
2054
+ usedPercent: size > 0 ? Math.round((used / size) * 1000) / 10 : 0,
2055
+ });
2056
+ }
2057
+ }
2058
+ }
2059
+ }
2060
+ else if (platform === "win32") {
2061
+ let parsedFromPowerShell = false;
2062
+ try {
2063
+ const psOut = execSync('powershell -NoProfile -Command "Get-CimInstance Win32_LogicalDisk -Filter \\"DriveType=3\\" | Select-Object DeviceID,FreeSpace,Size | ConvertTo-Json -Compress"', { encoding: "utf-8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }).trim();
2064
+ if (psOut) {
2065
+ const parsed = JSON.parse(psOut);
2066
+ const entries = Array.isArray(parsed) ? parsed : [parsed];
2067
+ for (const entry of entries) {
2068
+ const mount = String(entry.DeviceID || "").trim();
2069
+ const free = Number(entry.FreeSpace || 0);
2070
+ const size = Number(entry.Size || 0);
2071
+ const used = Math.max(0, size - free);
2072
+ if (mount && size > 0) {
2073
+ disks.push({
2074
+ mount,
2075
+ filesystem: "NTFS",
2076
+ size,
2077
+ used,
2078
+ free,
2079
+ usedPercent: Math.round((used / size) * 1000) / 10,
2080
+ });
2081
+ }
2082
+ }
2083
+ parsedFromPowerShell = disks.length > 0;
2084
+ }
2085
+ }
2086
+ catch {
2087
+ // fallback to legacy wmic or statfs
2088
+ }
2089
+ if (!parsedFromPowerShell) {
2090
+ try {
2091
+ const output = execSync("wmic logicaldisk get size,freespace,caption", {
2092
+ encoding: "utf-8",
2093
+ timeout: 5000,
2094
+ stdio: ["ignore", "pipe", "ignore"],
2095
+ });
2096
+ const lines = output.trim().split("\n").slice(1);
2097
+ for (const line of lines) {
2098
+ const parts = line.trim().split(/\s+/);
2099
+ if (parts.length >= 3) {
2100
+ const mount = parts[0];
2101
+ const free = parseInt(parts[1]) || 0;
2102
+ const size = parseInt(parts[2]) || 0;
2103
+ const used = size - free;
2104
+ if (size > 0) {
2105
+ disks.push({
2106
+ mount,
2107
+ filesystem: "NTFS",
2108
+ size,
2109
+ used,
2110
+ free,
2111
+ usedPercent: Math.round((used / size) * 1000) / 10,
2112
+ });
2113
+ }
2114
+ }
2115
+ }
2116
+ }
2117
+ catch {
2118
+ // Last-resort cross-platform statfs fallback for root drive
2119
+ const rootDrive = path.parse(ROOT_DIR).root || ROOT_DIR;
2120
+ const stat = fssync.statfsSync(rootDrive);
2121
+ const size = Number(stat.blocks) * Number(stat.bsize);
2122
+ const free = Number(stat.bavail) * Number(stat.bsize);
2123
+ const used = Math.max(0, size - free);
2124
+ if (size > 0) {
2125
+ disks.push({
2126
+ mount: rootDrive.replace(/\\+$/, ""),
2127
+ filesystem: "NTFS",
2128
+ size,
2129
+ used,
2130
+ free,
2131
+ usedPercent: Math.round((used / size) * 1000) / 10,
2132
+ });
2133
+ }
2134
+ }
2135
+ }
2136
+ }
2137
+ }
2138
+ catch {
2139
+ // Return empty on error
2140
+ }
2141
+ return disks;
2142
+ }
2143
+ function getBatteryInfo() {
2144
+ const platform = os.platform();
2145
+ try {
2146
+ if (platform === "darwin") {
2147
+ const output = execSync("pmset -g batt 2>/dev/null || true", { encoding: "utf-8" });
2148
+ const percentMatch = output.match(/(\d+)%/);
2149
+ const chargingMatch = output.match(/AC Power|charging|charged/i);
2150
+ const timeMatch = output.match(/(\d+):(\d+) remaining/);
2151
+ if (percentMatch) {
2152
+ return {
2153
+ hasBattery: true,
2154
+ percent: parseInt(percentMatch[1]),
2155
+ charging: !!chargingMatch,
2156
+ timeRemaining: timeMatch ? parseInt(timeMatch[1]) * 60 + parseInt(timeMatch[2]) : null,
2157
+ };
2158
+ }
2159
+ }
2160
+ else if (platform === "linux") {
2161
+ try {
2162
+ const capacityPath = "/sys/class/power_supply/BAT0/capacity";
2163
+ const statusPath = "/sys/class/power_supply/BAT0/status";
2164
+ const capacity = parseInt(execSync(`cat ${capacityPath} 2>/dev/null || echo 0`, { encoding: "utf-8" }).trim());
2165
+ const status = execSync(`cat ${statusPath} 2>/dev/null || echo Unknown`, { encoding: "utf-8" }).trim();
2166
+ if (capacity > 0) {
2167
+ return {
2168
+ hasBattery: true,
2169
+ percent: capacity,
2170
+ charging: status === "Charging" || status === "Full",
2171
+ timeRemaining: null,
2172
+ };
2173
+ }
2174
+ }
2175
+ catch {
2176
+ // No battery
2177
+ }
2178
+ }
2179
+ else if (platform === "win32") {
2180
+ try {
2181
+ const psOut = execSync('powershell -NoProfile -Command "Get-CimInstance Win32_Battery | Select-Object -First 1 EstimatedChargeRemaining,BatteryStatus | ConvertTo-Json -Compress"', { encoding: "utf-8", timeout: 4000, stdio: ["ignore", "pipe", "ignore"] }).trim();
2182
+ if (psOut) {
2183
+ const parsed = JSON.parse(psOut);
2184
+ if (typeof parsed.EstimatedChargeRemaining === "number") {
2185
+ return {
2186
+ hasBattery: true,
2187
+ percent: parsed.EstimatedChargeRemaining,
2188
+ charging: parsed.BatteryStatus === 2 || parsed.BatteryStatus === 6,
2189
+ timeRemaining: null,
2190
+ };
2191
+ }
2192
+ }
2193
+ }
2194
+ catch {
2195
+ const output = execSync("WMIC Path Win32_Battery Get EstimatedChargeRemaining,BatteryStatus 2>nul || echo", {
2196
+ encoding: "utf-8",
2197
+ timeout: 4000,
2198
+ stdio: ["ignore", "pipe", "ignore"],
2199
+ });
2200
+ const lines = output.trim().split("\n").slice(1);
2201
+ if (lines.length > 0) {
2202
+ const parts = lines[0].trim().split(/\s+/);
2203
+ if (parts.length >= 2) {
2204
+ const status = parseInt(parts[0]);
2205
+ const percent = parseInt(parts[1]);
2206
+ return {
2207
+ hasBattery: true,
2208
+ percent: percent || 0,
2209
+ charging: status === 2 || status === 6, // Charging or Charging High
2210
+ timeRemaining: null,
2211
+ };
2212
+ }
2213
+ }
2214
+ }
2215
+ }
2216
+ }
2217
+ catch {
2218
+ // No battery or error
2219
+ }
2220
+ return { hasBattery: false, percent: 0, charging: false, timeRemaining: null };
2221
+ }
2222
+ function handleMonitorSystem() {
2223
+ return {
2224
+ cpu: getCpuUsage(),
2225
+ memory: getMemoryInfo(),
2226
+ disk: getDiskInfo(),
2227
+ battery: getBatteryInfo(),
2228
+ };
2229
+ }
2230
+ function handleMonitorCpu() {
2231
+ const cpuInfo = getCpuUsage();
2232
+ const cpus = os.cpus();
2233
+ return {
2234
+ ...cpuInfo,
2235
+ model: cpus[0]?.model || "Unknown",
2236
+ speed: cpus[0]?.speed || 0,
2237
+ };
2238
+ }
2239
+ function handleMonitorMemory() {
2240
+ return getMemoryInfo();
2241
+ }
2242
+ function handleMonitorDisk() {
2243
+ return { disks: getDiskInfo() };
2244
+ }
2245
+ function handleMonitorBattery() {
2246
+ return getBatteryInfo();
2247
+ }
2248
+ // ============================================================================
2249
+ // HTTP Handlers
2250
+ // ============================================================================
2251
+ const MAX_HTTP_RESPONSE_BYTES = 10 * 1024 * 1024;
2252
+ function isBlockedMetadataUrl(parsed) {
2253
+ const host = parsed.hostname.toLowerCase();
2254
+ return (host === "169.254.169.254" ||
2255
+ host === "metadata.google.internal" ||
2256
+ host === "metadata" ||
2257
+ host === "100.100.100.200");
2258
+ }
2259
+ async function handleHttpRequest(payload) {
2260
+ const method = payload.method || "GET";
2261
+ const url = payload.url;
2262
+ const headers = payload.headers || {};
2263
+ const body = payload.body;
2264
+ const rawTimeout = Number(payload.timeout ?? 30_000);
2265
+ const timeout = Number.isFinite(rawTimeout) ? Math.min(120_000, Math.max(500, rawTimeout)) : 30_000;
2266
+ if (!url)
2267
+ throw Object.assign(new Error("url is required"), { code: "EINVAL" });
2268
+ let parsedUrl;
2269
+ try {
2270
+ parsedUrl = new URL(url);
2271
+ }
2272
+ catch {
2273
+ throw Object.assign(new Error("invalid URL"), { code: "EINVAL" });
2274
+ }
2275
+ if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
2276
+ throw Object.assign(new Error("Only http:// and https:// URLs are allowed"), { code: "EACCES" });
2277
+ }
2278
+ if (isBlockedMetadataUrl(parsedUrl)) {
2279
+ throw Object.assign(new Error("Metadata endpoint blocked"), { code: "EACCES" });
2280
+ }
2281
+ const startTime = Date.now();
2282
+ const controller = new AbortController();
2283
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
2284
+ try {
2285
+ const response = await fetch(parsedUrl.toString(), {
2286
+ method,
2287
+ headers,
2288
+ body: body || undefined,
2289
+ signal: controller.signal,
2290
+ });
2291
+ const responseHeaders = {};
2292
+ response.headers.forEach((value, key) => {
2293
+ responseHeaders[key] = value;
2294
+ });
2295
+ const chunks = [];
2296
+ let totalBytes = 0;
2297
+ if (response.body) {
2298
+ const reader = response.body.getReader();
2299
+ while (true) {
2300
+ const { done, value } = await reader.read();
2301
+ if (done)
2302
+ break;
2303
+ if (value) {
2304
+ totalBytes += value.byteLength;
2305
+ if (totalBytes > MAX_HTTP_RESPONSE_BYTES) {
2306
+ controller.abort();
2307
+ throw Object.assign(new Error("Response exceeded maximum size limit"), { code: "E2BIG" });
2308
+ }
2309
+ chunks.push(value);
2310
+ }
2311
+ }
2312
+ }
2313
+ const responseBody = Buffer.concat(chunks.map((c) => Buffer.from(c))).toString("utf-8");
2314
+ const timing = Date.now() - startTime;
2315
+ return {
2316
+ status: response.status,
2317
+ statusText: response.statusText,
2318
+ headers: responseHeaders,
2319
+ body: responseBody,
2320
+ timing,
2321
+ };
2322
+ }
2323
+ catch (err) {
2324
+ const error = err;
2325
+ if (error.code === "E2BIG") {
2326
+ throw error;
2327
+ }
2328
+ if (error.name === "AbortError") {
2329
+ throw Object.assign(new Error("Request timed out"), { code: "ETIMEOUT" });
2330
+ }
2331
+ throw Object.assign(new Error(error.message || "Network error"), { code: "ENETWORK" });
2332
+ }
2333
+ finally {
2334
+ clearTimeout(timeoutId);
2335
+ }
2336
+ }
2337
+ // ============================================================================
2338
+ // AI Handlers — delegated to the active AIProvider
2339
+ // ============================================================================
2340
+ // (Implementation lives in cli/src/ai/opencode.ts or cli/src/ai/codex.ts)
2341
+ // Proxy Handlers
2342
+ // ============================================================================
2343
+ async function scanDevPorts() {
2344
+ const openPorts = [];
2345
+ const scanPorts = Array.from(trackedProxyPorts).sort((a, b) => a - b);
2346
+ if (scanPorts.length === 0) {
2347
+ return openPorts;
2348
+ }
2349
+ const checks = scanPorts.map((port) => {
2350
+ return new Promise((resolve) => {
2351
+ let finished = false;
2352
+ let pending = LOOPBACK_HOSTS.length;
2353
+ const sockets = [];
2354
+ for (const host of LOOPBACK_HOSTS) {
2355
+ const socket = createConnection({ port, host });
2356
+ sockets.push(socket);
2357
+ socket.setTimeout(200);
2358
+ socket.on("connect", () => {
2359
+ if (finished) {
2360
+ socket.destroy();
2361
+ return;
2362
+ }
2363
+ finished = true;
2364
+ openPorts.push(port);
2365
+ for (const s of sockets)
2366
+ s.destroy();
2367
+ resolve();
2368
+ });
2369
+ const onDone = () => {
2370
+ if (finished)
2371
+ return;
2372
+ pending -= 1;
2373
+ if (pending <= 0) {
2374
+ finished = true;
2375
+ resolve();
2376
+ }
2377
+ };
2378
+ socket.on("timeout", () => {
2379
+ socket.destroy();
2380
+ onDone();
2381
+ });
2382
+ socket.on("error", () => {
2383
+ socket.destroy();
2384
+ onDone();
2385
+ });
2386
+ }
2387
+ });
2388
+ });
2389
+ await Promise.all(checks);
2390
+ return openPorts.sort((a, b) => a - b);
2391
+ }
2392
+ function getTrackedProxyPorts() {
2393
+ return Array.from(trackedProxyPorts).sort((a, b) => a - b);
2394
+ }
2395
+ async function publishDiscoveredPorts(force = false) {
2396
+ if (portScanInFlight)
2397
+ return;
2398
+ if (!activeV2Transport)
2399
+ return;
2400
+ portScanInFlight = true;
2401
+ try {
2402
+ const openPorts = await scanDevPorts();
2403
+ if (!force && samePortSet(openPorts, lastDiscoveredPorts)) {
2404
+ return;
2405
+ }
2406
+ lastDiscoveredPorts = openPorts;
2407
+ emitAppEvent({
2408
+ v: 1,
2409
+ id: `evt-${Date.now()}`,
2410
+ ns: "proxy",
2411
+ action: "ports_discovered",
2412
+ payload: { ports: openPorts },
2413
+ });
2414
+ debugLog(`[proxy] ports updated (${openPorts.length}): ${openPorts.join(", ") || "-"}`);
2415
+ }
2416
+ catch (err) {
2417
+ console.error("Port scan failed:", err);
2418
+ }
2419
+ finally {
2420
+ portScanInFlight = false;
2421
+ }
2422
+ }
2423
+ async function getProxyState() {
2424
+ const openPorts = await scanDevPorts();
2425
+ lastDiscoveredPorts = openPorts;
2426
+ return {
2427
+ trackedPorts: getTrackedProxyPorts(),
2428
+ openPorts,
2429
+ };
2430
+ }
2431
+ async function handleTrackProxyPort(payload) {
2432
+ const port = Number(payload.port);
2433
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
2434
+ throw Object.assign(new Error("port must be an integer between 1 and 65535"), { code: "EINVAL" });
2435
+ }
2436
+ trackedProxyPorts.add(port);
2437
+ debugLog("[proxy] tracking custom port", {
2438
+ port,
2439
+ trackedPorts: getTrackedProxyPorts(),
2440
+ });
2441
+ await publishDiscoveredPorts(true);
2442
+ return {
2443
+ trackedPorts: getTrackedProxyPorts(),
2444
+ openPorts: lastDiscoveredPorts,
2445
+ };
2446
+ }
2447
+ async function handleUntrackProxyPort(payload) {
2448
+ const port = Number(payload.port);
2449
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
2450
+ throw Object.assign(new Error("port must be an integer between 1 and 65535"), { code: "EINVAL" });
2451
+ }
2452
+ trackedProxyPorts.delete(port);
2453
+ debugLog("[proxy] removed custom port tracking", {
2454
+ port,
2455
+ trackedPorts: getTrackedProxyPorts(),
2456
+ });
2457
+ await publishDiscoveredPorts(true);
2458
+ return {
2459
+ trackedPorts: getTrackedProxyPorts(),
2460
+ openPorts: lastDiscoveredPorts,
2461
+ };
2462
+ }
2463
+ function stopPortSync() {
2464
+ if (portSyncTimer) {
2465
+ clearInterval(portSyncTimer);
2466
+ portSyncTimer = null;
2467
+ }
2468
+ portScanInFlight = false;
2469
+ }
2470
+ function startPortSync() {
2471
+ stopPortSync();
2472
+ void publishDiscoveredPorts(true);
2473
+ portSyncTimer = setInterval(() => {
2474
+ void publishDiscoveredPorts(false);
2475
+ }, PORT_SYNC_INTERVAL_MS);
2476
+ }
2477
+ async function handleProxyConnect(payload) {
2478
+ const tunnelId = payload.tunnelId;
2479
+ const port = Number(payload.port);
2480
+ const setupStartedAt = Date.now();
2481
+ const getRemainingSetupMs = () => TUNNEL_SETUP_BUDGET_MS - (Date.now() - setupStartedAt);
2482
+ debugLog("[proxy] handleProxyConnect received", {
2483
+ tunnelId,
2484
+ port,
2485
+ hasSessionCode: Boolean(currentSessionCode),
2486
+ hasSessionPassword: Boolean(currentSessionPassword),
2487
+ activeGatewayUrl,
2488
+ });
2489
+ if (typeof tunnelId !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/.test(tunnelId)) {
2490
+ throw Object.assign(new Error("valid tunnelId is required"), { code: "EINVAL" });
2491
+ }
2492
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
2493
+ throw Object.assign(new Error("port must be an integer between 1 and 65535"), { code: "EINVAL" });
2494
+ }
2495
+ if (process.env.KODORUN_STRICT_TRACKED_PORTS === "1" && !trackedProxyPorts.has(port)) {
2496
+ throw Object.assign(new Error(`port ${port} is not in trackedProxyPorts`), { code: "EACCES" });
2497
+ }
2498
+ if (!currentSessionCode && !currentSessionPassword)
2499
+ throw Object.assign(new Error("no active session"), { code: "ENOENT" });
2500
+ if (getRemainingSetupMs() <= 0) {
2501
+ throw Object.assign(new Error("Tunnel setup timeout before start"), { code: "ETIMEOUT" });
2502
+ }
2503
+ // 1. Open TCP connection to the local service (dual-stack localhost fallback)
2504
+ let tcpSocket = null;
2505
+ let tcpConnectError = null;
2506
+ for (const host of LOOPBACK_HOSTS) {
2507
+ const remainingMs = getRemainingSetupMs();
2508
+ if (remainingMs <= 0) {
2509
+ throw Object.assign(new Error("Tunnel setup timeout before local TCP connect"), { code: "ETIMEOUT" });
2510
+ }
2511
+ const tcpConnectTimeoutMs = Math.min(CLI_LOCAL_TCP_CONNECT_TIMEOUT_MS, Math.max(250, remainingMs));
2512
+ const candidate = createConnection({ port, host });
2513
+ try {
2514
+ await new Promise((resolve, reject) => {
2515
+ const timeout = setTimeout(() => {
2516
+ candidate.destroy();
2517
+ reject(Object.assign(new Error(`TCP connect timeout to ${host}:${port}`), { code: "ETIMEOUT" }));
2518
+ }, tcpConnectTimeoutMs);
2519
+ candidate.on("connect", () => {
2520
+ clearTimeout(timeout);
2521
+ resolve();
2522
+ });
2523
+ candidate.on("error", (err) => {
2524
+ clearTimeout(timeout);
2525
+ reject(Object.assign(new Error(`TCP connect failed to ${host}:${port}: ${err.message}`), { code: "ECONNREFUSED" }));
2526
+ });
2527
+ });
2528
+ tcpSocket = candidate;
2529
+ break;
2530
+ }
2531
+ catch (error) {
2532
+ tcpConnectError = error;
2533
+ try {
2534
+ candidate.destroy();
2535
+ }
2536
+ catch {
2537
+ // ignore
2538
+ }
2539
+ }
2540
+ }
2541
+ if (!tcpSocket) {
2542
+ debugLog("[proxy] local tcp connect failed", {
2543
+ tunnelId,
2544
+ port,
2545
+ error: tcpConnectError?.message ?? null,
2546
+ });
2547
+ throw tcpConnectError || Object.assign(new Error(`TCP connect failed to localhost:${port}`), { code: "ECONNREFUSED" });
2548
+ }
2549
+ debugLog("[proxy] local tcp connected", { tunnelId, port });
2550
+ // 2. Open proxy WebSocket to gateway
2551
+ let wsBase;
2552
+ try {
2553
+ wsBase = normalizeGatewayUrl(activeGatewayUrl).replace(/^https?:/, (scheme) => (scheme === "https:" ? "wss:" : "ws:"));
2554
+ }
2555
+ catch (err) {
2556
+ tcpSocket.destroy();
2557
+ throw Object.assign(new Error(err instanceof Error ? err.message : "Invalid gateway URL"), { code: "EPROTO" });
2558
+ }
2559
+ const authQuery = currentSessionPassword
2560
+ ? `password=${encodeURIComponent(currentSessionPassword)}`
2561
+ : `code=${encodeURIComponent(currentSessionCode)}`;
2562
+ const generationQuery = currentReattachGeneration && currentReattachGeneration > 0
2563
+ ? `&generation=${encodeURIComponent(String(currentReattachGeneration))}`
2564
+ : "";
2565
+ const proxyWsUrl = `${wsBase}/v1/ws/proxy?${authQuery}&tunnelId=${encodeURIComponent(tunnelId)}&role=cli${generationQuery}`;
2566
+ debugLog("[proxy] connecting cli proxy websocket", {
2567
+ tunnelId,
2568
+ port,
2569
+ authMode: currentSessionPassword ? "password" : "code",
2570
+ wsBase,
2571
+ });
2572
+ let proxyWs = null;
2573
+ let lastProxyError = null;
2574
+ for (let attempt = 0; attempt <= PROXY_WS_CONNECT_RETRY_ATTEMPTS; attempt++) {
2575
+ const remainingMs = getRemainingSetupMs();
2576
+ if (remainingMs <= 0) {
2577
+ tcpSocket.destroy();
2578
+ throw Object.assign(new Error("Tunnel setup timeout while connecting proxy WS"), { code: "ETIMEOUT" });
2579
+ }
2580
+ const wsConnectTimeoutMs = Math.min(PROXY_WS_CONNECT_TIMEOUT_MS, Math.max(250, remainingMs));
2581
+ const candidateWs = new WebSocket(proxyWsUrl);
2582
+ try {
2583
+ await new Promise((resolve, reject) => {
2584
+ const timeout = setTimeout(() => {
2585
+ candidateWs.close();
2586
+ reject(Object.assign(new Error("Proxy WS connect timeout"), { code: "ETIMEOUT" }));
2587
+ }, wsConnectTimeoutMs);
2588
+ candidateWs.on("open", () => {
2589
+ clearTimeout(timeout);
2590
+ resolve();
2591
+ });
2592
+ candidateWs.on("error", (err) => {
2593
+ clearTimeout(timeout);
2594
+ reject(Object.assign(new Error(`Proxy WS failed: ${err.message}`), { code: "ECONNREFUSED" }));
2595
+ });
2596
+ candidateWs.on("close", () => {
2597
+ clearTimeout(timeout);
2598
+ reject(Object.assign(new Error("Proxy WS closed during connect"), { code: "ECONNRESET" }));
2599
+ });
2600
+ });
2601
+ proxyWs = candidateWs;
2602
+ break;
2603
+ }
2604
+ catch (error) {
2605
+ lastProxyError = error;
2606
+ try {
2607
+ candidateWs.close();
2608
+ }
2609
+ catch {
2610
+ // ignore
2611
+ }
2612
+ if (attempt >= PROXY_WS_CONNECT_RETRY_ATTEMPTS) {
2613
+ break;
2614
+ }
2615
+ const jitterSpan = PROXY_WS_RETRY_JITTER_MAX_MS - PROXY_WS_RETRY_JITTER_MIN_MS;
2616
+ const jitterMs = PROXY_WS_RETRY_JITTER_MIN_MS + Math.floor(Math.random() * (jitterSpan + 1));
2617
+ if (getRemainingSetupMs() <= jitterMs) {
2618
+ break;
2619
+ }
2620
+ await new Promise((resolve) => setTimeout(resolve, jitterMs));
2621
+ }
2622
+ }
2623
+ if (!proxyWs) {
2624
+ tcpSocket.destroy();
2625
+ const err = lastProxyError || Object.assign(new Error("Proxy WS connect failed"), { code: "ECONNREFUSED" });
2626
+ debugLog("[proxy] cli proxy websocket connect failed", {
2627
+ tunnelId,
2628
+ port,
2629
+ error: err.message,
2630
+ });
2631
+ throw err;
2632
+ }
2633
+ debugLog("[proxy] cli proxy websocket connected", { tunnelId, port });
2634
+ // 3. Store the tunnel
2635
+ activeTunnels.set(tunnelId, {
2636
+ tunnelId,
2637
+ port,
2638
+ tcpSocket,
2639
+ proxyWs,
2640
+ localEnded: false,
2641
+ remoteEnded: false,
2642
+ finSent: false,
2643
+ finalizeTimer: null,
2644
+ closing: false,
2645
+ });
2646
+ // 4. Pipe: TCP data -> proxy WS (as binary)
2647
+ tcpSocket.on("data", (chunk) => {
2648
+ if (proxyWs.readyState === WebSocket.OPEN) {
2649
+ proxyWs.send(chunk);
2650
+ }
2651
+ });
2652
+ // 5. Pipe: proxy WS -> TCP socket (as binary)
2653
+ proxyWs.on("message", (data) => {
2654
+ const control = parseProxyControlFrame(data);
2655
+ if (control) {
2656
+ const tunnel = activeTunnels.get(tunnelId);
2657
+ if (!tunnel || tunnel.closing)
2658
+ return;
2659
+ if (control.action === "fin") {
2660
+ tunnel.remoteEnded = true;
2661
+ if (!tcpSocket.destroyed) {
2662
+ tcpSocket.end();
2663
+ }
2664
+ maybeFinalizeTunnel(tunnelId);
2665
+ }
2666
+ else {
2667
+ tunnel.closing = true;
2668
+ activeTunnels.delete(tunnelId);
2669
+ if (!tcpSocket.destroyed) {
2670
+ tcpSocket.destroy();
2671
+ }
2672
+ if (proxyWs.readyState === WebSocket.OPEN || proxyWs.readyState === WebSocket.CONNECTING) {
2673
+ proxyWs.close();
2674
+ }
2675
+ }
2676
+ return;
2677
+ }
2678
+ if (!tcpSocket.destroyed) {
2679
+ const chunk = Buffer.isBuffer(data)
2680
+ ? data
2681
+ : typeof data === "string"
2682
+ ? Buffer.from(data)
2683
+ : Array.isArray(data)
2684
+ ? Buffer.concat(data)
2685
+ : Buffer.from(data);
2686
+ tcpSocket.write(chunk);
2687
+ }
2688
+ });
2689
+ const markLocalEnded = () => {
2690
+ const tunnel = activeTunnels.get(tunnelId);
2691
+ if (!tunnel || tunnel.closing)
2692
+ return;
2693
+ tunnel.localEnded = true;
2694
+ if (!tunnel.finSent) {
2695
+ tunnel.finSent = true;
2696
+ sendProxyControl(tunnel, "fin");
2697
+ }
2698
+ maybeFinalizeTunnel(tunnelId);
2699
+ };
2700
+ // 6. Half-close handling
2701
+ tcpSocket.on("end", () => {
2702
+ markLocalEnded();
2703
+ });
2704
+ tcpSocket.on("close", () => {
2705
+ markLocalEnded();
2706
+ });
2707
+ tcpSocket.on("error", () => {
2708
+ debugLog("[proxy] local tcp socket error", { tunnelId, port });
2709
+ const tunnel = activeTunnels.get(tunnelId);
2710
+ if (tunnel && !tunnel.finSent) {
2711
+ sendProxyControl(tunnel, "rst", "tcp_error");
2712
+ }
2713
+ if (tunnel) {
2714
+ tunnel.closing = true;
2715
+ if (tunnel.finalizeTimer) {
2716
+ clearTimeout(tunnel.finalizeTimer);
2717
+ }
2718
+ }
2719
+ activeTunnels.delete(tunnelId);
2720
+ if (proxyWs.readyState === WebSocket.OPEN || proxyWs.readyState === WebSocket.CONNECTING) {
2721
+ proxyWs.close();
2722
+ }
2723
+ });
2724
+ // 7. Close cascade: WS closes -> close TCP
2725
+ proxyWs.on("close", () => {
2726
+ debugLog("[proxy] cli proxy websocket closed", { tunnelId, port });
2727
+ const tunnel = activeTunnels.get(tunnelId);
2728
+ if (tunnel) {
2729
+ tunnel.closing = true;
2730
+ if (tunnel.finalizeTimer) {
2731
+ clearTimeout(tunnel.finalizeTimer);
2732
+ }
2733
+ }
2734
+ activeTunnels.delete(tunnelId);
2735
+ if (!tcpSocket.destroyed) {
2736
+ tcpSocket.destroy();
2737
+ }
2738
+ });
2739
+ proxyWs.on("error", () => {
2740
+ debugLog("[proxy] cli proxy websocket error", { tunnelId, port });
2741
+ const tunnel = activeTunnels.get(tunnelId);
2742
+ if (tunnel) {
2743
+ tunnel.closing = true;
2744
+ if (tunnel.finalizeTimer) {
2745
+ clearTimeout(tunnel.finalizeTimer);
2746
+ }
2747
+ }
2748
+ activeTunnels.delete(tunnelId);
2749
+ if (!tcpSocket.destroyed) {
2750
+ tcpSocket.destroy();
2751
+ }
2752
+ });
2753
+ return { tunnelId, port };
2754
+ }
2755
+ function cleanupAllTunnels() {
2756
+ for (const [, tunnel] of activeTunnels) {
2757
+ if (tunnel.finalizeTimer) {
2758
+ clearTimeout(tunnel.finalizeTimer);
2759
+ }
2760
+ tunnel.tcpSocket.destroy();
2761
+ if (tunnel.proxyWs.readyState === WebSocket.OPEN) {
2762
+ tunnel.proxyWs.close();
2763
+ }
2764
+ }
2765
+ activeTunnels.clear();
2766
+ }
2767
+ // ============================================================================
2768
+ // Message Router
2769
+ // ============================================================================
2770
+ async function processMessage(message) {
2771
+ const { v, id, ns, action, payload } = message;
2772
+ const startedAt = Date.now();
2773
+ const pathValue = typeof payload?.path === "string" ? payload.path : null;
2774
+ logWithTimestamp("router", "request received", { id, ns, action, path: pathValue });
2775
+ // Validate protocol version
2776
+ if (v !== 1) {
2777
+ return {
2778
+ v: 1,
2779
+ id,
2780
+ ns,
2781
+ action,
2782
+ ok: false,
2783
+ payload: {},
2784
+ error: { code: "EPROTO", message: `Unsupported protocol version: ${v}` },
2785
+ };
2786
+ }
2787
+ // Validate required fields
2788
+ if (!ns || !action) {
2789
+ debugWarn("[router] Ignoring message with missing ns/action:", redactSensitive(JSON.stringify(message).substring(0, 300)));
2790
+ return {
2791
+ v: 1,
2792
+ id,
2793
+ ns,
2794
+ action,
2795
+ ok: false,
2796
+ payload: {},
2797
+ error: { code: "EINVAL", message: `Missing namespace or action` },
2798
+ };
2799
+ }
2800
+ try {
2801
+ let result;
2802
+ switch (ns) {
2803
+ case "system":
2804
+ switch (action) {
2805
+ case "capabilities":
2806
+ result = handleSystemCapabilities();
2807
+ void publishDiscoveredPorts(true);
2808
+ break;
2809
+ case "ping":
2810
+ result = handleSystemPing();
2811
+ break;
2812
+ case "pairDevice": {
2813
+ throw Object.assign(new Error("pairDevice is no longer supported"), { code: "EINVAL" });
2814
+ }
2815
+ default:
2816
+ throw Object.assign(new Error(`Unknown action: ${ns}.${action}`), { code: "EINVAL" });
2817
+ }
2818
+ break;
2819
+ case "fs":
2820
+ switch (action) {
2821
+ case "ls":
2822
+ result = await handleFsLs(payload);
2823
+ break;
2824
+ case "searchFiles":
2825
+ result = await handleFsSearchFiles(payload);
2826
+ break;
2827
+ case "stat":
2828
+ result = await handleFsStat(payload);
2829
+ break;
2830
+ case "read":
2831
+ result = await handleFsRead(payload);
2832
+ break;
2833
+ case "write":
2834
+ result = await handleFsWrite(payload);
2835
+ break;
2836
+ case "mkdir":
2837
+ result = await handleFsMkdir(payload);
2838
+ break;
2839
+ case "rm":
2840
+ result = await handleFsRm(payload);
2841
+ break;
2842
+ case "mv":
2843
+ result = await handleFsMv(payload);
2844
+ break;
2845
+ case "grep":
2846
+ result = await handleFsGrep(payload);
2847
+ break;
2848
+ case "create":
2849
+ result = await handleFsCreate(payload);
2850
+ break;
2851
+ default:
2852
+ throw Object.assign(new Error(`Unknown action: ${ns}.${action}`), { code: "EINVAL" });
2853
+ }
2854
+ break;
2855
+ case "editor":
2856
+ switch (action) {
2857
+ case "open":
2858
+ result = await trackEditorFile(payload.path);
2859
+ break;
2860
+ case "close":
2861
+ result = untrackEditorFile(payload.path);
2862
+ break;
2863
+ case "rename":
2864
+ result = await renameTrackedEditorFile(payload.from, payload.to);
2865
+ break;
2866
+ case "delete":
2867
+ result = deleteTrackedEditorFile(payload.path);
2868
+ break;
2869
+ default:
2870
+ throw Object.assign(new Error(`Unknown action: ${ns}.${action}`), { code: "EINVAL" });
2871
+ }
2872
+ break;
2873
+ case "git":
2874
+ switch (action) {
2875
+ case "status":
2876
+ result = await handleGitStatus();
2877
+ break;
2878
+ case "stage":
2879
+ result = await handleGitStage(payload);
2880
+ break;
2881
+ case "unstage":
2882
+ result = await handleGitUnstage(payload);
2883
+ break;
2884
+ case "commit":
2885
+ result = await handleGitCommit(payload);
2886
+ break;
2887
+ case "log":
2888
+ result = await handleGitLog(payload);
2889
+ break;
2890
+ case "commitDetails":
2891
+ result = await handleGitCommitDetails(payload);
2892
+ break;
2893
+ case "diff":
2894
+ result = await handleGitDiff(payload);
2895
+ break;
2896
+ case "branches":
2897
+ result = await handleGitBranches();
2898
+ break;
2899
+ case "checkout":
2900
+ result = await handleGitCheckout(payload);
2901
+ break;
2902
+ case "deleteBranch":
2903
+ result = await handleGitDeleteBranch(payload);
2904
+ break;
2905
+ case "pull":
2906
+ result = await handleGitPull();
2907
+ break;
2908
+ case "push":
2909
+ result = await handleGitPush(payload);
2910
+ break;
2911
+ case "discard":
2912
+ result = await handleGitDiscard(payload);
2913
+ break;
2914
+ default:
2915
+ throw Object.assign(new Error(`Unknown action: ${ns}.${action}`), { code: "EINVAL" });
2916
+ }
2917
+ break;
2918
+ case "terminal":
2919
+ switch (action) {
2920
+ case "spawn":
2921
+ result = await handleTerminalSpawn(payload);
2922
+ break;
2923
+ case "write":
2924
+ result = handleTerminalWrite(payload);
2925
+ break;
2926
+ case "resize":
2927
+ result = handleTerminalResize(payload);
2928
+ break;
2929
+ case "kill":
2930
+ result = handleTerminalKill(payload);
2931
+ break;
2932
+ case "scroll":
2933
+ result = handleTerminalScroll(payload);
2934
+ break;
2935
+ default:
2936
+ throw Object.assign(new Error(`Unknown action: ${ns}.${action}`), { code: "EINVAL" });
2937
+ }
2938
+ break;
2939
+ case "processes":
2940
+ switch (action) {
2941
+ case "list":
2942
+ result = handleProcessesList();
2943
+ break;
2944
+ case "spawn":
2945
+ result = await handleProcessesSpawn(payload);
2946
+ break;
2947
+ case "kill":
2948
+ result = handleProcessesKill(payload);
2949
+ break;
2950
+ case "getOutput":
2951
+ result = handleProcessesGetOutput(payload);
2952
+ break;
2953
+ case "clearOutput":
2954
+ result = handleProcessesClearOutput(payload);
2955
+ break;
2956
+ default:
2957
+ throw Object.assign(new Error(`Unknown action: ${ns}.${action}`), { code: "EINVAL" });
2958
+ }
2959
+ break;
2960
+ case "ports":
2961
+ switch (action) {
2962
+ case "list":
2963
+ result = handlePortsList();
2964
+ break;
2965
+ case "isAvailable":
2966
+ result = await handlePortsIsAvailable(payload);
2967
+ break;
2968
+ case "kill":
2969
+ result = handlePortsKill(payload);
2970
+ break;
2971
+ default:
2972
+ throw Object.assign(new Error(`Unknown action: ${ns}.${action}`), { code: "EINVAL" });
2973
+ }
2974
+ break;
2975
+ case "monitor":
2976
+ switch (action) {
2977
+ case "system":
2978
+ result = handleMonitorSystem();
2979
+ break;
2980
+ case "cpu":
2981
+ result = handleMonitorCpu();
2982
+ break;
2983
+ case "memory":
2984
+ result = handleMonitorMemory();
2985
+ break;
2986
+ case "disk":
2987
+ result = handleMonitorDisk();
2988
+ break;
2989
+ case "battery":
2990
+ result = handleMonitorBattery();
2991
+ break;
2992
+ default:
2993
+ throw Object.assign(new Error(`Unknown action: ${ns}.${action}`), { code: "EINVAL" });
2994
+ }
2995
+ break;
2996
+ case "http":
2997
+ switch (action) {
2998
+ case "request":
2999
+ result = await handleHttpRequest(payload);
3000
+ break;
3001
+ default:
3002
+ throw Object.assign(new Error(`Unknown action: ${ns}.${action}`), { code: "EINVAL" });
3003
+ }
3004
+ break;
3005
+ case "ai": {
3006
+ if (!aiManager)
3007
+ throw Object.assign(new Error("AI manager not initialized"), { code: "EUNAVAILABLE" });
3008
+ const rawBackend = typeof payload.backend === "string" ? payload.backend : "opencode";
3009
+ const backend = ALL_AI_BACKENDS.includes(rawBackend)
3010
+ ? rawBackend
3011
+ : "opencode";
3012
+ switch (action) {
3013
+ case "backends":
3014
+ result = { backends: aiManager.availableBackends() };
3015
+ break;
3016
+ case "prompt":
3017
+ result = await aiManager.prompt(backend, payload.sessionId, payload.text, payload.model, payload.agent, payload.files, payload.codexOptions);
3018
+ break;
3019
+ case "createSession":
3020
+ result = await aiManager.createSession(backend, payload.title);
3021
+ break;
3022
+ case "listSessions":
3023
+ result = await aiManager.listAllSessions();
3024
+ break;
3025
+ case "getSession":
3026
+ result = await aiManager.getSession(backend, payload.id);
3027
+ break;
3028
+ case "deleteSession":
3029
+ result = await aiManager.deleteSession(backend, payload.id);
3030
+ break;
3031
+ case "renameSession":
3032
+ result = await aiManager.renameSession(backend, payload.id, payload.title);
3033
+ break;
3034
+ case "getMessages":
3035
+ result = await aiManager.getMessages(backend, payload.id);
3036
+ break;
3037
+ case "statuses":
3038
+ result = await aiManager.statuses(backend);
3039
+ break;
3040
+ case "abort":
3041
+ result = await aiManager.abort(backend, payload.sessionId);
3042
+ break;
3043
+ case "agents":
3044
+ result = await aiManager.agents(backend);
3045
+ break;
3046
+ case "providers":
3047
+ result = await aiManager.providers(backend);
3048
+ break;
3049
+ case "setAuth":
3050
+ result = await aiManager.setAuth(backend, payload.providerId, payload.key);
3051
+ break;
3052
+ case "command":
3053
+ result = await aiManager.command(backend, payload.sessionId, payload.command, payload.arguments || "");
3054
+ break;
3055
+ case "revert":
3056
+ result = await aiManager.revert(backend, payload.sessionId, payload.messageId);
3057
+ break;
3058
+ case "unrevert":
3059
+ result = await aiManager.unrevert(backend, payload.sessionId);
3060
+ break;
3061
+ case "share":
3062
+ result = await aiManager.share(backend, payload.sessionId);
3063
+ break;
3064
+ case "permission": {
3065
+ const r = payload.response;
3066
+ const permResp = r === "once" || r === "always" || r === "reject" ? r : (payload.approved ? "once" : "reject");
3067
+ result = await aiManager.permissionReply(backend, payload.sessionId, payload.permissionId, permResp);
3068
+ break;
3069
+ }
3070
+ case "questionReply":
3071
+ result = await aiManager.questionReply(backend, payload.sessionId, payload.questionId, payload.answers || []);
3072
+ break;
3073
+ case "questionReject":
3074
+ result = await aiManager.questionReject(backend, payload.sessionId, payload.questionId);
3075
+ break;
3076
+ default:
3077
+ throw Object.assign(new Error(`Unknown action: ${ns}.${action}`), { code: "EINVAL" });
3078
+ }
3079
+ break;
3080
+ }
3081
+ case "proxy":
3082
+ switch (action) {
3083
+ case "connect":
3084
+ result = await handleProxyConnect(payload);
3085
+ break;
3086
+ case "getState":
3087
+ result = await getProxyState();
3088
+ break;
3089
+ case "trackPort":
3090
+ result = await handleTrackProxyPort(payload);
3091
+ break;
3092
+ case "untrackPort":
3093
+ result = await handleUntrackProxyPort(payload);
3094
+ break;
3095
+ default:
3096
+ throw Object.assign(new Error(`Unknown action: ${ns}.${action}`), { code: "EINVAL" });
3097
+ }
3098
+ break;
3099
+ default:
3100
+ throw Object.assign(new Error(`Unknown namespace: ${ns}`), { code: "EINVAL" });
3101
+ }
3102
+ const response = { v: 1, id, ns, action, ok: true, payload: result };
3103
+ logWithTimestamp("router", "request completed", {
3104
+ id,
3105
+ ns,
3106
+ action,
3107
+ path: pathValue,
3108
+ durationMs: Date.now() - startedAt,
3109
+ ok: true,
3110
+ });
3111
+ return response;
3112
+ }
3113
+ catch (error) {
3114
+ const err = error;
3115
+ if (DEBUG_MODE) {
3116
+ console.error(`[router] ${ns}.${action} error:`, err.code || "ERROR", err.message);
3117
+ }
3118
+ logWithTimestamp("router", "request failed", {
3119
+ id,
3120
+ ns,
3121
+ action,
3122
+ path: pathValue,
3123
+ durationMs: Date.now() - startedAt,
3124
+ code: err.code || "ERROR",
3125
+ message: err.message || "Unknown error",
3126
+ });
3127
+ return {
3128
+ v: 1,
3129
+ id,
3130
+ ns,
3131
+ action,
3132
+ ok: false,
3133
+ payload: {},
3134
+ error: {
3135
+ code: err.code || "ERROR",
3136
+ message: err.message || "Unknown error",
3137
+ },
3138
+ };
3139
+ }
3140
+ }
3141
+ let currentReattachGeneration = null;
3142
+ function normalizeGatewayUrl(input) {
3143
+ const raw = input.trim();
3144
+ if (!raw) {
3145
+ throw new Error("Gateway URL is required");
3146
+ }
3147
+ const withScheme = /^[a-z]+:\/\//i.test(raw) ? raw : `https://${raw}`;
3148
+ let parsed;
3149
+ try {
3150
+ parsed = new URL(withScheme);
3151
+ }
3152
+ catch {
3153
+ throw new Error(`Invalid gateway URL: ${input}`);
3154
+ }
3155
+ const hostLower = parsed.hostname.toLowerCase();
3156
+ const isLoopback = hostLower === "localhost" || hostLower === "127.0.0.1" || hostLower === "[::1]";
3157
+ if ((parsed.protocol === "http:" || parsed.protocol === "ws:") && isLoopback) {
3158
+ const path = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/+$/, "");
3159
+ return `http://${parsed.host}${path}`;
3160
+ }
3161
+ if (raw.toLowerCase().startsWith("http://") || raw.toLowerCase().startsWith("ws://")) {
3162
+ throw new Error("Insecure gateway protocol is not allowed; use https://");
3163
+ }
3164
+ if (parsed.protocol !== "https:") {
3165
+ throw new Error("Gateway URL must use https://");
3166
+ }
3167
+ const path = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/+$/, "");
3168
+ return `${parsed.protocol}//${parsed.host}${path}`;
3169
+ }
3170
+ async function createQrCode() {
3171
+ const response = await fetch(`${MANAGER_URL}/v2/qr`, { signal: AbortSignal.timeout(15_000) });
3172
+ if (!response.ok) {
3173
+ throw new Error(`Failed to create QR code from manager: ${response.status}`);
3174
+ }
3175
+ return (await response.json());
3176
+ }
3177
+ async function assembleWithCode(code) {
3178
+ const wsUrl = `${MANAGER_URL.replace(/^http(s?):/, "ws$1:")}/v2/assemble?code=${encodeURIComponent(code)}&role=cli`;
3179
+ return await new Promise((resolve, reject) => {
3180
+ const ws = new WebSocket(wsUrl);
3181
+ let settled = false;
3182
+ const fail = (error) => {
3183
+ if (settled)
3184
+ return;
3185
+ settled = true;
3186
+ try {
3187
+ ws.close();
3188
+ }
3189
+ catch {
3190
+ // ignore
3191
+ }
3192
+ reject(error);
3193
+ };
3194
+ ws.on("message", (data) => {
3195
+ try {
3196
+ const parsed = JSON.parse(data.toString());
3197
+ if (parsed.type !== "assembled" || typeof parsed.code !== "string" || typeof parsed.password !== "string") {
3198
+ fail(new Error("Invalid assemble payload"));
3199
+ return;
3200
+ }
3201
+ if (settled)
3202
+ return;
3203
+ settled = true;
3204
+ ws.send(JSON.stringify({ type: "ack" }));
3205
+ resolve({ code: parsed.code, password: parsed.password });
3206
+ }
3207
+ catch (error) {
3208
+ fail(error instanceof Error ? error : new Error(String(error)));
3209
+ }
3210
+ });
3211
+ ws.on("close", (codeValue, reason) => {
3212
+ if (settled)
3213
+ return;
3214
+ fail(new Error(`Assemble socket closed (${codeValue}: ${reason.toString()})`));
3215
+ });
3216
+ ws.on("error", (error) => {
3217
+ fail(new Error(`Assemble socket error: ${error.message}`));
3218
+ });
3219
+ });
3220
+ }
3221
+ async function getAssignedProxyUrl(password) {
3222
+ const url = new URL("/v2/proxy", MANAGER_URL);
3223
+ url.searchParams.set("password", password);
3224
+ const response = await fetch(url, { signal: AbortSignal.timeout(15_000) });
3225
+ if (!response.ok) {
3226
+ let message = `Failed to get proxy from manager: ${response.status}`;
3227
+ try {
3228
+ const payload = await response.json();
3229
+ if (payload.error) {
3230
+ message = payload.error;
3231
+ }
3232
+ else if (payload.reason) {
3233
+ message = payload.reason;
3234
+ }
3235
+ }
3236
+ catch {
3237
+ // ignore parse failures and use the fallback message
3238
+ }
3239
+ throw new Error(message);
3240
+ }
3241
+ const payload = await response.json();
3242
+ if (typeof payload.proxyUrl !== "string" || !payload.proxyUrl) {
3243
+ throw new Error("Manager returned invalid proxy assignment");
3244
+ }
3245
+ return normalizeGatewayUrl(payload.proxyUrl);
3246
+ }
3247
+ async function claimReattach(password) {
3248
+ const response = await fetch(new URL("/v2/reattach/claim", MANAGER_URL), {
3249
+ method: "POST",
3250
+ headers: { "Content-Type": "application/json" },
3251
+ body: JSON.stringify({
3252
+ password,
3253
+ role: "cli",
3254
+ }),
3255
+ signal: AbortSignal.timeout(15_000),
3256
+ });
3257
+ if (!response.ok) {
3258
+ let message = `Failed to claim reattach from manager: ${response.status}`;
3259
+ try {
3260
+ const payload = await response.json();
3261
+ if (payload.error) {
3262
+ message = payload.error;
3263
+ }
3264
+ else if (payload.reason) {
3265
+ message = payload.reason;
3266
+ }
3267
+ }
3268
+ catch {
3269
+ // ignore parse failures and use the fallback message
3270
+ }
3271
+ throw new Error(message);
3272
+ }
3273
+ const payload = await response.json();
3274
+ if (typeof payload.proxyUrl !== "string" || !payload.proxyUrl) {
3275
+ throw new Error("Manager returned invalid reattach proxy assignment");
3276
+ }
3277
+ if (typeof payload.generation !== "number" || !Number.isFinite(payload.generation) || payload.generation < 1) {
3278
+ throw new Error("Manager returned invalid reattach generation");
3279
+ }
3280
+ if (typeof payload.expiresAt !== "number" || !Number.isFinite(payload.expiresAt)) {
3281
+ throw new Error("Manager returned invalid reattach expiry");
3282
+ }
3283
+ return {
3284
+ proxyUrl: normalizeGatewayUrl(payload.proxyUrl),
3285
+ generation: payload.generation,
3286
+ expiresAt: payload.expiresAt,
3287
+ };
3288
+ }
3289
+ async function revokePassword(password, reason = "revoked by cli --new") {
3290
+ const response = await fetch(new URL("/v2/revoke", MANAGER_URL), {
3291
+ method: "POST",
3292
+ headers: { "Content-Type": "application/json" },
3293
+ body: JSON.stringify({ password, reason }),
3294
+ signal: AbortSignal.timeout(15_000),
3295
+ });
3296
+ if (response.ok || response.status === 404) {
3297
+ return;
3298
+ }
3299
+ let message = `Failed to revoke previous session: ${response.status}`;
3300
+ try {
3301
+ const payload = await response.json();
3302
+ if (payload.error) {
3303
+ message = payload.error;
3304
+ }
3305
+ else if (payload.reason) {
3306
+ message = payload.reason;
3307
+ }
3308
+ }
3309
+ catch {
3310
+ // ignore parse failures and use the fallback message
3311
+ }
3312
+ throw new Error(message);
3313
+ }
3314
+ function supportsUnicodeBox() {
3315
+ if (!process.stdout.isTTY)
3316
+ return false;
3317
+ if (process.platform === "win32") {
3318
+ return Boolean(process.env.WT_SESSION ||
3319
+ process.env.TERM_PROGRAM ||
3320
+ process.env.TERM === "xterm-256color");
3321
+ }
3322
+ const locale = `${process.env.LC_ALL || ""}${process.env.LC_CTYPE || ""}${process.env.LANG || ""}`;
3323
+ return /utf-?8/i.test(locale) || process.platform === "darwin";
3324
+ }
3325
+ function renderCard(lines, tone = "blue") {
3326
+ const useAnsiStyles = supportsAnsiStyles();
3327
+ const useUnicode = supportsUnicodeBox();
3328
+ const borderColor = !useAnsiStyles
3329
+ ? ""
3330
+ : tone === "blue"
3331
+ ? "\x1b[36m"
3332
+ : tone === "amber"
3333
+ ? "\x1b[33m"
3334
+ : "\x1b[90m";
3335
+ const bold = useAnsiStyles ? "\x1b[1m" : "";
3336
+ const reset = useAnsiStyles ? "\x1b[0m" : "";
3337
+ const tl = useUnicode ? "╭" : "+";
3338
+ const tr = useUnicode ? "╮" : "+";
3339
+ const bl = useUnicode ? "╰" : "+";
3340
+ const br = useUnicode ? "╯" : "+";
3341
+ const h = useUnicode ? "─" : "-";
3342
+ const v = useUnicode ? "│" : "|";
3343
+ const width = Math.max(...lines.map((line) => line.text.length));
3344
+ console.log("");
3345
+ console.log(`${borderColor}${tl}${h.repeat(width + 2)}${tr}${reset}`);
3346
+ for (const line of lines) {
3347
+ const padded = line.text.padEnd(width, " ");
3348
+ const content = line.emphasize && useAnsiStyles ? `${bold}${padded}${reset}` : padded;
3349
+ console.log(`${borderColor}${v}${reset} ${content} ${borderColor}${v}${reset}`);
3350
+ }
3351
+ console.log(`${borderColor}${bl}${h.repeat(width + 2)}${br}${reset}`);
3352
+ console.log("");
3353
+ }
3354
+ function displayQR(code) {
3355
+ console.log("\n");
3356
+ qrcode.generate(code, { small: true }, (qr) => {
3357
+ console.log(qr);
3358
+ renderCard([
3359
+ { text: `KodoRun Pairing · ${getPlatformDisplayLabel()}`, emphasize: true },
3360
+ { text: `Session code : ${code}`, emphasize: true },
3361
+ { text: `Workspace : ${ROOT_DIR}` },
3362
+ { text: "Scan QR on iOS/Android or enter code in Web/Desktop app." },
3363
+ { text: "Press Ctrl+C to stop host bridge." },
3364
+ ], "blue");
3365
+ });
3366
+ }
3367
+ function supportsAnsiStyles() {
3368
+ if (!process.stdout.isTTY)
3369
+ return false;
3370
+ if (process.env.NO_COLOR)
3371
+ return false;
3372
+ if (process.env.FORCE_COLOR)
3373
+ return true;
3374
+ if (process.platform !== "win32")
3375
+ return true;
3376
+ return Boolean(process.env.WT_SESSION ||
3377
+ process.env.ANSICON ||
3378
+ process.env.ConEmuANSI === "ON" ||
3379
+ process.env.TERM_PROGRAM ||
3380
+ process.env.TERM === "xterm-256color");
3381
+ }
3382
+ function displaySavedSessionNotice() {
3383
+ renderCard([
3384
+ { text: "Using existing paired workspace session", emphasize: true },
3385
+ { text: "Open Past Sessions in Mobile / Desktop Web app to reconnect." },
3386
+ { text: "Run `npx kodorun-cli -n` anytime for a fresh pairing code." },
3387
+ ], "amber");
3388
+ }
3389
+ function isCommandAvailable(command) {
3390
+ const probe = spawnSync(command, ["--version"], {
3391
+ stdio: "ignore",
3392
+ shell: process.platform === "win32",
3393
+ });
3394
+ const err = probe.error;
3395
+ if (err && (err.code === "ENOENT" || err.code === "ENOTDIR")) {
3396
+ return false;
3397
+ }
3398
+ return !err;
3399
+ }
3400
+ function askYesNo(question, defaultValue = false) {
3401
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
3402
+ return Promise.resolve(false);
3403
+ return new Promise((resolve) => {
3404
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
3405
+ const suffix = defaultValue ? " [Y/n] " : " [y/N] ";
3406
+ rl.question(`${question}${suffix}`, (answer) => {
3407
+ rl.close();
3408
+ const normalized = answer.trim().toLowerCase();
3409
+ if (!normalized) {
3410
+ resolve(defaultValue);
3411
+ return;
3412
+ }
3413
+ resolve(normalized === "y" || normalized === "yes");
3414
+ });
3415
+ });
3416
+ }
3417
+ function installLatestNpmPackage(pkg) {
3418
+ const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
3419
+ const result = spawnSync(npmCommand, ["install", "-g", `${pkg}@latest`], {
3420
+ stdio: "inherit",
3421
+ shell: process.platform === "win32",
3422
+ env: process.env,
3423
+ });
3424
+ return !result.error && result.status === 0;
3425
+ }
3426
+ async function ensureAiCliRuntimes() {
3427
+ const missingBackends = Object.keys(AI_RUNTIME_INSTALL_CANDIDATES)
3428
+ .filter((backend) => !isCommandAvailable(backend));
3429
+ if (missingBackends.length === 0)
3430
+ return;
3431
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
3432
+ console.warn(`[ai] Missing runtimes: ${missingBackends.join(", ")}. Run in an interactive shell to install them.`);
3433
+ return;
3434
+ }
3435
+ const installPrompt = `Missing AI runtimes (${missingBackends.join(", ")}). Install latest versions now?`;
3436
+ const approved = await askYesNo(installPrompt, false);
3437
+ if (!approved) {
3438
+ console.warn("[ai] Skipping AI runtime installation.");
3439
+ return;
3440
+ }
3441
+ for (const backend of missingBackends) {
3442
+ if (isCommandAvailable(backend))
3443
+ continue;
3444
+ const candidates = AI_RUNTIME_INSTALL_CANDIDATES[backend] ?? [];
3445
+ let installed = false;
3446
+ for (const pkg of candidates) {
3447
+ console.log(`[ai] Installing ${backend} via npm package ${pkg}@latest...`);
3448
+ if (!installLatestNpmPackage(pkg))
3449
+ continue;
3450
+ if (isCommandAvailable(backend)) {
3451
+ installed = true;
3452
+ console.log(`[ai] ${backend} installed successfully.`);
3453
+ break;
3454
+ }
3455
+ }
3456
+ if (!installed) {
3457
+ console.warn(`[ai] Failed to install ${backend}. You can install it manually and restart the CLI.`);
3458
+ }
3459
+ }
3460
+ }
3461
+ function gracefulShutdown() {
3462
+ if (shuttingDown)
3463
+ return;
3464
+ shuttingDown = true;
3465
+ console.log("\nShutting down...");
3466
+ stopPortSync();
3467
+ for (const trackedDir of trackedEditorDirectories.values()) {
3468
+ trackedDir.watcher.close();
3469
+ }
3470
+ trackedEditorDirectories.clear();
3471
+ trackedEditorFiles.clear();
3472
+ pendingTrackedFileChecks.clear();
3473
+ activeV2Transport?.close();
3474
+ activeV2Transport = null;
3475
+ if (ptyProcess) {
3476
+ try {
3477
+ ptyProcess.kill();
3478
+ }
3479
+ catch { /* ignore */ }
3480
+ ptyProcess = null;
3481
+ }
3482
+ terminals.clear();
3483
+ for (const [, managedProc] of processes) {
3484
+ try {
3485
+ managedProc.proc.kill();
3486
+ }
3487
+ catch { /* ignore */ }
3488
+ }
3489
+ processes.clear();
3490
+ processOutputBuffers.clear();
3491
+ cleanupAllTunnels();
3492
+ const destroyPromise = aiManager?.destroy?.();
3493
+ Promise.race([
3494
+ Promise.resolve(destroyPromise).catch(() => { }),
3495
+ new Promise((resolve) => setTimeout(resolve, 1500)),
3496
+ ]).finally(() => {
3497
+ process.exit(0);
3498
+ });
3499
+ }
3500
+ function startAiManagerInBackground() {
3501
+ if (aiManager || aiManagerInitPromise)
3502
+ return;
3503
+ aiManagerInitPromise = (async () => {
3504
+ try {
3505
+ const manager = await createAiManager();
3506
+ if (shuttingDown) {
3507
+ await manager.destroy();
3508
+ return;
3509
+ }
3510
+ aiManager = manager;
3511
+ aiManager.subscribe((backend, event) => {
3512
+ emitAppEvent({
3513
+ v: 1,
3514
+ id: `evt-${Date.now()}`,
3515
+ ns: "ai",
3516
+ action: "event",
3517
+ payload: { ...event, backend },
3518
+ });
3519
+ });
3520
+ }
3521
+ catch (error) {
3522
+ if (DEBUG_MODE) {
3523
+ const message = error instanceof Error ? error.message : String(error);
3524
+ console.error(`[ai] background init failed: ${message}`);
3525
+ }
3526
+ }
3527
+ finally {
3528
+ aiManagerInitPromise = null;
3529
+ }
3530
+ })();
3531
+ }
3532
+ async function connectWebSocketV2() {
3533
+ const gatewayUrl = currentPrimaryGateway;
3534
+ if (!currentSessionPassword) {
3535
+ throw new Error("missing password for websocket connect");
3536
+ }
3537
+ console.log(`Connecting to gateway ${gatewayUrl}...`);
3538
+ activeGatewayUrl = gatewayUrl;
3539
+ const transport = new V2SessionTransport({
3540
+ gatewayUrl,
3541
+ password: currentSessionPassword,
3542
+ sessionSecret: currentSessionPassword,
3543
+ generation: currentReattachGeneration,
3544
+ role: "cli",
3545
+ debugLog: DEBUG_MODE ? debugLog : undefined,
3546
+ handlers: {
3547
+ onSystemMessage: async (message) => {
3548
+ if (message.type === "connected")
3549
+ return;
3550
+ if (message.type === "peer_connected") {
3551
+ console.log("App connected!\n");
3552
+ void publishDiscoveredPorts(true);
3553
+ return;
3554
+ }
3555
+ if (message.type === "peer_disconnected") {
3556
+ console.log("App disconnected. Waiting for reconnect window.\n");
3557
+ stopPortSync();
3558
+ return;
3559
+ }
3560
+ if (message.type === "app_disconnected") {
3561
+ if (message.reconnectDeadline) {
3562
+ console.log(`[session] app disconnected, waiting until ${new Date(message.reconnectDeadline).toISOString()}`);
3563
+ }
3564
+ return;
3565
+ }
3566
+ if (message.type === "close_connection") {
3567
+ const reason = message.reason || "expired";
3568
+ console.log(`[session] closed by gateway: ${reason}`);
3569
+ if (reason === "session ended from app") {
3570
+ console.log("[session] Run `npx kodorun-cli` again and scan the new QR code to reconnect.");
3571
+ }
3572
+ gracefulShutdown();
3573
+ }
3574
+ },
3575
+ onProtocolRequest: async (message) => {
3576
+ return await processMessage(message);
3577
+ },
3578
+ onProtocolResponse: async () => {
3579
+ // CLI does not currently await app responses outside request/reply routing.
3580
+ },
3581
+ onProtocolEvent: async (message) => {
3582
+ await processMessage(message);
3583
+ },
3584
+ onClose: (reason) => {
3585
+ if (shuttingDown)
3586
+ return;
3587
+ stopPortSync();
3588
+ cleanupAllTunnels();
3589
+ activeV2Transport = null;
3590
+ setTimeout(() => {
3591
+ if (shuttingDown)
3592
+ return;
3593
+ void handleConnectionDrop(reason);
3594
+ }, 50);
3595
+ },
3596
+ },
3597
+ });
3598
+ activeV2Transport = transport;
3599
+ await transport.connect();
3600
+ startPortSync();
3601
+ console.log("Connected to gateway (single secure session).\n");
3602
+ }
3603
+ let reconnectInFlight = false;
3604
+ async function handleConnectionDrop(reason) {
3605
+ if (shuttingDown || reconnectInFlight)
3606
+ return;
3607
+ reconnectInFlight = true;
3608
+ console.log(`\nDisconnected: ${reason}`);
3609
+ if (!currentSessionPassword) {
3610
+ console.error("No reconnect password available. Exiting.");
3611
+ reconnectInFlight = false;
3612
+ gracefulShutdown();
3613
+ return;
3614
+ }
3615
+ try {
3616
+ let attempt = 0;
3617
+ while (!shuttingDown) {
3618
+ attempt += 1;
3619
+ const base = Math.min(250 * 2 ** (attempt - 1), 30_000);
3620
+ const delayMs = Math.round(base * (0.8 + Math.random() * 0.4));
3621
+ try {
3622
+ const reattach = await claimReattach(currentSessionPassword);
3623
+ currentPrimaryGateway = reattach.proxyUrl;
3624
+ currentReattachGeneration = reattach.generation;
3625
+ await connectWebSocketV2();
3626
+ debugLog(`[reconnect] connected via ${activeGatewayUrl}`);
3627
+ return;
3628
+ }
3629
+ catch (err) {
3630
+ if (DEBUG_MODE)
3631
+ console.error(`[reconnect] attempt ${attempt} failed: ${err.message}`);
3632
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
3633
+ }
3634
+ }
3635
+ }
3636
+ finally {
3637
+ reconnectInFlight = false;
3638
+ }
3639
+ }
3640
+ async function main() {
3641
+ if (SHOW_HELP) {
3642
+ printHelp();
3643
+ return;
3644
+ }
3645
+ renderCard([
3646
+ { text: `KodoRun Host CLI v${VERSION} · ${getPlatformDisplayLabel()}`, emphasize: true },
3647
+ { text: `Root : ${ROOT_DIR}` },
3648
+ { text: `Shell : ${getDefaultTerminalShell()}` },
3649
+ ], "muted");
3650
+ if (EXTRA_PORTS.length > 0) {
3651
+ console.log(`Extra ports enabled: ${EXTRA_PORTS.join(", ")}`);
3652
+ }
3653
+ let usedSavedSession = false;
3654
+ try {
3655
+ const cliConfig = await getCliConfig();
3656
+ const savedSession = getSavedSessionForRoot(cliConfig, ROOT_DIR);
3657
+ debugLog("Checking PTY runtime...");
3658
+ let ptyBinaryPath = null;
3659
+ try {
3660
+ ptyBinaryPath = await ensurePtyBinaryReady();
3661
+ }
3662
+ catch (ptyErr) {
3663
+ console.warn(`[pty] PTY binary prefetch skipped: ${ptyErr.message}`);
3664
+ }
3665
+ if (ptyBinaryPath) {
3666
+ debugLog("PTY runtime ready.\n");
3667
+ }
3668
+ else {
3669
+ debugLog(`PTY runtime unsupported on ${os.platform()}/${os.arch()} or unavailable. Skipping prefetch.\n`);
3670
+ }
3671
+ await ensureAiCliRuntimes();
3672
+ // Start AI backends in the background so missing or slow AI runtimes never
3673
+ // block QR/session startup for the rest of the CLI.
3674
+ startAiManagerInBackground();
3675
+ let sessionCodeToUse = null;
3676
+ let sessionPasswordToUse;
3677
+ if (!FORCE_NEW_CODE && savedSession) {
3678
+ console.log(`Using saved session for ${ROOT_DIR}`);
3679
+ displaySavedSessionNotice();
3680
+ sessionCodeToUse = savedSession.sessionCode;
3681
+ sessionPasswordToUse = savedSession.sessionPassword;
3682
+ usedSavedSession = true;
3683
+ }
3684
+ else {
3685
+ if (FORCE_NEW_CODE && savedSession?.sessionPassword) {
3686
+ await revokePassword(savedSession.sessionPassword);
3687
+ await clearSavedSessionForRoot();
3688
+ }
3689
+ const qr = await createQrCode();
3690
+ currentSessionCode = qr.code;
3691
+ displayQR(qr.code);
3692
+ const assembled = await assembleWithCode(qr.code);
3693
+ sessionCodeToUse = assembled.code;
3694
+ sessionPasswordToUse = assembled.password;
3695
+ await saveSessionForRoot(sessionCodeToUse, sessionPasswordToUse);
3696
+ }
3697
+ currentSessionCode = sessionCodeToUse;
3698
+ currentSessionPassword = sessionPasswordToUse;
3699
+ if (usedSavedSession) {
3700
+ const reattach = await claimReattach(sessionPasswordToUse);
3701
+ currentPrimaryGateway = reattach.proxyUrl;
3702
+ currentReattachGeneration = reattach.generation;
3703
+ }
3704
+ else {
3705
+ currentPrimaryGateway = await getAssignedProxyUrl(sessionPasswordToUse);
3706
+ currentReattachGeneration = null;
3707
+ }
3708
+ activeGatewayUrl = currentPrimaryGateway;
3709
+ await connectWebSocketV2();
3710
+ }
3711
+ catch (error) {
3712
+ const message = error instanceof Error ? error.message : String(error);
3713
+ if (usedSavedSession &&
3714
+ /invalid|revoked|not found|expired|password invalid|password revoked/i.test(message)) {
3715
+ await clearSavedSessionForRoot().catch(() => { });
3716
+ }
3717
+ if (error instanceof Error) {
3718
+ console.error(`Error: ${error.message}`);
3719
+ if (DEBUG_MODE && error.stack)
3720
+ console.error(error.stack);
3721
+ }
3722
+ else {
3723
+ console.error("An unexpected error occurred");
3724
+ }
3725
+ process.exit(1);
3726
+ }
3727
+ }
3728
+ export { normalizeGatewayUrl, redactSensitive };
3729
+ const isTestRunner = process.env.KODORUN_CLI_NO_AUTOSTART === "1" ||
3730
+ process.execArgv.includes("--test") ||
3731
+ process.argv.slice(1).some((arg) => /\.test\.[cm]?[jt]s$/i.test(arg));
3732
+ if (!isTestRunner) {
3733
+ process.on("SIGINT", gracefulShutdown);
3734
+ process.on("SIGTERM", gracefulShutdown);
3735
+ main();
3736
+ }