peer-bridge 0.0.0-stage → 0.6.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/LICENSE +21 -0
- package/README.ko.md +134 -0
- package/README.md +161 -2
- package/adapters/antigravity/bin/agy-hook.mjs +24 -0
- package/adapters/antigravity/hooks.json +23 -0
- package/adapters/antigravity/mcp_config.json +8 -0
- package/adapters/antigravity/plugin.json +4 -0
- package/adapters/antigravity/rules/AGENTS.md +6 -0
- package/adapters/antigravity/skills/peer-bridge/SKILL.md +19 -0
- package/adapters/claude/.claude-plugin/plugin.json +5 -0
- package/adapters/claude/.mcp.json +8 -0
- package/adapters/claude/bin/cc-hook.mjs +20 -0
- package/adapters/claude/hooks/hooks.json +46 -0
- package/adapters/claude/skills/peer-bridge/SKILL.md +18 -0
- package/adapters/codex/bin/codex-hook.mjs +10 -0
- package/adapters/codex/config.toml.example +5 -0
- package/adapters/codex/hooks.json +44 -0
- package/adapters/codex/skills/peer-bridge/SKILL.md +12 -0
- package/adapters/gemini/bin/gemini-hook.mjs +10 -0
- package/adapters/gemini/settings.json +51 -0
- package/adapters/gemini/skills/peer-bridge/SKILL.md +12 -0
- package/adapters/paseo/SKILL.md +24 -0
- package/bin/pbridge-mcp.mjs +37 -0
- package/bin/pbridge-tui.mjs +7 -0
- package/bin/pbridge.mjs +5 -0
- package/bin/pbridged.mjs +16 -0
- package/package.json +42 -4
- package/src/adapters/antigravity/hooks.mjs +207 -0
- package/src/adapters/claude/hooks.mjs +204 -0
- package/src/adapters/codex/hooks.mjs +142 -0
- package/src/adapters/gemini/hooks.mjs +159 -0
- package/src/adapters/installer.mjs +328 -0
- package/src/cli/main.mjs +729 -0
- package/src/client/rpc.mjs +243 -0
- package/src/config.mjs +154 -0
- package/src/daemon/broker.mjs +1799 -0
- package/src/daemon/resolver.mjs +200 -0
- package/src/daemon/server.mjs +221 -0
- package/src/index.mjs +53 -0
- package/src/mcp/server.mjs +668 -0
- package/src/orchestrator/workflows.mjs +496 -0
- package/src/project.mjs +81 -0
- package/src/protocol.mjs +203 -0
- package/src/runtime/conv-api.mjs +101 -0
- package/src/runtime/host-discovery.mjs +635 -0
- package/src/runtime/native-claude.mjs +88 -0
- package/src/runtime/paseo.mjs +289 -0
- package/src/runtime/workers.mjs +751 -0
- package/src/storage/db.mjs +704 -0
- package/src/tui/render.mjs +472 -0
- package/src/tui/viewer.mjs +443 -0
|
@@ -0,0 +1,751 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { spawn, execFile } from 'node:child_process';
|
|
3
|
+
import { promisify } from 'node:util';
|
|
4
|
+
import { createLineSplitter, resolveAgyModels } from '../protocol.mjs';
|
|
5
|
+
|
|
6
|
+
const execFileAsync = promisify(execFile);
|
|
7
|
+
|
|
8
|
+
function buildSpawnOptions({ bin, cwd, env, stdio = ['pipe', 'pipe', 'pipe'] }) {
|
|
9
|
+
const opts = { cwd, env, stdio };
|
|
10
|
+
if (process.platform === 'win32') {
|
|
11
|
+
opts.windowsHide = true;
|
|
12
|
+
if (/\.(cmd|bat)$/i.test(String(bin || ''))) {
|
|
13
|
+
opts.shell = true;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return opts;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function spawnPortable(bin, args, { cwd, env, stdio = ['pipe', 'pipe', 'pipe'] }) {
|
|
20
|
+
if (process.platform === 'win32' && /\.(mjs|cjs|js)$/i.test(String(bin || ''))) {
|
|
21
|
+
return spawn(process.execPath, [bin, ...args], {
|
|
22
|
+
cwd,
|
|
23
|
+
env,
|
|
24
|
+
stdio,
|
|
25
|
+
windowsHide: true,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
return spawn(bin, args, buildSpawnOptions({ bin, cwd, env, stdio }));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
class BaseStreamWorker extends EventEmitter {
|
|
32
|
+
constructor({ peerId, runtime, bin, args, cwd, env }) {
|
|
33
|
+
super();
|
|
34
|
+
this.peerId = peerId;
|
|
35
|
+
this.runtime = runtime;
|
|
36
|
+
this.bin = bin;
|
|
37
|
+
this.args = args;
|
|
38
|
+
this.cwd = cwd || process.cwd();
|
|
39
|
+
this.env = { ...process.env, ...(env || {}) };
|
|
40
|
+
this.proc = null;
|
|
41
|
+
this.sessionId = null;
|
|
42
|
+
this.closed = false;
|
|
43
|
+
this.stderrTail = '';
|
|
44
|
+
this.pendingTurn = null;
|
|
45
|
+
this.turnQueue = Promise.resolve();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
start() {
|
|
49
|
+
this.proc = spawnPortable(this.bin, this.args, {
|
|
50
|
+
cwd: this.cwd,
|
|
51
|
+
env: this.env,
|
|
52
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const splitStdout = createLineSplitter((line) => this._handleStdoutLine(line));
|
|
56
|
+
this.proc.stdout.on('data', splitStdout);
|
|
57
|
+
|
|
58
|
+
this.proc.stderr.on('data', (chunk) => {
|
|
59
|
+
this.stderrTail = (this.stderrTail + chunk.toString('utf8')).slice(-2000);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
this.proc.on('error', (err) => {
|
|
63
|
+
this._rejectPendingTurn(err);
|
|
64
|
+
this.emit('error', err);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
this.proc.on('exit', (code, signal) => {
|
|
68
|
+
this.closed = true;
|
|
69
|
+
const err = new Error(`${this.runtime} worker exited (code=${code}, signal=${signal})`);
|
|
70
|
+
this._rejectPendingTurn(err);
|
|
71
|
+
this.emit('exit', { code, signal, stderr: this.stderrTail });
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
return this;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
get pid() {
|
|
78
|
+
return this.proc?.pid ?? null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
_handleStdoutLine(_line) {
|
|
82
|
+
throw new Error('Not implemented');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
_formatInput(_content) {
|
|
86
|
+
throw new Error('Not implemented');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
_resolvePendingTurn(result) {
|
|
90
|
+
if (!this.pendingTurn) return;
|
|
91
|
+
const { resolve, timer } = this.pendingTurn;
|
|
92
|
+
clearTimeout(timer);
|
|
93
|
+
this.pendingTurn = null;
|
|
94
|
+
resolve(result);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
_rejectPendingTurn(err) {
|
|
98
|
+
if (!this.pendingTurn) return;
|
|
99
|
+
const { reject, timer } = this.pendingTurn;
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
this.pendingTurn = null;
|
|
102
|
+
reject(err);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
sendTurn(content, { timeoutMs = 180_000 } = {}) {
|
|
106
|
+
const run = async () => {
|
|
107
|
+
if (this.closed || !this.proc || !this.proc.stdin.writable) {
|
|
108
|
+
throw new Error(`${this.runtime} worker is closed`);
|
|
109
|
+
}
|
|
110
|
+
this.emit('turn_start', { content });
|
|
111
|
+
const turnPromise = new Promise((resolve, reject) => {
|
|
112
|
+
const timer = setTimeout(() => {
|
|
113
|
+
this.pendingTurn = null;
|
|
114
|
+
reject(new Error(`${this.runtime} worker turn timed out after ${timeoutMs}ms`));
|
|
115
|
+
}, timeoutMs);
|
|
116
|
+
this.pendingTurn = { resolve, reject, timer, textParts: [] };
|
|
117
|
+
});
|
|
118
|
+
this.proc.stdin.write(`${JSON.stringify(this._formatInput(content))}\n`);
|
|
119
|
+
const res = await turnPromise;
|
|
120
|
+
this.emit('turn_result', res);
|
|
121
|
+
return res;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const next = this.turnQueue.then(run, run);
|
|
125
|
+
this.turnQueue = next.catch(() => {});
|
|
126
|
+
return next;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async stop({ graceMs = 2000 } = {}) {
|
|
130
|
+
if (!this.proc || this.closed) return;
|
|
131
|
+
const exitPromise = new Promise((resolve) => {
|
|
132
|
+
if (this.closed) return resolve();
|
|
133
|
+
this.once('exit', () => resolve());
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
try {
|
|
137
|
+
this.proc.stdin.end();
|
|
138
|
+
} catch {
|
|
139
|
+
// ignore
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const graceful = await Promise.race([
|
|
143
|
+
exitPromise.then(() => true),
|
|
144
|
+
new Promise((r) => setTimeout(() => r(false), graceMs)),
|
|
145
|
+
]);
|
|
146
|
+
|
|
147
|
+
if (!graceful && !this.closed) {
|
|
148
|
+
try {
|
|
149
|
+
this.proc.kill('SIGTERM');
|
|
150
|
+
} catch {
|
|
151
|
+
// ignore
|
|
152
|
+
}
|
|
153
|
+
const termed = await Promise.race([
|
|
154
|
+
exitPromise.then(() => true),
|
|
155
|
+
new Promise((r) => setTimeout(() => r(false), 1500)),
|
|
156
|
+
]);
|
|
157
|
+
if (!termed && !this.closed) {
|
|
158
|
+
try {
|
|
159
|
+
this.proc.kill('SIGKILL');
|
|
160
|
+
} catch {
|
|
161
|
+
// ignore
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export class AgyStreamWorker extends BaseStreamWorker {
|
|
169
|
+
constructor({ peerId, agyBin, conversationId, model, cwd, env }) {
|
|
170
|
+
const { cliModel } = resolveAgyModels(model);
|
|
171
|
+
const args = [];
|
|
172
|
+
if (conversationId) {
|
|
173
|
+
args.push('--conversation', conversationId);
|
|
174
|
+
}
|
|
175
|
+
args.push('--input-format', 'stream-json', '--output-format', 'stream-json', '--model', cliModel);
|
|
176
|
+
super({ peerId, runtime: 'agy', bin: agyBin, args, cwd, env });
|
|
177
|
+
this.sessionId = conversationId || null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
_formatInput(content) {
|
|
181
|
+
return { event: 'user', message: { content } };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
_handleStdoutLine(line) {
|
|
185
|
+
let ev;
|
|
186
|
+
try {
|
|
187
|
+
ev = JSON.parse(line);
|
|
188
|
+
} catch {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (ev.conversation_id && ev.conversation_id !== this.sessionId) {
|
|
193
|
+
this.sessionId = ev.conversation_id;
|
|
194
|
+
this.emit('session_id', this.sessionId);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (ev.event === 'step_update' && ev.step_update?.text_delta && this.pendingTurn) {
|
|
198
|
+
this.pendingTurn.textParts.push(ev.step_update.text_delta);
|
|
199
|
+
this.emit('progress', ev.step_update.text_delta);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (ev.event === 'result') {
|
|
203
|
+
const status = ev.result?.status || 'DONE';
|
|
204
|
+
const response =
|
|
205
|
+
ev.result?.response ??
|
|
206
|
+
(this.pendingTurn ? this.pendingTurn.textParts.join('') : '');
|
|
207
|
+
const result = {
|
|
208
|
+
status,
|
|
209
|
+
is_error: status === 'ERROR' || Boolean(ev.result?.error),
|
|
210
|
+
error: ev.result?.error || null,
|
|
211
|
+
response,
|
|
212
|
+
session_id: this.sessionId,
|
|
213
|
+
};
|
|
214
|
+
this._resolvePendingTurn(result);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export class CcStreamWorker extends BaseStreamWorker {
|
|
220
|
+
constructor({ peerId, claudeBin, model, permissionMode, noMcp = false, cwd, env }) {
|
|
221
|
+
const args = [
|
|
222
|
+
'-p',
|
|
223
|
+
'--input-format',
|
|
224
|
+
'stream-json',
|
|
225
|
+
'--output-format',
|
|
226
|
+
'stream-json',
|
|
227
|
+
'--verbose',
|
|
228
|
+
];
|
|
229
|
+
if (model) args.push('--model', model);
|
|
230
|
+
if (permissionMode) args.push('--permission-mode', permissionMode);
|
|
231
|
+
if (noMcp) {
|
|
232
|
+
args.push('--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}');
|
|
233
|
+
}
|
|
234
|
+
super({ peerId, runtime: 'cc', bin: claudeBin, args, cwd, env });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
_formatInput(content) {
|
|
238
|
+
return {
|
|
239
|
+
type: 'user',
|
|
240
|
+
message: { role: 'user', content },
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
_handleStdoutLine(line) {
|
|
245
|
+
let ev;
|
|
246
|
+
try {
|
|
247
|
+
ev = JSON.parse(line);
|
|
248
|
+
} catch {
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (ev.session_id && ev.session_id !== this.sessionId) {
|
|
253
|
+
this.sessionId = ev.session_id;
|
|
254
|
+
this.emit('session_id', this.sessionId);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (ev.type === 'assistant' && Array.isArray(ev.message?.content)) {
|
|
258
|
+
for (const block of ev.message.content) {
|
|
259
|
+
if (block?.type === 'tool_use' && block.name) {
|
|
260
|
+
const inp = block.input || {};
|
|
261
|
+
const detail =
|
|
262
|
+
inp.file_path || inp.path || inp.command || inp.pattern || inp.description || '';
|
|
263
|
+
const shortDetail = String(detail).split('/').slice(-2).join('/').slice(0, 60);
|
|
264
|
+
this.emit('progress', shortDetail ? `Tool: ${block.name} ${shortDetail}` : `Tool: ${block.name}`);
|
|
265
|
+
} else if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) {
|
|
266
|
+
this.emit('progress', block.text.trim());
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (ev.type === 'result') {
|
|
272
|
+
const result = {
|
|
273
|
+
status: ev.is_error ? 'ERROR' : 'DONE',
|
|
274
|
+
is_error: Boolean(ev.is_error),
|
|
275
|
+
error: ev.is_error ? String(ev.result || 'claude error') : null,
|
|
276
|
+
response: typeof ev.result === 'string' ? ev.result : '',
|
|
277
|
+
session_id: this.sessionId || ev.session_id || null,
|
|
278
|
+
duration_ms: ev.duration_ms ?? null,
|
|
279
|
+
};
|
|
280
|
+
this._resolvePendingTurn(result);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export class CodexExecWorker extends EventEmitter {
|
|
286
|
+
constructor({ peerId, codexBin, sessionId, model, sandboxMode, cwd, env }) {
|
|
287
|
+
super();
|
|
288
|
+
this.peerId = peerId;
|
|
289
|
+
this.runtime = 'codex';
|
|
290
|
+
this.bin = codexBin;
|
|
291
|
+
this.sessionId = sessionId || null;
|
|
292
|
+
this.model = model || null;
|
|
293
|
+
this.sandboxMode = sandboxMode || 'workspace-write';
|
|
294
|
+
this.cwd = cwd || process.cwd();
|
|
295
|
+
this.env = { ...process.env, ...(env || {}) };
|
|
296
|
+
this.closed = false;
|
|
297
|
+
this.activeProc = null;
|
|
298
|
+
this.turnQueue = Promise.resolve();
|
|
299
|
+
this.stderrTail = '';
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
get pid() {
|
|
303
|
+
return this.activeProc?.pid ?? null;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
start() {
|
|
307
|
+
if (this.sessionId) {
|
|
308
|
+
queueMicrotask(() => this.emit('session_id', this.sessionId));
|
|
309
|
+
}
|
|
310
|
+
return this;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
_buildArgs() {
|
|
314
|
+
if (!this.sessionId) {
|
|
315
|
+
const args = [
|
|
316
|
+
'exec',
|
|
317
|
+
'--json',
|
|
318
|
+
'--skip-git-repo-check',
|
|
319
|
+
'-C',
|
|
320
|
+
this.cwd,
|
|
321
|
+
];
|
|
322
|
+
if (this.sandboxMode === 'danger-full-access') {
|
|
323
|
+
args.push('--dangerously-bypass-approvals-and-sandbox');
|
|
324
|
+
} else if (!this.sandboxMode || this.sandboxMode === 'workspace-write') {
|
|
325
|
+
// codex-cli 0.174+: --approve-for-me implies workspace-write and conflicts with -s
|
|
326
|
+
args.push('--approve-for-me');
|
|
327
|
+
} else {
|
|
328
|
+
args.push('-s', this.sandboxMode);
|
|
329
|
+
}
|
|
330
|
+
if (this.model) args.push('-m', this.model);
|
|
331
|
+
args.push('-');
|
|
332
|
+
return args;
|
|
333
|
+
}
|
|
334
|
+
const args = ['exec', 'resume', '--json', '--skip-git-repo-check'];
|
|
335
|
+
if (this.sandboxMode === 'danger-full-access') {
|
|
336
|
+
args.push('--dangerously-bypass-approvals-and-sandbox');
|
|
337
|
+
}
|
|
338
|
+
if (this.model) args.push('-m', this.model);
|
|
339
|
+
args.push(this.sessionId, '-');
|
|
340
|
+
return args;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
sendTurn(content, { timeoutMs = 180_000 } = {}) {
|
|
344
|
+
const run = async () => {
|
|
345
|
+
if (this.closed) {
|
|
346
|
+
throw new Error('codex worker is closed');
|
|
347
|
+
}
|
|
348
|
+
this.emit('turn_start', { content });
|
|
349
|
+
const args = this._buildArgs();
|
|
350
|
+
return new Promise((resolve, reject) => {
|
|
351
|
+
const proc = spawnPortable(this.bin, args, {
|
|
352
|
+
cwd: this.cwd,
|
|
353
|
+
env: this.env,
|
|
354
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
355
|
+
});
|
|
356
|
+
this.activeProc = proc;
|
|
357
|
+
let settled = false;
|
|
358
|
+
const textParts = [];
|
|
359
|
+
let turnError = null;
|
|
360
|
+
let stderr = '';
|
|
361
|
+
|
|
362
|
+
const finish = (err, result) => {
|
|
363
|
+
if (settled) return;
|
|
364
|
+
settled = true;
|
|
365
|
+
clearTimeout(timer);
|
|
366
|
+
if (this.activeProc === proc) this.activeProc = null;
|
|
367
|
+
if (err) {
|
|
368
|
+
reject(err);
|
|
369
|
+
} else {
|
|
370
|
+
this.emit('turn_result', result);
|
|
371
|
+
resolve(result);
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
const timer = setTimeout(() => {
|
|
376
|
+
try {
|
|
377
|
+
proc.kill('SIGTERM');
|
|
378
|
+
} catch {
|
|
379
|
+
// ignore
|
|
380
|
+
}
|
|
381
|
+
finish(new Error(`codex worker turn timed out after ${timeoutMs}ms`));
|
|
382
|
+
}, timeoutMs);
|
|
383
|
+
|
|
384
|
+
let reconnectErrors = 0;
|
|
385
|
+
const splitStdout = createLineSplitter((line) => {
|
|
386
|
+
let ev;
|
|
387
|
+
try {
|
|
388
|
+
ev = JSON.parse(line);
|
|
389
|
+
} catch {
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (ev.type === 'thread.started' && ev.thread_id && ev.thread_id !== this.sessionId) {
|
|
393
|
+
this.sessionId = ev.thread_id;
|
|
394
|
+
this.emit('session_id', this.sessionId);
|
|
395
|
+
} else if (ev.type === 'turn.started') {
|
|
396
|
+
this.emit('progress', 'Codex turn started...');
|
|
397
|
+
} else if (ev.type === 'item.completed') {
|
|
398
|
+
reconnectErrors = 0;
|
|
399
|
+
if (ev.item?.type === 'agent_message' && typeof ev.item?.text === 'string') {
|
|
400
|
+
textParts.push(ev.item.text);
|
|
401
|
+
this.emit('progress', ev.item.text);
|
|
402
|
+
} else if (ev.item?.type === 'command_execution' && ev.item?.command) {
|
|
403
|
+
this.emit('progress', `Cmd: ${String(ev.item.command).slice(0, 70)}`);
|
|
404
|
+
} else if (ev.item?.type === 'file_change' && ev.item?.path) {
|
|
405
|
+
this.emit('progress', `File: ${String(ev.item.path).split('/').slice(-2).join('/')}`);
|
|
406
|
+
} else if (typeof ev.item?.text === 'string') {
|
|
407
|
+
textParts.push(ev.item.text);
|
|
408
|
+
}
|
|
409
|
+
} else if (ev.type === 'turn.failed' || ev.type === 'error') {
|
|
410
|
+
const msg = ev.error?.message || ev.message || 'codex turn failed';
|
|
411
|
+
turnError = msg;
|
|
412
|
+
this.emit('progress', `[error] ${msg}`);
|
|
413
|
+
if (/reconnecting|connection failed/i.test(msg)) {
|
|
414
|
+
reconnectErrors++;
|
|
415
|
+
if (reconnectErrors >= 3) {
|
|
416
|
+
try {
|
|
417
|
+
proc.kill('SIGTERM');
|
|
418
|
+
} catch {
|
|
419
|
+
// ignore
|
|
420
|
+
}
|
|
421
|
+
finish(new Error(`codex network unreachable after ${reconnectErrors} reconnects: ${msg}`));
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
proc.stdout.on('data', splitStdout);
|
|
428
|
+
proc.stderr.on('data', (chunk) => {
|
|
429
|
+
stderr = (stderr + chunk.toString('utf8')).slice(-2000);
|
|
430
|
+
this.stderrTail = stderr;
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
proc.on('error', (err) => finish(err));
|
|
434
|
+
proc.on('exit', (code, signal) => {
|
|
435
|
+
if (this.closed && !settled) {
|
|
436
|
+
finish(new Error('codex worker stopped'));
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
const isError = Boolean(turnError) || (code !== null && code !== 0) || Boolean(signal);
|
|
440
|
+
const errorMsg =
|
|
441
|
+
turnError || (isError ? stderr.trim() || `codex exited (code=${code}, signal=${signal})` : null);
|
|
442
|
+
finish(null, {
|
|
443
|
+
status: isError ? 'ERROR' : 'DONE',
|
|
444
|
+
is_error: isError,
|
|
445
|
+
error: errorMsg,
|
|
446
|
+
response: textParts.join('\n').trim(),
|
|
447
|
+
session_id: this.sessionId,
|
|
448
|
+
});
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
try {
|
|
452
|
+
proc.stdin.write(String(content ?? ''));
|
|
453
|
+
proc.stdin.end();
|
|
454
|
+
} catch (err) {
|
|
455
|
+
finish(err);
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
const next = this.turnQueue.then(run, run);
|
|
461
|
+
this.turnQueue = next.catch(() => {});
|
|
462
|
+
return next;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
async stop() {
|
|
466
|
+
if (this.closed) return;
|
|
467
|
+
this.closed = true;
|
|
468
|
+
const proc = this.activeProc;
|
|
469
|
+
this.activeProc = null;
|
|
470
|
+
if (proc && !proc.killed) {
|
|
471
|
+
try {
|
|
472
|
+
proc.kill('SIGTERM');
|
|
473
|
+
} catch {
|
|
474
|
+
// ignore
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
this.emit('exit', { code: 0, signal: null, stderr: this.stderrTail });
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
export class GeminiCliWorker extends EventEmitter {
|
|
482
|
+
constructor({ peerId, geminiBin, sessionId, model, approvalMode, cwd, env }) {
|
|
483
|
+
super();
|
|
484
|
+
this.peerId = peerId;
|
|
485
|
+
this.runtime = 'gemini';
|
|
486
|
+
this.bin = geminiBin;
|
|
487
|
+
this.sessionId = sessionId || null;
|
|
488
|
+
this.model = model || null;
|
|
489
|
+
this.approvalMode = approvalMode || 'yolo';
|
|
490
|
+
this.cwd = cwd || process.cwd();
|
|
491
|
+
this.env = { ...process.env, ...(env || {}) };
|
|
492
|
+
this.closed = false;
|
|
493
|
+
this.activeProc = null;
|
|
494
|
+
this.turnQueue = Promise.resolve();
|
|
495
|
+
this.stderrTail = '';
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
get pid() {
|
|
499
|
+
return this.activeProc?.pid ?? null;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
start() {
|
|
503
|
+
if (this.sessionId) {
|
|
504
|
+
queueMicrotask(() => this.emit('session_id', this.sessionId));
|
|
505
|
+
}
|
|
506
|
+
return this;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
sendTurn(content, { timeoutMs = 180_000 } = {}) {
|
|
510
|
+
const run = async () => {
|
|
511
|
+
if (this.closed) {
|
|
512
|
+
throw new Error('gemini worker is closed');
|
|
513
|
+
}
|
|
514
|
+
this.emit('turn_start', { content });
|
|
515
|
+
const text = String(content ?? '');
|
|
516
|
+
const useStdin = text.length > 32_000;
|
|
517
|
+
const args = [];
|
|
518
|
+
if (this.sessionId) {
|
|
519
|
+
args.push('-r', this.sessionId);
|
|
520
|
+
}
|
|
521
|
+
args.push('-p', useStdin ? '' : text, '-o', 'stream-json', '--approval-mode', this.approvalMode);
|
|
522
|
+
if (this.model) {
|
|
523
|
+
args.push('-m', this.model);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
return new Promise((resolve, reject) => {
|
|
527
|
+
const proc = spawnPortable(this.bin, args, {
|
|
528
|
+
cwd: this.cwd,
|
|
529
|
+
env: this.env,
|
|
530
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
531
|
+
});
|
|
532
|
+
this.activeProc = proc;
|
|
533
|
+
let settled = false;
|
|
534
|
+
let deltaText = '';
|
|
535
|
+
let fullMessage = '';
|
|
536
|
+
let fallbackJsonText = '';
|
|
537
|
+
let turnError = null;
|
|
538
|
+
let stderr = '';
|
|
539
|
+
|
|
540
|
+
const finish = (err, result) => {
|
|
541
|
+
if (settled) return;
|
|
542
|
+
settled = true;
|
|
543
|
+
clearTimeout(timer);
|
|
544
|
+
if (this.activeProc === proc) this.activeProc = null;
|
|
545
|
+
if (err) {
|
|
546
|
+
reject(err);
|
|
547
|
+
} else {
|
|
548
|
+
this.emit('turn_result', result);
|
|
549
|
+
resolve(result);
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
|
|
553
|
+
const timer = setTimeout(() => {
|
|
554
|
+
try {
|
|
555
|
+
proc.kill('SIGTERM');
|
|
556
|
+
} catch {
|
|
557
|
+
// ignore
|
|
558
|
+
}
|
|
559
|
+
finish(new Error(`gemini worker turn timed out after ${timeoutMs}ms`));
|
|
560
|
+
}, timeoutMs);
|
|
561
|
+
|
|
562
|
+
const splitStdout = createLineSplitter((line) => {
|
|
563
|
+
let ev;
|
|
564
|
+
try {
|
|
565
|
+
ev = JSON.parse(line);
|
|
566
|
+
} catch {
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
if (ev.type === 'init' && ev.session_id && ev.session_id !== this.sessionId) {
|
|
570
|
+
this.sessionId = ev.session_id;
|
|
571
|
+
this.emit('session_id', this.sessionId);
|
|
572
|
+
} else if (ev.type === 'message' && (ev.role === 'assistant' || ev.role === 'model')) {
|
|
573
|
+
if (typeof ev.content === 'string') {
|
|
574
|
+
if (ev.delta) {
|
|
575
|
+
deltaText += ev.content;
|
|
576
|
+
} else {
|
|
577
|
+
fullMessage = fullMessage ? `${fullMessage}\n${ev.content}` : ev.content;
|
|
578
|
+
this.emit('progress', ev.content);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
} else if (ev.type === 'error') {
|
|
582
|
+
turnError = ev.error?.message || ev.message || 'gemini error';
|
|
583
|
+
} else if (ev.type === 'result') {
|
|
584
|
+
if (ev.status === 'error' || ev.error) {
|
|
585
|
+
turnError = ev.error?.message || String(ev.error || 'gemini turn failed');
|
|
586
|
+
}
|
|
587
|
+
} else if (typeof ev.response === 'string') {
|
|
588
|
+
if (ev.session_id && ev.session_id !== this.sessionId) {
|
|
589
|
+
this.sessionId = ev.session_id;
|
|
590
|
+
this.emit('session_id', this.sessionId);
|
|
591
|
+
}
|
|
592
|
+
fallbackJsonText = ev.response;
|
|
593
|
+
if (ev.error) {
|
|
594
|
+
turnError = ev.error?.message || String(ev.error);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
});
|
|
598
|
+
|
|
599
|
+
proc.stdout.on('data', splitStdout);
|
|
600
|
+
proc.stderr.on('data', (chunk) => {
|
|
601
|
+
stderr = (stderr + chunk.toString('utf8')).slice(-2000);
|
|
602
|
+
this.stderrTail = stderr;
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
proc.on('error', (err) => finish(err));
|
|
606
|
+
proc.on('exit', (code, signal) => {
|
|
607
|
+
if (this.closed && !settled) {
|
|
608
|
+
finish(new Error('gemini worker stopped'));
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
const response = (deltaText || fullMessage || fallbackJsonText).trim();
|
|
612
|
+
const isError = Boolean(turnError) || (code !== null && code !== 0) || Boolean(signal);
|
|
613
|
+
const errorMsg =
|
|
614
|
+
turnError || (isError ? stderr.trim() || `gemini exited (code=${code}, signal=${signal})` : null);
|
|
615
|
+
finish(null, {
|
|
616
|
+
status: isError ? 'ERROR' : 'DONE',
|
|
617
|
+
is_error: isError,
|
|
618
|
+
error: errorMsg,
|
|
619
|
+
response,
|
|
620
|
+
session_id: this.sessionId,
|
|
621
|
+
});
|
|
622
|
+
});
|
|
623
|
+
|
|
624
|
+
try {
|
|
625
|
+
if (useStdin) {
|
|
626
|
+
proc.stdin.write(text);
|
|
627
|
+
}
|
|
628
|
+
// Critical: Gemini CLI appends stdin to -p; always close stdin immediately.
|
|
629
|
+
proc.stdin.end();
|
|
630
|
+
} catch (err) {
|
|
631
|
+
finish(err);
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
};
|
|
635
|
+
|
|
636
|
+
const next = this.turnQueue.then(run, run);
|
|
637
|
+
this.turnQueue = next.catch(() => {});
|
|
638
|
+
return next;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
async stop() {
|
|
642
|
+
if (this.closed) return;
|
|
643
|
+
this.closed = true;
|
|
644
|
+
const proc = this.activeProc;
|
|
645
|
+
this.activeProc = null;
|
|
646
|
+
if (proc && !proc.killed) {
|
|
647
|
+
try {
|
|
648
|
+
proc.kill('SIGTERM');
|
|
649
|
+
} catch {
|
|
650
|
+
// ignore
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
this.emit('exit', { code: 0, signal: null, stderr: this.stderrTail });
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
export class MockStreamWorker extends EventEmitter {
|
|
658
|
+
constructor({ peerId, runtime, sessionId, responder }) {
|
|
659
|
+
super();
|
|
660
|
+
this.peerId = peerId;
|
|
661
|
+
this.runtime = runtime;
|
|
662
|
+
this.sessionId = sessionId || `mock-${peerId}`;
|
|
663
|
+
this.closed = false;
|
|
664
|
+
this.pid = process.pid;
|
|
665
|
+
this.responder = responder || ((content) => `echo(${this.runtime}): ${content}`);
|
|
666
|
+
this.turnQueue = Promise.resolve();
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
start() {
|
|
670
|
+
queueMicrotask(() => this.emit('session_id', this.sessionId));
|
|
671
|
+
return this;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
sendTurn(content) {
|
|
675
|
+
const run = async () => {
|
|
676
|
+
if (this.closed) throw new Error('mock worker closed');
|
|
677
|
+
this.emit('turn_start', { content });
|
|
678
|
+
const response = await this.responder(content, this);
|
|
679
|
+
const res = { status: 'DONE', is_error: false, error: null, response, session_id: this.sessionId };
|
|
680
|
+
this.emit('turn_result', res);
|
|
681
|
+
return res;
|
|
682
|
+
};
|
|
683
|
+
const next = this.turnQueue.then(run, run);
|
|
684
|
+
this.turnQueue = next.catch(() => {});
|
|
685
|
+
return next;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
async stop() {
|
|
689
|
+
if (this.closed) return;
|
|
690
|
+
this.closed = true;
|
|
691
|
+
this.emit('exit', { code: 0, signal: null, stderr: '' });
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function shellQuote(arg) {
|
|
696
|
+
return `'${String(arg).replace(/'/g, `'\\''`)}'`;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
export async function spawnTmuxPane({ tmuxBin, runtime, bin, args, cwd, name, tmuxSocket }) {
|
|
700
|
+
const socketArgs = tmuxSocket ? ['-L', tmuxSocket] : [];
|
|
701
|
+
const cmdStr = [bin, ...args].map(shellQuote).join(' ');
|
|
702
|
+
const sessionName = 'pbridge';
|
|
703
|
+
|
|
704
|
+
const hasSession = await execFileAsync(tmuxBin, [...socketArgs, 'has-session', '-t', sessionName])
|
|
705
|
+
.then(() => true)
|
|
706
|
+
.catch(() => false);
|
|
707
|
+
|
|
708
|
+
let paneId;
|
|
709
|
+
if (!hasSession) {
|
|
710
|
+
const { stdout } = await execFileAsync(tmuxBin, [
|
|
711
|
+
...socketArgs,
|
|
712
|
+
'new-session',
|
|
713
|
+
'-d',
|
|
714
|
+
'-s',
|
|
715
|
+
sessionName,
|
|
716
|
+
'-n',
|
|
717
|
+
`${runtime}-${name}`,
|
|
718
|
+
'-c',
|
|
719
|
+
cwd,
|
|
720
|
+
'-P',
|
|
721
|
+
'-F',
|
|
722
|
+
'#{pane_id}',
|
|
723
|
+
cmdStr,
|
|
724
|
+
]);
|
|
725
|
+
paneId = stdout.trim();
|
|
726
|
+
} else {
|
|
727
|
+
const { stdout } = await execFileAsync(tmuxBin, [
|
|
728
|
+
...socketArgs,
|
|
729
|
+
'new-window',
|
|
730
|
+
'-t',
|
|
731
|
+
sessionName,
|
|
732
|
+
'-n',
|
|
733
|
+
`${runtime}-${name}`,
|
|
734
|
+
'-c',
|
|
735
|
+
cwd,
|
|
736
|
+
'-P',
|
|
737
|
+
'-F',
|
|
738
|
+
'#{pane_id}',
|
|
739
|
+
cmdStr,
|
|
740
|
+
]);
|
|
741
|
+
paneId = stdout.trim();
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
return { paneId, tmuxSession: sessionName, tmuxSocket: tmuxSocket || null };
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
export async function killTmuxPane({ tmuxBin, paneId, tmuxSocket }) {
|
|
748
|
+
if (!paneId) return;
|
|
749
|
+
const socketArgs = tmuxSocket ? ['-L', tmuxSocket] : [];
|
|
750
|
+
await execFileAsync(tmuxBin, [...socketArgs, 'kill-pane', '-t', paneId]).catch(() => {});
|
|
751
|
+
}
|