localmcp-cli 0.0.0-stage → 0.0.11

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.
@@ -0,0 +1,840 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+
7
+ import { childEnvironment } from "../core/config.js";
8
+ import { sanitizeSensitiveText } from "./store.js";
9
+
10
+ const execFileAsync = promisify(execFile);
11
+ const PLATFORM = os.platform();
12
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
+ const UUID_FIND_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
14
+
15
+ export function isUuid(value) {
16
+ return UUID_RE.test(String(value ?? "").trim());
17
+ }
18
+
19
+ export function isPidAlive(pid) {
20
+ if (!pid || !Number.isInteger(pid) || pid <= 0) return false;
21
+ try {
22
+ process.kill(pid, 0);
23
+ return true;
24
+ } catch (err) {
25
+ return err?.code === "EPERM";
26
+ }
27
+ }
28
+
29
+ export async function killProcessTree(pid) {
30
+ if (!pid || !Number.isInteger(pid) || pid <= 0) return false;
31
+ if (!isPidAlive(pid)) return false;
32
+ try {
33
+ if (PLATFORM === "win32") {
34
+ await execFileAsync("taskkill", ["/PID", String(pid), "/T", "/F"], {
35
+ timeout: 5000,
36
+ windowsHide: true,
37
+ }).catch(() => {});
38
+ return !isPidAlive(pid);
39
+ }
40
+ try {
41
+ process.kill(-pid, "SIGTERM");
42
+ } catch {
43
+ process.kill(pid, "SIGTERM");
44
+ }
45
+ await new Promise((r) => setTimeout(r, 300));
46
+ if (isPidAlive(pid)) {
47
+ try {
48
+ process.kill(-pid, "SIGKILL");
49
+ } catch {
50
+ process.kill(pid, "SIGKILL");
51
+ }
52
+ }
53
+ return !isPidAlive(pid);
54
+ } catch {
55
+ return !isPidAlive(pid);
56
+ }
57
+ }
58
+
59
+ function commonBinDirs() {
60
+ const home = os.homedir();
61
+ const pathDirs = String(process.env.PATH || "")
62
+ .split(path.delimiter)
63
+ .map((s) => s.trim())
64
+ .filter(Boolean);
65
+
66
+ const extra =
67
+ PLATFORM === "win32"
68
+ ? [
69
+ path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "agy", "bin"),
70
+ path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "Programs", "antigravity", "resources", "bin"),
71
+ path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "Programs", "antigravity", "bin"),
72
+ path.join(process.env.APPDATA || path.join(home, "AppData", "Roaming"), "npm"),
73
+ path.join(home, ".local", "bin"),
74
+ path.join(home, ".codex", "bin"),
75
+ ]
76
+ : [
77
+ "/opt/homebrew/bin",
78
+ "/usr/local/bin",
79
+ path.join(home, ".local", "bin"),
80
+ path.join(home, ".npm-global", "bin"),
81
+ "/Applications/Antigravity.app/Contents/Resources/bin",
82
+ "/Applications/Antigravity.app/Contents/Resources/app/extensions/antigravity/bin",
83
+ ];
84
+
85
+ return Array.from(new Set([...pathDirs, ...extra]));
86
+ }
87
+
88
+ function findExecutable(baseNames, extraCandidates = []) {
89
+ for (const cand of extraCandidates) {
90
+ if (cand && existsSync(cand)) return cand;
91
+ }
92
+ const exts = PLATFORM === "win32" ? [".exe", ".cmd", ".bat", ""] : [""];
93
+ const dirs = commonBinDirs();
94
+ for (const dir of dirs) {
95
+ for (const base of baseNames) {
96
+ for (const ext of exts) {
97
+ const full = path.join(dir, base.endsWith(ext) ? base : `${base}${ext}`);
98
+ if (existsSync(full)) return full;
99
+ }
100
+ }
101
+ }
102
+ return "";
103
+ }
104
+
105
+ function resolveAntigravityDaemonDir() {
106
+ return path.join(os.homedir(), ".gemini", "antigravity", "daemon");
107
+ }
108
+
109
+ function resolveAntigravityBrainDir() {
110
+ return path.join(os.homedir(), ".gemini", "antigravity", "brain");
111
+ }
112
+
113
+ function findActiveAntigravityHub() {
114
+ const daemonDir = resolveAntigravityDaemonDir();
115
+ if (!existsSync(daemonDir)) return null;
116
+ let files = [];
117
+ try {
118
+ files = readdirSync(daemonDir)
119
+ .filter((name) => /^hub_.*\.json$/i.test(name))
120
+ .map((name) => {
121
+ const full = path.join(daemonDir, name);
122
+ return { full, mtimeMs: statSync(full).mtimeMs };
123
+ })
124
+ .sort((a, b) => b.mtimeMs - a.mtimeMs);
125
+ } catch {
126
+ return null;
127
+ }
128
+
129
+ for (const item of files) {
130
+ try {
131
+ const data = JSON.parse(readFileSync(item.full, "utf8"));
132
+ const pid = Number(data?.pid);
133
+ const httpPort = Number(data?.httpPort);
134
+ const csrfToken = String(data?.csrfToken || "");
135
+ if (isPidAlive(pid) && httpPort > 0 && csrfToken) {
136
+ return { pid, httpPort, csrfToken };
137
+ }
138
+ } catch {
139
+ continue;
140
+ }
141
+ }
142
+ return null;
143
+ }
144
+
145
+ function readTranscriptTail(conversationId, maxLines = 12) {
146
+ const brainDir = resolveAntigravityBrainDir();
147
+ const compactPath = path.join(brainDir, conversationId, ".system_generated", "logs", "transcript.jsonl");
148
+ const fullPath = path.join(brainDir, conversationId, ".system_generated", "logs", "transcript_full.jsonl");
149
+ const target = existsSync(compactPath) ? compactPath : existsSync(fullPath) ? fullPath : "";
150
+ if (!target) return { entries: [], mtimeMs: 0 };
151
+
152
+ try {
153
+ const st = statSync(target);
154
+ const raw = readFileSync(target, "utf8");
155
+ const lines = raw.split(/\r?\n/).filter(Boolean).slice(-maxLines);
156
+ const entries = [];
157
+ for (const line of lines) {
158
+ try {
159
+ entries.push(JSON.parse(line));
160
+ } catch {
161
+ continue;
162
+ }
163
+ }
164
+ return { entries, mtimeMs: st.mtimeMs };
165
+ } catch {
166
+ return { entries: [], mtimeMs: 0 };
167
+ }
168
+ }
169
+
170
+ function inferAntigravityState(entries, mtimeMs) {
171
+ if (!entries.length) {
172
+ return { status: "working", summary: "", inputRequests: null };
173
+ }
174
+ const last = entries[entries.length - 1];
175
+ const ageMs = Date.now() - mtimeMs;
176
+ const lastPlanner = [...entries].reverse().find((e) => e.type === "PLANNER_RESPONSE");
177
+ const contentPreview = sanitizeSensitiveText(lastPlanner?.content || last?.content || "").trim();
178
+
179
+ if (last.type === "PLANNER_RESPONSE") {
180
+ const toolCalls = Array.isArray(last.tool_calls) ? last.tool_calls : [];
181
+ const askCall = toolCalls.find((tc) => tc?.name === "ask_question");
182
+ if (askCall) {
183
+ return {
184
+ status: "input_required",
185
+ summary: contentPreview.slice(0, 600) || "Waiting for user input via ask_question.",
186
+ inputRequests: {
187
+ ask_question: {
188
+ kind: "question",
189
+ prompt: contentPreview.slice(0, 600) || "Agent requested user input.",
190
+ },
191
+ },
192
+ };
193
+ }
194
+ if (toolCalls.length === 0 && last.status === "DONE") {
195
+ return {
196
+ status: "completed",
197
+ summary: contentPreview.slice(0, 2000),
198
+ inputRequests: null,
199
+ };
200
+ }
201
+ }
202
+
203
+ if (ageMs > 180_000 && lastPlanner && (!Array.isArray(lastPlanner.tool_calls) || lastPlanner.tool_calls.length === 0)) {
204
+ return {
205
+ status: "completed",
206
+ summary: contentPreview.slice(0, 2000),
207
+ inputRequests: null,
208
+ };
209
+ }
210
+
211
+ return {
212
+ status: "working",
213
+ summary: contentPreview.slice(0, 600) || `Last step: ${last.type || "running"}`,
214
+ inputRequests: null,
215
+ };
216
+ }
217
+
218
+ function createAntigravityAdapter() {
219
+ const findLsExe = () => {
220
+ const home = os.homedir();
221
+ const localAppData = process.env.LOCALAPPDATA || path.join(home, "AppData", "Local");
222
+ const extras =
223
+ PLATFORM === "win32"
224
+ ? [path.join(localAppData, "Programs", "antigravity", "resources", "bin", "language_server.exe")]
225
+ : [
226
+ "/Applications/Antigravity.app/Contents/Resources/bin/language_server",
227
+ "/Applications/Antigravity.app/Contents/Resources/app/extensions/antigravity/bin/language_server",
228
+ ];
229
+ return findExecutable(["language_server"], extras);
230
+ };
231
+
232
+ const findAgyCli = () => {
233
+ const home = os.homedir();
234
+ const localAppData = process.env.LOCALAPPDATA || path.join(home, "AppData", "Local");
235
+ const extras = [
236
+ process.env.AGY_BIN || "",
237
+ ...(PLATFORM === "win32"
238
+ ? [path.join(localAppData, "agy", "bin", "agy.exe")]
239
+ : [path.join(home, ".local", "bin", "agy"), "/opt/homebrew/bin/agy", "/usr/local/bin/agy"]),
240
+ ];
241
+ return findExecutable(["agy"], extras);
242
+ };
243
+
244
+ const parseAgyStreamLine = (line, state) => {
245
+ const trimmed = String(line || "").trim();
246
+ if (!trimmed) return;
247
+ try {
248
+ const obj = JSON.parse(trimmed);
249
+ const sid = obj.conversation_id || obj.conversationId || obj.session_id || obj.sessionId;
250
+ if (typeof sid === "string" && sid.trim()) {
251
+ state.sessionId = sid.trim();
252
+ }
253
+ if (typeof obj.result === "string" && obj.result.trim()) {
254
+ state.finalMessage = obj.result;
255
+ } else if (typeof obj.text === "string" && obj.text) {
256
+ state.finalMessage = obj.type === "delta" ? `${state.finalMessage}${obj.text}` : obj.text;
257
+ } else if (typeof obj.delta === "string" && obj.delta) {
258
+ state.finalMessage = `${state.finalMessage}${obj.delta}`;
259
+ } else if (typeof obj.message?.content === "string" && obj.message.content) {
260
+ state.finalMessage = obj.message.content;
261
+ } else if (Array.isArray(obj.message?.content)) {
262
+ const joined = obj.message.content
263
+ .map((item) => (typeof item === "string" ? item : item?.text || ""))
264
+ .filter(Boolean)
265
+ .join("\n");
266
+ if (joined) state.finalMessage = joined;
267
+ }
268
+ } catch {
269
+ const uuidHit = trimmed.match(UUID_FIND_RE);
270
+ if (uuidHit && !state.sessionId) state.sessionId = uuidHit[0];
271
+ if (!state.finalMessage) state.finalMessage = trimmed;
272
+ }
273
+ };
274
+
275
+ const buildAgyArgs = ({ prompt, model = "", profile = "", mode = "", conversationId = "" }) => {
276
+ const resolvedMode = ["accept-edits", "auto", "plan"].includes(mode)
277
+ ? mode
278
+ : ["accept-edits", "auto", "plan"].includes(profile)
279
+ ? profile
280
+ : "auto";
281
+ const args = ["--output-format", "stream-json", "--mode", resolvedMode];
282
+ if (model) args.push("--model", model);
283
+ if (conversationId) args.push("--conversation", conversationId);
284
+ args.push("-p", prompt);
285
+ return args;
286
+ };
287
+
288
+ const runAgentApi = async (args, timeoutMs = 20_000) => {
289
+ const lsExe = findLsExe();
290
+ if (!lsExe) {
291
+ throw new Error("Antigravity language_server binary not found on this machine.");
292
+ }
293
+ const hub = findActiveAntigravityHub();
294
+ if (!hub) {
295
+ throw new Error("Antigravity is not running (no active daemon hub found).");
296
+ }
297
+ const env = {
298
+ ...childEnvironment(),
299
+ ANTIGRAVITY_LS_ADDRESS: `127.0.0.1:${hub.httpPort}`,
300
+ ANTIGRAVITY_CSRF_TOKEN: hub.csrfToken,
301
+ };
302
+ const { stdout, stderr } = await execFileAsync(lsExe, ["agentapi", ...args], {
303
+ env,
304
+ timeout: timeoutMs,
305
+ maxBuffer: 4 * 1024 * 1024,
306
+ windowsHide: true,
307
+ }).catch(() => { throw new Error("Agent API request failed."); });
308
+ return {
309
+ stdout: sanitizeSensitiveText(String(stdout || "").replaceAll(hub.csrfToken, "[REDACTED]")),
310
+ stderr: sanitizeSensitiveText(String(stderr || "").replaceAll(hub.csrfToken, "[REDACTED]")),
311
+ };
312
+ };
313
+
314
+ return {
315
+ name: "antigravity",
316
+ supportsPush: true,
317
+
318
+ probe() {
319
+ const lsExe = findLsExe();
320
+ const agyCli = findAgyCli();
321
+ const hub = lsExe ? findActiveAntigravityHub() : null;
322
+ const agentApiReady = Boolean(lsExe && hub);
323
+ const available = Boolean(agyCli || agentApiReady);
324
+ return {
325
+ engine: "antigravity",
326
+ available,
327
+ installed: Boolean(agyCli || lsExe),
328
+ running: Boolean(hub),
329
+ supportsPush: available,
330
+ hasAgyCli: Boolean(agyCli),
331
+ transport: agyCli ? "agy_cli" : agentApiReady ? "agentapi" : "none",
332
+ detail: agyCli && agentApiReady
333
+ ? "Antigravity agy CLI ready (desktop agentapi fallback available)"
334
+ : agyCli
335
+ ? "Antigravity agy CLI ready"
336
+ : agentApiReady
337
+ ? "Active Antigravity daemon ready (agentapi)"
338
+ : lsExe
339
+ ? "Antigravity installed but daemon not running"
340
+ : "Antigravity not installed",
341
+ };
342
+ },
343
+
344
+ listSessions({ limit = 10 } = {}) {
345
+ const brainDir = resolveAntigravityBrainDir();
346
+ if (!existsSync(brainDir)) return [];
347
+ const pushReady = Boolean(findAgyCli() || (findLsExe() && findActiveAntigravityHub()));
348
+ let dirs = [];
349
+ try {
350
+ dirs = readdirSync(brainDir)
351
+ .filter((name) => isUuid(name))
352
+ .map((name) => {
353
+ const full = path.join(brainDir, name);
354
+ const st = statSync(full);
355
+ return { id: name, full, mtimeMs: st.mtimeMs, isDir: st.isDirectory() };
356
+ })
357
+ .filter((d) => d.isDir)
358
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
359
+ .slice(0, Math.max(1, Math.min(Number(limit) || 10, 30)));
360
+ } catch {
361
+ return [];
362
+ }
363
+
364
+ return dirs.map((d) => {
365
+ const { entries, mtimeMs } = readTranscriptTail(d.id, 8);
366
+ const inferred = inferAntigravityState(entries, mtimeMs || d.mtimeMs);
367
+ const busyState = inferred.status === "working" ? "busy" : inferred.status === "input_required" ? "waiting" : "idle";
368
+ return {
369
+ agentId: `ag:${d.id.slice(0, 8)}`,
370
+ sessionId: d.id,
371
+ engine: "antigravity",
372
+ status: busyState,
373
+ supportsPush: pushReady,
374
+ updatedAt: new Date(mtimeMs || d.mtimeMs).toISOString(),
375
+ preview: inferred.summary.slice(0, 140),
376
+ };
377
+ });
378
+ },
379
+
380
+ async dispatch({ prompt, cwd, title = "MCP Agent Task", model = "", profile = "", mode = "", taskId, store }) {
381
+ const agyCli = findAgyCli();
382
+ if (agyCli && taskId && store) {
383
+ try {
384
+ const args = buildAgyArgs({ prompt, model, profile, mode });
385
+ const child = spawnAsyncCli({
386
+ bin: agyCli,
387
+ args,
388
+ cwd: cwd || process.cwd(),
389
+ taskId,
390
+ store,
391
+ parseLine: parseAgyStreamLine,
392
+ });
393
+ return {
394
+ pid: child.pid || null,
395
+ status: "working",
396
+ statusMessage: "Antigravity agy CLI task started",
397
+ remoteStopSupported: true,
398
+ };
399
+ } catch (err) {
400
+ const agentApiReady = Boolean(findLsExe() && findActiveAntigravityHub());
401
+ if (!agentApiReady) throw err;
402
+ }
403
+ }
404
+
405
+ const args = ["new-conversation", `--title=${title || "MCP Agent Task"}`];
406
+ if (model) args.push(`--model=${model}`);
407
+ if (profile) args.push(`--profile=${profile}`);
408
+ args.push(prompt);
409
+ const { stdout, stderr } = await runAgentApi(args, 25_000);
410
+ const combined = `${stdout}\n${stderr}`.trim();
411
+ const match = combined.match(UUID_FIND_RE);
412
+ const sessionId = match ? match[0] : "";
413
+ if (!sessionId) {
414
+ throw new Error(`Antigravity new-conversation did not return a conversation ID: ${combined.slice(0, 240)}`);
415
+ }
416
+ return {
417
+ sessionId,
418
+ status: "working",
419
+ statusMessage: `Antigravity conversation started (${sessionId.slice(0, 8)})`,
420
+ remoteStopSupported: false,
421
+ initialOutput: combined,
422
+ };
423
+ },
424
+
425
+ async inspect(task) {
426
+ if (task.pid) {
427
+ if (isPidAlive(task.pid)) {
428
+ return { status: "working", statusMessage: "Antigravity agy CLI is running" };
429
+ }
430
+ return { status: task.status, statusMessage: task.statusMessage };
431
+ }
432
+ if (!task.sessionId) {
433
+ return { status: task.status, statusMessage: task.statusMessage };
434
+ }
435
+ let metadataText = "";
436
+ try {
437
+ const { stdout } = await runAgentApi(["get-conversation-metadata", task.sessionId], 10_000);
438
+ metadataText = stdout.trim();
439
+ } catch {
440
+ // Fallback purely to transcript if metadata call fails transiently.
441
+ }
442
+ const { entries, mtimeMs } = readTranscriptTail(task.sessionId, 16);
443
+ const inferred = inferAntigravityState(entries, mtimeMs);
444
+
445
+ const runningHint = /"running"\s*:\s*true|STATUS_RUNNING|in_progress/i.test(metadataText);
446
+ let status = inferred.status;
447
+ if (runningHint && status === "completed") {
448
+ status = "working";
449
+ }
450
+
451
+ if (status === "completed") {
452
+ return {
453
+ status: "completed",
454
+ statusMessage: "Antigravity turn completed",
455
+ result: {
456
+ summary: inferred.summary,
457
+ sessionId: task.sessionId,
458
+ },
459
+ };
460
+ }
461
+ if (status === "input_required") {
462
+ return {
463
+ status: "input_required",
464
+ statusMessage: inferred.summary.slice(0, 200) || "Waiting for user input",
465
+ inputRequests: inferred.inputRequests,
466
+ };
467
+ }
468
+ return {
469
+ status: "working",
470
+ statusMessage: inferred.summary.slice(0, 200) || "Antigravity conversation is running",
471
+ };
472
+ },
473
+
474
+ async pushMessage({ targetId, title = "External Notification", message, cwd = "", model = "" }) {
475
+ const agyCli = findAgyCli();
476
+ if (agyCli && targetId) {
477
+ try {
478
+ const payload = title ? `[${title}]\n${message}` : message;
479
+ const args = buildAgyArgs({ prompt: payload, model, conversationId: targetId });
480
+ const child = spawnAsyncCli({
481
+ bin: agyCli,
482
+ args,
483
+ cwd: cwd || process.cwd(),
484
+ taskId: null,
485
+ store: null,
486
+ });
487
+ if (child.pid) {
488
+ return {
489
+ delivered: true,
490
+ transport: "agy_cli",
491
+ output: `Dispatched follow-up via agy CLI (pid=${child.pid})`,
492
+ };
493
+ }
494
+ } catch (err) {
495
+ const agentApiReady = Boolean(findLsExe() && findActiveAntigravityHub());
496
+ if (!agentApiReady) throw err;
497
+ }
498
+ }
499
+
500
+ const { stdout, stderr } = await runAgentApi(
501
+ ["send-message", `--title=${title || "External Notification"}`, targetId, message],
502
+ 20_000
503
+ );
504
+ return {
505
+ delivered: true,
506
+ transport: "agentapi",
507
+ output: `${stdout}\n${stderr}`.trim().slice(0, 400),
508
+ };
509
+ },
510
+
511
+ async cancel(task, reason = "") {
512
+ if (task.pid) {
513
+ const killed = await killProcessTree(task.pid);
514
+ return { processKilled: killed, remoteStopSupported: true };
515
+ }
516
+ if (task.sessionId && reason) {
517
+ await runAgentApi(
518
+ ["send-message", "--title=Task Cancelled", task.sessionId, `[Cancelled] ${reason}`],
519
+ 10_000
520
+ ).catch(() => {});
521
+ }
522
+ return {
523
+ processKilled: false,
524
+ remoteStopSupported: false,
525
+ };
526
+ },
527
+ };
528
+ }
529
+
530
+ function spawnAsyncCli({ bin, args, cwd, taskId, store, parseLine, wholeDocument = false, onDone }) {
531
+ if (PLATFORM === "win32" && /\.(cmd|bat)$/i.test(bin)) {
532
+ const name = path.basename(bin, path.extname(bin)).toLowerCase();
533
+ const packages = { codex: "@openai/codex", gemini: "@google/gemini-cli", claude: "@anthropic-ai/claude-code" };
534
+ const dir = path.join(path.dirname(bin), "node_modules", packages[name]);
535
+ const pkg = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8"));
536
+ const entry = path.resolve(dir, typeof pkg.bin === "string" ? pkg.bin : pkg.bin[name]);
537
+ if (!/\.(?:mjs|cjs|js)$/i.test(entry)) throw new Error("Expected an installed CLI JavaScript entry point.");
538
+ args = [entry, ...args];
539
+ bin = process.execPath;
540
+ }
541
+ const child = spawn(bin, args, {
542
+ cwd,
543
+ shell: false,
544
+ detached: PLATFORM !== "win32",
545
+ stdio: ["ignore", "pipe", "pipe"],
546
+ windowsHide: true,
547
+ env: { ...childEnvironment(), FORCE_COLOR: "0" },
548
+ });
549
+
550
+ if (!taskId) {
551
+ child.stdout?.resume();
552
+ child.stderr?.resume();
553
+ child.on("error", () => {});
554
+ return child;
555
+ }
556
+ store.updateTask(taskId, { pid: child.pid || null, status: "working" });
557
+
558
+ let stdoutBuf = "";
559
+ const state = { sessionId: "", finalMessage: "" };
560
+
561
+ const handleChunk = text => {
562
+ stdoutBuf += text;
563
+ if (wholeDocument) return;
564
+ const lines = stdoutBuf.split(/\r?\n/);
565
+ stdoutBuf = lines.pop() ?? "";
566
+ for (const line of lines) {
567
+ if (parseLine) parseLine(line, state);
568
+ }
569
+ if (state.sessionId) {
570
+ const cur = store.getTask(taskId);
571
+ if (cur && !cur.sessionId) {
572
+ store.updateTask(taskId, { sessionId: state.sessionId });
573
+ }
574
+ }
575
+ };
576
+
577
+ child.stdout?.setEncoding("utf8");
578
+ child.stdout?.on("data", handleChunk);
579
+ child.stderr?.resume();
580
+
581
+ child.once("error", (err) => {
582
+ store.updateTask(taskId, {
583
+ status: "failed",
584
+ statusMessage: err.message,
585
+ error: { code: -32000, message: err.message },
586
+ pid: null,
587
+ });
588
+ });
589
+
590
+ child.once("close", (code) => {
591
+ if (stdoutBuf.trim() && parseLine) {
592
+ parseLine(stdoutBuf.trim(), state);
593
+ }
594
+ const latest = store.getTask(taskId);
595
+ if (!latest || latest.status === "cancelled") {
596
+ return;
597
+ }
598
+ if (code === 0) {
599
+ const message = sanitizeSensitiveText(state.finalMessage || "").trim();
600
+ if (message) store.appendTaskOutput(taskId, message);
601
+ const summary = message.slice(-2000);
602
+ store.updateTask(taskId, {
603
+ status: "completed",
604
+ statusMessage: "CLI agent completed",
605
+ sessionId: state.sessionId || latest.sessionId,
606
+ pid: null,
607
+ result: {
608
+ summary,
609
+ exitCode: 0,
610
+ sessionId: state.sessionId || latest.sessionId || undefined,
611
+ },
612
+ });
613
+ } else {
614
+ const errMsg = `CLI exited with code ${code ?? 1}`;
615
+ store.updateTask(taskId, {
616
+ status: "failed",
617
+ statusMessage: errMsg,
618
+ sessionId: state.sessionId || latest.sessionId,
619
+ pid: null,
620
+ error: { code: -32000, message: errMsg, data: { exitCode: code ?? 1 } },
621
+ });
622
+ }
623
+ if (onDone) onDone(code);
624
+ });
625
+
626
+ return child;
627
+ }
628
+
629
+ function createCodexAdapter() {
630
+ const findBin = () => findExecutable(["codex"]);
631
+ const parseCodexLine = (line, state) => {
632
+ try {
633
+ const obj = JSON.parse(line);
634
+ if (obj.thread_id) state.sessionId = String(obj.thread_id);
635
+ if (obj.item?.type === "agent_message" && obj.item?.text) {
636
+ state.finalMessage = String(obj.item.text);
637
+ } else if (typeof obj.message === "string") {
638
+ state.finalMessage = obj.message;
639
+ }
640
+ } catch {
641
+ // Non-JSON line.
642
+ }
643
+ };
644
+
645
+ return {
646
+ name: "codex",
647
+ supportsPush: true,
648
+ probe() {
649
+ const bin = findBin();
650
+ return {
651
+ engine: "codex",
652
+ available: Boolean(bin),
653
+ installed: Boolean(bin),
654
+ running: false,
655
+ supportsPush: Boolean(bin),
656
+ detail: bin ? `Codex CLI detected (${path.basename(bin)})` : "Codex CLI not installed",
657
+ };
658
+ },
659
+ async dispatch({ prompt, cwd, model, taskId, store }) {
660
+ const bin = findBin();
661
+ if (!bin) throw new Error("Codex CLI is not installed on this machine.");
662
+ const args = ["exec", "--json"];
663
+ if (model) args.push("-m", model);
664
+ if (cwd) args.push("-C", cwd);
665
+ args.push(prompt);
666
+ const child = spawnAsyncCli({ bin, args, cwd, taskId, store, parseLine: parseCodexLine });
667
+ return {
668
+ pid: child.pid || null,
669
+ status: "working",
670
+ statusMessage: "Codex CLI task started",
671
+ remoteStopSupported: true,
672
+ };
673
+ },
674
+ async pushMessage({ targetId, message, cwd, taskId, store }) {
675
+ const bin = findBin();
676
+ if (!bin) throw new Error("Codex CLI is not installed on this machine.");
677
+ const args = ["exec", "resume", targetId, "--json", message];
678
+ const child = spawnAsyncCli({ bin, args, cwd, taskId, store, parseLine: parseCodexLine });
679
+ return { delivered: true, pid: child.pid || null };
680
+ },
681
+ async inspect(task) {
682
+ if (task.status === "working" && task.pid && !isPidAlive(task.pid)) {
683
+ return {
684
+ status: "failed",
685
+ statusMessage: "Codex process exited unexpectedly",
686
+ error: { code: -32000, message: "Codex process is no longer running." },
687
+ };
688
+ }
689
+ return null;
690
+ },
691
+ async cancel(task) {
692
+ const killed = task.pid ? await killProcessTree(task.pid) : false;
693
+ return { processKilled: killed, remoteStopSupported: true };
694
+ },
695
+ };
696
+ }
697
+
698
+ function createClaudeAdapter() {
699
+ const findBin = () => findExecutable(["claude"]);
700
+ const parseClaudeLine = (line, state) => {
701
+ try {
702
+ const obj = JSON.parse(line);
703
+ if (obj.session_id) state.sessionId = String(obj.session_id);
704
+ if (obj.type === "result" && typeof obj.result === "string") {
705
+ state.finalMessage = obj.result;
706
+ }
707
+ } catch {
708
+ // Non-JSON line.
709
+ }
710
+ };
711
+
712
+ return {
713
+ name: "claude",
714
+ supportsPush: true,
715
+ probe() {
716
+ const bin = findBin();
717
+ return {
718
+ engine: "claude",
719
+ available: Boolean(bin),
720
+ installed: Boolean(bin),
721
+ running: false,
722
+ supportsPush: Boolean(bin),
723
+ detail: bin ? `Claude Code CLI detected (${path.basename(bin)})` : "Claude Code CLI not installed",
724
+ };
725
+ },
726
+ async dispatch({ prompt, cwd, model, taskId, store }) {
727
+ const bin = findBin();
728
+ if (!bin) throw new Error("Claude Code CLI is not installed on this machine.");
729
+ const args = ["-p", prompt, "--output-format", "stream-json", "--verbose"];
730
+ if (model) args.push("--model", model);
731
+ const child = spawnAsyncCli({ bin, args, cwd, taskId, store, parseLine: parseClaudeLine });
732
+ return {
733
+ pid: child.pid || null,
734
+ status: "working",
735
+ statusMessage: "Claude Code CLI task started",
736
+ remoteStopSupported: true,
737
+ };
738
+ },
739
+ async pushMessage({ targetId, message, cwd, taskId, store }) {
740
+ const bin = findBin();
741
+ if (!bin) throw new Error("Claude Code CLI is not installed on this machine.");
742
+ const args = ["-p", message, "--resume", targetId, "--output-format", "stream-json", "--verbose"];
743
+ const child = spawnAsyncCli({ bin, args, cwd, taskId, store, parseLine: parseClaudeLine });
744
+ return { delivered: true, pid: child.pid || null };
745
+ },
746
+ async inspect(task) {
747
+ if (task.status === "working" && task.pid && !isPidAlive(task.pid)) {
748
+ return {
749
+ status: "failed",
750
+ statusMessage: "Claude Code process exited unexpectedly",
751
+ error: { code: -32000, message: "Claude Code process is no longer running." },
752
+ };
753
+ }
754
+ return null;
755
+ },
756
+ async cancel(task) {
757
+ const killed = task.pid ? await killProcessTree(task.pid) : false;
758
+ return { processKilled: killed, remoteStopSupported: true };
759
+ },
760
+ };
761
+ }
762
+
763
+ function createGeminiCliAdapter() {
764
+ const findBin = () => findExecutable(["gemini"]);
765
+ const parseGeminiLine = (line, state) => {
766
+ try {
767
+ const obj = JSON.parse(line);
768
+ if (typeof obj.response === "string") state.finalMessage = obj.response;
769
+ if (obj.session_id) state.sessionId = String(obj.session_id);
770
+ } catch {
771
+ // Non-JSON line.
772
+ }
773
+ };
774
+
775
+ return {
776
+ name: "gemini",
777
+ supportsPush: false,
778
+ probe() {
779
+ const bin = findBin();
780
+ return {
781
+ engine: "gemini",
782
+ available: Boolean(bin),
783
+ installed: Boolean(bin),
784
+ running: false,
785
+ supportsPush: false,
786
+ detail: bin ? `Gemini CLI detected (${path.basename(bin)})` : "Gemini CLI not installed",
787
+ };
788
+ },
789
+ async dispatch({ prompt, cwd, model, taskId, store }) {
790
+ const bin = findBin();
791
+ if (!bin) throw new Error("Gemini CLI is not installed on this machine.");
792
+ const args = ["-p", prompt, "--output-format", "json"];
793
+ if (model) args.push("-m", model);
794
+ const child = spawnAsyncCli({ bin, args, cwd, taskId, store, parseLine: parseGeminiLine, wholeDocument: true });
795
+ return {
796
+ pid: child.pid || null,
797
+ status: "working",
798
+ statusMessage: "Gemini CLI task started",
799
+ remoteStopSupported: true,
800
+ };
801
+ },
802
+ async inspect(task) {
803
+ if (task.status === "working" && task.pid && !isPidAlive(task.pid)) {
804
+ return {
805
+ status: "failed",
806
+ statusMessage: "Gemini CLI process exited unexpectedly",
807
+ error: { code: -32000, message: "Gemini CLI process is no longer running." },
808
+ };
809
+ }
810
+ return null;
811
+ },
812
+ async cancel(task) {
813
+ const killed = task.pid ? await killProcessTree(task.pid) : false;
814
+ return { processKilled: killed, remoteStopSupported: true };
815
+ },
816
+ };
817
+ }
818
+
819
+ function discoveryProvider(name, dataDir, candidates = []) {
820
+ return {
821
+ name,
822
+ probe() {
823
+ const executable = findExecutable([name], candidates);
824
+ return { engine: name, installed: Boolean(executable || existsSync(dataDir)), running: false,
825
+ available: false, supportsPush: false, detail: "Discovery only; use a registered inbox for dispatch", dataDir, executable };
826
+ },
827
+ };
828
+ }
829
+
830
+ export function createDefaultProviders() {
831
+ const list = [
832
+ createAntigravityAdapter(),
833
+ createCodexAdapter(),
834
+ createClaudeAdapter(),
835
+ createGeminiCliAdapter(),
836
+ discoveryProvider("dsh", path.join(os.homedir(), ".dsh", "sessions"), process.env.LOCALAPPDATA ? [path.join(process.env.LOCALAPPDATA, "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin", "dsh.cmd")] : []),
837
+ discoveryProvider("workbuddy", path.join(os.homedir(), ".workbuddy")),
838
+ ];
839
+ return new Map(list.map((p) => [p.name, p]));
840
+ }