gemini-agent-bridge 0.0.0-stage → 0.1.0

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/cli.js ADDED
@@ -0,0 +1,4492 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+
6
+ // src/adapters/opencode-adapter.ts
7
+ import { execFile as execFile2, spawn } from "child_process";
8
+ import { promisify as promisify2 } from "util";
9
+
10
+ // src/runtime/binary-resolver.ts
11
+ import { execFile, execFileSync } from "child_process";
12
+ import fs2 from "fs";
13
+ import os2 from "os";
14
+ import path2 from "path";
15
+ import { promisify } from "util";
16
+
17
+ // src/config/paths.ts
18
+ import fs from "fs";
19
+ import os from "os";
20
+ import path from "path";
21
+ var APP_NAME = "gemini-agent-bridge";
22
+ function expandHome(inputPath) {
23
+ if (inputPath === "~") {
24
+ return os.homedir();
25
+ }
26
+ if (inputPath.startsWith("~/") || inputPath.startsWith("~\\")) {
27
+ return path.join(os.homedir(), inputPath.slice(2));
28
+ }
29
+ return inputPath;
30
+ }
31
+ function resolveRealPathOrClosest(inputPath) {
32
+ const expanded = path.resolve(expandHome(inputPath));
33
+ try {
34
+ return fs.realpathSync(expanded);
35
+ } catch {
36
+ const parts = [];
37
+ let current = expanded;
38
+ while (true) {
39
+ const parent = path.dirname(current);
40
+ if (parent === current) {
41
+ return expanded;
42
+ }
43
+ parts.unshift(path.basename(current));
44
+ current = parent;
45
+ try {
46
+ const realParent = fs.realpathSync(current);
47
+ return path.join(realParent, ...parts);
48
+ } catch {
49
+ }
50
+ }
51
+ }
52
+ }
53
+ function getDataDir(customDataDir, env = process.env) {
54
+ if (customDataDir && customDataDir.trim() !== "") {
55
+ return path.resolve(expandHome(customDataDir.trim()));
56
+ }
57
+ if (env.GEMINI_AGENT_BRIDGE_DATA_DIR && env.GEMINI_AGENT_BRIDGE_DATA_DIR.trim() !== "") {
58
+ return path.resolve(expandHome(env.GEMINI_AGENT_BRIDGE_DATA_DIR.trim()));
59
+ }
60
+ if (env.XDG_DATA_HOME && env.XDG_DATA_HOME.trim() !== "") {
61
+ return path.join(path.resolve(expandHome(env.XDG_DATA_HOME.trim())), APP_NAME);
62
+ }
63
+ return path.join(os.homedir(), ".local", "share", APP_NAME);
64
+ }
65
+ function getConfigPath(dataDir, customConfigPath, env = process.env) {
66
+ if (customConfigPath && customConfigPath.trim() !== "") {
67
+ return path.resolve(expandHome(customConfigPath.trim()));
68
+ }
69
+ if (env.GEMINI_AGENT_BRIDGE_CONFIG && env.GEMINI_AGENT_BRIDGE_CONFIG.trim() !== "") {
70
+ return path.resolve(expandHome(env.GEMINI_AGENT_BRIDGE_CONFIG.trim()));
71
+ }
72
+ return path.join(dataDir, "config.json");
73
+ }
74
+ function getTasksDir(dataDir) {
75
+ return path.join(dataDir, "tasks");
76
+ }
77
+ function getTaskDir(dataDir, taskId) {
78
+ return path.join(getTasksDir(dataDir), taskId);
79
+ }
80
+ function getPiSessionsDir(dataDir, taskId) {
81
+ return path.join(getTaskDir(dataDir, taskId), "pi-sessions");
82
+ }
83
+ function getWorktreesDir(dataDir) {
84
+ return path.join(dataDir, "worktrees");
85
+ }
86
+ function getStagingDir(dataDir) {
87
+ return path.join(dataDir, "staging");
88
+ }
89
+ function getLogsDir(dataDir) {
90
+ return path.join(dataDir, "logs");
91
+ }
92
+ function isPathInsideOrEqual(candidatePath, parentPath) {
93
+ const realCandidate = resolveRealPathOrClosest(candidatePath);
94
+ const realParent = resolveRealPathOrClosest(parentPath);
95
+ const rel = path.relative(realParent, realCandidate);
96
+ return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
97
+ }
98
+
99
+ // src/runtime/binary-resolver.ts
100
+ var execFileAsync = promisify(execFile);
101
+ var cachedShellPathEntries = null;
102
+ function compareSemverDesc(a, b) {
103
+ const parse = (s) => s.replace(/^v/i, "").split(".").map((part) => Number.parseInt(part, 10) || 0);
104
+ const pa = parse(a);
105
+ const pb = parse(b);
106
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
107
+ const diff = (pb[i] ?? 0) - (pa[i] ?? 0);
108
+ if (diff !== 0) return diff;
109
+ }
110
+ return 0;
111
+ }
112
+ function getWellKnownMacPathEntries() {
113
+ const home = os2.homedir();
114
+ const entries = [
115
+ path2.dirname(process.execPath),
116
+ path2.join(home, "Library", "pnpm", "bin"),
117
+ path2.join(home, "Library", "pnpm"),
118
+ path2.join(home, ".opencode", "bin"),
119
+ path2.join(home, ".npm-global", "bin"),
120
+ path2.join(home, ".local", "bin"),
121
+ path2.join(home, ".bun", "bin"),
122
+ "/opt/homebrew/bin",
123
+ "/opt/homebrew/sbin",
124
+ "/usr/local/bin",
125
+ path2.join(home, ".volta", "bin"),
126
+ path2.join(home, ".asdf", "shims"),
127
+ path2.join(home, ".mise", "shims"),
128
+ path2.join(home, ".local", "share", "mise", "shims")
129
+ ];
130
+ const nvmDir = path2.join(home, ".nvm", "versions", "node");
131
+ try {
132
+ if (fs2.existsSync(nvmDir)) {
133
+ const versions = fs2.readdirSync(nvmDir).sort(compareSemverDesc);
134
+ for (const ver of versions.slice(0, 2)) {
135
+ entries.push(path2.join(nvmDir, ver, "bin"));
136
+ }
137
+ }
138
+ } catch {
139
+ }
140
+ return entries;
141
+ }
142
+ function probeLoginShellPath() {
143
+ if (cachedShellPathEntries !== null) {
144
+ return cachedShellPathEntries;
145
+ }
146
+ if (process.platform === "win32") {
147
+ cachedShellPathEntries = [];
148
+ return cachedShellPathEntries;
149
+ }
150
+ const shell = process.env.SHELL && fs2.existsSync(process.env.SHELL) ? process.env.SHELL : "/bin/zsh";
151
+ try {
152
+ const out = execFileSync(shell, ["-lc", 'printf "%s" "$PATH"'], {
153
+ timeout: 1500,
154
+ encoding: "utf8",
155
+ stdio: ["ignore", "pipe", "ignore"]
156
+ });
157
+ cachedShellPathEntries = out.split(path2.delimiter).map((p) => p.trim()).filter(Boolean);
158
+ } catch {
159
+ cachedShellPathEntries = [];
160
+ }
161
+ return cachedShellPathEntries;
162
+ }
163
+ function buildAugmentedEnv(baseEnv = process.env, options = {}) {
164
+ const existingPath = (baseEnv.PATH ?? "").split(path2.delimiter).map((p) => p.trim()).filter(Boolean);
165
+ const combined = [
166
+ ...options.extraPathEntries ?? [],
167
+ path2.dirname(process.execPath),
168
+ ...existingPath,
169
+ ...getWellKnownMacPathEntries(),
170
+ ...options.probeLoginShell ? probeLoginShellPath() : []
171
+ ];
172
+ const seen = /* @__PURE__ */ new Set();
173
+ const deduped = [];
174
+ for (const entry of combined) {
175
+ if (!entry || seen.has(entry)) continue;
176
+ seen.add(entry);
177
+ deduped.push(entry);
178
+ }
179
+ const currentDepth = Number.parseInt(baseEnv.GEMINI_AGENT_BRIDGE_DEPTH ?? "0", 10);
180
+ const nextDepth = options.incrementDepth === false ? baseEnv.GEMINI_AGENT_BRIDGE_DEPTH : String((Number.isFinite(currentDepth) ? currentDepth : 0) + 1);
181
+ return {
182
+ ...baseEnv,
183
+ PATH: deduped.join(path2.delimiter),
184
+ ...nextDepth !== void 0 ? { GEMINI_AGENT_BRIDGE_DEPTH: nextDepth } : {}
185
+ };
186
+ }
187
+ function isExecutableFile(filePath) {
188
+ try {
189
+ const stat = fs2.statSync(filePath);
190
+ if (stat.isDirectory()) return false;
191
+ fs2.accessSync(filePath, fs2.constants.X_OK);
192
+ return true;
193
+ } catch {
194
+ return false;
195
+ }
196
+ }
197
+ function resolveBinary(name, explicitPath, env = process.env) {
198
+ if (explicitPath && explicitPath.trim() !== "") {
199
+ const resolved = path2.resolve(expandHome(explicitPath.trim()));
200
+ if (isExecutableFile(resolved)) {
201
+ return {
202
+ found: true,
203
+ path: resolved,
204
+ source: "explicit",
205
+ searchedPaths: [resolved]
206
+ };
207
+ }
208
+ return {
209
+ found: false,
210
+ searchedPaths: [resolved],
211
+ error: `Configured binary path for "${name}" is not executable or not found: ${resolved}`
212
+ };
213
+ }
214
+ const pathEntries = (env.PATH ?? "").split(path2.delimiter).map((p) => p.trim()).filter(Boolean);
215
+ const searchedPaths = [];
216
+ for (const dir of pathEntries) {
217
+ const candidate = path2.join(dir, name);
218
+ searchedPaths.push(candidate);
219
+ if (isExecutableFile(candidate)) {
220
+ return {
221
+ found: true,
222
+ path: candidate,
223
+ source: "path",
224
+ searchedPaths
225
+ };
226
+ }
227
+ }
228
+ return {
229
+ found: false,
230
+ searchedPaths,
231
+ error: `Executable "${name}" not found in PATH (${pathEntries.slice(0, 8).join(", ")}${pathEntries.length > 8 ? ", ..." : ""})`
232
+ };
233
+ }
234
+ async function probeBinaryVersion(binPath, args = ["--version"], env = process.env, timeoutMs = 5e3) {
235
+ try {
236
+ const { stdout, stderr } = await execFileAsync(binPath, args, {
237
+ env,
238
+ timeout: timeoutMs,
239
+ maxBuffer: 256 * 1024
240
+ });
241
+ const text = (stdout || stderr || "").trim();
242
+ const firstLine = text.split(/\r?\n/)[0]?.trim() || "unknown";
243
+ return { ok: true, version: firstLine };
244
+ } catch (err) {
245
+ const message = err instanceof Error ? err.message : String(err);
246
+ return { ok: false, error: message };
247
+ }
248
+ }
249
+
250
+ // src/runtime/jsonl-stream.ts
251
+ function createJsonlParser(onRecord, onParseError) {
252
+ let buffer = Buffer.alloc(0);
253
+ const emitLine = (lineBuf) => {
254
+ let end = lineBuf.length;
255
+ if (end > 0 && lineBuf[end - 1] === 13) {
256
+ end -= 1;
257
+ }
258
+ if (end === 0) return;
259
+ const rawLine = lineBuf.subarray(0, end).toString("utf8");
260
+ if (rawLine.trim().length === 0) return;
261
+ try {
262
+ const parsed = JSON.parse(rawLine);
263
+ onRecord(parsed, rawLine);
264
+ } catch (err) {
265
+ if (onParseError) {
266
+ onParseError(err instanceof Error ? err : new Error(String(err)), rawLine);
267
+ }
268
+ }
269
+ };
270
+ return {
271
+ push(chunk) {
272
+ const next = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
273
+ if (next.length === 0) return;
274
+ buffer = buffer.length === 0 ? next : Buffer.concat([buffer, next]);
275
+ let start = 0;
276
+ while (true) {
277
+ const nlIndex = buffer.indexOf(10, start);
278
+ if (nlIndex === -1) break;
279
+ emitLine(buffer.subarray(start, nlIndex));
280
+ start = nlIndex + 1;
281
+ }
282
+ if (start > 0) {
283
+ buffer = start >= buffer.length ? Buffer.alloc(0) : Buffer.from(buffer.subarray(start));
284
+ }
285
+ },
286
+ flush() {
287
+ if (buffer.length > 0) {
288
+ emitLine(buffer);
289
+ buffer = Buffer.alloc(0);
290
+ }
291
+ }
292
+ };
293
+ }
294
+
295
+ // src/adapters/opencode-adapter.ts
296
+ var execFileAsync2 = promisify2(execFile2);
297
+ var OPENCODE_CAPABILITIES = {
298
+ rpcSteer: true,
299
+ followUp: true,
300
+ sessionResume: true,
301
+ readOnlyMode: true,
302
+ interactiveInput: false,
303
+ tokenStats: true,
304
+ costStats: true
305
+ };
306
+ function sanitizePromptArg(prompt) {
307
+ return prompt.startsWith("-") ? `[Director Task]
308
+ ${prompt}` : prompt;
309
+ }
310
+ function summarizeOpenCodeTool(toolName, input, title) {
311
+ if (title && title.trim()) {
312
+ return `${toolName}: ${title.trim().slice(0, 80)}`;
313
+ }
314
+ if (input && typeof input === "object") {
315
+ const obj = input;
316
+ if (typeof obj.command === "string") return `${toolName}: ${obj.command.slice(0, 80)}`;
317
+ if (typeof obj.filePath === "string") return `${toolName}: ${obj.filePath}`;
318
+ if (typeof obj.path === "string") return `${toolName}: ${obj.path}`;
319
+ if (typeof obj.pattern === "string") return `${toolName}: ${obj.pattern}`;
320
+ }
321
+ return toolName;
322
+ }
323
+ var OpenCodeAdapter = class {
324
+ id = "opencode";
325
+ name = "OpenCode";
326
+ capabilities = OPENCODE_CAPABILITIES;
327
+ async detect(config, env) {
328
+ const res = resolveBinary("opencode", config.agents.opencode.bin, env);
329
+ if (!res.found || !res.path) {
330
+ return {
331
+ id: this.id,
332
+ name: this.name,
333
+ available: false,
334
+ error: res.error ?? "opencode binary not found",
335
+ capabilities: this.capabilities
336
+ };
337
+ }
338
+ const ver = await probeBinaryVersion(res.path, ["--version"], env);
339
+ return {
340
+ id: this.id,
341
+ name: this.name,
342
+ available: ver.ok,
343
+ binaryPath: res.path,
344
+ version: ver.version,
345
+ ...ver.ok ? {} : { error: ver.error },
346
+ capabilities: this.capabilities
347
+ };
348
+ }
349
+ async listModels(config, env) {
350
+ const res = resolveBinary("opencode", config.agents.opencode.bin, env);
351
+ if (!res.found || !res.path) {
352
+ return [];
353
+ }
354
+ try {
355
+ const { stdout } = await execFileAsync2(res.path, ["models"], {
356
+ env,
357
+ timeout: 6e3,
358
+ maxBuffer: 512 * 1024
359
+ });
360
+ return stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("Available")).slice(0, 100);
361
+ } catch {
362
+ return [];
363
+ }
364
+ }
365
+ async startRun(params) {
366
+ const res = resolveBinary("opencode", params.config.agents.opencode.bin, params.env);
367
+ if (!res.found || !res.path) {
368
+ throw new Error(res.error ?? "opencode binary not found");
369
+ }
370
+ const binPath = res.path;
371
+ let sessionId = params.sessionId;
372
+ if (sessionId) {
373
+ params.onSessionId?.(sessionId);
374
+ }
375
+ let seq = 0;
376
+ const emit = (type, summary, data) => {
377
+ seq += 1;
378
+ params.onEvent({
379
+ seq,
380
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
381
+ type,
382
+ summary,
383
+ ...data ? { data } : {}
384
+ });
385
+ };
386
+ let currentChild = null;
387
+ let aborted = false;
388
+ let steerInterruptPrompt = null;
389
+ const followUpQueue = [];
390
+ let toolCallsCount = 0;
391
+ const toolDigest = [];
392
+ const textParts = [];
393
+ let streamError;
394
+ const stderrLines = [];
395
+ const usageAcc = {
396
+ inputTokens: 0,
397
+ outputTokens: 0,
398
+ cacheReadTokens: 0,
399
+ cacheWriteTokens: 0,
400
+ reasoningTokens: 0,
401
+ totalTokens: 0,
402
+ costUsd: 0
403
+ };
404
+ let sawUsage = false;
405
+ const runSingleTurn = (promptText, isFirstTurn) => {
406
+ const args = ["run", "--format", "json"];
407
+ if (params.config.agents.opencode.standalone !== false) {
408
+ args.push("--standalone");
409
+ }
410
+ if (params.config.agents.opencode.archived !== false) {
411
+ args.push("--archived");
412
+ }
413
+ if (sessionId) {
414
+ args.push("--session", sessionId);
415
+ }
416
+ const model = params.model ?? params.config.agents.opencode.defaultModel;
417
+ if (model) {
418
+ args.push("--model", model);
419
+ }
420
+ const profile = params.workspaceMode === "readonly" || params.agentProfile === "plan" ? "plan" : params.agentProfile ?? params.config.agents.opencode.defaultAgent;
421
+ if (profile) {
422
+ args.push("--agent", profile);
423
+ }
424
+ if (params.title) {
425
+ args.push("--title", params.title.slice(0, 80));
426
+ }
427
+ if (params.interactionPolicy !== "deny_interactive" && params.workspaceMode !== "readonly") {
428
+ args.push("--auto");
429
+ }
430
+ if (params.config.agents.opencode.extraArgs.length > 0) {
431
+ args.push(...params.config.agents.opencode.extraArgs);
432
+ }
433
+ const fullPrompt = isFirstTurn && params.systemAppendPrompt ? `${params.systemAppendPrompt}
434
+
435
+ ---
436
+
437
+ ${promptText}` : promptText;
438
+ args.push(sanitizePromptArg(fullPrompt));
439
+ return new Promise((resolveTurn, rejectTurn) => {
440
+ const child = spawn(binPath, args, {
441
+ cwd: params.executionDir,
442
+ env: params.env,
443
+ stdio: ["ignore", "pipe", "pipe"]
444
+ });
445
+ currentChild = child;
446
+ const unregister = params.processRegistry.register(child, `opencode:${params.taskId}`);
447
+ const parser = createJsonlParser(
448
+ (record) => {
449
+ const part = record.part && typeof record.part === "object" ? record.part : void 0;
450
+ const recSession = typeof record.sessionID === "string" ? record.sessionID : typeof part?.sessionID === "string" ? part.sessionID : void 0;
451
+ if (recSession && recSession !== sessionId) {
452
+ sessionId = recSession;
453
+ params.onSessionId?.(sessionId);
454
+ }
455
+ const type = typeof record.type === "string" ? record.type : "";
456
+ if (type === "step_start") {
457
+ emit("started", "OpenCode step started");
458
+ return;
459
+ }
460
+ if (type === "text") {
461
+ const txt = typeof part?.text === "string" ? part.text : "";
462
+ if (txt) {
463
+ textParts.push(txt);
464
+ emit("text", txt.slice(-200));
465
+ }
466
+ return;
467
+ }
468
+ if (type === "reasoning") {
469
+ const txt = typeof part?.text === "string" ? part.text : "";
470
+ if (txt) {
471
+ emit("thinking", txt.slice(0, 140));
472
+ }
473
+ return;
474
+ }
475
+ if (type === "tool_use") {
476
+ const toolName = typeof part?.tool === "string" ? part.tool : "tool";
477
+ const state = part?.state && typeof part.state === "object" ? part.state : {};
478
+ const status = typeof state.status === "string" ? state.status : "completed";
479
+ const title = typeof state.title === "string" ? state.title : void 0;
480
+ const metadata = state.metadata && typeof state.metadata === "object" ? state.metadata : void 0;
481
+ const exitVal = typeof metadata?.exit === "number" ? metadata.exit : void 0;
482
+ const isError = status === "error" || exitVal !== void 0 && exitVal !== 0;
483
+ toolCallsCount += 1;
484
+ const digest = summarizeOpenCodeTool(toolName, state.input, title);
485
+ toolDigest.push(digest);
486
+ emit("tool_end", `${digest}${isError ? " (error)" : ""}`, {
487
+ toolName,
488
+ callID: part?.callID,
489
+ status,
490
+ isError,
491
+ exit: exitVal
492
+ });
493
+ return;
494
+ }
495
+ if (type === "step_finish") {
496
+ const tokens = part?.tokens && typeof part.tokens === "object" ? part.tokens : void 0;
497
+ if (tokens) {
498
+ sawUsage = true;
499
+ if (typeof tokens.input === "number") usageAcc.inputTokens += tokens.input;
500
+ if (typeof tokens.output === "number") usageAcc.outputTokens += tokens.output;
501
+ if (typeof tokens.reasoning === "number") {
502
+ usageAcc.reasoningTokens += tokens.reasoning;
503
+ }
504
+ const cache = tokens.cache && typeof tokens.cache === "object" ? tokens.cache : void 0;
505
+ if (cache) {
506
+ if (typeof cache.read === "number") usageAcc.cacheReadTokens += cache.read;
507
+ if (typeof cache.write === "number") usageAcc.cacheWriteTokens += cache.write;
508
+ }
509
+ usageAcc.totalTokens = usageAcc.inputTokens + usageAcc.outputTokens + usageAcc.reasoningTokens + usageAcc.cacheReadTokens + usageAcc.cacheWriteTokens;
510
+ }
511
+ if (typeof part?.cost === "number") {
512
+ sawUsage = true;
513
+ usageAcc.costUsd += part.cost;
514
+ }
515
+ emit("status", `OpenCode step finished (${String(part?.reason ?? "done")})`);
516
+ return;
517
+ }
518
+ if (type === "error") {
519
+ const errObj = record.error && typeof record.error === "object" ? record.error : void 0;
520
+ const errData = errObj?.data && typeof errObj.data === "object" ? errObj.data : void 0;
521
+ streamError = typeof errData?.message === "string" && errData.message || typeof errObj?.message === "string" && errObj.message || typeof errObj?.name === "string" && errObj.name || "OpenCode reported an error";
522
+ emit("error", streamError);
523
+ }
524
+ },
525
+ (err, rawLine) => {
526
+ params.logger.warn("Malformed JSONL line from opencode stdout", {
527
+ taskId: params.taskId,
528
+ error: err.message,
529
+ linePreview: rawLine.slice(0, 120)
530
+ });
531
+ }
532
+ );
533
+ child.stdout.on("data", (chunk) => parser.push(chunk));
534
+ child.stderr.on("data", (chunk) => {
535
+ const text = chunk.toString("utf8").trim();
536
+ if (text) {
537
+ for (const line of text.split(/\r?\n/)) {
538
+ if (line.trim()) {
539
+ stderrLines.push(line.trim());
540
+ if (stderrLines.length > 50) stderrLines.shift();
541
+ }
542
+ }
543
+ }
544
+ });
545
+ child.on("error", (err) => {
546
+ unregister();
547
+ currentChild = null;
548
+ rejectTurn(err);
549
+ });
550
+ child.on("close", (code) => {
551
+ parser.flush();
552
+ unregister();
553
+ currentChild = null;
554
+ resolveTurn({ exitCode: code });
555
+ });
556
+ });
557
+ };
558
+ const completion = (async () => {
559
+ let nextPrompt = params.prompt;
560
+ let isFirstTurn = true;
561
+ let lastExitCode = 0;
562
+ try {
563
+ while (true) {
564
+ streamError = void 0;
565
+ const resTurn = await runSingleTurn(nextPrompt, isFirstTurn);
566
+ isFirstTurn = false;
567
+ lastExitCode = resTurn.exitCode;
568
+ if (aborted) {
569
+ emit("error", "OpenCode run aborted");
570
+ return {
571
+ ok: false,
572
+ aborted: true,
573
+ sessionId,
574
+ finalSummary: textParts.join("\n\n").trim(),
575
+ error: "Task aborted",
576
+ toolCallsCount,
577
+ toolDigest: toolDigest.slice(0, 50),
578
+ ...sawUsage ? { usage: usageAcc } : {}
579
+ };
580
+ }
581
+ if (steerInterruptPrompt !== null) {
582
+ nextPrompt = steerInterruptPrompt;
583
+ steerInterruptPrompt = null;
584
+ continue;
585
+ }
586
+ if (lastExitCode === 0 && !streamError && followUpQueue.length > 0) {
587
+ nextPrompt = followUpQueue.shift();
588
+ continue;
589
+ }
590
+ break;
591
+ }
592
+ } catch (err) {
593
+ const msg = err instanceof Error ? err.message : String(err);
594
+ emit("error", `Failed to execute opencode: ${msg}`);
595
+ return {
596
+ ok: false,
597
+ sessionId,
598
+ finalSummary: textParts.join("\n\n").trim(),
599
+ error: msg,
600
+ toolCallsCount,
601
+ toolDigest: toolDigest.slice(0, 50),
602
+ ...sawUsage ? { usage: usageAcc } : {}
603
+ };
604
+ }
605
+ const ok = lastExitCode === 0 && !streamError;
606
+ const errorMsg = ok ? void 0 : streamError ?? `opencode exited with code ${String(lastExitCode)}${stderrLines.length > 0 ? `: ${stderrLines.slice(-8).join("\n")}` : ""}`;
607
+ emit(ok ? "completed" : "error", ok ? "OpenCode run completed" : errorMsg ?? "OpenCode failed");
608
+ return {
609
+ ok,
610
+ sessionId,
611
+ finalSummary: textParts.join("\n\n").trim(),
612
+ ...errorMsg ? { error: errorMsg } : {},
613
+ toolCallsCount,
614
+ toolDigest: toolDigest.slice(0, 50),
615
+ ...sawUsage ? { usage: usageAcc } : {}
616
+ };
617
+ })();
618
+ return {
619
+ getSessionId: () => sessionId,
620
+ async steer(message, mode) {
621
+ if (mode === "follow_up") {
622
+ followUpQueue.push(message);
623
+ emit("status", "Queued follow_up instruction for OpenCode after current turn");
624
+ return;
625
+ }
626
+ if (!sessionId) {
627
+ throw new Error(
628
+ 'OpenCode has not emitted a sessionID yet; wait a moment or use mode="follow_up".'
629
+ );
630
+ }
631
+ steerInterruptPrompt = message;
632
+ emit("status", "Steering OpenCode: restarting current turn with updated guidance");
633
+ if (currentChild && currentChild.exitCode === null) {
634
+ currentChild.kill("SIGTERM");
635
+ }
636
+ },
637
+ async respondInput() {
638
+ throw new Error(
639
+ "OpenCode CLI mode does not pause for interactive dialog input (needs_input)."
640
+ );
641
+ },
642
+ async abort() {
643
+ aborted = true;
644
+ if (currentChild && currentChild.exitCode === null) {
645
+ currentChild.kill("SIGTERM");
646
+ setTimeout(() => {
647
+ if (currentChild && currentChild.exitCode === null) {
648
+ try {
649
+ currentChild.kill("SIGKILL");
650
+ } catch {
651
+ }
652
+ }
653
+ }, 2500).unref?.();
654
+ }
655
+ },
656
+ completion
657
+ };
658
+ }
659
+ };
660
+
661
+ // src/adapters/pi-adapter.ts
662
+ import { execFile as execFile3, spawn as spawn2 } from "child_process";
663
+ import crypto from "crypto";
664
+ import fs3 from "fs";
665
+ import { promisify as promisify3 } from "util";
666
+ var execFileAsync3 = promisify3(execFile3);
667
+ var PI_CAPABILITIES = {
668
+ rpcSteer: true,
669
+ followUp: true,
670
+ sessionResume: true,
671
+ readOnlyMode: true,
672
+ interactiveInput: true,
673
+ tokenStats: true,
674
+ costStats: true
675
+ };
676
+ function summarizeToolArgs(toolName, args) {
677
+ if (!args || typeof args !== "object") return toolName;
678
+ const obj = args;
679
+ if (typeof obj.command === "string") {
680
+ return `${toolName}: ${obj.command.slice(0, 80)}`;
681
+ }
682
+ if (typeof obj.path === "string") {
683
+ return `${toolName}: ${obj.path}`;
684
+ }
685
+ if (typeof obj.file_path === "string") {
686
+ return `${toolName}: ${obj.file_path}`;
687
+ }
688
+ if (typeof obj.pattern === "string") {
689
+ return `${toolName}: ${obj.pattern}`;
690
+ }
691
+ return toolName;
692
+ }
693
+ function extractTextFromMessage(message) {
694
+ if (!message || typeof message !== "object") return "";
695
+ const msg = message;
696
+ const content = msg.content;
697
+ if (typeof content === "string") return content;
698
+ if (!Array.isArray(content)) return "";
699
+ const chunks = [];
700
+ for (const block of content) {
701
+ if (block && typeof block === "object") {
702
+ const b = block;
703
+ if (b.type === "text" && typeof b.text === "string") {
704
+ chunks.push(b.text);
705
+ }
706
+ }
707
+ }
708
+ return chunks.join("\n");
709
+ }
710
+ function parseUsageFromStats(data) {
711
+ if (!data) return void 0;
712
+ const tokens = data.tokens && typeof data.tokens === "object" ? data.tokens : void 0;
713
+ const usage = {};
714
+ if (tokens) {
715
+ if (typeof tokens.input === "number") usage.inputTokens = tokens.input;
716
+ if (typeof tokens.output === "number") usage.outputTokens = tokens.output;
717
+ if (typeof tokens.cacheRead === "number") usage.cacheReadTokens = tokens.cacheRead;
718
+ if (typeof tokens.cacheWrite === "number") usage.cacheWriteTokens = tokens.cacheWrite;
719
+ if (typeof tokens.total === "number") usage.totalTokens = tokens.total;
720
+ }
721
+ if (typeof data.cost === "number") {
722
+ usage.costUsd = data.cost;
723
+ }
724
+ return Object.keys(usage).length > 0 ? usage : void 0;
725
+ }
726
+ var PiAdapter = class {
727
+ id = "pi";
728
+ name = "Pi Coding Agent";
729
+ capabilities = PI_CAPABILITIES;
730
+ async detect(config, env) {
731
+ const res = resolveBinary("pi", config.agents.pi.bin, env);
732
+ if (!res.found || !res.path) {
733
+ return {
734
+ id: this.id,
735
+ name: this.name,
736
+ available: false,
737
+ error: res.error ?? "pi binary not found",
738
+ capabilities: this.capabilities
739
+ };
740
+ }
741
+ const ver = await probeBinaryVersion(res.path, ["--version"], env);
742
+ return {
743
+ id: this.id,
744
+ name: this.name,
745
+ available: ver.ok,
746
+ binaryPath: res.path,
747
+ version: ver.version,
748
+ ...ver.ok ? {} : { error: ver.error },
749
+ capabilities: this.capabilities
750
+ };
751
+ }
752
+ async listModels(config, env) {
753
+ const res = resolveBinary("pi", config.agents.pi.bin, env);
754
+ if (!res.found || !res.path) {
755
+ return [];
756
+ }
757
+ try {
758
+ const { stdout } = await execFileAsync3(res.path, ["--list-models"], {
759
+ env,
760
+ timeout: 6e3,
761
+ maxBuffer: 512 * 1024
762
+ });
763
+ return stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("Available") && !l.startsWith("---")).slice(0, 100);
764
+ } catch {
765
+ return [];
766
+ }
767
+ }
768
+ async startRun(params) {
769
+ const res = resolveBinary("pi", params.config.agents.pi.bin, params.env);
770
+ if (!res.found || !res.path) {
771
+ throw new Error(res.error ?? "pi binary not found");
772
+ }
773
+ fs3.mkdirSync(params.piSessionsDir, { recursive: true });
774
+ let sessionId = params.sessionId ?? crypto.randomUUID();
775
+ params.onSessionId?.(sessionId);
776
+ const args = [
777
+ "--mode",
778
+ "rpc",
779
+ "--session-dir",
780
+ params.piSessionsDir,
781
+ "--session-id",
782
+ sessionId,
783
+ "--name",
784
+ params.title.slice(0, 80)
785
+ ];
786
+ if (params.config.agents.pi.disableMcp !== false) {
787
+ args.push("--no-mcp");
788
+ }
789
+ if (params.workspaceMode === "readonly" || params.agentProfile === "readonly") {
790
+ args.push("--tools", "read,grep,find,ls");
791
+ } else if (params.agentProfile === "no-bash") {
792
+ args.push("--tools", "read,edit,write,grep,find,ls");
793
+ }
794
+ const model = params.model ?? params.config.agents.pi.defaultModel;
795
+ if (model) {
796
+ args.push("--model", model);
797
+ }
798
+ const thinking = params.thinking ?? params.config.agents.pi.defaultThinking;
799
+ if (thinking) {
800
+ args.push("--thinking", thinking);
801
+ }
802
+ if (params.systemAppendPrompt) {
803
+ args.push("--append-system-prompt", params.systemAppendPrompt);
804
+ }
805
+ if (params.interactionPolicy === "auto_approve" || params.config.agents.pi.trustProjectFiles) {
806
+ args.push("--approve");
807
+ } else if (params.interactionPolicy === "deny_interactive") {
808
+ args.push("--no-approve");
809
+ }
810
+ if (params.config.agents.pi.extraArgs.length > 0) {
811
+ args.push(...params.config.agents.pi.extraArgs);
812
+ }
813
+ const child = spawn2(res.path, args, {
814
+ cwd: params.executionDir,
815
+ env: params.env,
816
+ stdio: ["pipe", "pipe", "pipe"]
817
+ });
818
+ let seq = 0;
819
+ const emit = (type, summary, data) => {
820
+ seq += 1;
821
+ params.onEvent({
822
+ seq,
823
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
824
+ type,
825
+ summary,
826
+ ...data ? { data } : {}
827
+ });
828
+ };
829
+ let reqCounter = 0;
830
+ const pendingRpc = /* @__PURE__ */ new Map();
831
+ const pendingDialogs = /* @__PURE__ */ new Map();
832
+ const writeStdinJson = (payload) => {
833
+ if (!child.stdin.writable || child.exitCode !== null) {
834
+ throw new Error("Cannot write to pi RPC process stdin (process already closed).");
835
+ }
836
+ child.stdin.write(`${JSON.stringify(payload)}
837
+ `, "utf8");
838
+ };
839
+ const sendCommand = (type, payload = {}, timeoutMs = 15e3) => {
840
+ const id = `req-${++reqCounter}`;
841
+ return new Promise((resolve, reject) => {
842
+ const timer = setTimeout(() => {
843
+ pendingRpc.delete(id);
844
+ reject(new Error(`pi RPC command "${type}" timed out after ${timeoutMs}ms`));
845
+ }, timeoutMs);
846
+ timer.unref?.();
847
+ pendingRpc.set(id, { resolve, reject, timer });
848
+ try {
849
+ writeStdinJson({ id, type, ...payload });
850
+ } catch (err) {
851
+ clearTimeout(timer);
852
+ pendingRpc.delete(id);
853
+ reject(err instanceof Error ? err : new Error(String(err)));
854
+ }
855
+ });
856
+ };
857
+ let toolCallsCount = 0;
858
+ const toolDigest = [];
859
+ let streamingBuffer = "";
860
+ let lastAssistantText = "";
861
+ let lastAssistantStopReason;
862
+ let lastAssistantError;
863
+ const stderrLines = [];
864
+ let aborted = false;
865
+ let settledReceived = false;
866
+ let finishing = false;
867
+ const unregister = params.processRegistry.register(child, `pi:${params.taskId}`, () => {
868
+ try {
869
+ if (child.stdin.writable) {
870
+ child.stdin.end();
871
+ }
872
+ } catch {
873
+ }
874
+ });
875
+ const completion = new Promise((resolveCompletion) => {
876
+ let resolved = false;
877
+ const finishOnce = (result) => {
878
+ if (resolved) return;
879
+ resolved = true;
880
+ unregister();
881
+ for (const [id, entry] of pendingRpc.entries()) {
882
+ clearTimeout(entry.timer);
883
+ entry.reject(new Error("pi RPC process terminated"));
884
+ pendingRpc.delete(id);
885
+ }
886
+ resolveCompletion(result);
887
+ };
888
+ const shutdownGracefully = () => {
889
+ if (child.exitCode !== null) return;
890
+ try {
891
+ if (child.stdin.writable) {
892
+ child.stdin.end();
893
+ }
894
+ } catch {
895
+ }
896
+ const killTimer = setTimeout(() => {
897
+ if (child.exitCode === null) {
898
+ try {
899
+ child.kill("SIGTERM");
900
+ } catch {
901
+ }
902
+ }
903
+ }, 2500);
904
+ killTimer.unref?.();
905
+ };
906
+ const finalizeAfterSettled = async (wasAborted) => {
907
+ if (finishing) return;
908
+ finishing = true;
909
+ let usage;
910
+ let finalText = lastAssistantText || streamingBuffer;
911
+ try {
912
+ const statsResp = await sendCommand("get_session_stats", {}, 4e3);
913
+ if (statsResp.success) {
914
+ usage = parseUsageFromStats(statsResp.data);
915
+ if (typeof statsResp.data?.sessionId === "string") {
916
+ sessionId = statsResp.data.sessionId;
917
+ params.onSessionId?.(sessionId);
918
+ }
919
+ }
920
+ } catch {
921
+ }
922
+ try {
923
+ const textResp = await sendCommand("get_last_assistant_text", {}, 4e3);
924
+ if (textResp.success && typeof textResp.data?.text === "string") {
925
+ finalText = textResp.data.text;
926
+ }
927
+ } catch {
928
+ }
929
+ shutdownGracefully();
930
+ const hasErrorStop = lastAssistantStopReason === "error" || Boolean(lastAssistantError);
931
+ const finalAborted = aborted || wasAborted || lastAssistantStopReason === "aborted";
932
+ const ok = !finalAborted && !hasErrorStop;
933
+ const errorMsg = finalAborted ? "Task aborted" : lastAssistantError ?? (lastAssistantStopReason === "error" ? "pi assistant turn ended with stopReason=error" : void 0);
934
+ emit(ok ? "completed" : "error", ok ? "pi run settled" : errorMsg ?? "pi run failed");
935
+ finishOnce({
936
+ ok,
937
+ ...finalAborted ? { aborted: true } : {},
938
+ sessionId,
939
+ finalSummary: finalText.trim(),
940
+ ...errorMsg ? { error: errorMsg } : {},
941
+ toolCallsCount,
942
+ toolDigest: toolDigest.slice(0, 50),
943
+ ...usage ? { usage } : {}
944
+ });
945
+ };
946
+ const handleExtensionUiRequest = (rec) => {
947
+ const reqId = typeof rec.id === "string" ? rec.id : crypto.randomUUID();
948
+ const method = typeof rec.method === "string" ? rec.method : "notify";
949
+ if (method === "notify" || method === "setStatus" || method === "setWidget" || method === "setTitle" || method === "set_editor_text") {
950
+ const msg = typeof rec.message === "string" ? rec.message : typeof rec.statusText === "string" ? rec.statusText : typeof rec.title === "string" ? rec.title : method;
951
+ emit("status", `pi UI (${method}): ${msg}`);
952
+ return;
953
+ }
954
+ const dialogMethod = method === "select" || method === "confirm" || method === "input" || method === "editor" ? method : "confirm";
955
+ const title = typeof rec.title === "string" ? rec.title : "pi extension input request";
956
+ const message = typeof rec.message === "string" ? rec.message : void 0;
957
+ const options = Array.isArray(rec.options) ? rec.options.filter((o) => typeof o === "string") : void 0;
958
+ const placeholder = typeof rec.placeholder === "string" ? rec.placeholder : void 0;
959
+ const prefill = typeof rec.prefill === "string" ? rec.prefill : void 0;
960
+ const timeoutMs = typeof rec.timeout === "number" ? rec.timeout : void 0;
961
+ if (params.interactionPolicy === "deny_interactive") {
962
+ writeStdinJson({ type: "extension_ui_response", id: reqId, cancelled: true });
963
+ emit("status", `Auto-cancelled pi dialog (${dialogMethod}): ${title}`);
964
+ return;
965
+ }
966
+ if (params.interactionPolicy === "auto_approve") {
967
+ if (dialogMethod === "confirm") {
968
+ writeStdinJson({ type: "extension_ui_response", id: reqId, confirmed: true });
969
+ emit("status", `Auto-confirmed pi dialog: ${title}`);
970
+ return;
971
+ }
972
+ if (dialogMethod === "select" && options && options.length > 0) {
973
+ writeStdinJson({ type: "extension_ui_response", id: reqId, value: options[0] });
974
+ emit("status", `Auto-selected "${options[0]}" for pi dialog: ${title}`);
975
+ return;
976
+ }
977
+ }
978
+ const pendingReq = {
979
+ requestId: reqId,
980
+ method: dialogMethod,
981
+ title,
982
+ ...message ? { message } : {},
983
+ ...options ? { options } : {},
984
+ ...placeholder ? { placeholder } : {},
985
+ ...prefill ? { prefill } : {},
986
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
987
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
988
+ };
989
+ pendingDialogs.set(reqId, pendingReq);
990
+ emit("input_required", `Waiting for orchestrator response: ${title}`, {
991
+ requestId: reqId,
992
+ method: dialogMethod
993
+ });
994
+ params.onInputRequired?.(pendingReq);
995
+ };
996
+ const parser = createJsonlParser(
997
+ (record) => {
998
+ const type = typeof record.type === "string" ? record.type : "";
999
+ if (type === "response") {
1000
+ const resp = record;
1001
+ if (resp.id && pendingRpc.has(resp.id)) {
1002
+ const entry = pendingRpc.get(resp.id);
1003
+ clearTimeout(entry.timer);
1004
+ pendingRpc.delete(resp.id);
1005
+ entry.resolve(resp);
1006
+ } else if (!resp.success && resp.error) {
1007
+ emit("error", `pi RPC parse/command error: ${resp.error}`);
1008
+ }
1009
+ return;
1010
+ }
1011
+ if (type === "extension_ui_request") {
1012
+ handleExtensionUiRequest(record);
1013
+ return;
1014
+ }
1015
+ if (type === "agent_start") {
1016
+ emit("started", "pi agent turn started");
1017
+ return;
1018
+ }
1019
+ if (type === "message_start") {
1020
+ streamingBuffer = "";
1021
+ return;
1022
+ }
1023
+ if (type === "message_update") {
1024
+ const ame = record.assistantMessageEvent;
1025
+ if (ame && ame.type === "text_delta" && typeof ame.delta === "string") {
1026
+ streamingBuffer += ame.delta;
1027
+ }
1028
+ return;
1029
+ }
1030
+ if (type === "message_end") {
1031
+ const msg = record.message;
1032
+ if (msg && msg.role === "assistant") {
1033
+ const text = extractTextFromMessage(msg);
1034
+ if (text) lastAssistantText = text;
1035
+ if (typeof msg.stopReason === "string") {
1036
+ lastAssistantStopReason = msg.stopReason;
1037
+ }
1038
+ if (typeof msg.errorMessage === "string" && msg.errorMessage) {
1039
+ lastAssistantError = msg.errorMessage;
1040
+ }
1041
+ if (text) {
1042
+ emit("text", text.slice(-200));
1043
+ }
1044
+ }
1045
+ return;
1046
+ }
1047
+ if (type === "tool_execution_start") {
1048
+ const toolName = typeof record.toolName === "string" ? record.toolName : "tool";
1049
+ toolCallsCount += 1;
1050
+ const digest = summarizeToolArgs(toolName, record.args);
1051
+ toolDigest.push(digest);
1052
+ emit("tool_start", digest, { toolName, toolCallId: record.toolCallId });
1053
+ return;
1054
+ }
1055
+ if (type === "tool_execution_end") {
1056
+ const toolName = typeof record.toolName === "string" ? record.toolName : "tool";
1057
+ const isError = Boolean(record.isError);
1058
+ const durationMs = typeof record.durationMs === "number" ? record.durationMs : void 0;
1059
+ emit("tool_end", `${toolName}${isError ? " (error)" : ""}`, {
1060
+ toolName,
1061
+ isError,
1062
+ durationMs
1063
+ });
1064
+ return;
1065
+ }
1066
+ if (type === "auto_retry_start") {
1067
+ emit(
1068
+ "retry",
1069
+ `Retrying (${String(record.attempt ?? "?")}/${String(record.maxAttempts ?? "?")}): ${String(record.errorMessage ?? "")}`
1070
+ );
1071
+ return;
1072
+ }
1073
+ if (type === "compaction_start") {
1074
+ emit("compaction", `Context compaction started (${String(record.reason ?? "")})`);
1075
+ return;
1076
+ }
1077
+ if (type === "extension_error") {
1078
+ emit("error", `pi extension error: ${String(record.error ?? "unknown")}`);
1079
+ return;
1080
+ }
1081
+ if (type === "agent_settled") {
1082
+ settledReceived = true;
1083
+ const wasAborted = Boolean(record.aborted);
1084
+ void finalizeAfterSettled(wasAborted);
1085
+ }
1086
+ },
1087
+ (err, rawLine) => {
1088
+ params.logger.warn("Malformed JSONL line from pi stdout", {
1089
+ taskId: params.taskId,
1090
+ error: err.message,
1091
+ linePreview: rawLine.slice(0, 120)
1092
+ });
1093
+ }
1094
+ );
1095
+ child.stdout.on("data", (chunk) => parser.push(chunk));
1096
+ child.stderr.on("data", (chunk) => {
1097
+ const text = chunk.toString("utf8").trim();
1098
+ if (text) {
1099
+ for (const line of text.split(/\r?\n/)) {
1100
+ if (line.trim()) {
1101
+ stderrLines.push(line.trim());
1102
+ if (stderrLines.length > 50) stderrLines.shift();
1103
+ }
1104
+ }
1105
+ }
1106
+ });
1107
+ child.on("error", (err) => {
1108
+ emit("error", `Failed to spawn pi: ${err.message}`);
1109
+ finishOnce({
1110
+ ok: false,
1111
+ sessionId,
1112
+ finalSummary: lastAssistantText.trim(),
1113
+ error: `Failed to spawn pi: ${err.message}`,
1114
+ toolCallsCount,
1115
+ toolDigest: toolDigest.slice(0, 50)
1116
+ });
1117
+ });
1118
+ child.on("close", (code, signal) => {
1119
+ parser.flush();
1120
+ if (!settledReceived && !finishing) {
1121
+ const stderrText = stderrLines.slice(-10).join("\n");
1122
+ const msg = aborted ? "Task aborted" : `pi exited unexpectedly before agent_settled (code=${String(code)}, signal=${String(signal)})${stderrText ? `: ${stderrText}` : ""}`;
1123
+ emit("error", msg);
1124
+ finishOnce({
1125
+ ok: false,
1126
+ ...aborted ? { aborted: true } : {},
1127
+ sessionId,
1128
+ finalSummary: (lastAssistantText || streamingBuffer).trim(),
1129
+ error: msg,
1130
+ toolCallsCount,
1131
+ toolDigest: toolDigest.slice(0, 50)
1132
+ });
1133
+ }
1134
+ });
1135
+ void sendCommand("prompt", { message: params.prompt }, 3e4).then((resp) => {
1136
+ if (!resp.success) {
1137
+ const errMsg = resp.error || "pi rejected prompt command";
1138
+ emit("error", errMsg);
1139
+ shutdownGracefully();
1140
+ finishOnce({
1141
+ ok: false,
1142
+ sessionId,
1143
+ finalSummary: "",
1144
+ error: errMsg,
1145
+ toolCallsCount,
1146
+ toolDigest: []
1147
+ });
1148
+ return;
1149
+ }
1150
+ const disposition = resp.data?.disposition;
1151
+ if (disposition === "handled") {
1152
+ settledReceived = true;
1153
+ void finalizeAfterSettled(false);
1154
+ }
1155
+ }).catch((err) => {
1156
+ if (!settledReceived && !finishing) {
1157
+ const msg = err instanceof Error ? err.message : String(err);
1158
+ emit("error", msg);
1159
+ shutdownGracefully();
1160
+ finishOnce({
1161
+ ok: false,
1162
+ sessionId,
1163
+ finalSummary: lastAssistantText.trim(),
1164
+ error: msg,
1165
+ toolCallsCount,
1166
+ toolDigest: toolDigest.slice(0, 50)
1167
+ });
1168
+ }
1169
+ });
1170
+ });
1171
+ return {
1172
+ getSessionId: () => sessionId,
1173
+ async steer(message, mode) {
1174
+ const cmd = mode === "steer" ? "steer" : "follow_up";
1175
+ const resp = await sendCommand(cmd, { message });
1176
+ if (!resp.success) {
1177
+ throw new Error(resp.error ?? `pi ${cmd} failed`);
1178
+ }
1179
+ emit("status", `Sent ${mode} instruction to pi`);
1180
+ },
1181
+ async respondInput(requestId, response) {
1182
+ const dialog = pendingDialogs.get(requestId);
1183
+ if (!dialog) {
1184
+ throw new Error(`No pending input request found with id "${requestId}"`);
1185
+ }
1186
+ const reply = {
1187
+ type: "extension_ui_response",
1188
+ id: requestId
1189
+ };
1190
+ if (response.cancelled) {
1191
+ reply.cancelled = true;
1192
+ } else if (dialog.method === "confirm") {
1193
+ reply.confirmed = Boolean(response.confirmed);
1194
+ } else {
1195
+ reply.value = response.value ?? "";
1196
+ }
1197
+ writeStdinJson(reply);
1198
+ pendingDialogs.delete(requestId);
1199
+ params.onInputResolved?.(requestId);
1200
+ emit("status", `Resolved pi dialog "${dialog.title}"`);
1201
+ },
1202
+ async abort() {
1203
+ aborted = true;
1204
+ try {
1205
+ await sendCommand("clear_queue", {}, 3e3);
1206
+ } catch {
1207
+ }
1208
+ try {
1209
+ await sendCommand("abort", {}, 5e3);
1210
+ } catch {
1211
+ if (child.exitCode === null) {
1212
+ child.kill("SIGTERM");
1213
+ }
1214
+ }
1215
+ },
1216
+ completion
1217
+ };
1218
+ }
1219
+ };
1220
+
1221
+ // src/adapters/registry.ts
1222
+ var AdapterRegistry = class {
1223
+ adapters = /* @__PURE__ */ new Map();
1224
+ constructor(customAdapters) {
1225
+ const list = customAdapters ?? [new PiAdapter(), new OpenCodeAdapter()];
1226
+ for (const adapter of list) {
1227
+ this.adapters.set(adapter.id, adapter);
1228
+ }
1229
+ }
1230
+ get(id) {
1231
+ const adapter = this.adapters.get(id);
1232
+ if (!adapter) {
1233
+ throw new Error(`Unsupported agent "${id}". Available: ${Array.from(this.adapters.keys()).join(", ")}`);
1234
+ }
1235
+ return adapter;
1236
+ }
1237
+ all() {
1238
+ return Array.from(this.adapters.values());
1239
+ }
1240
+ async detectAll(config, env, includeModels = false) {
1241
+ return Promise.all(
1242
+ this.all().map(async (adapter) => {
1243
+ const info = await adapter.detect(config, env);
1244
+ if (includeModels && info.available) {
1245
+ info.models = await adapter.listModels(config, env);
1246
+ }
1247
+ return info;
1248
+ })
1249
+ );
1250
+ }
1251
+ };
1252
+
1253
+ // src/config/loader.ts
1254
+ import fs4 from "fs";
1255
+ import os3 from "os";
1256
+ import path3 from "path";
1257
+
1258
+ // src/config/schema.ts
1259
+ import { z } from "zod";
1260
+ var AgentIdSchema = z.enum(["pi", "opencode"]);
1261
+ var WorkspaceModeSchema = z.enum(["worktree", "staging", "direct", "readonly"]);
1262
+ var DefaultWorkspaceModeSchema = z.enum(["worktree", "staging", "direct"]);
1263
+ var MergeStrategySchema = z.enum([
1264
+ "apply_patch",
1265
+ "merge_commit",
1266
+ "squash_merge",
1267
+ "fast_forward",
1268
+ "keep_branch"
1269
+ ]);
1270
+ var InteractionPolicySchema = z.enum([
1271
+ "ask_orchestrator",
1272
+ "auto_approve",
1273
+ "deny_interactive"
1274
+ ]);
1275
+ var LogLevelSchema = z.enum(["debug", "info", "warn", "error"]);
1276
+ var PiAgentConfigSchema = z.object({
1277
+ bin: z.string().min(1).optional(),
1278
+ defaultModel: z.string().min(1).optional(),
1279
+ defaultThinking: z.enum(["off", "minimal", "low", "medium", "high", "xhigh", "max"]).optional(),
1280
+ disableMcp: z.boolean().default(true),
1281
+ trustProjectFiles: z.boolean().default(false),
1282
+ extraArgs: z.array(z.string()).default([])
1283
+ }).default({});
1284
+ var OpenCodeAgentConfigSchema = z.object({
1285
+ bin: z.string().min(1).optional(),
1286
+ defaultModel: z.string().min(1).optional(),
1287
+ defaultAgent: z.string().min(1).default("build"),
1288
+ archived: z.boolean().default(true),
1289
+ standalone: z.boolean().default(true),
1290
+ extraArgs: z.array(z.string()).default([])
1291
+ }).default({});
1292
+ var RawAppConfigSchema = z.object({
1293
+ dataDir: z.string().min(1).optional(),
1294
+ defaultAgent: AgentIdSchema.default("pi"),
1295
+ allowedWorkspaces: z.array(z.string().min(1)).default([]),
1296
+ defaultWorkspaceMode: DefaultWorkspaceModeSchema.default("worktree"),
1297
+ defaultMergeStrategy: MergeStrategySchema.default("apply_patch"),
1298
+ defaultInteractionPolicy: InteractionPolicySchema.default("ask_orchestrator"),
1299
+ defaultTimeoutSeconds: z.number().int().min(30).max(3600).default(900),
1300
+ defaultWaitSeconds: z.number().int().min(0).max(120).default(15),
1301
+ maxConcurrentTasks: z.number().int().min(1).max(16).default(4),
1302
+ stagingMaxBytes: z.number().int().min(1024).default(50 * 1024 * 1024),
1303
+ stagingMaxFiles: z.number().int().min(1).default(2e3),
1304
+ logLevel: LogLevelSchema.default("info"),
1305
+ agents: z.object({
1306
+ pi: PiAgentConfigSchema,
1307
+ opencode: OpenCodeAgentConfigSchema
1308
+ }).default({})
1309
+ });
1310
+
1311
+ // src/config/loader.ts
1312
+ var SENSITIVE_PATH_PATTERNS = [
1313
+ () => path3.join(os3.homedir(), ".ssh"),
1314
+ () => path3.join(os3.homedir(), ".gnupg"),
1315
+ () => path3.join(os3.homedir(), ".aws"),
1316
+ () => "/etc",
1317
+ () => "/private/etc",
1318
+ () => "/System",
1319
+ () => "/Library",
1320
+ () => "/usr",
1321
+ () => "/bin",
1322
+ () => "/sbin",
1323
+ () => "/"
1324
+ ];
1325
+ function parsePositiveInt(value) {
1326
+ if (!value || value.trim() === "") return void 0;
1327
+ const parsed = Number.parseInt(value, 10);
1328
+ return Number.isFinite(parsed) ? parsed : void 0;
1329
+ }
1330
+ function readConfigFile(configPath, explicitPathProvided) {
1331
+ if (!fs4.existsSync(configPath)) {
1332
+ if (explicitPathProvided) {
1333
+ throw new Error(`Config file not found: ${configPath}`);
1334
+ }
1335
+ return { data: {}, exists: false };
1336
+ }
1337
+ const rawText = fs4.readFileSync(configPath, "utf8");
1338
+ let parsed;
1339
+ try {
1340
+ parsed = JSON.parse(rawText);
1341
+ } catch (err) {
1342
+ throw new Error(
1343
+ `Invalid JSON in config file ${configPath}: ${err instanceof Error ? err.message : String(err)}`
1344
+ );
1345
+ }
1346
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1347
+ throw new Error(`Config file ${configPath} must contain a JSON object`);
1348
+ }
1349
+ return { data: parsed, exists: true };
1350
+ }
1351
+ function loadConfig(cli = {}, env = process.env) {
1352
+ const initialDataDir = getDataDir(cli.dataDir, env);
1353
+ const explicitConfigPath = cli.configPath ?? env.GEMINI_AGENT_BRIDGE_CONFIG;
1354
+ const configPath = getConfigPath(initialDataDir, cli.configPath, env);
1355
+ const { data: fileRaw, exists: configFileExists } = readConfigFile(
1356
+ configPath,
1357
+ Boolean(explicitConfigPath)
1358
+ );
1359
+ const fileParsed = RawAppConfigSchema.parse(fileRaw);
1360
+ const dataDir = getDataDir(cli.dataDir ?? fileParsed.dataDir, env);
1361
+ const merged = {
1362
+ ...fileParsed,
1363
+ agents: {
1364
+ pi: { ...fileParsed.agents.pi },
1365
+ opencode: { ...fileParsed.agents.opencode }
1366
+ }
1367
+ };
1368
+ if (env.GEMINI_AGENT_BRIDGE_DEFAULT_AGENT) {
1369
+ merged.defaultAgent = AgentIdSchema.parse(env.GEMINI_AGENT_BRIDGE_DEFAULT_AGENT.trim());
1370
+ }
1371
+ if (env.GEMINI_AGENT_BRIDGE_WORKSPACES) {
1372
+ const items = env.GEMINI_AGENT_BRIDGE_WORKSPACES.split(/[:,]/).map((s) => s.trim()).filter(Boolean);
1373
+ if (items.length > 0) {
1374
+ merged.allowedWorkspaces = items;
1375
+ }
1376
+ }
1377
+ if (env.GEMINI_AGENT_BRIDGE_DEFAULT_MODE) {
1378
+ merged.defaultWorkspaceMode = DefaultWorkspaceModeSchema.parse(
1379
+ env.GEMINI_AGENT_BRIDGE_DEFAULT_MODE.trim()
1380
+ );
1381
+ }
1382
+ if (env.GEMINI_AGENT_BRIDGE_DEFAULT_MERGE_STRATEGY) {
1383
+ merged.defaultMergeStrategy = MergeStrategySchema.parse(
1384
+ env.GEMINI_AGENT_BRIDGE_DEFAULT_MERGE_STRATEGY.trim()
1385
+ );
1386
+ }
1387
+ if (env.GEMINI_AGENT_BRIDGE_INTERACTION_POLICY) {
1388
+ merged.defaultInteractionPolicy = InteractionPolicySchema.parse(
1389
+ env.GEMINI_AGENT_BRIDGE_INTERACTION_POLICY.trim()
1390
+ );
1391
+ }
1392
+ const envTimeout = parsePositiveInt(env.GEMINI_AGENT_BRIDGE_TIMEOUT_SECONDS);
1393
+ if (envTimeout !== void 0) merged.defaultTimeoutSeconds = envTimeout;
1394
+ const envWait = parsePositiveInt(env.GEMINI_AGENT_BRIDGE_WAIT_SECONDS);
1395
+ if (envWait !== void 0) merged.defaultWaitSeconds = envWait;
1396
+ if (env.GEMINI_AGENT_BRIDGE_LOG_LEVEL) {
1397
+ merged.logLevel = LogLevelSchema.parse(env.GEMINI_AGENT_BRIDGE_LOG_LEVEL.trim());
1398
+ }
1399
+ const agentsObj = merged.agents;
1400
+ if (env.GEMINI_AGENT_BRIDGE_PI_BIN) {
1401
+ agentsObj.pi.bin = env.GEMINI_AGENT_BRIDGE_PI_BIN.trim();
1402
+ }
1403
+ if (env.GEMINI_AGENT_BRIDGE_OPENCODE_BIN) {
1404
+ agentsObj.opencode.bin = env.GEMINI_AGENT_BRIDGE_OPENCODE_BIN.trim();
1405
+ }
1406
+ if (cli.defaultAgent) {
1407
+ merged.defaultAgent = AgentIdSchema.parse(cli.defaultAgent);
1408
+ }
1409
+ if (cli.defaultMode) {
1410
+ merged.defaultWorkspaceMode = DefaultWorkspaceModeSchema.parse(cli.defaultMode);
1411
+ }
1412
+ if (cli.logLevel) {
1413
+ merged.logLevel = LogLevelSchema.parse(cli.logLevel);
1414
+ }
1415
+ if (cli.workspaces && cli.workspaces.length > 0) {
1416
+ merged.allowedWorkspaces = cli.workspaces;
1417
+ }
1418
+ if (cli.piBin) {
1419
+ agentsObj.pi.bin = cli.piBin;
1420
+ }
1421
+ if (cli.opencodeBin) {
1422
+ agentsObj.opencode.bin = cli.opencodeBin;
1423
+ }
1424
+ const validated = RawAppConfigSchema.parse(merged);
1425
+ const normalizedAllowedWorkspaces = validated.allowedWorkspaces.map(
1426
+ (w) => resolveRealPathOrClosest(w)
1427
+ );
1428
+ return {
1429
+ ...validated,
1430
+ allowedWorkspaces: Array.from(new Set(normalizedAllowedWorkspaces)),
1431
+ dataDir,
1432
+ configPath,
1433
+ configFileExists
1434
+ };
1435
+ }
1436
+ function validateWorkspacePath(targetPath, config) {
1437
+ const resolvedPath = resolveRealPathOrClosest(targetPath);
1438
+ if (!fs4.existsSync(resolvedPath)) {
1439
+ return {
1440
+ allowed: false,
1441
+ resolvedPath,
1442
+ reason: `Workspace directory does not exist: ${resolvedPath}`
1443
+ };
1444
+ }
1445
+ const stat = fs4.statSync(resolvedPath);
1446
+ if (!stat.isDirectory()) {
1447
+ return {
1448
+ allowed: false,
1449
+ resolvedPath,
1450
+ reason: `Workspace path is not a directory: ${resolvedPath}`
1451
+ };
1452
+ }
1453
+ for (const getDenied of SENSITIVE_PATH_PATTERNS) {
1454
+ const denied = resolveRealPathOrClosest(getDenied());
1455
+ if (denied === "/") {
1456
+ if (resolvedPath === "/") {
1457
+ return {
1458
+ allowed: false,
1459
+ resolvedPath,
1460
+ reason: `Workspace path "/" is restricted for safety.`
1461
+ };
1462
+ }
1463
+ continue;
1464
+ }
1465
+ if (isPathInsideOrEqual(resolvedPath, denied)) {
1466
+ return {
1467
+ allowed: false,
1468
+ resolvedPath,
1469
+ reason: `Workspace path ${resolvedPath} is inside sensitive restricted directory ${denied}.`
1470
+ };
1471
+ }
1472
+ }
1473
+ if (config.allowedWorkspaces.length > 0) {
1474
+ const matched = config.allowedWorkspaces.some(
1475
+ (allowedRoot) => isPathInsideOrEqual(resolvedPath, allowedRoot)
1476
+ );
1477
+ if (!matched) {
1478
+ return {
1479
+ allowed: false,
1480
+ resolvedPath,
1481
+ reason: `Workspace ${resolvedPath} is outside allowedWorkspaces: [${config.allowedWorkspaces.join(", ")}]`
1482
+ };
1483
+ }
1484
+ return { allowed: true, resolvedPath };
1485
+ }
1486
+ return {
1487
+ allowed: true,
1488
+ resolvedPath,
1489
+ warning: "allowedWorkspaces is empty (open mode). Consider restricting allowedWorkspaces via `gemini-agent-bridge init` or `--workspace`."
1490
+ };
1491
+ }
1492
+ function writeConfigFile(configPath, updates) {
1493
+ let existing = {};
1494
+ if (fs4.existsSync(configPath)) {
1495
+ try {
1496
+ const parsed = JSON.parse(fs4.readFileSync(configPath, "utf8"));
1497
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1498
+ existing = parsed;
1499
+ }
1500
+ } catch {
1501
+ existing = {};
1502
+ }
1503
+ }
1504
+ const existingAgents = existing.agents && typeof existing.agents === "object" && !Array.isArray(existing.agents) ? existing.agents : {};
1505
+ const nextConfig = {
1506
+ defaultAgent: existing.defaultAgent ?? updates.defaultAgent ?? "pi",
1507
+ allowedWorkspaces: updates.allowedWorkspaces ?? (Array.isArray(existing.allowedWorkspaces) ? existing.allowedWorkspaces : []),
1508
+ defaultWorkspaceMode: existing.defaultWorkspaceMode ?? "worktree",
1509
+ defaultMergeStrategy: existing.defaultMergeStrategy ?? "apply_patch",
1510
+ defaultInteractionPolicy: existing.defaultInteractionPolicy ?? "ask_orchestrator",
1511
+ defaultTimeoutSeconds: existing.defaultTimeoutSeconds ?? 900,
1512
+ defaultWaitSeconds: existing.defaultWaitSeconds ?? 15,
1513
+ maxConcurrentTasks: existing.maxConcurrentTasks ?? 4,
1514
+ logLevel: existing.logLevel ?? "info",
1515
+ agents: {
1516
+ pi: {
1517
+ ...existingAgents.pi ?? {},
1518
+ ...updates.piBin ? { bin: updates.piBin } : {},
1519
+ disableMcp: existingAgents.pi?.disableMcp ?? true
1520
+ },
1521
+ opencode: {
1522
+ ...existingAgents.opencode ?? {},
1523
+ ...updates.opencodeBin ? { bin: updates.opencodeBin } : {},
1524
+ archived: existingAgents.opencode?.archived ?? true,
1525
+ standalone: existingAgents.opencode?.standalone ?? true
1526
+ }
1527
+ }
1528
+ };
1529
+ fs4.mkdirSync(path3.dirname(configPath), { recursive: true });
1530
+ const tmpPath = `${configPath}.tmp.${process.pid}`;
1531
+ fs4.writeFileSync(tmpPath, `${JSON.stringify(nextConfig, null, 2)}
1532
+ `, { mode: 384 });
1533
+ fs4.renameSync(tmpPath, configPath);
1534
+ return nextConfig;
1535
+ }
1536
+
1537
+ // src/mcp/server.ts
1538
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1539
+
1540
+ // src/runtime/logger.ts
1541
+ import fs5 from "fs";
1542
+ import path4 from "path";
1543
+ var LEVEL_PRIORITY = {
1544
+ debug: 10,
1545
+ info: 20,
1546
+ warn: 30,
1547
+ error: 40
1548
+ };
1549
+ var Logger = class {
1550
+ level;
1551
+ logFilePath;
1552
+ constructor(level = "info", logDir) {
1553
+ this.level = level;
1554
+ if (logDir) {
1555
+ try {
1556
+ fs5.mkdirSync(logDir, { recursive: true });
1557
+ this.logFilePath = path4.join(logDir, "server.log");
1558
+ } catch {
1559
+ }
1560
+ }
1561
+ }
1562
+ setLevel(level) {
1563
+ this.level = level;
1564
+ }
1565
+ write(level, message, meta) {
1566
+ if (LEVEL_PRIORITY[level] < LEVEL_PRIORITY[this.level]) {
1567
+ return;
1568
+ }
1569
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
1570
+ const metaText = meta && Object.keys(meta).length > 0 ? ` ${JSON.stringify(meta)}` : "";
1571
+ const line = `${ts} [${level.toUpperCase()}] [gemini-agent-bridge] ${message}${metaText}
1572
+ `;
1573
+ process.stderr.write(line);
1574
+ if (this.logFilePath) {
1575
+ try {
1576
+ fs5.appendFileSync(this.logFilePath, line);
1577
+ } catch {
1578
+ }
1579
+ }
1580
+ }
1581
+ debug(message, meta) {
1582
+ this.write("debug", message, meta);
1583
+ }
1584
+ info(message, meta) {
1585
+ this.write("info", message, meta);
1586
+ }
1587
+ warn(message, meta) {
1588
+ this.write("warn", message, meta);
1589
+ }
1590
+ error(message, meta) {
1591
+ this.write("error", message, meta);
1592
+ }
1593
+ };
1594
+
1595
+ // src/runtime/process-registry.ts
1596
+ var ProcessRegistry = class {
1597
+ entries = /* @__PURE__ */ new Set();
1598
+ shuttingDown = false;
1599
+ register(child, label, gracefulStop) {
1600
+ const entry = { child, label, gracefulStop };
1601
+ this.entries.add(entry);
1602
+ const cleanup = () => {
1603
+ this.entries.delete(entry);
1604
+ };
1605
+ child.once("exit", cleanup);
1606
+ child.once("close", cleanup);
1607
+ return cleanup;
1608
+ }
1609
+ get activeCount() {
1610
+ return this.entries.size;
1611
+ }
1612
+ async shutdownAll(graceMs = 2e3) {
1613
+ if (this.shuttingDown || this.entries.size === 0) {
1614
+ return;
1615
+ }
1616
+ this.shuttingDown = true;
1617
+ const snapshot = Array.from(this.entries);
1618
+ await Promise.allSettled(
1619
+ snapshot.map(async (entry) => {
1620
+ if (entry.child.exitCode !== null || entry.child.killed) {
1621
+ return;
1622
+ }
1623
+ try {
1624
+ if (entry.gracefulStop) {
1625
+ await Promise.resolve(entry.gracefulStop());
1626
+ }
1627
+ } catch {
1628
+ }
1629
+ if (entry.child.exitCode !== null) return;
1630
+ try {
1631
+ entry.child.kill("SIGTERM");
1632
+ } catch {
1633
+ return;
1634
+ }
1635
+ await new Promise((resolve) => {
1636
+ const timer = setTimeout(() => {
1637
+ if (entry.child.exitCode === null) {
1638
+ try {
1639
+ entry.child.kill("SIGKILL");
1640
+ } catch {
1641
+ }
1642
+ }
1643
+ resolve();
1644
+ }, graceMs);
1645
+ timer.unref?.();
1646
+ entry.child.once("exit", () => {
1647
+ clearTimeout(timer);
1648
+ resolve();
1649
+ });
1650
+ });
1651
+ })
1652
+ );
1653
+ this.entries.clear();
1654
+ this.shuttingDown = false;
1655
+ }
1656
+ };
1657
+
1658
+ // src/tasks/manager.ts
1659
+ import crypto4 from "crypto";
1660
+ import { EventEmitter } from "events";
1661
+ import fs9 from "fs";
1662
+ import path8 from "path";
1663
+
1664
+ // src/workspace/direct-manager.ts
1665
+ import crypto2 from "crypto";
1666
+ import fs6 from "fs";
1667
+ import path5 from "path";
1668
+
1669
+ // src/workspace/git-utils.ts
1670
+ import { spawn as spawn3 } from "child_process";
1671
+ var GitCommandError = class extends Error {
1672
+ exitCode;
1673
+ stdout;
1674
+ stderr;
1675
+ args;
1676
+ constructor(message, args, result) {
1677
+ super(message);
1678
+ this.name = "GitCommandError";
1679
+ this.args = args;
1680
+ this.exitCode = result.exitCode;
1681
+ this.stdout = result.stdout;
1682
+ this.stderr = result.stderr;
1683
+ }
1684
+ };
1685
+ async function runGit(args, options) {
1686
+ const timeoutMs = options.timeoutMs ?? 6e4;
1687
+ return new Promise((resolve, reject) => {
1688
+ const child = spawn3("git", args, {
1689
+ cwd: options.cwd,
1690
+ env: options.env ?? process.env,
1691
+ stdio: ["pipe", "pipe", "pipe"]
1692
+ });
1693
+ const stdoutChunks = [];
1694
+ const stderrChunks = [];
1695
+ let settled = false;
1696
+ const timer = setTimeout(() => {
1697
+ if (!settled) {
1698
+ settled = true;
1699
+ child.kill("SIGTERM");
1700
+ reject(new Error(`git ${args[0] ?? ""} timed out after ${timeoutMs}ms`));
1701
+ }
1702
+ }, timeoutMs);
1703
+ timer.unref?.();
1704
+ child.stdout.on("data", (chunk) => stdoutChunks.push(chunk));
1705
+ child.stderr.on("data", (chunk) => stderrChunks.push(chunk));
1706
+ child.on("error", (err) => {
1707
+ clearTimeout(timer);
1708
+ if (!settled) {
1709
+ settled = true;
1710
+ reject(err);
1711
+ }
1712
+ });
1713
+ child.on("close", (code) => {
1714
+ clearTimeout(timer);
1715
+ if (settled) return;
1716
+ settled = true;
1717
+ const result = {
1718
+ exitCode: code ?? 1,
1719
+ stdout: Buffer.concat(stdoutChunks).toString("utf8"),
1720
+ stderr: Buffer.concat(stderrChunks).toString("utf8")
1721
+ };
1722
+ if (result.exitCode !== 0 && !options.allowFailure) {
1723
+ reject(
1724
+ new GitCommandError(
1725
+ `git ${args.join(" ")} failed (exit ${result.exitCode}): ${result.stderr.trim() || result.stdout.trim()}`,
1726
+ args,
1727
+ result
1728
+ )
1729
+ );
1730
+ return;
1731
+ }
1732
+ resolve(result);
1733
+ });
1734
+ if (options.input !== void 0) {
1735
+ child.stdin.end(options.input, "utf8");
1736
+ } else {
1737
+ child.stdin.end();
1738
+ }
1739
+ });
1740
+ }
1741
+ async function isGitRepo(dir, env) {
1742
+ const res = await runGit(["rev-parse", "--is-inside-work-tree"], {
1743
+ cwd: dir,
1744
+ env,
1745
+ allowFailure: true
1746
+ });
1747
+ return res.exitCode === 0 && res.stdout.trim() === "true";
1748
+ }
1749
+ async function getRepoRoot(dir, env) {
1750
+ const res = await runGit(["rev-parse", "--show-toplevel"], { cwd: dir, env });
1751
+ return res.stdout.trim();
1752
+ }
1753
+ async function hasHeadCommit(repoRoot, env) {
1754
+ const res = await runGit(["rev-parse", "--verify", "HEAD"], {
1755
+ cwd: repoRoot,
1756
+ env,
1757
+ allowFailure: true
1758
+ });
1759
+ return res.exitCode === 0;
1760
+ }
1761
+ async function resolveRefSha(repoRoot, ref, env) {
1762
+ const res = await runGit(["rev-parse", "--verify", ref], { cwd: repoRoot, env });
1763
+ return res.stdout.trim();
1764
+ }
1765
+ async function getCurrentBranch(repoRoot, env) {
1766
+ const res = await runGit(["symbolic-ref", "--quiet", "--short", "HEAD"], {
1767
+ cwd: repoRoot,
1768
+ env,
1769
+ allowFailure: true
1770
+ });
1771
+ return res.exitCode === 0 ? res.stdout.trim() : "HEAD";
1772
+ }
1773
+ async function hasUncommittedChanges(cwd, env) {
1774
+ const res = await runGit(["status", "--porcelain"], { cwd, env });
1775
+ return res.stdout.trim().length > 0;
1776
+ }
1777
+ async function getGitIdentityConfigArgs(cwd, env) {
1778
+ const [nameRes, emailRes] = await Promise.all([
1779
+ runGit(["config", "--get", "user.name"], { cwd, env, allowFailure: true }),
1780
+ runGit(["config", "--get", "user.email"], { cwd, env, allowFailure: true })
1781
+ ]);
1782
+ const args = [];
1783
+ if (nameRes.exitCode !== 0 || !nameRes.stdout.trim()) {
1784
+ args.push("-c", "user.name=gemini-agent-bridge");
1785
+ }
1786
+ if (emailRes.exitCode !== 0 || !emailRes.stdout.trim()) {
1787
+ args.push("-c", "user.email=gemini-agent-bridge@local");
1788
+ }
1789
+ return args;
1790
+ }
1791
+ async function commitAllInDir(cwd, message, env) {
1792
+ await runGit(["add", "-A"], { cwd, env });
1793
+ const dirty = await hasUncommittedChanges(cwd, env);
1794
+ if (dirty) {
1795
+ const identityArgs = await getGitIdentityConfigArgs(cwd, env);
1796
+ await runGit([...identityArgs, "-c", "commit.gpgsign=false", "commit", "-m", message], {
1797
+ cwd,
1798
+ env
1799
+ });
1800
+ }
1801
+ const sha = await resolveRefSha(cwd, "HEAD", env);
1802
+ return sha;
1803
+ }
1804
+
1805
+ // src/workspace/direct-manager.ts
1806
+ var IGNORED_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", ".gemini-agent-bridge"]);
1807
+ function hashFile(filePath) {
1808
+ const buf = fs6.readFileSync(filePath);
1809
+ const stat = fs6.statSync(filePath);
1810
+ const sha256 = crypto2.createHash("sha256").update(buf).digest("hex");
1811
+ return { sha256, size: stat.size, mode: stat.mode };
1812
+ }
1813
+ function snapshotDirectory(rootDir, limits) {
1814
+ const snapshot = {};
1815
+ let fileCount = 0;
1816
+ let totalBytes = 0;
1817
+ const walk = (dir) => {
1818
+ const entries = fs6.readdirSync(dir, { withFileTypes: true });
1819
+ for (const entry of entries) {
1820
+ if (IGNORED_DIRS.has(entry.name)) continue;
1821
+ const fullPath = path5.join(dir, entry.name);
1822
+ if (entry.isSymbolicLink()) continue;
1823
+ if (entry.isDirectory()) {
1824
+ walk(fullPath);
1825
+ continue;
1826
+ }
1827
+ if (!entry.isFile()) continue;
1828
+ const stat = fs6.statSync(fullPath);
1829
+ fileCount += 1;
1830
+ totalBytes += stat.size;
1831
+ if (limits?.maxFiles && fileCount > limits.maxFiles) {
1832
+ throw new Error(
1833
+ `Directory exceeds staging file limit (${limits.maxFiles} files). Initialize git for worktree mode or use workspaceMode="direct".`
1834
+ );
1835
+ }
1836
+ if (limits?.maxBytes && totalBytes > limits.maxBytes) {
1837
+ throw new Error(
1838
+ `Directory exceeds staging size limit (${Math.round(limits.maxBytes / (1024 * 1024))}MB). Initialize git for worktree mode or use workspaceMode="direct".`
1839
+ );
1840
+ }
1841
+ const rel = path5.relative(rootDir, fullPath).split(path5.sep).join("/");
1842
+ snapshot[rel] = hashFile(fullPath);
1843
+ }
1844
+ };
1845
+ walk(rootDir);
1846
+ return { snapshot, fileCount, totalBytes };
1847
+ }
1848
+ function prepareDirectOrReadonlyWorkspace(mode, sourceDir) {
1849
+ const { snapshot } = snapshotDirectory(sourceDir);
1850
+ return {
1851
+ mode,
1852
+ sourceDir,
1853
+ executionDir: sourceDir,
1854
+ initialSnapshot: snapshot,
1855
+ createdByDirector: false
1856
+ };
1857
+ }
1858
+ function prepareStagingWorkspace(dataDir, sourceDir, taskId, maxBytes, maxFiles) {
1859
+ const { snapshot } = snapshotDirectory(sourceDir, { maxBytes, maxFiles });
1860
+ const stagingRoot = path5.join(getStagingDir(dataDir), taskId);
1861
+ fs6.mkdirSync(stagingRoot, { recursive: true });
1862
+ for (const [relPath, entry] of Object.entries(snapshot)) {
1863
+ const src = path5.join(sourceDir, relPath);
1864
+ const dest = path5.join(stagingRoot, relPath);
1865
+ fs6.mkdirSync(path5.dirname(dest), { recursive: true });
1866
+ fs6.copyFileSync(src, dest);
1867
+ try {
1868
+ fs6.chmodSync(dest, entry.mode);
1869
+ } catch {
1870
+ }
1871
+ }
1872
+ return {
1873
+ mode: "staging",
1874
+ sourceDir,
1875
+ executionDir: stagingRoot,
1876
+ stagingRoot,
1877
+ initialSnapshot: snapshot,
1878
+ createdByDirector: true
1879
+ };
1880
+ }
1881
+ function compareSnapshots(before, after, pathsFilter) {
1882
+ const filterSet = pathsFilter && pathsFilter.length > 0 ? new Set(pathsFilter) : null;
1883
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
1884
+ const changed = [];
1885
+ for (const rel of Array.from(allKeys).sort()) {
1886
+ if (filterSet && !filterSet.has(rel)) continue;
1887
+ const prev = before[rel];
1888
+ const curr = after[rel];
1889
+ if (!prev && curr) {
1890
+ changed.push({ path: rel, status: "added" });
1891
+ } else if (prev && !curr) {
1892
+ changed.push({ path: rel, status: "deleted" });
1893
+ } else if (prev && curr && prev.sha256 !== curr.sha256) {
1894
+ changed.push({ path: rel, status: "modified" });
1895
+ }
1896
+ }
1897
+ return changed;
1898
+ }
1899
+ async function collectNonWorktreeDiff(handle, options = {}, env) {
1900
+ const before = handle.initialSnapshot ?? {};
1901
+ const { snapshot: after } = snapshotDirectory(handle.executionDir);
1902
+ const files = compareSnapshots(before, after, options.paths);
1903
+ const summaryStat = files.map((f) => `${f.status.toUpperCase()} ${f.path}`).join("\n");
1904
+ if (options.mode === "stat" || files.length === 0) {
1905
+ return {
1906
+ files,
1907
+ summaryStat,
1908
+ patch: "",
1909
+ totalLines: 0,
1910
+ truncated: false,
1911
+ offset: 0,
1912
+ ...handle.mode === "direct" && files.length > 0 ? { note: "direct mode tracks SHA-256 file changes; use git worktree or staging mode for unified line patches." } : {}
1913
+ };
1914
+ }
1915
+ if (handle.mode === "direct" || handle.mode === "readonly") {
1916
+ return {
1917
+ files,
1918
+ summaryStat,
1919
+ patch: summaryStat,
1920
+ totalLines: files.length,
1921
+ truncated: false,
1922
+ offset: 0,
1923
+ note: "direct/readonly mode does not retain pre-edit file contents for unified line diffs; changed files are listed above."
1924
+ };
1925
+ }
1926
+ const patchChunks = [];
1927
+ for (const file of files) {
1928
+ const oldFile = file.status === "added" ? "/dev/null" : path5.join(handle.sourceDir, file.path);
1929
+ const newFile = file.status === "deleted" ? "/dev/null" : path5.join(handle.executionDir, file.path);
1930
+ const res = await runGit(["diff", "--no-index", "--", oldFile, newFile], {
1931
+ cwd: handle.executionDir,
1932
+ env,
1933
+ allowFailure: true
1934
+ });
1935
+ if (res.stdout.trim()) {
1936
+ const normalized = res.stdout.replaceAll(handle.sourceDir, "a").replaceAll(handle.executionDir, "b");
1937
+ patchChunks.push(normalized.trimEnd());
1938
+ }
1939
+ }
1940
+ const rawPatch = patchChunks.join("\n");
1941
+ const allLines = rawPatch ? rawPatch.split("\n") : [];
1942
+ const offset = Math.max(0, options.offset ?? 0);
1943
+ const maxLines = Math.max(1, options.maxLines ?? 400);
1944
+ const slice = allLines.slice(offset, offset + maxLines);
1945
+ return {
1946
+ files,
1947
+ summaryStat,
1948
+ patch: slice.join("\n"),
1949
+ totalLines: allLines.length,
1950
+ truncated: offset + slice.length < allLines.length,
1951
+ offset
1952
+ };
1953
+ }
1954
+ function discardStagingWorkspace(dataDir, handle) {
1955
+ if (handle.mode !== "staging" || !handle.stagingRoot) return false;
1956
+ if (!handle.createdByDirector) {
1957
+ throw new Error("Refusing to remove staging directory not created by gemini-agent-bridge.");
1958
+ }
1959
+ if (!isPathInsideOrEqual(handle.stagingRoot, getStagingDir(dataDir))) {
1960
+ throw new Error(`Refusing to delete staging dir outside managed root: ${handle.stagingRoot}`);
1961
+ }
1962
+ if (fs6.existsSync(handle.stagingRoot)) {
1963
+ fs6.rmSync(handle.stagingRoot, { recursive: true, force: true });
1964
+ }
1965
+ return true;
1966
+ }
1967
+ function landNonWorktreeWorkspace(dataDir, handle, options) {
1968
+ if (handle.mode === "readonly") {
1969
+ throw new Error("Cannot approve and land a readonly workspace task.");
1970
+ }
1971
+ const before = handle.initialSnapshot ?? {};
1972
+ const { snapshot: after } = snapshotDirectory(handle.executionDir);
1973
+ const files = compareSnapshots(before, after);
1974
+ const appliedFiles = files.map((f) => f.path);
1975
+ if (handle.mode === "direct") {
1976
+ return {
1977
+ strategy: options.strategy,
1978
+ appliedFiles,
1979
+ cleanedUp: true,
1980
+ message: `Approved direct-mode task (${appliedFiles.length} file(s) changed in place at ${handle.sourceDir}).`
1981
+ };
1982
+ }
1983
+ const { snapshot: currentSource } = snapshotDirectory(handle.sourceDir);
1984
+ const conflicts = [];
1985
+ for (const file of files) {
1986
+ const initialEntry = before[file.path];
1987
+ const currentEntry = currentSource[file.path];
1988
+ if (file.status === "added" && currentEntry) {
1989
+ conflicts.push(`${file.path} (created concurrently in source directory)`);
1990
+ } else if ((file.status === "modified" || file.status === "deleted") && initialEntry?.sha256 !== currentEntry?.sha256) {
1991
+ conflicts.push(`${file.path} (modified concurrently in source directory)`);
1992
+ }
1993
+ }
1994
+ if (conflicts.length > 0) {
1995
+ throw new Error(
1996
+ `Conflict detected in source directory ${handle.sourceDir}; staging changes not applied:
1997
+ - ${conflicts.join("\n- ")}`
1998
+ );
1999
+ }
2000
+ for (const file of files) {
2001
+ const src = path5.join(handle.executionDir, file.path);
2002
+ const dest = path5.join(handle.sourceDir, file.path);
2003
+ if (file.status === "deleted") {
2004
+ if (fs6.existsSync(dest)) fs6.unlinkSync(dest);
2005
+ } else {
2006
+ fs6.mkdirSync(path5.dirname(dest), { recursive: true });
2007
+ fs6.copyFileSync(src, dest);
2008
+ const entry = after[file.path];
2009
+ if (entry) {
2010
+ try {
2011
+ fs6.chmodSync(dest, entry.mode);
2012
+ } catch {
2013
+ }
2014
+ }
2015
+ }
2016
+ }
2017
+ const cleanedUp = options.cleanupWorktree !== false ? discardStagingWorkspace(dataDir, handle) : false;
2018
+ return {
2019
+ strategy: options.strategy,
2020
+ appliedFiles,
2021
+ cleanedUp,
2022
+ message: `Applied ${appliedFiles.length} staged file(s) cleanly to ${handle.sourceDir}.`
2023
+ };
2024
+ }
2025
+
2026
+ // src/workspace/worktree-manager.ts
2027
+ import crypto3 from "crypto";
2028
+ import fs7 from "fs";
2029
+ import os4 from "os";
2030
+ import path6 from "path";
2031
+ function sanitizeBranchSegment(value) {
2032
+ return value.replace(/[^a-zA-Z0-9._-]/g, "-").replace(/^-+/, "");
2033
+ }
2034
+ async function withTempIndex(worktreeRoot, env, fn) {
2035
+ const realIndexRes = await runGit(["rev-parse", "--git-path", "index"], {
2036
+ cwd: worktreeRoot,
2037
+ env
2038
+ });
2039
+ const realIndexPath = path6.resolve(worktreeRoot, realIndexRes.stdout.trim());
2040
+ const tempIndexPath = path6.join(
2041
+ os4.tmpdir(),
2042
+ `gemini-agent-bridge-idx-${process.pid}-${crypto3.randomUUID()}`
2043
+ );
2044
+ try {
2045
+ if (fs7.existsSync(realIndexPath)) {
2046
+ fs7.copyFileSync(realIndexPath, tempIndexPath);
2047
+ }
2048
+ const tempEnv = {
2049
+ ...env ?? process.env,
2050
+ GIT_INDEX_FILE: tempIndexPath
2051
+ };
2052
+ await runGit(["add", "-A"], { cwd: worktreeRoot, env: tempEnv });
2053
+ return await fn(tempEnv);
2054
+ } finally {
2055
+ try {
2056
+ if (fs7.existsSync(tempIndexPath)) {
2057
+ fs7.unlinkSync(tempIndexPath);
2058
+ }
2059
+ } catch {
2060
+ }
2061
+ }
2062
+ }
2063
+ function parseNameStatus(output) {
2064
+ const map = /* @__PURE__ */ new Map();
2065
+ const lines = output.split(/\r?\n/).filter((l) => l.trim().length > 0);
2066
+ for (const line of lines) {
2067
+ const parts = line.split(" ");
2068
+ const code = parts[0] ?? "";
2069
+ if (code.startsWith("R") && parts.length >= 3) {
2070
+ const oldPath = parts[1];
2071
+ const newPath = parts[2];
2072
+ map.set(newPath, { status: "renamed", oldPath });
2073
+ } else if (parts.length >= 2) {
2074
+ const filePath = parts[1];
2075
+ let status = "modified";
2076
+ if (code.startsWith("A")) status = "added";
2077
+ else if (code.startsWith("D")) status = "deleted";
2078
+ map.set(filePath, { status });
2079
+ }
2080
+ }
2081
+ return map;
2082
+ }
2083
+ function parseNumstat(output, statusMap) {
2084
+ const files = [];
2085
+ const seen = /* @__PURE__ */ new Set();
2086
+ const lines = output.split(/\r?\n/).filter((l) => l.trim().length > 0);
2087
+ for (const line of lines) {
2088
+ const parts = line.split(" ");
2089
+ if (parts.length < 3) continue;
2090
+ const addRaw = parts[0];
2091
+ const delRaw = parts[1];
2092
+ const filePath = parts.slice(2).join(" ");
2093
+ const meta = statusMap.get(filePath);
2094
+ const binary = addRaw === "-" || delRaw === "-";
2095
+ files.push({
2096
+ path: filePath,
2097
+ status: meta?.status ?? "modified",
2098
+ ...meta?.oldPath ? { oldPath: meta.oldPath } : {},
2099
+ binary,
2100
+ ...binary ? {} : {
2101
+ additions: Number.parseInt(addRaw, 10) || 0,
2102
+ deletions: Number.parseInt(delRaw, 10) || 0
2103
+ }
2104
+ });
2105
+ seen.add(filePath);
2106
+ }
2107
+ for (const [filePath, meta] of statusMap.entries()) {
2108
+ if (!seen.has(filePath)) {
2109
+ files.push({
2110
+ path: filePath,
2111
+ status: meta.status,
2112
+ ...meta.oldPath ? { oldPath: meta.oldPath } : {}
2113
+ });
2114
+ }
2115
+ }
2116
+ return files;
2117
+ }
2118
+ async function prepareWorktree(dataDir, sourceDir, taskId, agent, baseRef, env) {
2119
+ const repoRoot = await getRepoRoot(sourceDir, env);
2120
+ if (!await hasHeadCommit(repoRoot, env)) {
2121
+ throw new Error(
2122
+ `Git repository at ${repoRoot} has no commits yet. Make an initial commit first or use workspaceMode="staging" / "direct".`
2123
+ );
2124
+ }
2125
+ const targetRef = baseRef?.trim() || "HEAD";
2126
+ const baseSha = await resolveRefSha(repoRoot, targetRef, env);
2127
+ const baseBranch = await getCurrentBranch(repoRoot, env);
2128
+ const repoHash = crypto3.createHash("sha1").update(repoRoot).digest("hex").slice(0, 12);
2129
+ const worktreeRoot = path6.join(getWorktreesDir(dataDir), repoHash, taskId);
2130
+ const branchName = `agent/${sanitizeBranchSegment(agent)}/${sanitizeBranchSegment(taskId)}`;
2131
+ fs7.mkdirSync(path6.dirname(worktreeRoot), { recursive: true });
2132
+ await runGit(["worktree", "add", "-b", branchName, worktreeRoot, baseSha], {
2133
+ cwd: repoRoot,
2134
+ env
2135
+ });
2136
+ const relSubdir = path6.relative(repoRoot, sourceDir);
2137
+ const executionDir = relSubdir && relSubdir !== "." && !relSubdir.startsWith("..") ? path6.join(worktreeRoot, relSubdir) : worktreeRoot;
2138
+ return {
2139
+ mode: "worktree",
2140
+ sourceDir,
2141
+ executionDir,
2142
+ repoRoot,
2143
+ worktreeRoot,
2144
+ branchName,
2145
+ baseSha,
2146
+ baseBranch,
2147
+ createdByDirector: true
2148
+ };
2149
+ }
2150
+ async function collectWorktreeDiff(handle, options = {}, env) {
2151
+ const worktreeRoot = handle.worktreeRoot ?? handle.executionDir;
2152
+ const baseSha = handle.baseSha ?? "HEAD";
2153
+ const pathFilterArgs = options.paths && options.paths.length > 0 ? ["--", ...options.paths] : [];
2154
+ return withTempIndex(worktreeRoot, env, async (tempEnv) => {
2155
+ const [statusRes, numstatRes, statRes] = await Promise.all([
2156
+ runGit(["diff", "--cached", "--name-status", "-M", baseSha, ...pathFilterArgs], {
2157
+ cwd: worktreeRoot,
2158
+ env: tempEnv
2159
+ }),
2160
+ runGit(["diff", "--cached", "--numstat", "-M", baseSha, ...pathFilterArgs], {
2161
+ cwd: worktreeRoot,
2162
+ env: tempEnv
2163
+ }),
2164
+ runGit(["diff", "--cached", "--stat", "-M", baseSha, ...pathFilterArgs], {
2165
+ cwd: worktreeRoot,
2166
+ env: tempEnv
2167
+ })
2168
+ ]);
2169
+ const statusMap = parseNameStatus(statusRes.stdout);
2170
+ const files = parseNumstat(numstatRes.stdout, statusMap);
2171
+ const summaryStat = statRes.stdout.trim();
2172
+ if (options.mode === "stat") {
2173
+ return {
2174
+ files,
2175
+ summaryStat,
2176
+ patch: "",
2177
+ totalLines: 0,
2178
+ truncated: false,
2179
+ offset: 0
2180
+ };
2181
+ }
2182
+ const patchRes = await runGit(["diff", "--cached", "-M", baseSha, ...pathFilterArgs], {
2183
+ cwd: worktreeRoot,
2184
+ env: tempEnv
2185
+ });
2186
+ const rawPatch = patchRes.stdout;
2187
+ if (!rawPatch) {
2188
+ return {
2189
+ files,
2190
+ summaryStat,
2191
+ patch: "",
2192
+ totalLines: 0,
2193
+ truncated: false,
2194
+ offset: 0
2195
+ };
2196
+ }
2197
+ const allLines = rawPatch.split("\n");
2198
+ const offset = Math.max(0, options.offset ?? 0);
2199
+ const maxLines = Math.max(1, options.maxLines ?? 400);
2200
+ const slice = allLines.slice(offset, offset + maxLines);
2201
+ const truncated = offset + slice.length < allLines.length;
2202
+ return {
2203
+ files,
2204
+ summaryStat,
2205
+ patch: slice.join("\n"),
2206
+ totalLines: allLines.length,
2207
+ truncated,
2208
+ offset
2209
+ };
2210
+ });
2211
+ }
2212
+ function assertSafeToCleanupWorktree(dataDir, handle) {
2213
+ if (!handle.createdByDirector) {
2214
+ throw new Error("Refusing to clean up workspace not created by gemini-agent-bridge.");
2215
+ }
2216
+ if (handle.worktreeRoot) {
2217
+ const worktreesDir = getWorktreesDir(dataDir);
2218
+ if (!isPathInsideOrEqual(handle.worktreeRoot, worktreesDir)) {
2219
+ throw new Error(
2220
+ `Refusing to remove worktree outside managed directory: ${handle.worktreeRoot}`
2221
+ );
2222
+ }
2223
+ }
2224
+ if (handle.branchName && !handle.branchName.startsWith("agent/")) {
2225
+ throw new Error(
2226
+ `Refusing to delete branch without "agent/" prefix: ${handle.branchName}`
2227
+ );
2228
+ }
2229
+ }
2230
+ async function discardWorktree(dataDir, handle, env) {
2231
+ assertSafeToCleanupWorktree(dataDir, handle);
2232
+ const repoRoot = handle.repoRoot;
2233
+ if (!repoRoot) return false;
2234
+ if (handle.worktreeRoot && fs7.existsSync(handle.worktreeRoot)) {
2235
+ await runGit(["worktree", "remove", "--force", handle.worktreeRoot], {
2236
+ cwd: repoRoot,
2237
+ env,
2238
+ allowFailure: true
2239
+ });
2240
+ if (fs7.existsSync(handle.worktreeRoot)) {
2241
+ fs7.rmSync(handle.worktreeRoot, { recursive: true, force: true });
2242
+ }
2243
+ await runGit(["worktree", "prune"], { cwd: repoRoot, env, allowFailure: true });
2244
+ }
2245
+ if (handle.branchName) {
2246
+ await runGit(["branch", "-D", handle.branchName], {
2247
+ cwd: repoRoot,
2248
+ env,
2249
+ allowFailure: true
2250
+ });
2251
+ }
2252
+ return true;
2253
+ }
2254
+ async function landWorktree(dataDir, handle, options, env) {
2255
+ const repoRoot = handle.repoRoot;
2256
+ const worktreeRoot = handle.worktreeRoot ?? handle.executionDir;
2257
+ const baseSha = handle.baseSha ?? "HEAD";
2258
+ if (!repoRoot) {
2259
+ throw new Error("Worktree handle missing repoRoot.");
2260
+ }
2261
+ const diffPreview = await collectWorktreeDiff(handle, { mode: "stat" }, env);
2262
+ const appliedFiles = diffPreview.files.map((f) => f.path);
2263
+ if (appliedFiles.length === 0) {
2264
+ let cleanedUp2 = false;
2265
+ if (options.cleanupWorktree !== false) {
2266
+ cleanedUp2 = await discardWorktree(dataDir, handle, env);
2267
+ }
2268
+ return {
2269
+ strategy: options.strategy,
2270
+ appliedFiles: [],
2271
+ cleanedUp: cleanedUp2,
2272
+ message: "No changes to land; cleaned up isolated worktree."
2273
+ };
2274
+ }
2275
+ const cleanupIfRequested = async (keepBranch) => {
2276
+ if (options.cleanupWorktree === false) return false;
2277
+ assertSafeToCleanupWorktree(dataDir, handle);
2278
+ if (handle.worktreeRoot && fs7.existsSync(handle.worktreeRoot)) {
2279
+ await runGit(["worktree", "remove", "--force", handle.worktreeRoot], {
2280
+ cwd: repoRoot,
2281
+ env,
2282
+ allowFailure: true
2283
+ });
2284
+ await runGit(["worktree", "prune"], { cwd: repoRoot, env, allowFailure: true });
2285
+ }
2286
+ if (!keepBranch && handle.branchName) {
2287
+ await runGit(["branch", "-D", handle.branchName], {
2288
+ cwd: repoRoot,
2289
+ env,
2290
+ allowFailure: true
2291
+ });
2292
+ }
2293
+ return true;
2294
+ };
2295
+ if (options.strategy === "apply_patch") {
2296
+ const binaryPatch = await withTempIndex(worktreeRoot, env, async (tempEnv) => {
2297
+ const res = await runGit(["diff", "--cached", "--binary", "-M", baseSha], {
2298
+ cwd: worktreeRoot,
2299
+ env: tempEnv
2300
+ });
2301
+ return res.stdout;
2302
+ });
2303
+ const checkRes = await runGit(["apply", "--check", "-"], {
2304
+ cwd: repoRoot,
2305
+ env,
2306
+ input: binaryPatch,
2307
+ allowFailure: true
2308
+ });
2309
+ if (checkRes.exitCode !== 0) {
2310
+ throw new Error(
2311
+ `Conflict detected while pre-checking patch on ${repoRoot}; main workspace left untouched.
2312
+ ${checkRes.stderr.trim()}`
2313
+ );
2314
+ }
2315
+ await runGit(["apply", "-"], {
2316
+ cwd: repoRoot,
2317
+ env,
2318
+ input: binaryPatch
2319
+ });
2320
+ const cleanedUp2 = await cleanupIfRequested(false);
2321
+ return {
2322
+ strategy: "apply_patch",
2323
+ appliedFiles,
2324
+ cleanedUp: cleanedUp2,
2325
+ message: `Applied ${appliedFiles.length} changed file(s) cleanly to ${repoRoot} working tree.`
2326
+ };
2327
+ }
2328
+ const commitMessage = options.commitMessage?.trim() || `chore(gemini-agent-bridge): apply ${handle.branchName ?? "task"} changes`;
2329
+ if (options.strategy === "keep_branch") {
2330
+ const commitSha2 = await commitAllInDir(worktreeRoot, commitMessage, env);
2331
+ const cleanedUp2 = await cleanupIfRequested(true);
2332
+ return {
2333
+ strategy: "keep_branch",
2334
+ appliedFiles,
2335
+ commitSha: commitSha2,
2336
+ branchName: handle.branchName,
2337
+ cleanedUp: cleanedUp2,
2338
+ message: `Committed changes to branch ${handle.branchName} (${commitSha2.slice(0, 8)}); main working tree untouched.`
2339
+ };
2340
+ }
2341
+ if (await hasUncommittedChanges(repoRoot, env)) {
2342
+ throw new Error(
2343
+ `Main repository ${repoRoot} has uncommitted changes. Commit/stash them first, or approve with mergeStrategy="apply_patch" / "keep_branch".`
2344
+ );
2345
+ }
2346
+ if (!handle.branchName) {
2347
+ throw new Error("Worktree handle missing branchName for git merge.");
2348
+ }
2349
+ await commitAllInDir(worktreeRoot, commitMessage, env);
2350
+ const identityArgs = await getGitIdentityConfigArgs(repoRoot, env);
2351
+ if (options.strategy === "merge_commit") {
2352
+ const mergeRes = await runGit(
2353
+ [...identityArgs, "-c", "commit.gpgsign=false", "merge", "--no-ff", handle.branchName, "-m", commitMessage],
2354
+ { cwd: repoRoot, env, allowFailure: true }
2355
+ );
2356
+ if (mergeRes.exitCode !== 0) {
2357
+ await runGit(["merge", "--abort"], { cwd: repoRoot, env, allowFailure: true });
2358
+ throw new Error(`Merge conflict during merge_commit; aborted cleanly.
2359
+ ${mergeRes.stderr.trim()}`);
2360
+ }
2361
+ const commitSha2 = await resolveRefSha(repoRoot, "HEAD", env);
2362
+ const cleanedUp2 = await cleanupIfRequested(false);
2363
+ return {
2364
+ strategy: "merge_commit",
2365
+ appliedFiles,
2366
+ commitSha: commitSha2,
2367
+ cleanedUp: cleanedUp2,
2368
+ message: `Merged ${handle.branchName} into ${handle.baseBranch ?? "HEAD"} (${commitSha2.slice(0, 8)}).`
2369
+ };
2370
+ }
2371
+ if (options.strategy === "squash_merge") {
2372
+ const squashRes = await runGit(["merge", "--squash", handle.branchName], {
2373
+ cwd: repoRoot,
2374
+ env,
2375
+ allowFailure: true
2376
+ });
2377
+ if (squashRes.exitCode !== 0) {
2378
+ await runGit(["reset", "--merge"], { cwd: repoRoot, env, allowFailure: true });
2379
+ throw new Error(`Merge conflict during squash_merge; reset cleanly.
2380
+ ${squashRes.stderr.trim()}`);
2381
+ }
2382
+ await runGit([...identityArgs, "-c", "commit.gpgsign=false", "commit", "-m", commitMessage], {
2383
+ cwd: repoRoot,
2384
+ env
2385
+ });
2386
+ const commitSha2 = await resolveRefSha(repoRoot, "HEAD", env);
2387
+ const cleanedUp2 = await cleanupIfRequested(false);
2388
+ return {
2389
+ strategy: "squash_merge",
2390
+ appliedFiles,
2391
+ commitSha: commitSha2,
2392
+ cleanedUp: cleanedUp2,
2393
+ message: `Squash-merged ${handle.branchName} into ${handle.baseBranch ?? "HEAD"} (${commitSha2.slice(0, 8)}).`
2394
+ };
2395
+ }
2396
+ const ffRes = await runGit(["merge", "--ff-only", handle.branchName], {
2397
+ cwd: repoRoot,
2398
+ env,
2399
+ allowFailure: true
2400
+ });
2401
+ if (ffRes.exitCode !== 0) {
2402
+ throw new Error(
2403
+ `Cannot fast-forward ${handle.branchName} onto current HEAD (branches diverged). Use merge_commit or apply_patch.
2404
+ ${ffRes.stderr.trim()}`
2405
+ );
2406
+ }
2407
+ const commitSha = await resolveRefSha(repoRoot, "HEAD", env);
2408
+ const cleanedUp = await cleanupIfRequested(false);
2409
+ return {
2410
+ strategy: "fast_forward",
2411
+ appliedFiles,
2412
+ commitSha,
2413
+ cleanedUp,
2414
+ message: `Fast-forwarded ${handle.baseBranch ?? "HEAD"} to ${commitSha.slice(0, 8)}.`
2415
+ };
2416
+ }
2417
+
2418
+ // src/tasks/store.ts
2419
+ import fs8 from "fs";
2420
+ import path7 from "path";
2421
+ var TaskStore = class {
2422
+ dataDir;
2423
+ logger;
2424
+ constructor(dataDir, logger) {
2425
+ this.dataDir = dataDir;
2426
+ this.logger = logger;
2427
+ }
2428
+ getTaskJsonPath(taskId) {
2429
+ return path7.join(getTaskDir(this.dataDir, taskId), "task.json");
2430
+ }
2431
+ getEventsJsonlPath(taskId) {
2432
+ return path7.join(getTaskDir(this.dataDir, taskId), "events.jsonl");
2433
+ }
2434
+ saveTask(record) {
2435
+ const taskDir = getTaskDir(this.dataDir, record.id);
2436
+ fs8.mkdirSync(taskDir, { recursive: true });
2437
+ const filePath = this.getTaskJsonPath(record.id);
2438
+ const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
2439
+ fs8.writeFileSync(tmpPath, `${JSON.stringify(record, null, 2)}
2440
+ `, "utf8");
2441
+ fs8.renameSync(tmpPath, filePath);
2442
+ }
2443
+ appendEvent(taskId, event) {
2444
+ const taskDir = getTaskDir(this.dataDir, taskId);
2445
+ fs8.mkdirSync(taskDir, { recursive: true });
2446
+ const filePath = this.getEventsJsonlPath(taskId);
2447
+ fs8.appendFileSync(filePath, `${JSON.stringify(event)}
2448
+ `, "utf8");
2449
+ }
2450
+ readEvents(taskId, options = {}) {
2451
+ const filePath = this.getEventsJsonlPath(taskId);
2452
+ if (!fs8.existsSync(filePath)) {
2453
+ return { events: [], total: 0 };
2454
+ }
2455
+ const content = fs8.readFileSync(filePath, "utf8");
2456
+ let events = [];
2457
+ for (const line of content.split("\n")) {
2458
+ if (!line.trim()) continue;
2459
+ try {
2460
+ events.push(JSON.parse(line));
2461
+ } catch {
2462
+ }
2463
+ }
2464
+ if (options.eventTypes && options.eventTypes.length > 0) {
2465
+ const allowed = new Set(options.eventTypes);
2466
+ events = events.filter((e) => allowed.has(e.type));
2467
+ }
2468
+ const total = events.length;
2469
+ if (options.tail !== void 0 && options.tail > 0) {
2470
+ return { events: events.slice(-options.tail), total };
2471
+ }
2472
+ const offset = Math.max(0, options.offset ?? 0);
2473
+ return { events: events.slice(offset, offset + 200), total };
2474
+ }
2475
+ loadAllAndRehydrate() {
2476
+ const tasksRoot = getTasksDir(this.dataDir);
2477
+ if (!fs8.existsSync(tasksRoot)) {
2478
+ return [];
2479
+ }
2480
+ const entries = fs8.readdirSync(tasksRoot, { withFileTypes: true });
2481
+ const loaded = [];
2482
+ for (const entry of entries) {
2483
+ if (!entry.isDirectory()) continue;
2484
+ const jsonPath = path7.join(tasksRoot, entry.name, "task.json");
2485
+ if (!fs8.existsSync(jsonPath)) continue;
2486
+ try {
2487
+ const raw = fs8.readFileSync(jsonPath, "utf8");
2488
+ const record = JSON.parse(raw);
2489
+ if (!record || typeof record.id !== "string") continue;
2490
+ if (record.status === "queued" || record.status === "running" || record.status === "needs_input") {
2491
+ record.status = "failed";
2492
+ record.pendingInput = void 0;
2493
+ record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2494
+ const lastRound = record.rounds[record.rounds.length - 1];
2495
+ if (lastRound && (lastRound.status === "running" || lastRound.status === "needs_input")) {
2496
+ lastRound.status = "failed";
2497
+ lastRound.finishedAt = record.updatedAt;
2498
+ lastRound.error = "MCP server restarted while task was in progress; isolated workspace preserved for inspection or request_changes retry.";
2499
+ }
2500
+ this.saveTask(record);
2501
+ }
2502
+ loaded.push(record);
2503
+ } catch (err) {
2504
+ this.logger.warn("Failed to load persisted task file", {
2505
+ path: jsonPath,
2506
+ error: err instanceof Error ? err.message : String(err)
2507
+ });
2508
+ }
2509
+ }
2510
+ loaded.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
2511
+ return loaded;
2512
+ }
2513
+ };
2514
+
2515
+ // src/tasks/verifier.ts
2516
+ import { spawn as spawn4 } from "child_process";
2517
+ var MAX_OUTPUT_CHARS = 8192;
2518
+ function tailString(text, maxChars = MAX_OUTPUT_CHARS) {
2519
+ if (text.length <= maxChars) return text;
2520
+ return `...[truncated ${text.length - maxChars} chars]...
2521
+ ${text.slice(-maxChars)}`;
2522
+ }
2523
+ async function runSingleVerificationCommand(cwd, command, env, timeoutMs = 18e4) {
2524
+ const start = Date.now();
2525
+ const shell = process.platform === "win32" ? process.env.ComSpec || "cmd.exe" : "/bin/sh";
2526
+ const shellArgs = process.platform === "win32" ? ["/d", "/s", "/c", command] : ["-c", command];
2527
+ return new Promise((resolve) => {
2528
+ const child = spawn4(shell, shellArgs, {
2529
+ cwd,
2530
+ env,
2531
+ stdio: ["ignore", "pipe", "pipe"]
2532
+ });
2533
+ const stdoutChunks = [];
2534
+ const stderrChunks = [];
2535
+ let timedOut = false;
2536
+ let settled = false;
2537
+ const timer = setTimeout(() => {
2538
+ timedOut = true;
2539
+ try {
2540
+ child.kill("SIGTERM");
2541
+ setTimeout(() => {
2542
+ if (child.exitCode === null) {
2543
+ try {
2544
+ child.kill("SIGKILL");
2545
+ } catch {
2546
+ }
2547
+ }
2548
+ }, 2e3).unref?.();
2549
+ } catch {
2550
+ }
2551
+ }, timeoutMs);
2552
+ timer.unref?.();
2553
+ child.stdout.on("data", (chunk) => stdoutChunks.push(chunk));
2554
+ child.stderr.on("data", (chunk) => stderrChunks.push(chunk));
2555
+ child.on("error", (err) => {
2556
+ clearTimeout(timer);
2557
+ if (settled) return;
2558
+ settled = true;
2559
+ resolve({
2560
+ command,
2561
+ exitCode: 1,
2562
+ passed: false,
2563
+ durationMs: Date.now() - start,
2564
+ stdoutTail: tailString(Buffer.concat(stdoutChunks).toString("utf8")),
2565
+ stderrTail: tailString(err.message),
2566
+ timedOut
2567
+ });
2568
+ });
2569
+ child.on("close", (code) => {
2570
+ clearTimeout(timer);
2571
+ if (settled) return;
2572
+ settled = true;
2573
+ const exitCode = code ?? (timedOut ? 124 : 1);
2574
+ resolve({
2575
+ command,
2576
+ exitCode,
2577
+ passed: !timedOut && exitCode === 0,
2578
+ durationMs: Date.now() - start,
2579
+ stdoutTail: tailString(Buffer.concat(stdoutChunks).toString("utf8")),
2580
+ stderrTail: tailString(Buffer.concat(stderrChunks).toString("utf8")),
2581
+ timedOut
2582
+ });
2583
+ });
2584
+ });
2585
+ }
2586
+ async function runVerificationCommands(cwd, commands, env, timeoutMsPerCmd = 18e4) {
2587
+ const results = [];
2588
+ for (const cmd of commands) {
2589
+ const trimmed = cmd.trim();
2590
+ if (!trimmed) continue;
2591
+ const res = await runSingleVerificationCommand(cwd, trimmed, env, timeoutMsPerCmd);
2592
+ results.push(res);
2593
+ }
2594
+ return results;
2595
+ }
2596
+
2597
+ // src/tasks/manager.ts
2598
+ function generateTaskId() {
2599
+ const now = /* @__PURE__ */ new Date();
2600
+ const stamp = [
2601
+ now.getUTCFullYear(),
2602
+ String(now.getUTCMonth() + 1).padStart(2, "0"),
2603
+ String(now.getUTCDate()).padStart(2, "0"),
2604
+ String(now.getUTCHours()).padStart(2, "0"),
2605
+ String(now.getUTCMinutes()).padStart(2, "0"),
2606
+ String(now.getUTCSeconds()).padStart(2, "0")
2607
+ ].join("");
2608
+ const rand = crypto4.randomBytes(3).toString("hex");
2609
+ return `tsk_${stamp}_${rand}`;
2610
+ }
2611
+ function buildSystemAppendPrompt(acceptanceCriteria, verifyCommands, workspaceMode) {
2612
+ const lines = [
2613
+ "You are working as a delegated execution agent under an orchestrator (Gemini) inside an isolated workspace.",
2614
+ "Complete the task accurately within the current working directory. Do not attempt to invoke external orchestrator MCP servers."
2615
+ ];
2616
+ if (workspaceMode === "readonly") {
2617
+ lines.push("IMPORTANT: You are in READ-ONLY mode. Do not modify files.");
2618
+ }
2619
+ if (acceptanceCriteria.length > 0) {
2620
+ lines.push("", "Acceptance criteria that the reviewer will verify:");
2621
+ for (const c of acceptanceCriteria) {
2622
+ lines.push(`- ${c}`);
2623
+ }
2624
+ }
2625
+ if (verifyCommands.length > 0) {
2626
+ lines.push("", "Verification commands that will be executed automatically after you finish:");
2627
+ for (const cmd of verifyCommands) {
2628
+ lines.push(`- \`${cmd}\``);
2629
+ }
2630
+ }
2631
+ lines.push(
2632
+ "",
2633
+ "When finished, provide a concise final report summarizing: (1) what was changed, (2) checks run and observed outcomes, and (3) any caveats or remaining risks."
2634
+ );
2635
+ return lines.join("\n");
2636
+ }
2637
+ function buildRevisionPrompt(task, input) {
2638
+ const lines = [
2639
+ `[Review Round ${task.currentRound} Feedback \u2014 Requested Changes]`,
2640
+ "",
2641
+ "The orchestrator reviewed your previous deliverable and requested the following changes:",
2642
+ input.feedback.trim()
2643
+ ];
2644
+ if (input.comments && input.comments.length > 0) {
2645
+ lines.push("", "File-specific review comments:");
2646
+ for (const c of input.comments) {
2647
+ const loc = c.line !== void 0 ? `${c.path}:${c.line}` : c.path;
2648
+ lines.push(`- ${loc}: ${c.note}`);
2649
+ }
2650
+ }
2651
+ if (task.acceptanceCriteria.length > 0) {
2652
+ lines.push("", "Original acceptance criteria reminder:");
2653
+ for (const item of task.acceptanceCriteria) {
2654
+ lines.push(`- ${item}`);
2655
+ }
2656
+ }
2657
+ if (task.verifyCommands.length > 0) {
2658
+ lines.push("", "Verification commands to pass:");
2659
+ for (const cmd of task.verifyCommands) {
2660
+ lines.push(`- \`${cmd}\``);
2661
+ }
2662
+ }
2663
+ lines.push("", "Apply the requested fixes in the current workspace and summarize what you fixed.");
2664
+ return lines.join("\n");
2665
+ }
2666
+ var TaskManager = class {
2667
+ config;
2668
+ adapters;
2669
+ processRegistry;
2670
+ logger;
2671
+ store;
2672
+ env;
2673
+ tasks = /* @__PURE__ */ new Map();
2674
+ activeRuns = /* @__PURE__ */ new Map();
2675
+ emitter = new EventEmitter();
2676
+ constructor(deps) {
2677
+ this.config = deps.config;
2678
+ this.adapters = deps.adapters;
2679
+ this.processRegistry = deps.processRegistry;
2680
+ this.logger = deps.logger;
2681
+ this.env = buildAugmentedEnv(deps.env ?? process.env, { probeLoginShell: true });
2682
+ this.store = new TaskStore(deps.config.dataDir, deps.logger);
2683
+ this.emitter.setMaxListeners(100);
2684
+ }
2685
+ init() {
2686
+ const loaded = this.store.loadAllAndRehydrate();
2687
+ for (const task of loaded) {
2688
+ this.tasks.set(task.id, task);
2689
+ }
2690
+ this.logger.info("TaskManager initialized", { loadedTasks: loaded.length });
2691
+ }
2692
+ getAugmentedEnv() {
2693
+ return this.env;
2694
+ }
2695
+ getTaskOrThrow(taskId) {
2696
+ const task = this.tasks.get(taskId);
2697
+ if (!task) {
2698
+ throw new Error(`Task not found: ${taskId}`);
2699
+ }
2700
+ return task;
2701
+ }
2702
+ saveAndEmit(task, event) {
2703
+ task.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2704
+ this.store.saveTask(task);
2705
+ if (event) {
2706
+ this.store.appendEvent(task.id, event);
2707
+ }
2708
+ this.emitter.emit(`task:${task.id}`, { task, event });
2709
+ }
2710
+ async dispatchTask(input, onProgress) {
2711
+ if (this.activeRuns.size >= this.config.maxConcurrentTasks) {
2712
+ throw new Error(
2713
+ `Maximum concurrent tasks limit reached (${this.config.maxConcurrentTasks}). Wait for or cancel an active task first.`
2714
+ );
2715
+ }
2716
+ const validation = validateWorkspacePath(input.workspace, this.config);
2717
+ if (!validation.allowed) {
2718
+ throw new Error(validation.reason ?? `Workspace not allowed: ${input.workspace}`);
2719
+ }
2720
+ const sourceDir = validation.resolvedPath;
2721
+ const agentId = input.agent ?? this.config.defaultAgent;
2722
+ const adapter = this.adapters.get(agentId);
2723
+ const agentInfo = await adapter.detect(this.config, this.env);
2724
+ if (!agentInfo.available) {
2725
+ throw new Error(
2726
+ `Agent "${agentId}" is unavailable: ${agentInfo.error ?? "not found"}. Run \`doctor\` to inspect.`
2727
+ );
2728
+ }
2729
+ const gitRepo = await isGitRepo(sourceDir, this.env);
2730
+ let workspaceMode = input.workspaceMode ?? this.config.defaultWorkspaceMode;
2731
+ if (!input.workspaceMode && !gitRepo && workspaceMode === "worktree") {
2732
+ workspaceMode = "staging";
2733
+ }
2734
+ if (workspaceMode === "worktree" && !gitRepo) {
2735
+ throw new Error(
2736
+ `Workspace ${sourceDir} is not a git repository; cannot use workspaceMode="worktree". Use "staging", "direct", or "readonly".`
2737
+ );
2738
+ }
2739
+ const taskId = generateTaskId();
2740
+ let workspaceHandle;
2741
+ if (workspaceMode === "worktree") {
2742
+ workspaceHandle = await prepareWorktree(
2743
+ this.config.dataDir,
2744
+ sourceDir,
2745
+ taskId,
2746
+ agentId,
2747
+ input.baseRef,
2748
+ this.env
2749
+ );
2750
+ } else if (workspaceMode === "staging") {
2751
+ workspaceHandle = prepareStagingWorkspace(
2752
+ this.config.dataDir,
2753
+ sourceDir,
2754
+ taskId,
2755
+ this.config.stagingMaxBytes,
2756
+ this.config.stagingMaxFiles
2757
+ );
2758
+ } else {
2759
+ workspaceHandle = prepareDirectOrReadonlyWorkspace(workspaceMode, sourceDir);
2760
+ }
2761
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2762
+ const title = input.title?.trim() || input.prompt.trim().split(/\r?\n/)[0]?.slice(0, 72) || `${agentId} task`;
2763
+ const acceptanceCriteria = input.acceptanceCriteria ?? [];
2764
+ const verifyCommands = input.verifyCommands ?? [];
2765
+ const interactionPolicy = input.interactionPolicy ?? this.config.defaultInteractionPolicy;
2766
+ const timeoutSeconds = Math.min(
2767
+ 3600,
2768
+ Math.max(30, input.timeoutSeconds ?? this.config.defaultTimeoutSeconds)
2769
+ );
2770
+ const task = {
2771
+ id: taskId,
2772
+ title,
2773
+ agent: agentId,
2774
+ workspace: sourceDir,
2775
+ workspaceMode,
2776
+ acceptanceCriteria,
2777
+ verifyCommands,
2778
+ interactionPolicy,
2779
+ ...input.model ? { model: input.model } : {},
2780
+ ...input.thinking ? { thinking: input.thinking } : {},
2781
+ ...input.agentProfile ? { agentProfile: input.agentProfile } : {},
2782
+ timeoutSeconds,
2783
+ status: "queued",
2784
+ currentRound: 1,
2785
+ rounds: [],
2786
+ workspaceHandle,
2787
+ createdAt: now,
2788
+ updatedAt: now
2789
+ };
2790
+ this.tasks.set(taskId, task);
2791
+ this.saveAndEmit(task);
2792
+ try {
2793
+ await this.launchRound(task, input.prompt, 1);
2794
+ } catch (err) {
2795
+ await this.cleanupIsolatedWorkspace(task).catch(() => {
2796
+ });
2797
+ task.status = "failed";
2798
+ this.saveAndEmit(task);
2799
+ throw err;
2800
+ }
2801
+ const waitSeconds = Math.min(120, Math.max(0, input.waitSeconds ?? this.config.defaultWaitSeconds));
2802
+ const settled = await this.waitTask(task.id, waitSeconds, onProgress);
2803
+ if (settled.status !== "running" && settled.status !== "queued") {
2804
+ const deliverable = await this.getDeliverable(task.id);
2805
+ return { task: settled, deliverable, settledWithinWait: true };
2806
+ }
2807
+ return { task: settled, settledWithinWait: false };
2808
+ }
2809
+ async launchRound(task, promptText, roundNumber, revisionMeta) {
2810
+ const adapter = this.adapters.get(task.agent);
2811
+ const round = {
2812
+ round: roundNumber,
2813
+ prompt: promptText,
2814
+ ...revisionMeta?.feedback ? { feedback: revisionMeta.feedback } : {},
2815
+ ...revisionMeta?.comments ? { comments: revisionMeta.comments } : {},
2816
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
2817
+ status: "running",
2818
+ toolCallsCount: 0,
2819
+ toolDigest: [],
2820
+ verification: []
2821
+ };
2822
+ task.currentRound = roundNumber;
2823
+ task.status = "running";
2824
+ task.pendingInput = void 0;
2825
+ task.rounds.push(round);
2826
+ this.saveAndEmit(task);
2827
+ const systemAppendPrompt = roundNumber === 1 ? buildSystemAppendPrompt(task.acceptanceCriteria, task.verifyCommands, task.workspaceMode) : void 0;
2828
+ const handle = await adapter.startRun({
2829
+ taskId: task.id,
2830
+ title: task.title,
2831
+ prompt: promptText,
2832
+ systemAppendPrompt,
2833
+ executionDir: task.workspaceHandle.executionDir,
2834
+ piSessionsDir: getPiSessionsDir(this.config.dataDir, task.id),
2835
+ workspaceMode: task.workspaceMode,
2836
+ interactionPolicy: task.interactionPolicy,
2837
+ sessionId: task.sessionId,
2838
+ model: task.model,
2839
+ thinking: task.thinking,
2840
+ agentProfile: task.agentProfile,
2841
+ config: this.config,
2842
+ env: this.env,
2843
+ logger: this.logger,
2844
+ processRegistry: this.processRegistry,
2845
+ onEvent: (event) => {
2846
+ if (event.type === "tool_start" || event.type === "tool_end") {
2847
+ round.toolCallsCount = Math.max(round.toolCallsCount, round.toolDigest.length);
2848
+ }
2849
+ this.store.appendEvent(task.id, event);
2850
+ this.emitter.emit(`task:${task.id}`, { task, event });
2851
+ },
2852
+ onSessionId: (sid) => {
2853
+ if (sid && sid !== task.sessionId) {
2854
+ task.sessionId = sid;
2855
+ this.saveAndEmit(task);
2856
+ }
2857
+ },
2858
+ onInputRequired: (req) => {
2859
+ task.status = "needs_input";
2860
+ task.pendingInput = req;
2861
+ round.status = "needs_input";
2862
+ this.saveAndEmit(task);
2863
+ },
2864
+ onInputResolved: () => {
2865
+ if (task.status === "needs_input") {
2866
+ task.status = "running";
2867
+ task.pendingInput = void 0;
2868
+ round.status = "running";
2869
+ this.saveAndEmit(task);
2870
+ }
2871
+ }
2872
+ });
2873
+ const activeCtx = {
2874
+ handle,
2875
+ cancelledByUser: false
2876
+ };
2877
+ activeCtx.timeoutTimer = setTimeout(() => {
2878
+ this.logger.warn("Task exceeded timeoutSeconds; aborting run", {
2879
+ taskId: task.id,
2880
+ timeoutSeconds: task.timeoutSeconds
2881
+ });
2882
+ void handle.abort();
2883
+ }, task.timeoutSeconds * 1e3);
2884
+ activeCtx.timeoutTimer.unref?.();
2885
+ this.activeRuns.set(task.id, activeCtx);
2886
+ void handle.completion.then(async (result) => {
2887
+ if (activeCtx.timeoutTimer) {
2888
+ clearTimeout(activeCtx.timeoutTimer);
2889
+ }
2890
+ this.activeRuns.delete(task.id);
2891
+ if (result.sessionId) {
2892
+ task.sessionId = result.sessionId;
2893
+ }
2894
+ round.toolCallsCount = result.toolCallsCount;
2895
+ round.toolDigest = result.toolDigest;
2896
+ round.usage = result.usage;
2897
+ round.finalSummary = result.finalSummary;
2898
+ round.error = result.error;
2899
+ round.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
2900
+ task.pendingInput = void 0;
2901
+ if (activeCtx.cancelledByUser || result.aborted) {
2902
+ round.status = "cancelled";
2903
+ task.status = "cancelled";
2904
+ this.saveAndEmit(task);
2905
+ return;
2906
+ }
2907
+ if (result.ok) {
2908
+ if (task.verifyCommands.length > 0) {
2909
+ const verifyEvent = {
2910
+ seq: 9e5 + roundNumber,
2911
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2912
+ type: "status",
2913
+ summary: `Running ${task.verifyCommands.length} verification command(s)...`
2914
+ };
2915
+ this.saveAndEmit(task, verifyEvent);
2916
+ round.verification = await runVerificationCommands(
2917
+ task.workspaceHandle.executionDir,
2918
+ task.verifyCommands,
2919
+ this.env
2920
+ );
2921
+ }
2922
+ round.status = "completed";
2923
+ task.status = "awaiting_review";
2924
+ } else {
2925
+ round.status = "failed";
2926
+ task.status = "failed";
2927
+ }
2928
+ this.saveAndEmit(task);
2929
+ });
2930
+ }
2931
+ async waitTask(taskId, waitSeconds = 30, onProgress) {
2932
+ const task = this.getTaskOrThrow(taskId);
2933
+ if (task.status !== "running" && task.status !== "queued") {
2934
+ return task;
2935
+ }
2936
+ const clampedWaitMs = Math.min(120, Math.max(0, waitSeconds)) * 1e3;
2937
+ if (clampedWaitMs === 0) {
2938
+ return task;
2939
+ }
2940
+ return new Promise((resolve) => {
2941
+ let progressStep = 0;
2942
+ let done = false;
2943
+ const cleanup = () => {
2944
+ if (done) return;
2945
+ done = true;
2946
+ clearTimeout(timer);
2947
+ this.emitter.off(`task:${taskId}`, onTaskUpdate);
2948
+ };
2949
+ const onTaskUpdate = (payload) => {
2950
+ if (payload.event && onProgress) {
2951
+ progressStep += 1;
2952
+ onProgress({
2953
+ progress: progressStep,
2954
+ message: `[${payload.task.agent}:${payload.event.type}] ${payload.event.summary}`
2955
+ });
2956
+ }
2957
+ if (payload.task.status !== "running" && payload.task.status !== "queued") {
2958
+ cleanup();
2959
+ resolve(payload.task);
2960
+ }
2961
+ };
2962
+ const timer = setTimeout(() => {
2963
+ cleanup();
2964
+ resolve(this.getTaskOrThrow(taskId));
2965
+ }, clampedWaitMs);
2966
+ timer.unref?.();
2967
+ this.emitter.on(`task:${taskId}`, onTaskUpdate);
2968
+ const latest = this.getTaskOrThrow(taskId);
2969
+ if (latest.status !== "running" && latest.status !== "queued") {
2970
+ cleanup();
2971
+ resolve(latest);
2972
+ }
2973
+ });
2974
+ }
2975
+ async steerTask(taskId, message, mode = "steer") {
2976
+ const task = this.getTaskOrThrow(taskId);
2977
+ const active = this.activeRuns.get(taskId);
2978
+ if (!active || task.status !== "running" && task.status !== "needs_input") {
2979
+ throw new Error(
2980
+ `Task ${taskId} is not currently running (status=${task.status}). Use request_changes for awaiting_review/failed tasks.`
2981
+ );
2982
+ }
2983
+ await active.handle.steer(message, mode);
2984
+ return { taskId, mode, status: task.status };
2985
+ }
2986
+ async respondTaskInput(taskId, response, requestId) {
2987
+ const task = this.getTaskOrThrow(taskId);
2988
+ const active = this.activeRuns.get(taskId);
2989
+ if (task.status !== "needs_input" || !task.pendingInput || !active) {
2990
+ throw new Error(`Task ${taskId} is not awaiting input (status=${task.status}).`);
2991
+ }
2992
+ const targetRequestId = requestId ?? task.pendingInput.requestId;
2993
+ if (targetRequestId !== task.pendingInput.requestId) {
2994
+ throw new Error(
2995
+ `Mismatched requestId "${targetRequestId}"; pending request is "${task.pendingInput.requestId}".`
2996
+ );
2997
+ }
2998
+ await active.handle.respondInput(targetRequestId, response);
2999
+ return { taskId, requestId: targetRequestId, status: task.status };
3000
+ }
3001
+ async cancelTask(taskId, cleanupWorktree = false) {
3002
+ const task = this.getTaskOrThrow(taskId);
3003
+ const active = this.activeRuns.get(taskId);
3004
+ if (active) {
3005
+ active.cancelledByUser = true;
3006
+ await active.handle.abort();
3007
+ await active.handle.completion.catch(() => {
3008
+ });
3009
+ } else if (task.status === "running" || task.status === "queued" || task.status === "needs_input") {
3010
+ task.status = "cancelled";
3011
+ task.pendingInput = void 0;
3012
+ this.saveAndEmit(task);
3013
+ }
3014
+ if (cleanupWorktree) {
3015
+ await this.cleanupIsolatedWorkspace(task);
3016
+ }
3017
+ return this.getTaskOrThrow(taskId);
3018
+ }
3019
+ listTasks(filters) {
3020
+ let list = Array.from(this.tasks.values());
3021
+ if (filters?.status) {
3022
+ list = list.filter((t) => t.status === filters.status);
3023
+ }
3024
+ if (filters?.agent) {
3025
+ list = list.filter((t) => t.agent === filters.agent);
3026
+ }
3027
+ if (filters?.workspace) {
3028
+ const target = path8.resolve(filters.workspace);
3029
+ list = list.filter((t) => t.workspace === target || t.workspace.startsWith(target));
3030
+ }
3031
+ list.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
3032
+ const limit = Math.max(1, Math.min(200, filters?.limit ?? 50));
3033
+ return list.slice(0, limit);
3034
+ }
3035
+ async getDiff(taskId, options = {}) {
3036
+ const task = this.getTaskOrThrow(taskId);
3037
+ if (task.workspaceMode === "worktree") {
3038
+ return collectWorktreeDiff(task.workspaceHandle, options, this.env);
3039
+ }
3040
+ return collectNonWorktreeDiff(task.workspaceHandle, options, this.env);
3041
+ }
3042
+ readTaskFile(taskId, relativePath, startLine = 1, endLine = 250) {
3043
+ const task = this.getTaskOrThrow(taskId);
3044
+ const rootDir = task.workspaceHandle.executionDir;
3045
+ const candidate = path8.resolve(rootDir, relativePath);
3046
+ if (!isPathInsideOrEqual(candidate, rootDir)) {
3047
+ throw new Error(`Path escapes isolated workspace: ${relativePath}`);
3048
+ }
3049
+ if (!fs9.existsSync(candidate)) {
3050
+ throw new Error(`File not found in task workspace: ${relativePath}`);
3051
+ }
3052
+ const stat = fs9.statSync(candidate);
3053
+ if (!stat.isFile()) {
3054
+ throw new Error(`Target is not a regular file: ${relativePath}`);
3055
+ }
3056
+ const lines = fs9.readFileSync(candidate, "utf8").split("\n");
3057
+ const safeStart = Math.max(1, startLine);
3058
+ const safeEnd = Math.min(lines.length, Math.max(safeStart, endLine));
3059
+ const slice = lines.slice(safeStart - 1, safeEnd);
3060
+ return {
3061
+ path: relativePath,
3062
+ totalLines: lines.length,
3063
+ startLine: safeStart,
3064
+ endLine: safeEnd,
3065
+ content: slice.join("\n")
3066
+ };
3067
+ }
3068
+ getLogs(taskId, options = {}) {
3069
+ this.getTaskOrThrow(taskId);
3070
+ return this.store.readEvents(taskId, options);
3071
+ }
3072
+ async verifyTask(taskId, commands) {
3073
+ const task = this.getTaskOrThrow(taskId);
3074
+ if (task.status === "running" || task.status === "queued" || task.status === "needs_input") {
3075
+ throw new Error(`Cannot run verification while task is ${task.status}. Wait until it finishes.`);
3076
+ }
3077
+ if (task.status === "rejected") {
3078
+ throw new Error(`Task ${taskId} was already rejected and its isolated workspace was removed.`);
3079
+ }
3080
+ const results = await runVerificationCommands(
3081
+ task.workspaceHandle.executionDir,
3082
+ commands,
3083
+ this.env
3084
+ );
3085
+ const latestRound = task.rounds[task.rounds.length - 1];
3086
+ if (latestRound) {
3087
+ latestRound.verification.push(...results);
3088
+ }
3089
+ this.saveAndEmit(task);
3090
+ return results;
3091
+ }
3092
+ async requestChanges(taskId, input, onProgress) {
3093
+ const task = this.getTaskOrThrow(taskId);
3094
+ if (task.status !== "awaiting_review" && task.status !== "failed") {
3095
+ throw new Error(
3096
+ `request_changes only applies to tasks in awaiting_review or failed state (current: ${task.status}).`
3097
+ );
3098
+ }
3099
+ if (task.workspaceMode === "readonly") {
3100
+ throw new Error("Cannot request code changes on a readonly task.");
3101
+ }
3102
+ if (this.activeRuns.size >= this.config.maxConcurrentTasks) {
3103
+ throw new Error(`Maximum concurrent tasks limit reached (${this.config.maxConcurrentTasks}).`);
3104
+ }
3105
+ if (input.verifyCommands !== void 0) {
3106
+ task.verifyCommands = input.verifyCommands;
3107
+ }
3108
+ const nextRound = task.currentRound + 1;
3109
+ task.currentRound = nextRound;
3110
+ const revisionPrompt = buildRevisionPrompt(task, input);
3111
+ await this.launchRound(task, revisionPrompt, nextRound, {
3112
+ feedback: input.feedback,
3113
+ comments: input.comments
3114
+ });
3115
+ const waitSeconds = Math.min(120, Math.max(0, input.waitSeconds ?? this.config.defaultWaitSeconds));
3116
+ const settled = await this.waitTask(task.id, waitSeconds, onProgress);
3117
+ if (settled.status !== "running" && settled.status !== "queued") {
3118
+ const deliverable = await this.getDeliverable(task.id);
3119
+ return { task: settled, deliverable, settledWithinWait: true };
3120
+ }
3121
+ return { task: settled, settledWithinWait: false };
3122
+ }
3123
+ async approveTask(taskId, options = {}) {
3124
+ const task = this.getTaskOrThrow(taskId);
3125
+ if (task.status !== "awaiting_review") {
3126
+ throw new Error(
3127
+ `Only tasks in awaiting_review state can be approved (current: ${task.status}).`
3128
+ );
3129
+ }
3130
+ const strategy = options.mergeStrategy ?? this.config.defaultMergeStrategy;
3131
+ let landResult;
3132
+ if (task.workspaceMode === "worktree") {
3133
+ landResult = await landWorktree(
3134
+ this.config.dataDir,
3135
+ task.workspaceHandle,
3136
+ {
3137
+ strategy,
3138
+ commitMessage: options.commitMessage,
3139
+ cleanupWorktree: options.cleanupWorktree
3140
+ },
3141
+ this.env
3142
+ );
3143
+ } else {
3144
+ landResult = landNonWorktreeWorkspace(this.config.dataDir, task.workspaceHandle, {
3145
+ strategy,
3146
+ commitMessage: options.commitMessage,
3147
+ cleanupWorktree: options.cleanupWorktree
3148
+ });
3149
+ }
3150
+ task.status = "approved";
3151
+ task.landResult = landResult;
3152
+ this.saveAndEmit(task);
3153
+ return landResult;
3154
+ }
3155
+ async rejectTask(taskId, reason) {
3156
+ const task = this.getTaskOrThrow(taskId);
3157
+ if (task.status === "running" || task.status === "queued" || task.status === "needs_input") {
3158
+ throw new Error(`Task ${taskId} is still ${task.status}. Call cancel_task first.`);
3159
+ }
3160
+ if (task.status === "approved") {
3161
+ throw new Error(`Task ${taskId} has already been approved.`);
3162
+ }
3163
+ await this.cleanupIsolatedWorkspace(task);
3164
+ task.status = "rejected";
3165
+ if (reason) {
3166
+ task.rejectionReason = reason;
3167
+ }
3168
+ this.saveAndEmit(task);
3169
+ return task;
3170
+ }
3171
+ async cleanupIsolatedWorkspace(task) {
3172
+ if (task.workspaceMode === "worktree") {
3173
+ await discardWorktree(this.config.dataDir, task.workspaceHandle, this.env);
3174
+ } else if (task.workspaceMode === "staging") {
3175
+ discardStagingWorkspace(this.config.dataDir, task.workspaceHandle);
3176
+ }
3177
+ }
3178
+ async getDeliverable(taskId) {
3179
+ const task = this.getTaskOrThrow(taskId);
3180
+ const latestRound = task.rounds[task.rounds.length - 1];
3181
+ let diffStat = {
3182
+ files: [],
3183
+ summaryStat: "",
3184
+ patch: "",
3185
+ totalLines: 0,
3186
+ truncated: false,
3187
+ offset: 0
3188
+ };
3189
+ if (task.status !== "rejected" && fs9.existsSync(task.workspaceHandle.executionDir)) {
3190
+ try {
3191
+ diffStat = await this.getDiff(taskId, { mode: "stat" });
3192
+ } catch {
3193
+ }
3194
+ }
3195
+ const verificationResults = latestRound?.verification ?? [];
3196
+ const allVerificationsPassed = verificationResults.length === 0 || verificationResults.every((v) => v.passed);
3197
+ const durationMs = latestRound?.startedAt && latestRound?.finishedAt ? Date.parse(latestRound.finishedAt) - Date.parse(latestRound.startedAt) : void 0;
3198
+ const recommendedNextActions = [];
3199
+ if (task.status === "running" || task.status === "queued") {
3200
+ recommendedNextActions.push("Call wait_task to monitor progress until awaiting_review.");
3201
+ } else if (task.status === "needs_input") {
3202
+ recommendedNextActions.push("Call respond_task_input to answer the agent's pending dialog.");
3203
+ } else if (task.status === "awaiting_review") {
3204
+ if (diffStat.files.length > 0) {
3205
+ recommendedNextActions.push("Inspect changes with get_task_diff and read_task_file.");
3206
+ }
3207
+ if (!allVerificationsPassed) {
3208
+ recommendedNextActions.push(
3209
+ "One or more verification commands failed; review output and call request_changes or reject_task."
3210
+ );
3211
+ } else {
3212
+ recommendedNextActions.push(
3213
+ "If satisfied, call approve_task to land changes; otherwise call request_changes or reject_task."
3214
+ );
3215
+ }
3216
+ } else if (task.status === "failed") {
3217
+ recommendedNextActions.push(
3218
+ "Inspect get_task_logs, then call request_changes to retry in the preserved workspace or reject_task to clean up."
3219
+ );
3220
+ }
3221
+ return {
3222
+ taskId: task.id,
3223
+ title: task.title,
3224
+ agent: task.agent,
3225
+ status: task.status,
3226
+ currentRound: task.currentRound,
3227
+ sourceWorkspace: task.workspace,
3228
+ executionDir: task.workspaceHandle.executionDir,
3229
+ workspaceMode: task.workspaceMode,
3230
+ ...task.workspaceHandle.branchName ? { branchName: task.workspaceHandle.branchName } : {},
3231
+ ...task.sessionId ? { sessionId: task.sessionId } : {},
3232
+ ...durationMs !== void 0 ? { durationMs } : {},
3233
+ acceptanceCriteria: task.acceptanceCriteria,
3234
+ finalSummary: latestRound?.finalSummary ?? "",
3235
+ ...latestRound?.error ? { error: latestRound.error } : {},
3236
+ toolCallsCount: latestRound?.toolCallsCount ?? 0,
3237
+ toolDigest: latestRound?.toolDigest ?? [],
3238
+ ...latestRound?.usage ? { usage: latestRound.usage } : {},
3239
+ changedFiles: diffStat.files,
3240
+ diffStatSummary: diffStat.summaryStat,
3241
+ verificationResults,
3242
+ allVerificationsPassed,
3243
+ ...task.pendingInput ? { pendingInput: task.pendingInput } : {},
3244
+ ...task.landResult ? { landResult: task.landResult } : {},
3245
+ recommendedNextActions
3246
+ };
3247
+ }
3248
+ };
3249
+
3250
+ // src/mcp/prompts.ts
3251
+ import { z as z2 } from "zod";
3252
+ function registerPrompts(server) {
3253
+ server.registerPrompt(
3254
+ "delegate_and_review",
3255
+ {
3256
+ title: "Delegate Task & Review Deliverable SOP",
3257
+ description: "Standard operating workflow for Gemini to delegate coding work to pi/opencode, inspect diffs, verify checks, request revisions, and approve or reject.",
3258
+ argsSchema: {
3259
+ goal: z2.string().describe("What you want the coding agent to accomplish."),
3260
+ workspace: z2.string().describe("Target repository or folder path."),
3261
+ preferredAgent: z2.enum(["pi", "opencode"]).optional().describe("Preferred agent (defaults to pi).")
3262
+ }
3263
+ },
3264
+ ({ goal, workspace, preferredAgent }) => ({
3265
+ messages: [
3266
+ {
3267
+ role: "user",
3268
+ content: {
3269
+ type: "text",
3270
+ text: [
3271
+ "Follow this Tech Lead delegation & verification workflow:",
3272
+ "",
3273
+ `1. If you haven't checked agent availability yet, call \`list_agents\` (or \`doctor\` with workspace="${workspace}").`,
3274
+ `2. Call \`dispatch_task\` targeting agent="${preferredAgent ?? "pi"}" and workspace="${workspace}" for the goal:`,
3275
+ ` "${goal}"`,
3276
+ " Always provide explicit `acceptanceCriteria` and deterministic `verifyCommands` (tests / typecheck / lint) when applicable.",
3277
+ "3. If the task is still running after `dispatch_task` returns, call `wait_task` until status becomes `awaiting_review` or `needs_input`.",
3278
+ "4. If status is `needs_input`, review the agent's dialog question and answer via `respond_task_input`.",
3279
+ "5. Once `awaiting_review`, inspect the deliverable thoroughly:",
3280
+ " - `get_task_deliverable` to check summary, changed files, and verification results;",
3281
+ " - `get_task_diff` and `read_task_file` to review the actual code;",
3282
+ " - `verify_task` if you want to run additional checks yourself.",
3283
+ "6. Decide:",
3284
+ " - If issues remain: call `request_changes` with concrete feedback and file/line comments;",
3285
+ " - If all checks and code meet standards: call `approve_task` (default `apply_patch`);",
3286
+ " - If the approach should be abandoned: call `reject_task` to clean up without touching the main workspace."
3287
+ ].join("\n")
3288
+ }
3289
+ }
3290
+ ]
3291
+ })
3292
+ );
3293
+ }
3294
+
3295
+ // src/mcp/resources.ts
3296
+ import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
3297
+ function extractVar(val) {
3298
+ if (Array.isArray(val)) return val[0] ?? "";
3299
+ return val ?? "";
3300
+ }
3301
+ function registerResources(server, taskManager) {
3302
+ server.registerResource(
3303
+ "task-deliverable",
3304
+ new ResourceTemplate("task://{taskId}/deliverable", {
3305
+ list: async () => ({
3306
+ resources: taskManager.listTasks({ limit: 30 }).map((t) => ({
3307
+ uri: `task://${t.id}/deliverable`,
3308
+ name: `${t.title} (${t.status})`,
3309
+ mimeType: "application/json"
3310
+ }))
3311
+ })
3312
+ }),
3313
+ {
3314
+ title: "Task Deliverable Packet",
3315
+ description: "Structured JSON deliverable summary for a delegated agent task.",
3316
+ mimeType: "application/json"
3317
+ },
3318
+ async (uri, variables) => {
3319
+ const taskId = extractVar(variables.taskId);
3320
+ const packet = await taskManager.getDeliverable(taskId);
3321
+ return {
3322
+ contents: [
3323
+ {
3324
+ uri: uri.href,
3325
+ mimeType: "application/json",
3326
+ text: JSON.stringify(packet, null, 2)
3327
+ }
3328
+ ]
3329
+ };
3330
+ }
3331
+ );
3332
+ server.registerResource(
3333
+ "task-diff",
3334
+ new ResourceTemplate("task://{taskId}/diff", {
3335
+ list: async () => ({
3336
+ resources: taskManager.listTasks({ limit: 30 }).filter((t) => t.status !== "rejected").map((t) => ({
3337
+ uri: `task://${t.id}/diff`,
3338
+ name: `Diff: ${t.title}`,
3339
+ mimeType: "text/x-diff"
3340
+ }))
3341
+ })
3342
+ }),
3343
+ {
3344
+ title: "Task Unified Diff",
3345
+ description: "Unified diff patch produced inside the task's isolated workspace.",
3346
+ mimeType: "text/x-diff"
3347
+ },
3348
+ async (uri, variables) => {
3349
+ const taskId = extractVar(variables.taskId);
3350
+ const diff = await taskManager.getDiff(taskId, { mode: "patch", maxLines: 1500 });
3351
+ return {
3352
+ contents: [
3353
+ {
3354
+ uri: uri.href,
3355
+ mimeType: "text/x-diff",
3356
+ text: diff.patch || diff.summaryStat || ""
3357
+ }
3358
+ ]
3359
+ };
3360
+ }
3361
+ );
3362
+ }
3363
+
3364
+ // src/mcp/tools.ts
3365
+ import { z as z3 } from "zod";
3366
+
3367
+ // src/setup/doctor.ts
3368
+ import fs10 from "fs";
3369
+ import os5 from "os";
3370
+ import path9 from "path";
3371
+ function checkDirectoryWritable(dirPath) {
3372
+ try {
3373
+ fs10.mkdirSync(dirPath, { recursive: true });
3374
+ const probeFile = path9.join(dirPath, `.write-probe-${process.pid}`);
3375
+ fs10.writeFileSync(probeFile, "ok", "utf8");
3376
+ fs10.unlinkSync(probeFile);
3377
+ return { ok: true };
3378
+ } catch (err) {
3379
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
3380
+ }
3381
+ }
3382
+ async function runDoctor(config, adapters, workspace, baseEnv = process.env) {
3383
+ const env = buildAugmentedEnv(baseEnv, { probeLoginShell: true });
3384
+ const checks = [];
3385
+ const sandboxHints = [];
3386
+ const nodeMajor = Number.parseInt(process.versions.node.split(".")[0] ?? "0", 10);
3387
+ checks.push({
3388
+ name: "node",
3389
+ ok: nodeMajor >= 20,
3390
+ detail: `Node.js v${process.versions.node} (${process.execPath})`,
3391
+ ...nodeMajor < 20 ? { remediation: "Install Node.js >= 20.0.0." } : {}
3392
+ });
3393
+ const gitBin = resolveBinary("git", void 0, env);
3394
+ if (gitBin.found && gitBin.path) {
3395
+ const gitVer = await probeBinaryVersion(gitBin.path, ["--version"], env);
3396
+ checks.push({
3397
+ name: "git",
3398
+ ok: gitVer.ok,
3399
+ detail: gitVer.ok ? `${gitVer.version} (${gitBin.path})` : `Found at ${gitBin.path} but failed: ${gitVer.error}`,
3400
+ ...gitVer.ok ? {} : { remediation: "Ensure Xcode Command Line Tools / git is functional inside sandbox." }
3401
+ });
3402
+ } else {
3403
+ checks.push({
3404
+ name: "git",
3405
+ ok: false,
3406
+ detail: gitBin.error ?? "git not found",
3407
+ remediation: "Install git (`xcode-select --install`) and ensure `/usr/bin` is reachable."
3408
+ });
3409
+ }
3410
+ const dataWrite = checkDirectoryWritable(config.dataDir);
3411
+ checks.push({
3412
+ name: "dataDir",
3413
+ ok: dataWrite.ok,
3414
+ detail: dataWrite.ok ? `Writable: ${config.dataDir}` : `Not writable (${config.dataDir}): ${dataWrite.error}`,
3415
+ ...dataWrite.ok ? {} : {
3416
+ remediation: "In Gemini Mac Local MCP -> Customize Sandbox, ensure `~/.local/share/gemini-agent-bridge` is writable."
3417
+ }
3418
+ });
3419
+ const worktreeWrite = checkDirectoryWritable(getWorktreesDir(config.dataDir));
3420
+ checks.push({
3421
+ name: "worktreesDir",
3422
+ ok: worktreeWrite.ok,
3423
+ detail: worktreeWrite.ok ? `Writable: ${getWorktreesDir(config.dataDir)}` : `Not writable: ${worktreeWrite.error}`
3424
+ });
3425
+ const agents = await adapters.detectAll(config, env, false);
3426
+ const anyAgentOk = agents.some((a) => a.available);
3427
+ for (const agent of agents) {
3428
+ checks.push({
3429
+ name: `agent:${agent.id}`,
3430
+ ok: agent.available,
3431
+ detail: agent.available ? `${agent.version ?? "ok"} (${agent.binaryPath})` : agent.error ?? `${agent.id} unavailable`,
3432
+ ...agent.available ? {} : {
3433
+ remediation: agent.id === "pi" ? `Run \`gemini-agent-bridge init\` or allow ~/Library/pnpm in Gemini Mac Customize Sandbox.` : `Run \`gemini-agent-bridge init\` or allow ~/.opencode in Gemini Mac Customize Sandbox.`
3434
+ }
3435
+ });
3436
+ }
3437
+ if (workspace) {
3438
+ const validation = validateWorkspacePath(workspace, config);
3439
+ let gitState = "non-git";
3440
+ if (validation.allowed) {
3441
+ gitState = await isGitRepo(validation.resolvedPath, env) ? "git-repo (worktree ready)" : "non-git (staging/direct)";
3442
+ }
3443
+ checks.push({
3444
+ name: "workspace",
3445
+ ok: validation.allowed,
3446
+ detail: validation.allowed ? `Allowed: ${validation.resolvedPath} [${gitState}]${validation.warning ? ` \u2014 ${validation.warning}` : ""}` : validation.reason ?? `Denied: ${workspace}`,
3447
+ ...validation.allowed ? {} : {
3448
+ remediation: "Add this directory to `allowedWorkspaces` in ~/.local/share/gemini-agent-bridge/config.json or pass `--workspace <dir>`."
3449
+ }
3450
+ });
3451
+ }
3452
+ if (process.platform === "darwin") {
3453
+ const home = os5.homedir();
3454
+ sandboxHints.push(
3455
+ "Gemini Mac Local MCP sandbox checklist (More -> Connectors -> gemini-agent-bridge -> Customize Sandbox):",
3456
+ "1. Enable Network access (so pi / opencode can call LLM provider APIs).",
3457
+ `2. Allow read/write access to your target project folders (e.g. ${path9.join(home, "Documents")}).`,
3458
+ `3. Allow access to agent binaries & state dirs: ${path9.join(home, "Library/pnpm")}, ${path9.join(home, ".opencode")}, ${path9.join(home, ".pi")}, ${path9.join(home, ".config/opencode")}, ${path9.join(home, ".local/share/opencode")}.`
3459
+ );
3460
+ }
3461
+ const criticalChecks = checks.filter(
3462
+ (c) => !c.name.startsWith("agent:") || !anyAgentOk
3463
+ );
3464
+ const overallOk = anyAgentOk && criticalChecks.every((c) => c.ok) && (workspace ? checks.find((c) => c.name === "workspace")?.ok !== false : true);
3465
+ return {
3466
+ overallOk,
3467
+ platform: `${process.platform}/${process.arch}`,
3468
+ nodeVersion: process.versions.node,
3469
+ dataDir: config.dataDir,
3470
+ configPath: config.configPath,
3471
+ configFileExists: config.configFileExists,
3472
+ checks,
3473
+ agents,
3474
+ sandboxHints
3475
+ };
3476
+ }
3477
+ function formatDoctorReport(report) {
3478
+ const lines = [
3479
+ `Gemini Agent Bridge Doctor \u2014 ${report.overallOk ? "HEALTHY" : "ISSUES DETECTED"}`,
3480
+ `Platform: ${report.platform} | Node: v${report.nodeVersion}`,
3481
+ `Data Dir: ${report.dataDir}`,
3482
+ `Config: ${report.configPath} (${report.configFileExists ? "exists" : "using defaults"})`,
3483
+ "",
3484
+ "Checks:"
3485
+ ];
3486
+ for (const chk of report.checks) {
3487
+ const badge = chk.ok ? "[PASS]" : "[FAIL]";
3488
+ lines.push(` ${badge} ${chk.name}: ${chk.detail}`);
3489
+ if (!chk.ok && chk.remediation) {
3490
+ lines.push(` -> Fix: ${chk.remediation}`);
3491
+ }
3492
+ }
3493
+ if (report.sandboxHints.length > 0) {
3494
+ lines.push("", ...report.sandboxHints);
3495
+ }
3496
+ return lines.join("\n");
3497
+ }
3498
+
3499
+ // src/mcp/tools.ts
3500
+ function textResult(text) {
3501
+ return {
3502
+ content: [{ type: "text", text }]
3503
+ };
3504
+ }
3505
+ function errorResult(err) {
3506
+ const message = err instanceof Error ? err.message : String(err);
3507
+ return {
3508
+ isError: true,
3509
+ content: [{ type: "text", text: `Error: ${message}` }]
3510
+ };
3511
+ }
3512
+ function makeProgressSender(extra) {
3513
+ const token = extra._meta?.progressToken;
3514
+ if (token === void 0) return void 0;
3515
+ return (info) => {
3516
+ void extra.sendNotification({
3517
+ method: "notifications/progress",
3518
+ params: {
3519
+ progressToken: token,
3520
+ progress: info.progress,
3521
+ ...info.total !== void 0 ? { total: info.total } : {},
3522
+ message: info.message
3523
+ }
3524
+ }).catch(() => {
3525
+ });
3526
+ };
3527
+ }
3528
+ function formatDeliverableMarkdown(d) {
3529
+ const lines = [
3530
+ `# Deliverable Packet: ${d.title} (\`${d.taskId}\`)`,
3531
+ `- **Status**: \`${d.status}\` | **Agent**: \`${d.agent}\` | **Round**: ${d.currentRound}`,
3532
+ `- **Source Workspace**: \`${d.sourceWorkspace}\``,
3533
+ `- **Isolated Workspace** (\`${d.workspaceMode}\`): \`${d.executionDir}\`${d.branchName ? ` (branch \`${d.branchName}\`)` : ""}`
3534
+ ];
3535
+ if (d.sessionId) lines.push(`- **Session ID**: \`${d.sessionId}\``);
3536
+ if (d.durationMs !== void 0) {
3537
+ lines.push(`- **Round Duration**: ${(d.durationMs / 1e3).toFixed(1)}s`);
3538
+ }
3539
+ if (d.usage) {
3540
+ const parts = [];
3541
+ if (d.usage.totalTokens !== void 0) parts.push(`total=${d.usage.totalTokens}`);
3542
+ if (d.usage.inputTokens !== void 0) parts.push(`in=${d.usage.inputTokens}`);
3543
+ if (d.usage.outputTokens !== void 0) parts.push(`out=${d.usage.outputTokens}`);
3544
+ if (d.usage.costUsd !== void 0) parts.push(`cost=$${d.usage.costUsd.toFixed(4)}`);
3545
+ if (parts.length > 0) lines.push(`- **Usage**: ${parts.join(", ")}`);
3546
+ }
3547
+ if (d.error) {
3548
+ lines.push("", "## Error", "```", d.error, "```");
3549
+ }
3550
+ if (d.pendingInput) {
3551
+ lines.push(
3552
+ "",
3553
+ "## Pending Input Required",
3554
+ `- **requestId**: \`${d.pendingInput.requestId}\``,
3555
+ `- **method**: \`${d.pendingInput.method}\``,
3556
+ `- **title**: ${d.pendingInput.title}`,
3557
+ ...d.pendingInput.message ? [`- **message**: ${d.pendingInput.message}`] : [],
3558
+ ...d.pendingInput.options ? [`- **options**: ${d.pendingInput.options.join(" | ")}`] : []
3559
+ );
3560
+ }
3561
+ if (d.acceptanceCriteria.length > 0) {
3562
+ lines.push("", "## Acceptance Criteria");
3563
+ for (const c of d.acceptanceCriteria) {
3564
+ lines.push(`- [ ] ${c}`);
3565
+ }
3566
+ }
3567
+ lines.push("", "## Agent Final Summary", d.finalSummary || "_(no summary text emitted)_");
3568
+ lines.push(
3569
+ "",
3570
+ `## Changed Files (${d.changedFiles.length})`,
3571
+ d.changedFiles.length === 0 ? "_No file modifications detected._" : d.changedFiles.map((f) => {
3572
+ const counts = f.additions !== void 0 || f.deletions !== void 0 ? ` (+${f.additions ?? 0}/-${f.deletions ?? 0})` : f.binary ? " (binary)" : "";
3573
+ return `- [${f.status}] \`${f.path}\`${counts}`;
3574
+ }).join("\n")
3575
+ );
3576
+ if (d.verificationResults.length > 0) {
3577
+ lines.push(
3578
+ "",
3579
+ `## Verification Results (${d.allVerificationsPassed ? "ALL PASSED" : "FAILURES PRESENT"})`
3580
+ );
3581
+ for (const v of d.verificationResults) {
3582
+ lines.push(
3583
+ `- \`${v.command}\`: **${v.passed ? "PASS" : "FAIL"}** (exit=${String(v.exitCode)}, ${v.durationMs}ms${v.timedOut ? ", TIMED OUT" : ""})`
3584
+ );
3585
+ if (!v.passed && (v.stderrTail || v.stdoutTail)) {
3586
+ const snippet = (v.stderrTail || v.stdoutTail).slice(-600);
3587
+ lines.push("```", snippet, "```");
3588
+ }
3589
+ }
3590
+ }
3591
+ if (d.toolDigest.length > 0) {
3592
+ lines.push(
3593
+ "",
3594
+ `## Tool Activity (${d.toolCallsCount} total calls, showing up to 20)`,
3595
+ ...d.toolDigest.slice(0, 20).map((item) => `- ${item}`)
3596
+ );
3597
+ }
3598
+ if (d.landResult) {
3599
+ lines.push("", "## Landing Result", d.landResult.message);
3600
+ }
3601
+ if (d.recommendedNextActions.length > 0) {
3602
+ lines.push("", "## Recommended Next Actions");
3603
+ for (const action of d.recommendedNextActions) {
3604
+ lines.push(`- ${action}`);
3605
+ }
3606
+ }
3607
+ return lines.join("\n");
3608
+ }
3609
+ function formatTaskSummaryRow(t) {
3610
+ return `- \`${t.id}\` [${t.status}] (${t.agent}, round ${t.currentRound}) \u2014 **${t.title}** | workspace: \`${t.workspace}\` | updated: ${t.updatedAt}`;
3611
+ }
3612
+ function registerAllTools(server, deps) {
3613
+ const { config, adapters, taskManager } = deps;
3614
+ server.registerTool(
3615
+ "list_agents",
3616
+ {
3617
+ title: "List Available Coding Agents",
3618
+ description: "Inspect installed local AI coding agents (pi, opencode), their resolved binary paths, versions, capabilities, and optionally available models.",
3619
+ inputSchema: {
3620
+ includeModels: z3.boolean().optional().describe("Also probe available model lists for detected agents (slower).")
3621
+ },
3622
+ annotations: {
3623
+ readOnlyHint: true,
3624
+ destructiveHint: false,
3625
+ idempotentHint: true,
3626
+ openWorldHint: false
3627
+ }
3628
+ },
3629
+ async ({ includeModels }) => {
3630
+ try {
3631
+ const agents = await adapters.detectAll(
3632
+ config,
3633
+ taskManager.getAugmentedEnv(),
3634
+ Boolean(includeModels)
3635
+ );
3636
+ return textResult(JSON.stringify({ defaultAgent: config.defaultAgent, agents }, null, 2));
3637
+ } catch (err) {
3638
+ return errorResult(err);
3639
+ }
3640
+ }
3641
+ );
3642
+ server.registerTool(
3643
+ "doctor",
3644
+ {
3645
+ title: "Diagnose Runtime & Sandbox Readiness",
3646
+ description: "Run inside the MCP server's live process/sandbox to verify Node, Git, pi, opencode, state directory permissions, and optional target workspace access.",
3647
+ inputSchema: {
3648
+ workspace: z3.string().optional().describe("Optional workspace path to test read/write allowlist and git status.")
3649
+ },
3650
+ annotations: {
3651
+ readOnlyHint: true,
3652
+ destructiveHint: false,
3653
+ idempotentHint: true,
3654
+ openWorldHint: false
3655
+ }
3656
+ },
3657
+ async ({ workspace }) => {
3658
+ try {
3659
+ const report = await runDoctor(config, adapters, workspace, taskManager.getAugmentedEnv());
3660
+ return textResult(
3661
+ `${formatDoctorReport(report)}
3662
+
3663
+ \`\`\`json
3664
+ ${JSON.stringify(report, null, 2)}
3665
+ \`\`\``
3666
+ );
3667
+ } catch (err) {
3668
+ return errorResult(err);
3669
+ }
3670
+ }
3671
+ );
3672
+ server.registerTool(
3673
+ "dispatch_task",
3674
+ {
3675
+ title: "Dispatch Task to Coding Agent",
3676
+ description: "Assign a coding or analysis task to a local agent (pi or opencode) inside an isolated workspace (git worktree by default). Returns a deliverable packet if completed within waitSeconds, or a taskId to poll via wait_task.",
3677
+ inputSchema: {
3678
+ agent: AgentIdSchema.optional().describe('Target agent: "pi" or "opencode".'),
3679
+ workspace: z3.string().min(1).describe("Absolute or ~-prefixed path to the target project."),
3680
+ prompt: z3.string().min(1).describe("Detailed task prompt for the agent."),
3681
+ title: z3.string().optional().describe("Short human-readable task title."),
3682
+ acceptanceCriteria: z3.array(z3.string()).optional().describe("Checklist of acceptance criteria to evaluate during review."),
3683
+ workspaceMode: WorkspaceModeSchema.optional().describe(
3684
+ 'Isolation mode: "worktree" (default for git), "staging", "direct", or "readonly".'
3685
+ ),
3686
+ baseRef: z3.string().optional().describe("Optional git ref/commit/branch to branch worktree from (defaults to HEAD)."),
3687
+ model: z3.string().optional().describe("Optional model override for the chosen agent."),
3688
+ thinking: z3.string().optional().describe("Optional thinking level for pi (off, minimal, low, medium, high, xhigh, max)."),
3689
+ agentProfile: z3.string().optional().describe('Optional agent profile (e.g. OpenCode "build"|"plan", or pi "readonly"|"no-bash").'),
3690
+ verifyCommands: z3.array(z3.string()).optional().describe("Shell commands run deterministically after the agent finishes (e.g. `npm test`)."),
3691
+ interactionPolicy: InteractionPolicySchema.optional().describe(
3692
+ 'How to handle agent dialogs: "ask_orchestrator" (default), "auto_approve", or "deny_interactive".'
3693
+ ),
3694
+ waitSeconds: z3.number().int().min(0).max(120).optional().describe("Seconds to wait for immediate completion (0..120, default 15)."),
3695
+ timeoutSeconds: z3.number().int().min(30).max(3600).optional().describe("Overall execution timeout in seconds (30..3600, default 900).")
3696
+ },
3697
+ annotations: {
3698
+ readOnlyHint: false,
3699
+ destructiveHint: false,
3700
+ idempotentHint: false,
3701
+ openWorldHint: true
3702
+ }
3703
+ },
3704
+ async (args, extra) => {
3705
+ try {
3706
+ const res = await taskManager.dispatchTask(args, makeProgressSender(extra));
3707
+ if (res.settledWithinWait && res.deliverable) {
3708
+ return textResult(formatDeliverableMarkdown(res.deliverable));
3709
+ }
3710
+ return textResult(
3711
+ [
3712
+ `Task dispatched and running asynchronously:`,
3713
+ `- **taskId**: \`${res.task.id}\``,
3714
+ `- **status**: \`${res.task.status}\``,
3715
+ `- **agent**: \`${res.task.agent}\``,
3716
+ `- **executionDir**: \`${res.task.workspaceHandle.executionDir}\``,
3717
+ res.task.workspaceHandle.branchName ? `- **branch**: \`${res.task.workspaceHandle.branchName}\`` : "",
3718
+ "",
3719
+ "Next: call `wait_task` with this `taskId` to monitor progress until `awaiting_review` or `needs_input`."
3720
+ ].filter(Boolean).join("\n")
3721
+ );
3722
+ } catch (err) {
3723
+ return errorResult(err);
3724
+ }
3725
+ }
3726
+ );
3727
+ server.registerTool(
3728
+ "wait_task",
3729
+ {
3730
+ title: "Wait for Running Task",
3731
+ description: "Long-poll a running task up to waitSeconds (max 120s) while streaming progress notifications. Returns immediately when the task reaches awaiting_review, needs_input, failed, or cancelled.",
3732
+ inputSchema: {
3733
+ taskId: z3.string().min(1).describe("Task ID returned by dispatch_task."),
3734
+ waitSeconds: z3.number().int().min(0).max(120).optional().describe("Max seconds to wait in this call (0..120, default 30).")
3735
+ },
3736
+ annotations: {
3737
+ readOnlyHint: true,
3738
+ destructiveHint: false,
3739
+ idempotentHint: true,
3740
+ openWorldHint: false
3741
+ }
3742
+ },
3743
+ async ({ taskId, waitSeconds }, extra) => {
3744
+ try {
3745
+ const task = await taskManager.waitTask(
3746
+ taskId,
3747
+ waitSeconds ?? 30,
3748
+ makeProgressSender(extra)
3749
+ );
3750
+ if (task.status !== "running" && task.status !== "queued") {
3751
+ const deliverable = await taskManager.getDeliverable(taskId);
3752
+ return textResult(formatDeliverableMarkdown(deliverable));
3753
+ }
3754
+ const logs = taskManager.getLogs(taskId, { tail: 8 });
3755
+ return textResult(
3756
+ [
3757
+ `Task \`${task.id}\` is still \`${task.status}\` (round ${task.currentRound}).`,
3758
+ "Recent activity:",
3759
+ ...logs.events.map((e) => `- [${e.type}] ${e.summary}`),
3760
+ "",
3761
+ "Call `wait_task` again to continue waiting, or `steer_task` / `cancel_task`."
3762
+ ].join("\n")
3763
+ );
3764
+ } catch (err) {
3765
+ return errorResult(err);
3766
+ }
3767
+ }
3768
+ );
3769
+ server.registerTool(
3770
+ "steer_task",
3771
+ {
3772
+ title: "Steer or Follow-up Running Task",
3773
+ description: 'Send mid-flight steering or queued follow-up instructions to a running task (mode: "steer" or "follow_up").',
3774
+ inputSchema: {
3775
+ taskId: z3.string().min(1),
3776
+ message: z3.string().min(1).describe("New instruction or course correction."),
3777
+ mode: z3.enum(["steer", "follow_up"]).optional().describe('"steer" redirects immediately; "follow_up" runs after current turn.')
3778
+ },
3779
+ annotations: {
3780
+ readOnlyHint: false,
3781
+ destructiveHint: false,
3782
+ idempotentHint: false,
3783
+ openWorldHint: true
3784
+ }
3785
+ },
3786
+ async ({ taskId, message, mode }) => {
3787
+ try {
3788
+ const result = await taskManager.steerTask(taskId, message, mode ?? "steer");
3789
+ return textResult(
3790
+ `Delivered \`${result.mode}\` instruction to task \`${result.taskId}\` (status=\`${result.status}\`).`
3791
+ );
3792
+ } catch (err) {
3793
+ return errorResult(err);
3794
+ }
3795
+ }
3796
+ );
3797
+ server.registerTool(
3798
+ "respond_task_input",
3799
+ {
3800
+ title: "Respond to Agent Dialog Input",
3801
+ description: "Answer a pending interactive prompt (status=needs_input, e.g. pi extension select/confirm/input dialog) so the task can resume.",
3802
+ inputSchema: {
3803
+ taskId: z3.string().min(1),
3804
+ requestId: z3.string().optional().describe("Pending requestId (defaults to the active pendingInput.requestId)."),
3805
+ confirmed: z3.boolean().optional().describe("For confirm dialogs: true or false."),
3806
+ value: z3.string().optional().describe("For select/input/editor dialogs: chosen or entered string."),
3807
+ cancelled: z3.boolean().optional().describe("Set true to cancel/dismiss the dialog.")
3808
+ },
3809
+ annotations: {
3810
+ readOnlyHint: false,
3811
+ destructiveHint: false,
3812
+ idempotentHint: false,
3813
+ openWorldHint: false
3814
+ }
3815
+ },
3816
+ async ({ taskId, requestId, confirmed, value, cancelled }) => {
3817
+ try {
3818
+ const res = await taskManager.respondTaskInput(
3819
+ taskId,
3820
+ { confirmed, value, cancelled },
3821
+ requestId
3822
+ );
3823
+ return textResult(
3824
+ `Responded to input request \`${res.requestId}\` on task \`${res.taskId}\`. Task resumed.`
3825
+ );
3826
+ } catch (err) {
3827
+ return errorResult(err);
3828
+ }
3829
+ }
3830
+ );
3831
+ server.registerTool(
3832
+ "cancel_task",
3833
+ {
3834
+ title: "Cancel Running Task",
3835
+ description: "Gracefully abort a running task and optionally discard its isolated worktree/staging workspace.",
3836
+ inputSchema: {
3837
+ taskId: z3.string().min(1),
3838
+ cleanupWorktree: z3.boolean().optional().describe("If true, also remove the isolated worktree/branch immediately.")
3839
+ },
3840
+ annotations: {
3841
+ readOnlyHint: false,
3842
+ destructiveHint: true,
3843
+ idempotentHint: true,
3844
+ openWorldHint: false
3845
+ }
3846
+ },
3847
+ async ({ taskId, cleanupWorktree }) => {
3848
+ try {
3849
+ const task = await taskManager.cancelTask(taskId, Boolean(cleanupWorktree));
3850
+ return textResult(
3851
+ `Task \`${task.id}\` is now \`${task.status}\`${cleanupWorktree ? " (isolated workspace cleaned up)" : ""}.`
3852
+ );
3853
+ } catch (err) {
3854
+ return errorResult(err);
3855
+ }
3856
+ }
3857
+ );
3858
+ server.registerTool(
3859
+ "list_tasks",
3860
+ {
3861
+ title: "List Director Tasks",
3862
+ description: "List persisted tasks across sessions with status, agent, round count, and workspace info.",
3863
+ inputSchema: {
3864
+ status: z3.enum([
3865
+ "queued",
3866
+ "running",
3867
+ "needs_input",
3868
+ "awaiting_review",
3869
+ "approved",
3870
+ "rejected",
3871
+ "failed",
3872
+ "cancelled"
3873
+ ]).optional(),
3874
+ agent: AgentIdSchema.optional(),
3875
+ workspace: z3.string().optional(),
3876
+ limit: z3.number().int().min(1).max(200).optional()
3877
+ },
3878
+ annotations: {
3879
+ readOnlyHint: true,
3880
+ destructiveHint: false,
3881
+ idempotentHint: true,
3882
+ openWorldHint: false
3883
+ }
3884
+ },
3885
+ async (filters) => {
3886
+ try {
3887
+ const tasks = taskManager.listTasks(filters);
3888
+ if (tasks.length === 0) {
3889
+ return textResult("No matching tasks found.");
3890
+ }
3891
+ return textResult(
3892
+ `Found ${tasks.length} task(s):
3893
+ ${tasks.map(formatTaskSummaryRow).join("\n")}`
3894
+ );
3895
+ } catch (err) {
3896
+ return errorResult(err);
3897
+ }
3898
+ }
3899
+ );
3900
+ server.registerTool(
3901
+ "get_task_deliverable",
3902
+ {
3903
+ title: "Get Task Deliverable Packet",
3904
+ description: "Retrieve the structured review packet for a task: summary, changed files, verification results, usage/cost, pending inputs, and recommended next actions.",
3905
+ inputSchema: {
3906
+ taskId: z3.string().min(1)
3907
+ },
3908
+ annotations: {
3909
+ readOnlyHint: true,
3910
+ destructiveHint: false,
3911
+ idempotentHint: true,
3912
+ openWorldHint: false
3913
+ }
3914
+ },
3915
+ async ({ taskId }) => {
3916
+ try {
3917
+ const packet = await taskManager.getDeliverable(taskId);
3918
+ return textResult(formatDeliverableMarkdown(packet));
3919
+ } catch (err) {
3920
+ return errorResult(err);
3921
+ }
3922
+ }
3923
+ );
3924
+ server.registerTool(
3925
+ "get_task_diff",
3926
+ {
3927
+ title: "Inspect Task Diff",
3928
+ description: "View unified diff patches (including newly created files) or file stats inside the task's isolated workspace, supporting path filters and line pagination.",
3929
+ inputSchema: {
3930
+ taskId: z3.string().min(1),
3931
+ paths: z3.array(z3.string()).optional().describe("Optional subset of relative file paths."),
3932
+ mode: z3.enum(["stat", "patch"]).optional().describe('Defaults to "patch".'),
3933
+ offset: z3.number().int().min(0).optional().describe("Starting patch line offset (default 0)."),
3934
+ maxLines: z3.number().int().min(1).max(2e3).optional().describe("Maximum patch lines to return (default 400).")
3935
+ },
3936
+ annotations: {
3937
+ readOnlyHint: true,
3938
+ destructiveHint: false,
3939
+ idempotentHint: true,
3940
+ openWorldHint: false
3941
+ }
3942
+ },
3943
+ async ({ taskId, paths, mode, offset, maxLines }) => {
3944
+ try {
3945
+ const diff = await taskManager.getDiff(taskId, {
3946
+ paths,
3947
+ mode: mode ?? "patch",
3948
+ offset,
3949
+ maxLines
3950
+ });
3951
+ const lines = [
3952
+ `# Diff for \`${taskId}\` (${diff.files.length} changed file(s))`
3953
+ ];
3954
+ if (diff.summaryStat) {
3955
+ lines.push("", "## Stat", "```", diff.summaryStat, "```");
3956
+ }
3957
+ if (diff.note) {
3958
+ lines.push("", `> Note: ${diff.note}`);
3959
+ }
3960
+ if ((mode ?? "patch") === "patch") {
3961
+ lines.push(
3962
+ "",
3963
+ `## Patch (lines ${diff.offset}..${diff.offset + (diff.patch ? diff.patch.split("\n").length : 0)} of ${diff.totalLines}${diff.truncated ? ", truncated \u2014 pass offset to read more" : ""})`,
3964
+ diff.patch ? `\`\`\`diff
3965
+ ${diff.patch}
3966
+ \`\`\`` : "_(empty patch)_"
3967
+ );
3968
+ }
3969
+ return textResult(lines.join("\n"));
3970
+ } catch (err) {
3971
+ return errorResult(err);
3972
+ }
3973
+ }
3974
+ );
3975
+ server.registerTool(
3976
+ "read_task_file",
3977
+ {
3978
+ title: "Read File in Task Workspace",
3979
+ description: "Read a line range of any file inside the task's isolated workspace to inspect full context during code review.",
3980
+ inputSchema: {
3981
+ taskId: z3.string().min(1),
3982
+ path: z3.string().min(1).describe("Relative path inside the isolated workspace."),
3983
+ startLine: z3.number().int().min(1).optional().describe("1-based start line (default 1)."),
3984
+ endLine: z3.number().int().min(1).optional().describe("1-based end line (default 250).")
3985
+ },
3986
+ annotations: {
3987
+ readOnlyHint: true,
3988
+ destructiveHint: false,
3989
+ idempotentHint: true,
3990
+ openWorldHint: false
3991
+ }
3992
+ },
3993
+ async ({ taskId, path: filePath, startLine, endLine }) => {
3994
+ try {
3995
+ const res = taskManager.readTaskFile(taskId, filePath, startLine, endLine);
3996
+ return textResult(
3997
+ `File \`${res.path}\` (lines ${res.startLine}-${res.endLine} of ${res.totalLines}):
3998
+ \`\`\`
3999
+ ${res.content}
4000
+ \`\`\``
4001
+ );
4002
+ } catch (err) {
4003
+ return errorResult(err);
4004
+ }
4005
+ }
4006
+ );
4007
+ server.registerTool(
4008
+ "get_task_logs",
4009
+ {
4010
+ title: "Read Task Event Logs",
4011
+ description: "Inspect normalized execution events (tool calls, errors, retries, status updates) recorded for a task.",
4012
+ inputSchema: {
4013
+ taskId: z3.string().min(1),
4014
+ tail: z3.number().int().min(1).max(500).optional().describe("Return the last N events."),
4015
+ offset: z3.number().int().min(0).optional().describe("Pagination offset when tail is omitted."),
4016
+ eventTypes: z3.array(z3.string()).optional().describe("Filter by event types.")
4017
+ },
4018
+ annotations: {
4019
+ readOnlyHint: true,
4020
+ destructiveHint: false,
4021
+ idempotentHint: true,
4022
+ openWorldHint: false
4023
+ }
4024
+ },
4025
+ async ({ taskId, tail, offset, eventTypes }) => {
4026
+ try {
4027
+ const res = taskManager.getLogs(taskId, { tail, offset, eventTypes });
4028
+ return textResult(
4029
+ `Task \`${taskId}\` logs (${res.events.length} of ${res.total} event(s)):
4030
+ \`\`\`json
4031
+ ${JSON.stringify(res.events, null, 2)}
4032
+ \`\`\``
4033
+ );
4034
+ } catch (err) {
4035
+ return errorResult(err);
4036
+ }
4037
+ }
4038
+ );
4039
+ server.registerTool(
4040
+ "verify_task",
4041
+ {
4042
+ title: "Run Verification Commands in Task Workspace",
4043
+ description: "Execute deterministic shell checks (tests, typecheck, lint) inside the task's isolated workspace and attach results to the deliverable.",
4044
+ inputSchema: {
4045
+ taskId: z3.string().min(1),
4046
+ commands: z3.array(z3.string().min(1)).min(1).describe("Commands to run sequentially.")
4047
+ },
4048
+ annotations: {
4049
+ readOnlyHint: false,
4050
+ destructiveHint: false,
4051
+ idempotentHint: false,
4052
+ openWorldHint: false
4053
+ }
4054
+ },
4055
+ async ({ taskId, commands }) => {
4056
+ try {
4057
+ const results = await taskManager.verifyTask(taskId, commands);
4058
+ const allPass = results.every((r) => r.passed);
4059
+ const lines = [
4060
+ `Verification ${allPass ? "PASSED" : "FAILED"} (${results.length} command(s)):`,
4061
+ ...results.map(
4062
+ (r) => `- \`${r.command}\`: **${r.passed ? "PASS" : "FAIL"}** (exit=${String(r.exitCode)}, ${r.durationMs}ms)
4063
+ ${r.stdoutTail ? ` stdout:
4064
+ \`\`\`
4065
+ ${r.stdoutTail.slice(-1200)}
4066
+ \`\`\`
4067
+ ` : ""}${r.stderrTail ? ` stderr:
4068
+ \`\`\`
4069
+ ${r.stderrTail.slice(-1200)}
4070
+ \`\`\`` : ""}`
4071
+ )
4072
+ ];
4073
+ return textResult(lines.join("\n"));
4074
+ } catch (err) {
4075
+ return errorResult(err);
4076
+ }
4077
+ }
4078
+ );
4079
+ server.registerTool(
4080
+ "request_changes",
4081
+ {
4082
+ title: "Reject Deliverable & Request Revision",
4083
+ description: "Send review feedback and optional file/line comments back into the same isolated workspace & agent session for Round N+1 revision.",
4084
+ inputSchema: {
4085
+ taskId: z3.string().min(1),
4086
+ feedback: z3.string().min(1).describe("Clear explanation of what needs to be fixed or improved."),
4087
+ comments: z3.array(
4088
+ z3.object({
4089
+ path: z3.string().min(1),
4090
+ line: z3.number().int().min(1).optional(),
4091
+ note: z3.string().min(1)
4092
+ })
4093
+ ).optional(),
4094
+ verifyCommands: z3.array(z3.string()).optional().describe("Optional updated verification commands for this revision round."),
4095
+ waitSeconds: z3.number().int().min(0).max(120).optional()
4096
+ },
4097
+ annotations: {
4098
+ readOnlyHint: false,
4099
+ destructiveHint: false,
4100
+ idempotentHint: false,
4101
+ openWorldHint: true
4102
+ }
4103
+ },
4104
+ async ({ taskId, feedback, comments, verifyCommands, waitSeconds }, extra) => {
4105
+ try {
4106
+ const res = await taskManager.requestChanges(
4107
+ taskId,
4108
+ { feedback, comments, verifyCommands, waitSeconds },
4109
+ makeProgressSender(extra)
4110
+ );
4111
+ if (res.settledWithinWait && res.deliverable) {
4112
+ return textResult(formatDeliverableMarkdown(res.deliverable));
4113
+ }
4114
+ return textResult(
4115
+ `Revision Round ${res.task.currentRound} started for \`${res.task.id}\` (status=\`${res.task.status}\`). Call \`wait_task\` to monitor completion.`
4116
+ );
4117
+ } catch (err) {
4118
+ return errorResult(err);
4119
+ }
4120
+ }
4121
+ );
4122
+ server.registerTool(
4123
+ "approve_task",
4124
+ {
4125
+ title: "Approve & Land Task Deliverable",
4126
+ description: "Approve a reviewed task (status=awaiting_review) and cleanly land its changes into the main workspace (default: apply_patch with conflict pre-check).",
4127
+ inputSchema: {
4128
+ taskId: z3.string().min(1),
4129
+ mergeStrategy: MergeStrategySchema.optional().describe(
4130
+ '"apply_patch" (default), "merge_commit", "squash_merge", "fast_forward", or "keep_branch".'
4131
+ ),
4132
+ commitMessage: z3.string().optional().describe("Commit message when using a commit/merge strategy."),
4133
+ cleanupWorktree: z3.boolean().optional().describe("Whether to remove the isolated worktree/staging directory after landing (default true).")
4134
+ },
4135
+ annotations: {
4136
+ readOnlyHint: false,
4137
+ destructiveHint: true,
4138
+ idempotentHint: false,
4139
+ openWorldHint: false
4140
+ }
4141
+ },
4142
+ async ({ taskId, mergeStrategy, commitMessage, cleanupWorktree }) => {
4143
+ try {
4144
+ const res = await taskManager.approveTask(taskId, {
4145
+ mergeStrategy,
4146
+ commitMessage,
4147
+ cleanupWorktree
4148
+ });
4149
+ return textResult(
4150
+ [
4151
+ `Task \`${taskId}\` **APPROVED** and landed!`,
4152
+ `- **Strategy**: \`${res.strategy}\``,
4153
+ `- **Applied files (${res.appliedFiles.length})**: ${res.appliedFiles.join(", ") || "none"}`,
4154
+ res.commitSha ? `- **Commit SHA**: \`${res.commitSha}\`` : "",
4155
+ res.branchName ? `- **Branch**: \`${res.branchName}\`` : "",
4156
+ `- **Cleaned up isolated workspace**: ${res.cleanedUp}`,
4157
+ `- **Detail**: ${res.message}`
4158
+ ].filter(Boolean).join("\n")
4159
+ );
4160
+ } catch (err) {
4161
+ return errorResult(err);
4162
+ }
4163
+ }
4164
+ );
4165
+ server.registerTool(
4166
+ "reject_task",
4167
+ {
4168
+ title: "Reject & Discard Task",
4169
+ description: "Reject a task deliverable and safely delete its isolated worktree/staging directory and temporary branch without touching the main workspace.",
4170
+ inputSchema: {
4171
+ taskId: z3.string().min(1),
4172
+ reason: z3.string().optional().describe("Optional reason for rejecting the deliverable.")
4173
+ },
4174
+ annotations: {
4175
+ readOnlyHint: false,
4176
+ destructiveHint: true,
4177
+ idempotentHint: true,
4178
+ openWorldHint: false
4179
+ }
4180
+ },
4181
+ async ({ taskId, reason }) => {
4182
+ try {
4183
+ const task = await taskManager.rejectTask(taskId, reason);
4184
+ return textResult(
4185
+ `Task \`${task.id}\` **REJECTED** and isolated workspace cleaned up.${reason ? ` Reason: ${reason}` : ""}`
4186
+ );
4187
+ } catch (err) {
4188
+ return errorResult(err);
4189
+ }
4190
+ }
4191
+ );
4192
+ }
4193
+
4194
+ // src/mcp/server.ts
4195
+ var SERVER_NAME = "gemini-agent-bridge";
4196
+ var SERVER_VERSION = "0.1.0";
4197
+ function createGeminiAgentBridgeServer(config, options) {
4198
+ const logger = new Logger(config.logLevel, getLogsDir(config.dataDir));
4199
+ const processRegistry = new ProcessRegistry();
4200
+ const adapters = options?.adapters ?? new AdapterRegistry();
4201
+ const taskManager = new TaskManager({
4202
+ config,
4203
+ adapters,
4204
+ processRegistry,
4205
+ logger,
4206
+ env: options?.env
4207
+ });
4208
+ taskManager.init();
4209
+ const server = new McpServer(
4210
+ {
4211
+ name: SERVER_NAME,
4212
+ version: SERVER_VERSION
4213
+ },
4214
+ {
4215
+ instructions: "Use gemini-agent-bridge to delegate tasks to local pi or opencode agents inside isolated worktrees, inspect deliverables and diffs, request revisions, and approve or reject changes."
4216
+ }
4217
+ );
4218
+ registerAllTools(server, { config, adapters, taskManager });
4219
+ registerPrompts(server);
4220
+ registerResources(server, taskManager);
4221
+ const shutdown = async () => {
4222
+ logger.info("Shutting down gemini-agent-bridge...");
4223
+ await processRegistry.shutdownAll(2e3);
4224
+ await server.close().catch(() => {
4225
+ });
4226
+ };
4227
+ return {
4228
+ server,
4229
+ taskManager,
4230
+ adapters,
4231
+ processRegistry,
4232
+ logger,
4233
+ shutdown
4234
+ };
4235
+ }
4236
+
4237
+ // src/setup/guides.ts
4238
+ import os6 from "os";
4239
+ import path10 from "path";
4240
+ function renderSetupGuide(target, config) {
4241
+ const home = os6.homedir();
4242
+ const npxCmd = "npx -y gemini-agent-bridge";
4243
+ if (target === "gemini-mac") {
4244
+ return [
4245
+ "# Mount gemini-agent-bridge in Gemini for Mac (Gemini.app)",
4246
+ "",
4247
+ "Step 1 \u2014 Initialize local config once in Terminal (auto-detects pi / opencode paths):",
4248
+ " gemini-agent-bridge init",
4249
+ ` # Config path (readable by Gemini default sandbox): ${config.configPath}`,
4250
+ "",
4251
+ "Step 2 \u2014 Add Local MCP inside Gemini.app:",
4252
+ " 1. Open Gemini.app -> More -> Connectors -> + Custom -> Local MCP",
4253
+ " 2. Fill in the form:",
4254
+ " - Server Name: Gemini Agent Bridge",
4255
+ " - Description: Delegate coding tasks to local pi & opencode in isolated worktrees, verify & approve deliverables.",
4256
+ ` - Command: ${npxCmd}`,
4257
+ " (Or if installed locally/globally without registry: `gemini-agent-bridge` or `node /path/to/gemini-agent-bridge/dist/cli.js`)",
4258
+ " - Note: Gemini Mac Local MCP has no env-var form; settings live in ~/.local/share/gemini-agent-bridge/config.json.",
4259
+ "",
4260
+ "Step 3 \u2014 Configure Customize Sandbox in Gemini.app:",
4261
+ " Click 'Customize Sandbox' and allow:",
4262
+ " - [x] Network access (required for pi/opencode LLM requests)",
4263
+ ` - [x] Your project workspace root(s), e.g. ${path10.join(home, "Documents")}`,
4264
+ " - [x] Local agent binaries & config dirs:",
4265
+ ` * ${path10.join(home, "Library/pnpm")}`,
4266
+ ` * ${path10.join(home, ".opencode")}`,
4267
+ ` * ${path10.join(home, ".pi")}`,
4268
+ ` * ${path10.join(home, ".config/opencode")}`,
4269
+ ` * ${path10.join(home, ".local/share/opencode")}`,
4270
+ "",
4271
+ "Step 4 \u2014 Verify inside Gemini chat:",
4272
+ ' Ask Gemini: "Run gemini-agent-bridge doctor and list_agents."'
4273
+ ].join("\n");
4274
+ }
4275
+ if (target === "gemini-cli") {
4276
+ const snippet = {
4277
+ mcpServers: {
4278
+ "gemini-agent-bridge": {
4279
+ command: "npx",
4280
+ args: ["-y", "gemini-agent-bridge"]
4281
+ }
4282
+ }
4283
+ };
4284
+ return [
4285
+ "# Mount gemini-agent-bridge in Gemini CLI (~/.gemini/settings.json)",
4286
+ "",
4287
+ "Option A \u2014 CLI one-liner:",
4288
+ " gemini mcp add --scope user gemini-agent-bridge npx -- -y gemini-agent-bridge",
4289
+ "",
4290
+ "Option B \u2014 Merge into ~/.gemini/settings.json:",
4291
+ JSON.stringify(snippet, null, 2)
4292
+ ].join("\n");
4293
+ }
4294
+ const agySnippet = {
4295
+ mcpServers: {
4296
+ "gemini-agent-bridge": {
4297
+ command: "npx",
4298
+ args: ["-y", "gemini-agent-bridge"]
4299
+ }
4300
+ }
4301
+ };
4302
+ return [
4303
+ "# Mount gemini-agent-bridge in Antigravity (~/.gemini/config/mcp_config.json)",
4304
+ "",
4305
+ "Merge the following entry into ~/.gemini/config/mcp_config.json under `mcpServers`:",
4306
+ JSON.stringify(agySnippet, null, 2)
4307
+ ].join("\n");
4308
+ }
4309
+
4310
+ // src/cli.ts
4311
+ function printHelp() {
4312
+ process.stdout.write(
4313
+ [
4314
+ `gemini-agent-bridge v${SERVER_VERSION}`,
4315
+ "",
4316
+ "MCP server allowing Gemini (Mac app, CLI, Antigravity) to orchestrate local pi & opencode agents.",
4317
+ "",
4318
+ "Usage:",
4319
+ " gemini-agent-bridge [options] Start stdio MCP server (default)",
4320
+ " gemini-agent-bridge init [options] Auto-detect agents & write config.json",
4321
+ " gemini-agent-bridge doctor [--workspace dir] Run environment & sandbox diagnostics",
4322
+ " gemini-agent-bridge setup <target> Print setup instructions",
4323
+ "",
4324
+ "Setup targets:",
4325
+ " --gemini-mac Gemini for Mac (Gemini.app -> Local MCP)",
4326
+ " --gemini-cli Gemini CLI (~/.gemini/settings.json)",
4327
+ " --antigravity Antigravity (~/.gemini/config/mcp_config.json)",
4328
+ "",
4329
+ "Server / CLI options:",
4330
+ " --config <path> Explicit config.json path",
4331
+ " --data-dir <path> Override state/worktrees directory",
4332
+ " --workspace <dir> Allowed workspace root (repeatable)",
4333
+ " --pi-bin <path> Explicit pi binary path",
4334
+ " --opencode-bin <path> Explicit opencode binary path",
4335
+ " --default-agent <name> pi | opencode",
4336
+ " --default-mode <mode> worktree | staging | direct",
4337
+ " --log-level <level> debug | info | warn | error",
4338
+ " --json JSON output (for doctor)",
4339
+ " -v, --version Show version",
4340
+ " -h, --help Show help",
4341
+ ""
4342
+ ].join("\n")
4343
+ );
4344
+ }
4345
+ function parseCliArgs(argv) {
4346
+ const args = [...argv];
4347
+ let subcommand = "serve";
4348
+ let setupTarget = "gemini-mac";
4349
+ let json = false;
4350
+ let doctorWorkspace;
4351
+ const workspaces = [];
4352
+ const overrides = {};
4353
+ const first = args[0];
4354
+ if (first === "init" || first === "doctor" || first === "setup") {
4355
+ subcommand = first;
4356
+ args.shift();
4357
+ }
4358
+ for (let i = 0; i < args.length; i++) {
4359
+ const arg = args[i];
4360
+ const nextValue = () => {
4361
+ const val = args[i + 1];
4362
+ if (!val || val.startsWith("-")) {
4363
+ throw new Error(`Option ${arg} requires a value`);
4364
+ }
4365
+ i += 1;
4366
+ return val;
4367
+ };
4368
+ if (arg === "-h" || arg === "--help") {
4369
+ subcommand = "help";
4370
+ } else if (arg === "-v" || arg === "--version") {
4371
+ subcommand = "version";
4372
+ } else if (arg === "--json") {
4373
+ json = true;
4374
+ } else if (arg === "--gemini-mac") {
4375
+ setupTarget = "gemini-mac";
4376
+ } else if (arg === "--gemini-cli") {
4377
+ setupTarget = "gemini-cli";
4378
+ } else if (arg === "--antigravity") {
4379
+ setupTarget = "antigravity";
4380
+ } else if (arg === "--config") {
4381
+ overrides.configPath = nextValue();
4382
+ } else if (arg === "--data-dir") {
4383
+ overrides.dataDir = nextValue();
4384
+ } else if (arg === "--workspace") {
4385
+ const dir = nextValue();
4386
+ workspaces.push(dir);
4387
+ doctorWorkspace = dir;
4388
+ } else if (arg === "--pi-bin") {
4389
+ overrides.piBin = nextValue();
4390
+ } else if (arg === "--opencode-bin") {
4391
+ overrides.opencodeBin = nextValue();
4392
+ } else if (arg === "--default-agent") {
4393
+ overrides.defaultAgent = nextValue();
4394
+ } else if (arg === "--default-mode") {
4395
+ overrides.defaultMode = nextValue();
4396
+ } else if (arg === "--log-level") {
4397
+ overrides.logLevel = nextValue();
4398
+ } else {
4399
+ throw new Error(`Unknown argument: ${arg}`);
4400
+ }
4401
+ }
4402
+ if (workspaces.length > 0 && subcommand !== "doctor") {
4403
+ overrides.workspaces = workspaces;
4404
+ }
4405
+ return { subcommand, setupTarget, json, doctorWorkspace, overrides };
4406
+ }
4407
+ async function main() {
4408
+ const parsed = parseCliArgs(process.argv.slice(2));
4409
+ if (parsed.subcommand === "help") {
4410
+ printHelp();
4411
+ return;
4412
+ }
4413
+ if (parsed.subcommand === "version") {
4414
+ process.stdout.write(`${SERVER_VERSION}
4415
+ `);
4416
+ return;
4417
+ }
4418
+ const config = loadConfig(parsed.overrides);
4419
+ if (parsed.subcommand === "setup") {
4420
+ process.stdout.write(`${renderSetupGuide(parsed.setupTarget, config)}
4421
+ `);
4422
+ return;
4423
+ }
4424
+ if (parsed.subcommand === "doctor") {
4425
+ const adapters = new AdapterRegistry();
4426
+ const env = buildAugmentedEnv(process.env, { probeLoginShell: true });
4427
+ const report = await runDoctor(config, adapters, parsed.doctorWorkspace, env);
4428
+ if (parsed.json) {
4429
+ process.stdout.write(`${JSON.stringify(report, null, 2)}
4430
+ `);
4431
+ } else {
4432
+ process.stdout.write(`${formatDoctorReport(report)}
4433
+ `);
4434
+ }
4435
+ process.exitCode = report.overallOk ? 0 : 1;
4436
+ return;
4437
+ }
4438
+ if (parsed.subcommand === "init") {
4439
+ const adapters = new AdapterRegistry();
4440
+ const env = buildAugmentedEnv(process.env, { probeLoginShell: true });
4441
+ const detected = await adapters.detectAll(config, env, false);
4442
+ const piInfo = detected.find((a) => a.id === "pi");
4443
+ const ocInfo = detected.find((a) => a.id === "opencode");
4444
+ const written = writeConfigFile(config.configPath, {
4445
+ piBin: piInfo?.binaryPath,
4446
+ opencodeBin: ocInfo?.binaryPath,
4447
+ ...parsed.overrides.workspaces ? { allowedWorkspaces: parsed.overrides.workspaces } : {}
4448
+ });
4449
+ process.stdout.write(
4450
+ [
4451
+ `Initialized gemini-agent-bridge config at: ${config.configPath}`,
4452
+ ` pi: ${piInfo?.available ? `${piInfo.binaryPath} (${piInfo.version})` : `not found (${piInfo?.error ?? ""})`}`,
4453
+ ` opencode: ${ocInfo?.available ? `${ocInfo.binaryPath} (${ocInfo.version})` : `not found (${ocInfo?.error ?? ""})`}`,
4454
+ "",
4455
+ JSON.stringify(written, null, 2),
4456
+ "",
4457
+ "Run `gemini-agent-bridge setup --gemini-mac` for Gemini Mac mounting instructions.",
4458
+ ""
4459
+ ].join("\n")
4460
+ );
4461
+ return;
4462
+ }
4463
+ const instance = createGeminiAgentBridgeServer(config);
4464
+ const transport = new StdioServerTransport();
4465
+ let closing = false;
4466
+ const handleSignal = () => {
4467
+ if (closing) return;
4468
+ closing = true;
4469
+ void instance.shutdown().finally(() => {
4470
+ process.exit(0);
4471
+ });
4472
+ };
4473
+ process.on("SIGINT", handleSignal);
4474
+ process.on("SIGTERM", handleSignal);
4475
+ transport.onclose = () => {
4476
+ handleSignal();
4477
+ };
4478
+ await instance.server.connect(transport);
4479
+ instance.logger.info("gemini-agent-bridge stdio server ready", {
4480
+ version: SERVER_VERSION,
4481
+ dataDir: config.dataDir,
4482
+ defaultAgent: config.defaultAgent
4483
+ });
4484
+ }
4485
+ main().catch((err) => {
4486
+ process.stderr.write(
4487
+ `[gemini-agent-bridge] Fatal startup error: ${err instanceof Error ? err.stack || err.message : String(err)}
4488
+ `
4489
+ );
4490
+ process.exit(1);
4491
+ });
4492
+ //# sourceMappingURL=cli.js.map