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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.ko.md +134 -0
  3. package/README.md +161 -2
  4. package/adapters/antigravity/bin/agy-hook.mjs +24 -0
  5. package/adapters/antigravity/hooks.json +23 -0
  6. package/adapters/antigravity/mcp_config.json +8 -0
  7. package/adapters/antigravity/plugin.json +4 -0
  8. package/adapters/antigravity/rules/AGENTS.md +6 -0
  9. package/adapters/antigravity/skills/peer-bridge/SKILL.md +19 -0
  10. package/adapters/claude/.claude-plugin/plugin.json +5 -0
  11. package/adapters/claude/.mcp.json +8 -0
  12. package/adapters/claude/bin/cc-hook.mjs +20 -0
  13. package/adapters/claude/hooks/hooks.json +46 -0
  14. package/adapters/claude/skills/peer-bridge/SKILL.md +18 -0
  15. package/adapters/codex/bin/codex-hook.mjs +10 -0
  16. package/adapters/codex/config.toml.example +5 -0
  17. package/adapters/codex/hooks.json +44 -0
  18. package/adapters/codex/skills/peer-bridge/SKILL.md +12 -0
  19. package/adapters/gemini/bin/gemini-hook.mjs +10 -0
  20. package/adapters/gemini/settings.json +51 -0
  21. package/adapters/gemini/skills/peer-bridge/SKILL.md +12 -0
  22. package/adapters/paseo/SKILL.md +24 -0
  23. package/bin/pbridge-mcp.mjs +37 -0
  24. package/bin/pbridge-tui.mjs +7 -0
  25. package/bin/pbridge.mjs +5 -0
  26. package/bin/pbridged.mjs +16 -0
  27. package/package.json +42 -4
  28. package/src/adapters/antigravity/hooks.mjs +207 -0
  29. package/src/adapters/claude/hooks.mjs +204 -0
  30. package/src/adapters/codex/hooks.mjs +142 -0
  31. package/src/adapters/gemini/hooks.mjs +159 -0
  32. package/src/adapters/installer.mjs +328 -0
  33. package/src/cli/main.mjs +729 -0
  34. package/src/client/rpc.mjs +243 -0
  35. package/src/config.mjs +154 -0
  36. package/src/daemon/broker.mjs +1799 -0
  37. package/src/daemon/resolver.mjs +200 -0
  38. package/src/daemon/server.mjs +221 -0
  39. package/src/index.mjs +53 -0
  40. package/src/mcp/server.mjs +668 -0
  41. package/src/orchestrator/workflows.mjs +496 -0
  42. package/src/project.mjs +81 -0
  43. package/src/protocol.mjs +203 -0
  44. package/src/runtime/conv-api.mjs +101 -0
  45. package/src/runtime/host-discovery.mjs +635 -0
  46. package/src/runtime/native-claude.mjs +88 -0
  47. package/src/runtime/paseo.mjs +289 -0
  48. package/src/runtime/workers.mjs +751 -0
  49. package/src/storage/db.mjs +704 -0
  50. package/src/tui/render.mjs +472 -0
  51. package/src/tui/viewer.mjs +443 -0
@@ -0,0 +1,635 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { isProcessAlive } from '../config.mjs';
5
+ import { isSameProjectScope } from '../project.mjs';
6
+ import { cleanSummary, makeHandle } from '../protocol.mjs';
7
+ import { PaseoClient } from './paseo.mjs';
8
+
9
+ function safeReadJson(filePath) {
10
+ try {
11
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
12
+ } catch {
13
+ return null;
14
+ }
15
+ }
16
+
17
+ function toEpochMs(value, fallback = 0) {
18
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
19
+ return value > 1e12 ? value : value * 1000;
20
+ }
21
+ if (typeof value === 'string' && value.trim()) {
22
+ const num = Number(value);
23
+ if (Number.isFinite(num) && num > 0) return num > 1e12 ? num : num * 1000;
24
+ const parsed = Date.parse(value);
25
+ if (Number.isFinite(parsed) && parsed > 0) return parsed;
26
+ }
27
+ return fallback;
28
+ }
29
+
30
+ function readHeadAndTail(filePath, headBytes = 2048, tailBytes = 4096) {
31
+ let fd = null;
32
+ try {
33
+ const stat = fs.statSync(filePath);
34
+ fd = fs.openSync(filePath, 'r');
35
+ const headLen = Math.min(headBytes, stat.size);
36
+ const headBuf = Buffer.alloc(headLen);
37
+ if (headLen > 0) fs.readSync(fd, headBuf, 0, headLen, 0);
38
+
39
+ const tailLen = Math.min(tailBytes, stat.size);
40
+ const tailPos = Math.max(0, stat.size - tailLen);
41
+ const tailBuf = Buffer.alloc(tailLen);
42
+ if (tailLen > 0) fs.readSync(fd, tailBuf, 0, tailLen, tailPos);
43
+
44
+ return {
45
+ size: stat.size,
46
+ mtimeMs: stat.mtimeMs,
47
+ head: headBuf.toString('utf8'),
48
+ tail: tailBuf.toString('utf8'),
49
+ };
50
+ } catch {
51
+ return null;
52
+ } finally {
53
+ if (fd !== null) {
54
+ try {
55
+ fs.closeSync(fd);
56
+ } catch {
57
+ // ignore close failure
58
+ }
59
+ }
60
+ }
61
+ }
62
+
63
+ function normalizeClaudeState(job, session, sessionAlive) {
64
+ const jobState = String(job?.state || '').toLowerCase();
65
+ if (jobState === 'blocked' || Boolean(job?.needsAsk)) {
66
+ return 'needs_input';
67
+ }
68
+ if (jobState === 'working') {
69
+ return 'working';
70
+ }
71
+ const sessStatus = String(session?.status || '').toLowerCase();
72
+ if (sessionAlive && ['busy', 'running', 'shell'].includes(sessStatus) && jobState !== 'done') {
73
+ return 'working';
74
+ }
75
+ if (jobState === 'done') {
76
+ return 'done';
77
+ }
78
+ if (sessionAlive && ['idle', 'active', 'ready', 'waiting'].includes(sessStatus)) {
79
+ return 'done';
80
+ }
81
+ if (sessionAlive) {
82
+ return 'done';
83
+ }
84
+ return 'stopped';
85
+ }
86
+
87
+ function extractClaudeSummary(displayState, job, session) {
88
+ if (displayState === 'done') {
89
+ return cleanSummary(job?.output?.result || job?.detail || session?.summary || '');
90
+ }
91
+ if (displayState === 'needs_input') {
92
+ const ask = typeof job?.needsAsk === 'string' ? job.needsAsk : job?.needsAsk?.question || '';
93
+ return cleanSummary(job?.detail || ask || 'Awaiting input');
94
+ }
95
+ if (displayState === 'working') {
96
+ const fallback = session?.status === 'shell' ? 'Running shell' : 'Working';
97
+ return cleanSummary(job?.detail || fallback);
98
+ }
99
+ return cleanSummary(job?.detail || 'stopped');
100
+ }
101
+
102
+ export function scanClaudeHostPeers(claudeDir, { skipPidCheck = false, includeStopped = true } = {}) {
103
+ const peers = [];
104
+ if (!claudeDir || !fs.existsSync(claudeDir)) return peers;
105
+
106
+ const sessionsByJob = new Map();
107
+ const sessionsBySid = new Map();
108
+ const liveSessions = [];
109
+
110
+ const sessionsDir = path.join(claudeDir, 'sessions');
111
+ if (fs.existsSync(sessionsDir)) {
112
+ let files = [];
113
+ try {
114
+ files = fs.readdirSync(sessionsDir);
115
+ } catch {
116
+ files = [];
117
+ }
118
+ for (const file of files) {
119
+ // Strictly ignore .key or non-JSON files
120
+ if (!file.endsWith('.json')) continue;
121
+ const fullPath = path.join(sessionsDir, file);
122
+ const data = safeReadJson(fullPath);
123
+ if (!data) continue;
124
+ const pid = Number(data.pid);
125
+ const alive = skipPidCheck ? true : Number.isInteger(pid) && pid > 0 && isProcessAlive(pid);
126
+ if (!alive && !includeStopped) continue;
127
+ let mtimeMs = 0;
128
+ try {
129
+ mtimeMs = fs.statSync(fullPath).mtimeMs;
130
+ } catch {
131
+ mtimeMs = Date.now();
132
+ }
133
+ const sessionId = String(data.sessionId || data.session_id || file.replace(/\.json$/, ''));
134
+ const jobId = String(data.jobId || sessionId.slice(0, 8));
135
+ const rec = { data, pid: Number.isInteger(pid) ? pid : null, alive, sessionId, jobId, mtimeMs };
136
+ liveSessions.push(rec);
137
+ sessionsByJob.set(jobId, rec);
138
+ sessionsBySid.set(sessionId, rec);
139
+ }
140
+ }
141
+
142
+ const matchedSessionIds = new Set();
143
+ const jobsDir = path.join(claudeDir, 'jobs');
144
+ if (fs.existsSync(jobsDir)) {
145
+ let jobEntries = [];
146
+ try {
147
+ jobEntries = fs.readdirSync(jobsDir);
148
+ } catch {
149
+ jobEntries = [];
150
+ }
151
+ for (const entry of jobEntries) {
152
+ const statePath = path.join(jobsDir, entry, 'state.json');
153
+ if (!fs.existsSync(statePath)) continue;
154
+ const job = safeReadJson(statePath);
155
+ if (!job) continue;
156
+ let mtimeMs = 0;
157
+ try {
158
+ mtimeMs = fs.statSync(statePath).mtimeMs;
159
+ } catch {
160
+ mtimeMs = Date.now();
161
+ }
162
+ const sid = String(job.sessionId || job.resumeSessionId || entry);
163
+ const sessRec = sessionsByJob.get(entry) || sessionsBySid.get(sid) || null;
164
+ if (sessRec) matchedSessionIds.add(sessRec.sessionId);
165
+
166
+ const displayState = normalizeClaudeState(job, sessRec?.data || null, Boolean(sessRec?.alive));
167
+ if (displayState === 'stopped' && !includeStopped) continue;
168
+
169
+ const name = String(job.name || sessRec?.data?.name || entry.slice(0, 8));
170
+ const cwd = job.cwd || sessRec?.data?.cwd || null;
171
+ const updatedMs = Math.max(
172
+ toEpochMs(job.updatedAt, 0),
173
+ toEpochMs(sessRec?.data?.updatedAt, 0),
174
+ toEpochMs(job.lastTerminalAt, 0),
175
+ toEpochMs(sessRec?.data?.startedAt, 0),
176
+ toEpochMs(job.createdAt, 0),
177
+ mtimeMs,
178
+ );
179
+
180
+ peers.push({
181
+ id: `host:cc:${sid}`,
182
+ peer_id: null,
183
+ handle: `cc:${name}`,
184
+ runtime: 'cc',
185
+ name,
186
+ session_id: sid,
187
+ job_id: entry,
188
+ cwd,
189
+ origin: 'host',
190
+ exec_mode: 'background',
191
+ state: job.state || (sessRec?.alive ? 'active' : 'stopped'),
192
+ display_state: displayState,
193
+ can_close: false,
194
+ pid: sessRec?.pid ?? null,
195
+ summary: extractClaudeSummary(displayState, job, sessRec?.data || null),
196
+ updated_ms: updatedMs || Date.now(),
197
+ source: 'claude-job',
198
+ });
199
+ }
200
+ }
201
+
202
+ for (const sessRec of liveSessions) {
203
+ if (matchedSessionIds.has(sessRec.sessionId)) continue;
204
+ const displayState = normalizeClaudeState(null, sessRec.data, sessRec.alive);
205
+ if (displayState === 'stopped' && !includeStopped) continue;
206
+ const name = String(sessRec.data.name || sessRec.data.agentName || sessRec.sessionId.slice(0, 8));
207
+ const updatedMs = Math.max(
208
+ toEpochMs(sessRec.data.updatedAt, 0),
209
+ toEpochMs(sessRec.data.startedAt, 0),
210
+ sessRec.mtimeMs,
211
+ );
212
+ peers.push({
213
+ id: `host:cc:${sessRec.sessionId}`,
214
+ peer_id: null,
215
+ handle: `cc:${name}`,
216
+ runtime: 'cc',
217
+ name,
218
+ session_id: sessRec.sessionId,
219
+ job_id: sessRec.jobId,
220
+ cwd: sessRec.data.cwd || null,
221
+ origin: 'host',
222
+ exec_mode: sessRec.data.kind || 'interactive',
223
+ state: sessRec.data.status || (sessRec.alive ? 'active' : 'stopped'),
224
+ display_state: displayState,
225
+ can_close: false,
226
+ pid: sessRec.pid,
227
+ summary: extractClaudeSummary(displayState, null, sessRec.data),
228
+ updated_ms: updatedMs || Date.now(),
229
+ source: 'claude-session',
230
+ });
231
+ }
232
+
233
+ const teamsDir = path.join(claudeDir, 'teams');
234
+ if (fs.existsSync(teamsDir)) {
235
+ let teamDirs = [];
236
+ try {
237
+ teamDirs = fs.readdirSync(teamsDir);
238
+ } catch {
239
+ teamDirs = [];
240
+ }
241
+ for (const team of teamDirs) {
242
+ const cfgPath = path.join(teamsDir, team, 'config.json');
243
+ const cfg = safeReadJson(cfgPath);
244
+ if (!cfg || !Array.isArray(cfg.members)) continue;
245
+ let mtimeMs = Date.now();
246
+ try {
247
+ mtimeMs = fs.statSync(cfgPath).mtimeMs;
248
+ } catch {
249
+ // ignore
250
+ }
251
+ for (const member of cfg.members) {
252
+ if (!member?.name) continue;
253
+ const st = String(member.status || 'active').toLowerCase();
254
+ const displayState =
255
+ st === 'stopped' || st === 'offline' ? 'stopped' : st === 'busy' || st === 'working' ? 'working' : 'done';
256
+ if (displayState === 'stopped' && !includeStopped) continue;
257
+ const sid = String(member.agentId || `${team}/${member.name}`);
258
+ peers.push({
259
+ id: `host:cc:team:${sid}`,
260
+ peer_id: null,
261
+ handle: `cc:${member.name}`,
262
+ runtime: 'cc',
263
+ name: String(member.name),
264
+ session_id: sid,
265
+ cwd: cfg.cwd || null,
266
+ origin: 'host',
267
+ exec_mode: 'teammate',
268
+ state: st,
269
+ display_state: displayState,
270
+ can_close: false,
271
+ pid: null,
272
+ summary: cleanSummary(member.summary || `team: ${team}`),
273
+ updated_ms: toEpochMs(member.updatedAt, mtimeMs),
274
+ source: 'claude-team',
275
+ });
276
+ }
277
+ }
278
+ }
279
+
280
+ return peers;
281
+ }
282
+
283
+ function collectJsonlFiles(dir, depth, maxDepth, out) {
284
+ if (depth > maxDepth) return;
285
+ let entries = [];
286
+ try {
287
+ entries = fs.readdirSync(dir, { withFileTypes: true });
288
+ } catch {
289
+ return;
290
+ }
291
+ for (const ent of entries) {
292
+ const full = path.join(dir, ent.name);
293
+ if (ent.isDirectory()) {
294
+ collectJsonlFiles(full, depth + 1, maxDepth, out);
295
+ } else if (ent.isFile() && ent.name.endsWith('.jsonl')) {
296
+ try {
297
+ const st = fs.statSync(full);
298
+ out.push({ path: full, mtimeMs: st.mtimeMs });
299
+ } catch {
300
+ // ignore
301
+ }
302
+ }
303
+ }
304
+ }
305
+
306
+ export function scanCodexHostPeers(
307
+ codexDir,
308
+ { includeStopped = true, maxFiles = 15, maxAgeDays = 14, nowMs = Date.now() } = {},
309
+ ) {
310
+ const peers = [];
311
+ if (!codexDir) return peers;
312
+ const sessionsDir = path.join(codexDir, 'sessions');
313
+ if (!fs.existsSync(sessionsDir)) return peers;
314
+
315
+ const files = [];
316
+ collectJsonlFiles(sessionsDir, 0, 4, files);
317
+ const cutoffMs = nowMs - maxAgeDays * 86_400_000;
318
+ const recent = files
319
+ .filter((f) => f.mtimeMs >= cutoffMs)
320
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
321
+ .slice(0, maxFiles);
322
+
323
+ for (const file of recent) {
324
+ const slice = readHeadAndTail(file.path, 2048, 4096);
325
+ if (!slice) continue;
326
+
327
+ let sessionId = null;
328
+ let cwd = null;
329
+ let createdMs = slice.mtimeMs;
330
+ const firstLine = slice.head.split(/\r?\n/).find((l) => l.trim().startsWith('{'));
331
+ if (firstLine) {
332
+ try {
333
+ const meta = JSON.parse(firstLine);
334
+ const payload = meta.payload || meta;
335
+ sessionId = payload.session_id || payload.id || null;
336
+ cwd = payload.cwd || null;
337
+ createdMs = toEpochMs(payload.timestamp || meta.timestamp, slice.mtimeMs);
338
+ } catch {
339
+ // ignore parse errors
340
+ }
341
+ }
342
+ if (!sessionId) {
343
+ const m = path.basename(file.path).match(/([0-9a-f-]{8,})\.jsonl$/i);
344
+ sessionId = m ? m[1] : path.basename(file.path, '.jsonl');
345
+ }
346
+
347
+ let lastSummary = '';
348
+ let lastEventType = '';
349
+ const tailLines = slice.tail.split(/\r?\n/).filter((l) => l.trim().startsWith('{'));
350
+ for (const line of tailLines) {
351
+ try {
352
+ const ev = JSON.parse(line);
353
+ const p = ev.payload || ev;
354
+ const pType = String(p.type || ev.type || '').toLowerCase();
355
+ if (pType) lastEventType = pType;
356
+ if (pType === 'agent_message' && (p.message || p.text)) {
357
+ lastSummary = cleanSummary(p.message || p.text, 120, { preferLast: true });
358
+ } else if (ev.type === 'response_item' && p.role === 'assistant' && Array.isArray(p.content)) {
359
+ const textPart = p.content.find((c) => c?.text || c?.output_text);
360
+ if (textPart) {
361
+ lastSummary = cleanSummary(textPart.text || textPart.output_text, 120, { preferLast: true });
362
+ }
363
+ }
364
+ } catch {
365
+ // partial tail line
366
+ }
367
+ }
368
+
369
+ const ageMs = Math.max(0, nowMs - slice.mtimeMs);
370
+ const isTerminal = lastEventType.includes('complete') || lastEventType.includes('abort');
371
+ let displayState = 'stopped';
372
+ if (ageMs < 15_000 && !isTerminal) {
373
+ displayState = 'working';
374
+ } else if (ageMs < 3_600_000) {
375
+ displayState = 'done';
376
+ }
377
+ if (displayState === 'stopped' && !includeStopped) continue;
378
+
379
+ const name = String(sessionId).slice(0, 8);
380
+ peers.push({
381
+ id: `host:codex:${sessionId}`,
382
+ peer_id: null,
383
+ handle: `codex:${name}`,
384
+ runtime: 'codex',
385
+ name,
386
+ session_id: String(sessionId),
387
+ cwd,
388
+ origin: 'host',
389
+ exec_mode: 'interactive',
390
+ state: displayState,
391
+ display_state: displayState,
392
+ can_close: false,
393
+ pid: null,
394
+ summary: lastSummary || (displayState === 'stopped' ? 'stopped' : 'codex session'),
395
+ updated_ms: Math.max(slice.mtimeMs, createdMs),
396
+ source: 'codex-session',
397
+ });
398
+ }
399
+
400
+ return peers;
401
+ }
402
+
403
+ function mapPaseoDisplayState(rawStatus) {
404
+ const s = String(rawStatus || '').toLowerCase();
405
+ if (['running', 'busy', 'starting', 'working', 'streaming'].includes(s)) return 'working';
406
+ if (['waiting', 'input', 'blocked', 'needs_input', 'awaiting_input', 'permission'].includes(s)) {
407
+ return 'needs_input';
408
+ }
409
+ if (['stopped', 'exited', 'closed', 'error', 'failed', 'offline'].includes(s)) return 'stopped';
410
+ return 'done';
411
+ }
412
+
413
+ export async function scanPaseoHostPeers(
414
+ config = {},
415
+ { includeStopped = true, paseoClientFactory = null } = {},
416
+ ) {
417
+ const paseoHome = config.paseoHome || path.join(os.homedir(), '.paseo');
418
+ const sockPath = path.join(paseoHome, 'daemon.sock');
419
+
420
+ if (!paseoClientFactory && !config.paseoHost && !fs.existsSync(sockPath)) {
421
+ return [];
422
+ }
423
+
424
+ try {
425
+ const client = paseoClientFactory
426
+ ? paseoClientFactory({ host: config.paseoHost, home: config.paseoHome })
427
+ : new PaseoClient({
428
+ paseoBin: config.paseoBin,
429
+ host: config.paseoHost,
430
+ home: config.paseoHome,
431
+ });
432
+
433
+ const agents = await Promise.race([
434
+ client.listAgents({ includeStopped }),
435
+ new Promise((_, reject) => setTimeout(() => reject(new Error('paseo timeout')), 1500)),
436
+ ]);
437
+ if (!Array.isArray(agents)) return [];
438
+
439
+ const peers = [];
440
+ for (const agent of agents) {
441
+ const id = String(agent.id || agent.agentId || '').trim();
442
+ if (!id) continue;
443
+ const displayState = mapPaseoDisplayState(agent.status);
444
+ if (displayState === 'stopped' && !includeStopped) continue;
445
+ const name = String(agent.title || agent.name || id.slice(0, 8));
446
+ peers.push({
447
+ id: `host:paseo:${id}`,
448
+ peer_id: null,
449
+ handle: `paseo:${name}`,
450
+ runtime: 'paseo',
451
+ name,
452
+ session_id: id,
453
+ cwd: agent.cwd || agent.workingDirectory || null,
454
+ origin: 'host',
455
+ exec_mode: 'external',
456
+ state: String(agent.status || 'idle'),
457
+ display_state: displayState,
458
+ can_close: false,
459
+ pid: null,
460
+ summary: cleanSummary(agent.summary || agent.lastMessage || agent.provider || 'paseo agent'),
461
+ updated_ms: toEpochMs(agent.updatedAt || agent.updated_at || agent.createdAt, Date.now()),
462
+ source: 'paseo-host',
463
+ });
464
+ }
465
+ return peers;
466
+ } catch {
467
+ return [];
468
+ }
469
+ }
470
+
471
+ export async function discoverHostPeers(config = {}, opts = {}) {
472
+ const includeStopped = opts.includeStopped !== false;
473
+ const ccPeers = scanClaudeHostPeers(config.claudeDir, {
474
+ skipPidCheck: Boolean(opts.skipPidCheck),
475
+ includeStopped,
476
+ });
477
+ const codexPeers = scanCodexHostPeers(config.codexDir, {
478
+ includeStopped,
479
+ nowMs: opts.nowMs || Date.now(),
480
+ });
481
+ const paseoPeers = await scanPaseoHostPeers(config, {
482
+ includeStopped,
483
+ paseoClientFactory: opts.paseoClientFactory || null,
484
+ });
485
+ return [...ccPeers, ...codexPeers, ...paseoPeers];
486
+ }
487
+
488
+ export function normalizeBrokerPeer(peer) {
489
+ const meta = peer.metadata || {};
490
+ const rawState = String(peer.state || 'idle').toLowerCase();
491
+ let displayState = 'done';
492
+ if (rawState === 'starting' || rawState === 'busy') {
493
+ displayState = 'working';
494
+ } else if (rawState === 'error') {
495
+ displayState = 'error';
496
+ } else if (rawState === 'blocked' || meta.needs_input === true) {
497
+ displayState = 'needs_input';
498
+ } else if (['archived', 'closed', 'deleted', 'detached'].includes(rawState)) {
499
+ displayState = 'stopped';
500
+ } else {
501
+ displayState = 'done';
502
+ }
503
+
504
+ let summary = cleanSummary(meta.summary || '');
505
+ if (rawState === 'error') {
506
+ summary = summary ? (summary.startsWith('[error]') ? summary : `[error] ${summary}`) : '[error] worker error';
507
+ } else if (!summary && displayState === 'stopped') {
508
+ summary = rawState;
509
+ }
510
+
511
+ const canClose =
512
+ peer.origin === 'spawned' && !['archived', 'closed', 'deleted', 'detached'].includes(rawState);
513
+
514
+ return {
515
+ id: peer.peer_id,
516
+ peer_id: peer.peer_id,
517
+ handle: peer.handle || makeHandle(peer),
518
+ runtime: peer.runtime,
519
+ name: peer.name,
520
+ session_id: peer.session_id || null,
521
+ cwd: peer.cwd || null,
522
+ origin: peer.origin || 'attached',
523
+ exec_mode: peer.exec_mode || 'interactive',
524
+ state: peer.state,
525
+ display_state: displayState,
526
+ can_close: canClose,
527
+ pid: peer.pid ?? null,
528
+ summary,
529
+ updated_ms: toEpochMs(peer.updated_at || peer.created_at, Date.now()),
530
+ source: 'broker',
531
+ };
532
+ }
533
+
534
+ export function computePeerCounts(peers) {
535
+ const counts = {
536
+ needs_input: 0,
537
+ working: 0,
538
+ done: 0,
539
+ error: 0,
540
+ stopped: 0,
541
+ spawned: 0,
542
+ total: peers.length,
543
+ };
544
+ for (const p of peers) {
545
+ if (p.display_state === 'needs_input') counts.needs_input++;
546
+ else if (p.display_state === 'working') counts.working++;
547
+ else if (p.display_state === 'error') counts.error++;
548
+ else if (p.display_state === 'done') counts.done++;
549
+ else counts.stopped++;
550
+ if (p.origin === 'spawned' && p.display_state !== 'stopped') counts.spawned++;
551
+ }
552
+ return counts;
553
+ }
554
+
555
+ export function mergeAllPeers(
556
+ brokerPeers = [],
557
+ hostPeers = [],
558
+ { runtime = null, cwd = null, includeStopped = true } = {},
559
+ ) {
560
+ const normalizedBroker = brokerPeers.map(normalizeBrokerPeer);
561
+ const bySid = new Map();
562
+ const byShortSid = new Map();
563
+ const byNameCwd = new Map();
564
+
565
+ for (const bp of normalizedBroker) {
566
+ if (bp.session_id) {
567
+ bySid.set(`${bp.runtime}:${bp.session_id}`, bp);
568
+ if (bp.session_id.length >= 8) {
569
+ byShortSid.set(`${bp.runtime}:${bp.session_id.slice(0, 8)}`, bp);
570
+ }
571
+ }
572
+ byNameCwd.set(`${bp.runtime}:${bp.name}:${bp.cwd || ''}`, bp);
573
+ }
574
+
575
+ const merged = [...normalizedBroker];
576
+ const seenHostIds = new Set();
577
+
578
+ for (const hp of hostPeers) {
579
+ if (seenHostIds.has(hp.id)) continue;
580
+ seenHostIds.add(hp.id);
581
+
582
+ let match = null;
583
+ if (hp.session_id) {
584
+ match =
585
+ bySid.get(`${hp.runtime}:${hp.session_id}`) ||
586
+ (hp.job_id ? byShortSid.get(`${hp.runtime}:${hp.job_id}`) : null) ||
587
+ (hp.session_id.length >= 8 ? byShortSid.get(`${hp.runtime}:${hp.session_id.slice(0, 8)}`) : null);
588
+ }
589
+ if (!match) {
590
+ match = byNameCwd.get(`${hp.runtime}:${hp.name}:${hp.cwd || ''}`) || null;
591
+ }
592
+
593
+ if (match) {
594
+ if (!match.summary && hp.summary) {
595
+ match.summary = hp.summary;
596
+ }
597
+ if (!match.cwd && hp.cwd) {
598
+ match.cwd = hp.cwd;
599
+ }
600
+ if (
601
+ match.origin === 'attached' &&
602
+ match.display_state === 'done' &&
603
+ (hp.display_state === 'working' || hp.display_state === 'needs_input') &&
604
+ hp.updated_ms >= match.updated_ms
605
+ ) {
606
+ match.display_state = hp.display_state;
607
+ match.updated_ms = hp.updated_ms;
608
+ if (hp.summary) match.summary = hp.summary;
609
+ }
610
+ continue;
611
+ }
612
+
613
+ merged.push(hp);
614
+ }
615
+
616
+ const runtimeFilter = runtime && runtime !== 'all' ? String(runtime).toLowerCase() : null;
617
+ const cwdFilter = cwd ? path.resolve(cwd) : null;
618
+
619
+ const filtered = merged.filter((p) => {
620
+ if (runtimeFilter && p.runtime !== runtimeFilter) return false;
621
+ if (!includeStopped && p.display_state === 'stopped') return false;
622
+ if (cwdFilter) {
623
+ if (!p.cwd) return false;
624
+ const resolved = path.resolve(p.cwd);
625
+ const exactOrSub = resolved === cwdFilter || resolved.startsWith(`${cwdFilter}${path.sep}`);
626
+ if (!exactOrSub && !isSameProjectScope(p.cwd, cwdFilter)) return false;
627
+ }
628
+ return true;
629
+ });
630
+
631
+ return {
632
+ peers: filtered,
633
+ counts: computePeerCounts(filtered),
634
+ };
635
+ }